state.rs 7.1 KB

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