tx.rs 5.4 KB

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