state.rs 7.2 KB

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