client.rs 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. use async_std::sync::{Arc, Mutex};
  2. use incrementalmerkletree::{bridgetree::BridgeTree, Tree};
  3. use lazy_init::Lazy;
  4. use log::{debug, error, info};
  5. use pasta_curves::group::ff::PrimeField;
  6. use super::state::{state_transition, State};
  7. use crate::{
  8. crypto::{
  9. address::Address,
  10. coin::{Coin, OwnCoin},
  11. constants::MERKLE_DEPTH,
  12. keypair::{Keypair, PublicKey},
  13. merkle_node::MerkleNode,
  14. proof::ProvingKey,
  15. types::DrkTokenId,
  16. },
  17. serial::Encodable,
  18. tx::{
  19. builder::{
  20. TransactionBuilder, TransactionBuilderClearInputInfo, TransactionBuilderInputInfo,
  21. TransactionBuilderOutputInfo,
  22. },
  23. Transaction,
  24. },
  25. wallet::walletdb::{Balances, WalletPtr},
  26. zk::circuit::{BurnContract, MintContract},
  27. ClientFailed, ClientResult, Result,
  28. };
  29. /// The Client structure, used for transaction operations.
  30. /// This includes, receiving, broadcasting, and building.
  31. pub struct Client {
  32. pub main_keypair: Mutex<Keypair>,
  33. pub wallet: WalletPtr,
  34. mint_pk: Lazy<ProvingKey>,
  35. burn_pk: Lazy<ProvingKey>,
  36. }
  37. impl Client {
  38. pub async fn new(wallet: WalletPtr) -> Result<Self> {
  39. // Initialize or load the wallet
  40. wallet.init_db().await?;
  41. // Get default keypair or create one
  42. let main_keypair = wallet.get_default_keypair_or_create_one().await?;
  43. info!(target: "client", "Main keypair: {}", Address::from(main_keypair.public));
  44. // Generate merkle tree if we don't have one.
  45. // TODO: See what to do about this
  46. if wallet.get_tree().await.is_err() {
  47. wallet.tree_gen().await?;
  48. }
  49. Ok(Self {
  50. main_keypair: Mutex::new(main_keypair),
  51. wallet,
  52. mint_pk: Lazy::new(),
  53. burn_pk: Lazy::new(),
  54. })
  55. }
  56. // TODO: Better function name
  57. async fn build_slab_from_tx(
  58. &self,
  59. pubkey: PublicKey,
  60. value: u64,
  61. token_id: DrkTokenId,
  62. clear_input: bool,
  63. state: Arc<Mutex<State>>,
  64. ) -> ClientResult<(Transaction, Vec<Coin>)> {
  65. debug!("build_slab_from_tx(): Begin building slab from tx");
  66. let mut clear_inputs = vec![];
  67. let mut inputs = vec![];
  68. let mut outputs = vec![];
  69. let mut coins = vec![];
  70. if clear_input {
  71. debug!("build_slab_from_tx(): Building clear input");
  72. let signature_secret = self.main_keypair.lock().await.secret;
  73. let input = TransactionBuilderClearInputInfo { value, token_id, signature_secret };
  74. clear_inputs.push(input);
  75. } else {
  76. debug!("build_slab_from_tx(): Building tx inputs");
  77. let mut inputs_value = 0;
  78. let state_m = state.lock().await;
  79. let own_coins = self.wallet.get_own_coins().await?;
  80. for own_coin in own_coins.iter() {
  81. if inputs_value >= value {
  82. debug!("build_slab_from_tx(): inputs_value >= value");
  83. break
  84. }
  85. let leaf_position = own_coin.leaf_position;
  86. let root = state_m.tree.root(0).unwrap();
  87. let merkle_path = state_m.tree.authentication_path(leaf_position, &root).unwrap();
  88. inputs_value += own_coin.note.value;
  89. let input = TransactionBuilderInputInfo {
  90. leaf_position,
  91. merkle_path,
  92. secret: own_coin.secret,
  93. note: own_coin.note.clone(),
  94. };
  95. inputs.push(input);
  96. coins.push(own_coin.coin);
  97. }
  98. // Release state lock
  99. drop(state_m);
  100. if inputs_value < value {
  101. error!("build_slab_from_tx(): Not enough value to build tx inputs");
  102. return Err(ClientFailed::NotEnoughValue(inputs_value))
  103. }
  104. if inputs_value > value {
  105. let return_value = inputs_value - value;
  106. outputs.push(TransactionBuilderOutputInfo {
  107. value: return_value,
  108. token_id,
  109. public: self.main_keypair.lock().await.public,
  110. });
  111. }
  112. debug!("build_slab_from_tx(): Finished building inputs");
  113. }
  114. outputs.push(TransactionBuilderOutputInfo { value, token_id, public: pubkey });
  115. let builder = TransactionBuilder { clear_inputs, inputs, outputs };
  116. let mut tx_data = vec![];
  117. let mint_pk = self.mint_pk.get_or_create(Client::build_mint_pk);
  118. let burn_pk = self.burn_pk.get_or_create(Client::build_burn_pk);
  119. let tx = builder.build(mint_pk, burn_pk)?;
  120. tx.encode(&mut tx_data)?;
  121. // Check if state transition is valid before broadcasting
  122. debug!("build_slab_from_tx(): Checking if state transition is valid");
  123. let state = &*state.lock().await;
  124. debug!("build_slab_from_tx(): Got state lock");
  125. state_transition(state, tx.clone())?;
  126. debug!("build_slab_from_tx(): Successful state transition");
  127. Ok((tx, coins))
  128. }
  129. /// Build a transaction given the required parameters and state machine.
  130. pub async fn build_transaction(
  131. &self,
  132. pubkey: PublicKey,
  133. amount: u64,
  134. token_id: DrkTokenId,
  135. clear_input: bool,
  136. state: Arc<Mutex<State>>,
  137. ) -> ClientResult<Transaction> {
  138. debug!(
  139. "send(): Sending {} {} tokens",
  140. amount,
  141. bs58::encode(token_id.to_repr()).into_string()
  142. );
  143. if amount == 0 {
  144. return Err(ClientFailed::InvalidAmount(0))
  145. }
  146. if !self.wallet.token_id_exists(token_id).await? && !clear_input {
  147. return Err(ClientFailed::NotEnoughValue(amount))
  148. }
  149. let (tx, coins) =
  150. self.build_slab_from_tx(pubkey, amount, token_id, clear_input, state).await?;
  151. for coin in coins.iter() {
  152. // TODO: This should be more robust. In case our transaction is denied,
  153. // we want to revert to be able to send again.
  154. self.wallet.confirm_spend_coin(coin).await?;
  155. }
  156. debug!("send(): Sent {}", amount);
  157. Ok(tx)
  158. }
  159. pub async fn init_db(&self) -> Result<()> {
  160. self.wallet.init_db().await
  161. }
  162. pub async fn get_own_coins(&self) -> Result<Vec<OwnCoin>> {
  163. self.wallet.get_own_coins().await
  164. }
  165. pub async fn confirm_spend_coin(&self, coin: &Coin) -> Result<()> {
  166. self.wallet.confirm_spend_coin(coin).await
  167. }
  168. pub async fn revert_spend_coin(&self, coin: &Coin) -> Result<()> {
  169. self.wallet.revert_spend_coin(coin).await
  170. }
  171. pub async fn get_keypairs(&self) -> Result<Vec<Keypair>> {
  172. self.wallet.get_keypairs().await
  173. }
  174. pub async fn put_keypair(&self, keypair: &Keypair) -> Result<()> {
  175. self.wallet.put_keypair(keypair).await
  176. }
  177. pub async fn set_default_keypair(&self, public: &PublicKey) -> Result<()> {
  178. let kp = self.wallet.set_default_keypair(public).await?;
  179. let mut mk = self.main_keypair.lock().await;
  180. *mk = kp;
  181. drop(mk);
  182. Ok(())
  183. }
  184. pub async fn keygen(&self) -> Result<Address> {
  185. let kp = self.wallet.keygen().await?;
  186. Ok(Address::from(kp.public))
  187. }
  188. pub async fn get_balances(&self) -> Result<Balances> {
  189. self.wallet.get_balances().await
  190. }
  191. pub async fn get_coins_valtok(
  192. &self,
  193. value: u64,
  194. token_id: DrkTokenId,
  195. unspent: bool,
  196. ) -> Result<Vec<OwnCoin>> {
  197. self.wallet.get_coins_valtok(value, token_id, unspent).await
  198. }
  199. pub async fn get_tree(&self) -> Result<BridgeTree<MerkleNode, MERKLE_DEPTH>> {
  200. self.wallet.get_tree().await
  201. }
  202. fn build_mint_pk() -> ProvingKey {
  203. debug!("Building proving key for MintContract");
  204. ProvingKey::build(11, &MintContract::default())
  205. }
  206. fn build_burn_pk() -> ProvingKey {
  207. debug!("Building proving key for BurnContract");
  208. ProvingKey::build(11, &BurnContract::default())
  209. }
  210. }