Make coin a dedicated library

Closes https://github.com/serai-dex/serai/issues/128.
This commit is contained in:
Luke Parker
2022-10-15 23:21:43 -04:00
parent f50148d17a
commit 65664dafa4
9 changed files with 119 additions and 42 deletions

41
coin/Cargo.toml Normal file
View File

@@ -0,0 +1,41 @@
[package]
name = "serai-coin"
version = "0.1.0"
description = "Abstract interface to represent a coin"
license = "MIT"
repository = "https://github.com/serai-dex/serai"
authors = ["Luke Parker <lukeparker5132@gmail.com>"]
keywords = []
edition = "2021"
publish = false
[dependencies]
async-trait = "0.1"
thiserror = "1"
curve25519-dalek = { version = "3", features = ["std"] }
transcript = { package = "flexible-transcript", path = "../crypto/transcript", features = ["recommended"] }
dalek-ff-group = { path = "../crypto/dalek-ff-group" }
frost = { package = "modular-frost", path = "../crypto/frost", features = ["secp256k1", "ed25519"] }
monero-serai = { path = "../coins/monero", features = ["multisig"] }
# Test Dependencies
rand_core = { version = "0.6", optional = true }
group = { version = "0.12", optional = true }
serde = { version = "1.0", features = ["derive"], optional = true }
serde_json = { version = "1.0", optional = true }
[dev-dependencies]
rand_core = "0.6"
group = "0.12"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
[features]
test = ["rand_core", "group", "serde", "serde_json"]

21
coin/LICENSE Normal file
View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2022 Luke Parker
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

92
coin/src/lib.rs Normal file
View File

@@ -0,0 +1,92 @@
use std::marker::Send;
use async_trait::async_trait;
use thiserror::Error;
use transcript::RecommendedTranscript;
use frost::{curve::Curve, FrostKeys, sign::PreprocessMachine};
pub(crate) mod utils;
pub mod monero;
pub use self::monero::Monero;
#[derive(Clone, Error, Debug)]
pub enum CoinError {
#[error("failed to connect to coin daemon")]
ConnectionError,
}
pub trait Output: Sized + Clone {
type Id: AsRef<[u8]>;
fn id(&self) -> Self::Id;
fn amount(&self) -> u64;
fn serialize(&self) -> Vec<u8>;
fn deserialize<R: std::io::Read>(reader: &mut R) -> std::io::Result<Self>;
}
#[async_trait]
pub trait Coin {
type Curve: Curve;
type Fee: Copy;
type Transaction;
type Block;
type Output: Output;
type SignableTransaction;
type TransactionMachine: PreprocessMachine<Signature = Self::Transaction>;
type Address: Send;
const ID: &'static [u8];
const CONFIRMATIONS: usize;
const MAX_INPUTS: usize;
const MAX_OUTPUTS: usize; // TODO: Decide if this includes change or not
// Doesn't have to take self, enables some level of caching which is pleasant
fn address(&self, key: <Self::Curve as Curve>::G) -> Self::Address;
async fn get_latest_block_number(&self) -> Result<usize, CoinError>;
async fn get_block(&self, number: usize) -> Result<Self::Block, CoinError>;
async fn get_outputs(
&self,
block: &Self::Block,
key: <Self::Curve as Curve>::G,
) -> Result<Vec<Self::Output>, CoinError>;
// TODO: Remove
async fn is_confirmed(&self, tx: &[u8]) -> Result<bool, CoinError>;
async fn prepare_send(
&self,
keys: FrostKeys<Self::Curve>,
transcript: RecommendedTranscript,
block_number: usize,
inputs: Vec<Self::Output>,
payments: &[(Self::Address, u64)],
fee: Self::Fee,
) -> Result<Self::SignableTransaction, CoinError>;
async fn attempt_send(
&self,
transaction: Self::SignableTransaction,
included: &[u16],
) -> Result<Self::TransactionMachine, CoinError>;
async fn publish_transaction(
&self,
tx: &Self::Transaction,
) -> Result<(Vec<u8>, Vec<<Self::Output as Output>::Id>), CoinError>;
#[cfg(any(test, feature = "test"))]
async fn get_fee(&self) -> Self::Fee;
#[cfg(any(test, feature = "test"))]
async fn mine_block(&self);
#[cfg(any(test, feature = "test"))]
async fn test_send(&self, key: Self::Address);
}

