state.rs 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  1. use incrementalmerkletree::{bridgetree::BridgeTree, Frontier, Tree};
  2. use log::debug;
  3. use crate::{
  4. blockchain::{rocks::columns, RocksColumn},
  5. crypto::{
  6. coin::Coin,
  7. keypair::{PublicKey, SecretKey},
  8. merkle_node::MerkleNode,
  9. note::{EncryptedNote, Note},
  10. nullifier::Nullifier,
  11. proof::VerifyingKey,
  12. OwnCoin,
  13. },
  14. tx::Transaction,
  15. wallet::walletdb::WalletPtr,
  16. Result,
  17. };
  18. pub trait ProgramState {
  19. fn is_valid_cashier_public_key(&self, public: &PublicKey) -> bool;
  20. fn is_valid_merkle(&self, merkle: &MerkleNode) -> bool;
  21. fn nullifier_exists(&self, nullifier: &Nullifier) -> bool;
  22. fn mint_vk(&self) -> &VerifyingKey;
  23. fn spend_vk(&self) -> &VerifyingKey;
  24. }
  25. pub struct StateUpdate {
  26. pub nullifiers: Vec<Nullifier>,
  27. pub coins: Vec<Coin>,
  28. pub enc_notes: Vec<EncryptedNote>,
  29. }
  30. pub type VerifyResult<T> = std::result::Result<T, VerifyFailed>;
  31. #[derive(Debug, Clone, thiserror::Error)]
  32. pub enum VerifyFailed {
  33. #[error("Invalid cashier public key for clear input {0}")]
  34. InvalidCashierKey(usize),
  35. #[error("Invalid merkle root for input {0}")]
  36. InvalidMerkle(usize),
  37. #[error("Duplicate nullifier for input {0}")]
  38. DuplicateNullifier(usize),
  39. #[error("Spend proof for input {0}")]
  40. SpendProof(usize),
  41. #[error("Mint proof for input {0}")]
  42. MintProof(usize),
  43. #[error("Invalid signature for clear input {0}")]
  44. ClearInputSignature(usize),
  45. #[error("Invalid signature for input {0}")]
  46. InputSignature(usize),
  47. #[error("Money in does not match money out (value commits)")]
  48. MissingFunds,
  49. #[error("Assets don't match some inputs or outputs (token commits)")]
  50. AssetMismatch,
  51. }
  52. pub fn state_transition<S: ProgramState>(state: &S, tx: Transaction) -> VerifyResult<StateUpdate> {
  53. // Check deposits are legit
  54. debug!(target: "STATE TRANSITION", "iterate clear_inputs");
  55. for (i, input) in tx.clear_inputs.iter().enumerate() {
  56. // Check the public key in the clear inputs
  57. // It should be a valid public key for the cashier
  58. if !state.is_valid_cashier_public_key(&input.signature_public) {
  59. log::error!(target: "STATE TRANSITION", "Invalid cashier public key");
  60. return Err(VerifyFailed::InvalidCashierKey(i))
  61. }
  62. }
  63. debug!(target: "STATE TRANSITION", "iterate inputs");
  64. for (i, input) in tx.inputs.iter().enumerate() {
  65. let merkle = &input.revealed.merkle_root;
  66. // Merkle is used to know whether this is a coin that existed
  67. // in a previous state.
  68. if !state.is_valid_merkle(merkle) {
  69. return Err(VerifyFailed::InvalidMerkle(i))
  70. }
  71. // The nullifiers should not already exist
  72. // It is double spend protection.
  73. let nullifier = &input.revealed.nullifier;
  74. if state.nullifier_exists(nullifier) {
  75. return Err(VerifyFailed::DuplicateNullifier(i))
  76. }
  77. }
  78. debug!(target: "STATE TRANSITION", "Check the tx verifies correctly");
  79. tx.verify(state.mint_vk(), state.spend_vk())?;
  80. debug!(target: "STATE TRANSITION", "Verified successfully");
  81. let mut nullifiers = vec![];
  82. for input in tx.inputs {
  83. nullifiers.push(input.revealed.nullifier);
  84. }
  85. // Newly created coins for this tx
  86. let mut coins = vec![];
  87. let mut enc_notes = vec![];
  88. for output in tx.outputs {
  89. // Gather all the coins
  90. coins.push(output.revealed.coin);
  91. enc_notes.push(output.enc_note);
  92. }
  93. Ok(StateUpdate { nullifiers, coins, enc_notes })
  94. }
  95. pub struct State {
  96. /// The entire Merkle tree state
  97. pub tree: BridgeTree<MerkleNode, 32>,
  98. /// List of all previous and the current merkle roots.
  99. /// This is the hashed value of all the children.
  100. pub merkle_roots: RocksColumn<columns::MerkleRoots>,
  101. /// Nullifiers prevent double-spending
  102. pub nullifiers: RocksColumn<columns::Nullifiers>,
  103. /// List of Cashier public keys
  104. pub public_keys: Vec<PublicKey>,
  105. /// Verifying key for the Mint contract
  106. pub mint_vk: VerifyingKey,
  107. /// Verifying key for the Spend contract
  108. pub spend_vk: VerifyingKey,
  109. }
  110. impl State {
  111. pub async fn apply(
  112. &mut self,
  113. update: StateUpdate,
  114. secret_keys: Vec<SecretKey>,
  115. notify: Option<async_channel::Sender<(PublicKey, u64)>>,
  116. wallet: WalletPtr,
  117. ) -> Result<()> {
  118. // Extend our list of nullifiers with the ones from the update.
  119. debug!("Extend nullifiers");
  120. for nullifier in update.nullifiers {
  121. self.nullifiers.put(nullifier, vec![] as Vec<u8>)?;
  122. }
  123. debug!("Update Merkle tree and witness");
  124. for (coin, enc_note) in update.coins.into_iter().zip(update.enc_notes.iter()) {
  125. // Add the new coins to the Merkle tree
  126. let node = MerkleNode(coin.0);
  127. self.tree.append(&node);
  128. // Keep track of all Merkle roots that have existed
  129. self.merkle_roots.put(self.tree.root(), vec![] as Vec<u8>)?;
  130. for secret in secret_keys.iter() {
  131. if let Some(note) = State::try_decrypt_note(enc_note, *secret) {
  132. // TODO: What to do with witnesses?
  133. self.tree.witness();
  134. let nullifier = Nullifier::new(*secret, note.serial);
  135. let own_coin = OwnCoin {
  136. coin,
  137. note,
  138. secret: *secret,
  139. // witness: witness.clone(),
  140. nullifier,
  141. };
  142. wallet.put_own_coins(own_coin).await?;
  143. let pubkey = PublicKey::from_secret(*secret);
  144. debug!("Received a coin: amount {}", note.value);
  145. debug!("Send a notification");
  146. if let Some(ch) = notify.clone() {
  147. ch.send((pubkey, note.value)).await?;
  148. }
  149. }
  150. }
  151. }
  152. debug!("apply() exiting successfully");
  153. Ok(())
  154. }
  155. fn try_decrypt_note(ciphertext: &EncryptedNote, secret: SecretKey) -> Option<Note> {
  156. match ciphertext.decrypt(&secret) {
  157. Ok(note) => Some(note),
  158. Err(_) => None,
  159. }
  160. }
  161. }
  162. impl ProgramState for State {
  163. fn is_valid_cashier_public_key(&self, public: &PublicKey) -> bool {
  164. debug!("Check if it is a valid cashier public key");
  165. self.public_keys.contains(public)
  166. }
  167. fn is_valid_merkle(&self, merkle_root: &MerkleNode) -> bool {
  168. debug!("Check if it is valid merkle");
  169. if let Ok(mr) = self.merkle_roots.key_exist(merkle_root.clone()) {
  170. return mr
  171. }
  172. false
  173. }
  174. fn nullifier_exists(&self, nullifier: &Nullifier) -> bool {
  175. debug!("Check if nullifier exists");
  176. if let Ok(nl) = self.nullifiers.key_exist(nullifier.to_bytes()) {
  177. return nl
  178. }
  179. false
  180. }
  181. fn mint_vk(&self) -> &VerifyingKey {
  182. &self.mint_vk
  183. }
  184. fn spend_vk(&self) -> &VerifyingKey {
  185. &self.spend_vk
  186. }
  187. }