tx.rs 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  1. // Example transaction flow
  2. use incrementalmerkletree::{bridgetree::BridgeTree, Frontier, Tree};
  3. use rand::rngs::OsRng;
  4. use darkfi::{
  5. crypto::{
  6. keypair::{Keypair, PublicKey, SecretKey},
  7. merkle_node::MerkleNode,
  8. note::{EncryptedNote, Note},
  9. nullifier::Nullifier,
  10. proof::{ProvingKey, VerifyingKey},
  11. token_id::generate_id2,
  12. OwnCoin, OwnCoins,
  13. },
  14. node::state::{state_transition, ProgramState, StateUpdate},
  15. tx::builder::{
  16. TransactionBuilder, TransactionBuilderClearInputInfo, TransactionBuilderInputInfo,
  17. TransactionBuilderOutputInfo,
  18. },
  19. util::NetworkName,
  20. zk::circuit::{BurnContract, MintContract},
  21. Result,
  22. };
  23. /// The state machine, held in memory.
  24. struct MemoryState {
  25. /// The entire Merkle tree state
  26. tree: BridgeTree<MerkleNode, 32>,
  27. /// List of all previous and the current Merkle roots.
  28. /// This is the hashed value of all the children.
  29. merkle_roots: Vec<MerkleNode>,
  30. /// Nullifiers prevent double spending
  31. nullifiers: Vec<Nullifier>,
  32. /// All received coins
  33. // NOTE: We need maybe a flag to keep track of which ones are
  34. // spent. Maybe the spend field links to a tx hash:input index.
  35. // We should also keep track of the tx hash:output index where
  36. // this coin was received.
  37. own_coins: OwnCoins,
  38. /// Verifying key for the mint zk circuit.
  39. mint_vk: VerifyingKey,
  40. /// Verifying key for the burn zk circuit.
  41. burn_vk: VerifyingKey,
  42. /// Public key of the cashier
  43. cashier_signature_public: PublicKey,
  44. /// Public key of the faucet
  45. faucet_signature_public: PublicKey,
  46. /// List of all our secret keys
  47. secrets: Vec<SecretKey>,
  48. }
  49. impl ProgramState for MemoryState {
  50. fn is_valid_cashier_public_key(&self, public: &PublicKey) -> bool {
  51. public == &self.cashier_signature_public
  52. }
  53. fn is_valid_faucet_public_key(&self, public: &PublicKey) -> bool {
  54. public == &self.faucet_signature_public
  55. }
  56. fn is_valid_merkle(&self, merkle_root: &MerkleNode) -> bool {
  57. self.merkle_roots.iter().any(|m| m == merkle_root)
  58. }
  59. fn nullifier_exists(&self, nullifier: &Nullifier) -> bool {
  60. self.nullifiers.iter().any(|n| n == nullifier)
  61. }
  62. fn mint_vk(&self) -> &VerifyingKey {
  63. &self.mint_vk
  64. }
  65. fn burn_vk(&self) -> &VerifyingKey {
  66. &self.burn_vk
  67. }
  68. }
  69. impl MemoryState {
  70. fn apply(&mut self, mut update: StateUpdate) {
  71. // Extend our list of nullifiers with the ones from the update
  72. self.nullifiers.append(&mut update.nullifiers);
  73. // Update merkle tree and witnesses
  74. for (coin, enc_note) in update.coins.into_iter().zip(update.enc_notes.into_iter()) {
  75. // Add the new coins to the Merkle tree
  76. let node = MerkleNode(coin.0);
  77. self.tree.append(&node);
  78. // Keep track of all Merkle roots that have existed
  79. self.merkle_roots.push(self.tree.root());
  80. // If it's our own coin, witness it and append to the vector.
  81. if let Some((note, secret)) = self.try_decrypt_note(enc_note) {
  82. let leaf_position = self.tree.witness().unwrap();
  83. let nullifier = Nullifier::new(secret, note.serial);
  84. let own_coin = OwnCoin { coin, note, secret, nullifier, leaf_position };
  85. self.own_coins.push(own_coin);
  86. }
  87. }
  88. }
  89. fn try_decrypt_note(&self, ciphertext: EncryptedNote) -> Option<(Note, SecretKey)> {
  90. // Loop through all our secret keys...
  91. for secret in &self.secrets {
  92. // .. attempt to decrypt the note ...
  93. if let Ok(note) = ciphertext.decrypt(secret) {
  94. // ... and return the decrypted note for this coin.
  95. return Some((note, *secret))
  96. }
  97. }
  98. // We weren't able to decrypt the note with any of our keys.
  99. None
  100. }
  101. }
  102. fn main() -> Result<()> {
  103. let cashier_signature_secret = SecretKey::random(&mut OsRng);
  104. let cashier_signature_public = PublicKey::from_secret(cashier_signature_secret);
  105. let faucet_signature_secret = SecretKey::random(&mut OsRng);
  106. let faucet_signature_public = PublicKey::from_secret(faucet_signature_secret);
  107. let keypair = Keypair::random(&mut OsRng);
  108. const K: u32 = 11;
  109. let mint_vk = VerifyingKey::build(K, &MintContract::default());
  110. let burn_vk = VerifyingKey::build(K, &BurnContract::default());
  111. let mut state = MemoryState {
  112. tree: BridgeTree::<MerkleNode, 32>::new(100),
  113. merkle_roots: vec![],
  114. nullifiers: vec![],
  115. own_coins: vec![],
  116. mint_vk,
  117. burn_vk,
  118. cashier_signature_public,
  119. faucet_signature_public,
  120. secrets: vec![keypair.secret],
  121. };
  122. let token_id =
  123. generate_id2("So11111111111111111111111111111111111111112", &NetworkName::Solana)?;
  124. let builder = TransactionBuilder {
  125. clear_inputs: vec![TransactionBuilderClearInputInfo {
  126. value: 110,
  127. token_id,
  128. signature_secret: cashier_signature_secret,
  129. }],
  130. inputs: vec![],
  131. outputs: vec![TransactionBuilderOutputInfo {
  132. value: 110,
  133. token_id,
  134. public: keypair.public,
  135. }],
  136. };
  137. let mint_pk = ProvingKey::build(K, &MintContract::default());
  138. let burn_pk = ProvingKey::build(K, &BurnContract::default());
  139. let tx = builder.build(&mint_pk, &burn_pk)?;
  140. tx.verify(&state.mint_vk, &state.burn_vk)?;
  141. let _note = tx.outputs[0].enc_note.decrypt(&keypair.secret)?;
  142. let update = state_transition(&state, tx)?;
  143. state.apply(update);
  144. // Now spend
  145. let owncoin = &state.own_coins[0];
  146. let note = owncoin.note;
  147. let leaf_position = owncoin.leaf_position;
  148. let merkle_path = state.tree.authentication_path(leaf_position).unwrap();
  149. let builder = TransactionBuilder {
  150. clear_inputs: vec![],
  151. inputs: vec![TransactionBuilderInputInfo {
  152. leaf_position,
  153. merkle_path,
  154. secret: keypair.secret,
  155. note,
  156. }],
  157. outputs: vec![TransactionBuilderOutputInfo {
  158. value: 110,
  159. token_id,
  160. public: keypair.public,
  161. }],
  162. };
  163. let tx = builder.build(&mint_pk, &burn_pk)?;
  164. let update = state_transition(&state, tx)?;
  165. state.apply(update);
  166. Ok(())
  167. }