state.rs 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  1. use incrementalmerkletree::{bridgetree::BridgeTree, Frontier, Tree};
  2. use lazy_init::Lazy;
  3. use log::{debug, error};
  4. use crate::{
  5. blockchain::{nfstore::NullifierStore, rootstore::RootStore},
  6. crypto::{
  7. coin::Coin,
  8. keypair::{PublicKey, SecretKey},
  9. merkle_node::MerkleNode,
  10. note::{EncryptedNote, Note},
  11. nullifier::Nullifier,
  12. proof::VerifyingKey,
  13. OwnCoin,
  14. },
  15. tx::Transaction,
  16. wallet::walletdb::WalletPtr,
  17. zk::circuit::{BurnContract, MintContract},
  18. Result, VerifyFailed, VerifyResult,
  19. };
  20. /// Trait implementing the state functions used by the state transition.
  21. pub trait ProgramState {
  22. /// Check if the public key is coming from a trusted cashier
  23. fn is_valid_cashier_public_key(&self, public: &PublicKey) -> bool;
  24. /// Check if the public key is coming from a trusted faucet
  25. fn is_valid_faucet_public_key(&self, public: &PublicKey) -> bool;
  26. /// Check if a merkle root is valid in this context
  27. fn is_valid_merkle(&self, merkle: &MerkleNode) -> bool;
  28. /// Check if the nullifier has been seen already
  29. fn nullifier_exists(&self, nullifier: &Nullifier) -> bool;
  30. /// Mint proof verification key
  31. fn mint_vk(&self) -> &VerifyingKey;
  32. /// Burn proof verification key
  33. fn burn_vk(&self) -> &VerifyingKey;
  34. }
  35. /// A struct representing a state update.
  36. /// This gets applied on top of an existing state.
  37. #[derive(Clone)]
  38. pub struct StateUpdate {
  39. /// All nullifiers in a transaction
  40. pub nullifiers: Vec<Nullifier>,
  41. /// All coins in a transaction
  42. pub coins: Vec<Coin>,
  43. /// All encrypted notes in a transaction
  44. pub enc_notes: Vec<EncryptedNote>,
  45. }
  46. /// State transition function
  47. pub fn state_transition<S: ProgramState>(state: &S, tx: Transaction) -> VerifyResult<StateUpdate> {
  48. // Check the public keys in the clear inputs to see if they're coming
  49. // from a valid cashier or faucet.
  50. debug!(target: "state_transition", "Iterate clear_inputs");
  51. for (i, input) in tx.clear_inputs.iter().enumerate() {
  52. let pk = &input.signature_public;
  53. if !state.is_valid_cashier_public_key(pk) && !state.is_valid_faucet_public_key(pk) {
  54. error!(target: "state_transition", "Invalid pubkey for clear input: {:?}", pk);
  55. return Err(VerifyFailed::InvalidCashierOrFaucetKey(i))
  56. }
  57. }
  58. debug!(target: "state_transition", "Iterate inputs");
  59. for (i, input) in tx.inputs.iter().enumerate() {
  60. let merkle = &input.revealed.merkle_root;
  61. // The Merkle root is used to know whether this is a coin that
  62. // existed in a previous state.
  63. if !state.is_valid_merkle(merkle) {
  64. error!(target: "state_transition", "Invalid Merkle root (input {})", i);
  65. debug!(target: "state_transition", "root: {:?}", merkle);
  66. return Err(VerifyFailed::InvalidMerkle(i))
  67. }
  68. // The nullifiers should not already exist.
  69. // It is the double-spend protection.
  70. let nullifier = &input.revealed.nullifier;
  71. if state.nullifier_exists(nullifier) {
  72. error!(target: "state_transition", "Duplicate nullifier found (input {})", i);
  73. debug!(target: "state_transition", "nullifier: {:?}", nullifier);
  74. return Err(VerifyFailed::NullifierExists(i))
  75. }
  76. }
  77. debug!(target: "state_transition", "Verifying zk proofs");
  78. match tx.verify(state.mint_vk(), state.burn_vk()) {
  79. Ok(()) => debug!(target: "state_transition", "Verified successfully"),
  80. Err(e) => {
  81. error!(target: "state_transition", "Failed verifying zk proofs: {}", e);
  82. return Err(VerifyFailed::ProofVerifyFailed(e.to_string()))
  83. }
  84. }
  85. // Gather all the nullifiers
  86. let mut nullifiers = Vec::with_capacity(tx.inputs.len());
  87. for input in tx.inputs {
  88. nullifiers.push(input.revealed.nullifier);
  89. }
  90. // Newly created coins for this transaction
  91. let mut coins = Vec::with_capacity(tx.outputs.len());
  92. let mut enc_notes = Vec::with_capacity(tx.outputs.len());
  93. for output in tx.outputs {
  94. // Gather all the coins
  95. coins.push(output.revealed.coin);
  96. enc_notes.push(output.enc_note);
  97. }
  98. Ok(StateUpdate { nullifiers, coins, enc_notes })
  99. }
  100. /// Struct holding the state which we can apply a [`StateUpdate`] onto.
  101. #[derive(Clone)]
  102. pub struct State {
  103. /// The entire Merkle tree state
  104. pub tree: BridgeTree<MerkleNode, 32>,
  105. /// List of all previous and the current merkle roots.
  106. /// This is the hashed value of all the children.
  107. pub merkle_roots: RootStore,
  108. /// Nullifiers prevent double-spending
  109. pub nullifiers: NullifierStore,
  110. /// List of Cashier public keys
  111. pub cashier_pubkeys: Vec<PublicKey>,
  112. /// List of Faucet public keys
  113. pub faucet_pubkeys: Vec<PublicKey>,
  114. /// Verifying key for the Mint ZK proof
  115. pub mint_vk: Lazy<VerifyingKey>,
  116. /// Verifying key for the Burn ZK proof
  117. pub burn_vk: Lazy<VerifyingKey>,
  118. }
  119. impl State {
  120. /// Apply a [`StateUpdate`] to some state.
  121. pub async fn apply(
  122. &mut self,
  123. update: StateUpdate,
  124. secret_keys: Vec<SecretKey>,
  125. notify: Option<async_channel::Sender<(PublicKey, u64)>>,
  126. wallet: WalletPtr,
  127. ) -> Result<()> {
  128. debug!(target: "state_apply", "Extend nullifier set");
  129. self.nullifiers.insert(&update.nullifiers)?;
  130. debug!(target: "state_apply", "Update Merkle tree and witnesses");
  131. for (coin, enc_note) in update.coins.into_iter().zip(update.enc_notes.iter()) {
  132. // Add the new coins to the Merkle tree
  133. let node = MerkleNode(coin.0);
  134. self.tree.append(&node);
  135. // Keep track of all Merkle roots that have existed
  136. self.merkle_roots.insert(&[self.tree.root()])?;
  137. for secret in secret_keys.iter() {
  138. if let Some(note) = State::try_decrypt_note(enc_note, *secret) {
  139. debug!(target: "state_apply", "Received a coin: amount {}", note.value);
  140. let leaf_position = self.tree.witness().unwrap();
  141. let nullifier = Nullifier::new(*secret, note.serial);
  142. let own_coin =
  143. OwnCoin { coin, note, secret: *secret, nullifier, leaf_position };
  144. wallet.put_own_coin(own_coin).await?;
  145. let pubkey = PublicKey::from_secret(*secret);
  146. debug!(target: "state_apply", "Send a notification");
  147. if let Some(ch) = notify.clone() {
  148. ch.send((pubkey, note.value)).await?;
  149. }
  150. }
  151. }
  152. // Save updated merkle tree into the wallet.
  153. wallet.put_tree(&self.tree).await?;
  154. }
  155. debug!(target: "state_apply", "Finished apply() successfully.");
  156. Ok(())
  157. }
  158. fn try_decrypt_note(ciphertext: &EncryptedNote, secret: SecretKey) -> Option<Note> {
  159. match ciphertext.decrypt(&secret) {
  160. Ok(note) => Some(note),
  161. Err(_) => None,
  162. }
  163. }
  164. }
  165. impl ProgramState for State {
  166. fn is_valid_cashier_public_key(&self, public: &PublicKey) -> bool {
  167. debug!(target: "state_transition", "Checking if pubkey is a valid cashier");
  168. self.cashier_pubkeys.contains(public)
  169. }
  170. fn is_valid_faucet_public_key(&self, public: &PublicKey) -> bool {
  171. debug!(target: "state_transition", "Checking if pubkey is a valid faucet");
  172. self.faucet_pubkeys.contains(public)
  173. }
  174. fn is_valid_merkle(&self, merkle_root: &MerkleNode) -> bool {
  175. debug!(target: "state_transition", "Checking if Merkle root is valid");
  176. if let Ok(mr) = self.merkle_roots.contains(merkle_root) {
  177. return mr
  178. }
  179. // FIXME: An error here means a db issue
  180. false
  181. }
  182. fn nullifier_exists(&self, nullifier: &Nullifier) -> bool {
  183. debug!(target: "state_transition", "Checking if Nullifier exists");
  184. if let Ok(nf) = self.nullifiers.contains(nullifier) {
  185. return nf
  186. }
  187. // FIXME: An error here means a db issue
  188. false
  189. }
  190. fn mint_vk(&self) -> &VerifyingKey {
  191. self.mint_vk.get_or_create(build_mint_vk)
  192. }
  193. fn burn_vk(&self) -> &VerifyingKey {
  194. self.burn_vk.get_or_create(build_burn_vk)
  195. }
  196. }
  197. fn build_mint_vk() -> VerifyingKey {
  198. VerifyingKey::build(11, &MintContract::default())
  199. }
  200. fn build_burn_vk() -> VerifyingKey {
  201. VerifyingKey::build(11, &BurnContract::default())
  202. }