client.rs 7.7 KB

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