269
coin/src/monero.rs Normal file
View File

@@ -0,0 +1,269 @@
use async_trait::async_trait;
use curve25519_dalek::scalar::Scalar;
use dalek_ff_group as dfg;
use transcript::RecommendedTranscript;
use frost::{curve::Ed25519, FrostKeys};
use monero_serai::{
transaction::Transaction,
block::Block,
rpc::Rpc,
wallet::{
ViewPair, Scanner,
address::{Network, Address},
Fee, SpendableOutput, SignableTransaction as MSignableTransaction, TransactionMachine,
},
};
use crate::{CoinError, Output as OutputTrait, Coin, utils::additional_key};
#[derive(Clone, Debug)]
pub struct Output(SpendableOutput);
impl From<SpendableOutput> for Output {
fn from(output: SpendableOutput) -> Output {
Output(output)
}
}
impl OutputTrait for Output {
// While we could use (tx, o), using the key ensures we won't be susceptible to the burning bug.
// While the Monero library offers a variant which allows senders to ensure their TXs have unique
// output keys, Serai can still be targeted using the classic burning bug
type Id = [u8; 32];
fn id(&self) -> Self::Id {
self.0.output.data.key.compress().to_bytes()
}
fn amount(&self) -> u64 {
self.0.commitment().amount
}
fn serialize(&self) -> Vec<u8> {
self.0.serialize()
}
fn deserialize<R: std::io::Read>(reader: &mut R) -> std::io::Result<Self> {
SpendableOutput::deserialize(reader).map(Output)
}
}
#[derive(Debug)]
pub struct SignableTransaction {
keys: FrostKeys<Ed25519>,
transcript: RecommendedTranscript,
// Monero height, defined as the length of the chain
height: usize,
actual: MSignableTransaction,
}
#[derive(Clone, Debug)]
pub struct Monero {
pub(crate) rpc: Rpc,
view: Scalar,
}
impl Monero {
pub async fn new(url: String) -> Monero {
Monero { rpc: Rpc::new(url), view: additional_key::<Monero>(0).0 }
}
fn scanner(&self, spend: dfg::EdwardsPoint) -> Scanner {
Scanner::from_view(ViewPair::new(spend.0, self.view), Network::Mainnet, None)
}
#[cfg(any(test, feature = "test"))]
fn empty_scanner() -> Scanner {
use group::Group;
Scanner::from_view(
ViewPair::new(*dfg::EdwardsPoint::generator(), Scalar::one()),
Network::Mainnet,
Some(std::collections::HashSet::new()),
)
}
#[cfg(any(test, feature = "test"))]
fn empty_address() -> Address {
Self::empty_scanner().address()
}
}
#[async_trait]
impl Coin for Monero {
type Curve = Ed25519;
type Fee = Fee;
type Transaction = Transaction;
type Block = Block;
type Output = Output;
type SignableTransaction = SignableTransaction;
type TransactionMachine = TransactionMachine;
type Address = Address;
const ID: &'static [u8] = b"Monero";
const CONFIRMATIONS: usize = 10;
// Testnet TX bb4d188a4c571f2f0de70dca9d475abc19078c10ffa8def26dd4f63ce1bcfd79 uses 146 inputs
// while using less than 100kb of space, albeit with just 2 outputs (though outputs share a BP)
// The TX size limit is half the contextual median block weight, where said weight is >= 300,000
// This means any TX which fits into 150kb will be accepted by Monero
// 128, even with 16 outputs, should fit into 100kb. Further efficiency by 192 may be viable
// TODO: Get hard numbers and tune
const MAX_INPUTS: usize = 128;
const MAX_OUTPUTS: usize = 16;
fn address(&self, key: dfg::EdwardsPoint) -> Self::Address {
self.scanner(key).address()
}
async fn get_latest_block_number(&self) -> Result<usize, CoinError> {
// Monero defines height as chain length, so subtract 1 for block number
Ok(self.rpc.get_height().await.map_err(|_| CoinError::ConnectionError)? - 1)
}
async fn get_block(&self, number: usize) -> Result<Self::Block, CoinError> {
self.rpc.get_block(number).await.map_err(|_| CoinError::ConnectionError)
}
async fn get_outputs(
&self,
block: &Self::Block,
key: dfg::EdwardsPoint,
) -> Result<Vec<Self::Output>, CoinError> {
Ok(
self
.scanner(key)
.scan(&self.rpc, block)
.await
.map_err(|_| CoinError::ConnectionError)?
.iter()
.flat_map(|outputs| outputs.not_locked())
.map(Output::from)
.collect(),
)
}
async fn is_confirmed(&self, tx: &[u8]) -> Result<bool, CoinError> {
let tx_block_number =
self.rpc.get_transaction_block_number(tx).await.map_err(|_| CoinError::ConnectionError)?;
Ok((self.get_latest_block_number().await?.saturating_sub(tx_block_number) + 1) >= 10)
}
async fn prepare_send(
&self,
keys: FrostKeys<Ed25519>,
transcript: RecommendedTranscript,
block_number: usize,
mut inputs: Vec<Output>,
payments: &[(Address, u64)],
fee: Fee,
) -> Result<SignableTransaction, CoinError> {
let spend = keys.group_key();
Ok(SignableTransaction {
keys,
transcript,
height: block_number + 1,
actual: MSignableTransaction::new(
self.rpc.get_protocol().await.unwrap(), // TODO: Make this deterministic
inputs.drain(..).map(|input| input.0).collect(),
payments.to_vec(),
Some(self.address(spend)),
None,
fee,
)
.map_err(|_| CoinError::ConnectionError)?,
})
}
async fn attempt_send(
&self,
transaction: SignableTransaction,
included: &[u16],
) -> Result<Self::TransactionMachine, CoinError> {
transaction
.actual
.clone()
.multisig(
&self.rpc,
transaction.keys.clone(),
transaction.transcript.clone(),
transaction.height,
included.to_vec(),
)
.await
.map_err(|_| CoinError::ConnectionError)
}
async fn publish_transaction(
&self,
tx: &Self::Transaction,
) -> Result<(Vec<u8>, Vec<<Self::Output as OutputTrait>::Id>), CoinError> {
self.rpc.publish_transaction(tx).await.map_err(|_| CoinError::ConnectionError)?;
Ok((tx.hash().to_vec(), tx.prefix.outputs.iter().map(|output| output.key.to_bytes()).collect()))
}
#[cfg(any(test, feature = "test"))]
async fn get_fee(&self) -> Self::Fee {
self.rpc.get_fee().await.unwrap()
}
#[cfg(any(test, feature = "test"))]
async fn mine_block(&self) {
#[derive(serde::Deserialize, Debug)]
struct EmptyResponse {}
let _: EmptyResponse = self
.rpc
.rpc_call(
"json_rpc",
Some(serde_json::json!({
"method": "generateblocks",
"params": {
"wallet_address": Self::empty_address().to_string(),
"amount_of_blocks": 10
},
})),
)
.await
.unwrap();
}
#[cfg(any(test, feature = "test"))]
async fn test_send(&self, address: Self::Address) {
use rand_core::OsRng;
let new_block = self.get_latest_block_number().await.unwrap() + 1;
self.mine_block().await;
for _ in 0 .. 7 {
self.mine_block().await;
}
let outputs = Self::empty_scanner()
.scan(&self.rpc, &self.rpc.get_block(new_block).await.unwrap())
.await
.unwrap()
.swap_remove(0)
.ignore_timelock();
let amount = outputs[0].commitment().amount;
let fee = 3000000000; // TODO
let tx = MSignableTransaction::new(
self.rpc.get_protocol().await.unwrap(),
outputs,
vec![(address, amount - fee)],
Some(Self::empty_address()),
None,
self.rpc.get_fee().await.unwrap(),
)
.unwrap()
.sign(&mut OsRng, &self.rpc, &Scalar::one())
.await
.unwrap();
self.rpc.publish_transaction(&tx).await.unwrap();
self.mine_block().await;
}
}

11
coin/src/utils.rs Normal file
View File

@@ -0,0 +1,11 @@
use frost::curve::Curve;
use crate::Coin;
// Generate a static additional key for a given chain in a globally consistent manner
// Doesn't consider the current group key to increase the simplicity of verifying Serai's status
// Takes an index, k, to support protocols which use multiple secondary keys
// Presumably a view key
pub(crate) fn additional_key<C: Coin>(k: u64) -> <C::Curve as Curve>::F {
C::Curve::hash_to_F(b"Serai DEX Additional Key", &[C::ID, &k.to_le_bytes()].concat())
}