state.rs 9.4 KB

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