state.rs 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  1. use bellman::groth16;
  2. use bls12_381::Bls12;
  3. use std::fmt;
  4. use crate::{
  5. crypto::{coin::Coin, merkle_node::MerkleNode, note::EncryptedNote, nullifier::Nullifier},
  6. tx,
  7. };
  8. pub trait ProgramState {
  9. fn is_valid_cashier_public_key(&self, public: &jubjub::SubgroupPoint) -> bool;
  10. fn is_valid_merkle(&self, merkle: &MerkleNode) -> bool;
  11. fn nullifier_exists(&self, nullifier: &Nullifier) -> bool;
  12. fn mint_pvk(&self) -> &groth16::PreparedVerifyingKey<Bls12>;
  13. fn spend_pvk(&self) -> &groth16::PreparedVerifyingKey<Bls12>;
  14. }
  15. pub struct StateUpdate {
  16. pub nullifiers: Vec<Nullifier>,
  17. pub coins: Vec<Coin>,
  18. pub enc_notes: Vec<EncryptedNote>,
  19. }
  20. pub type VerifyResult<T> = std::result::Result<T, VerifyFailed>;
  21. #[derive(Debug)]
  22. pub enum VerifyFailed {
  23. InvalidCashierKey(usize),
  24. InvalidMerkle(usize),
  25. DuplicateNullifier(usize),
  26. SpendProof(usize),
  27. MintProof(usize),
  28. ClearInputSignature(usize),
  29. InputSignature(usize),
  30. MissingFunds,
  31. AssetMismatch,
  32. }
  33. impl std::error::Error for VerifyFailed {}
  34. impl fmt::Display for VerifyFailed {
  35. fn fmt(&self, f: &mut fmt::Formatter) -> std::fmt::Result {
  36. match *self {
  37. VerifyFailed::InvalidCashierKey(i) => {
  38. write!(f, "Invalid cashier public key for clear input {}", i)
  39. }
  40. VerifyFailed::InvalidMerkle(i) => {
  41. write!(f, "Invalid merkle root for input {}", i)
  42. }
  43. VerifyFailed::DuplicateNullifier(i) => {
  44. write!(f, "Duplicate nullifier for input {}", i)
  45. }
  46. VerifyFailed::SpendProof(i) => write!(f, "Spend proof for input {}", i),
  47. VerifyFailed::MintProof(i) => write!(f, "Mint proof for input {}", i),
  48. VerifyFailed::ClearInputSignature(i) => {
  49. write!(f, "Invalid signature for clear input {}", i)
  50. }
  51. VerifyFailed::InputSignature(i) => write!(f, "Invalid signature for input {}", i),
  52. VerifyFailed::MissingFunds => {
  53. f.write_str("Money in does not match money out (value commits)")
  54. }
  55. VerifyFailed::AssetMismatch => {
  56. f.write_str("Assets don't match some inputs or outputs (asset commits)")
  57. }
  58. }
  59. }
  60. }
  61. pub fn state_transition<S: ProgramState>(
  62. state: &async_std::sync::MutexGuard<S>,
  63. tx: tx::Transaction,
  64. ) -> VerifyResult<StateUpdate> {
  65. // Check deposits are legit
  66. for (i, input) in tx.clear_inputs.iter().enumerate() {
  67. // Check the public key in the clear inputs
  68. // It should be a valid public key for the cashier
  69. if !state.is_valid_cashier_public_key(&input.signature_public) {
  70. return Err(VerifyFailed::InvalidCashierKey(i));
  71. }
  72. }
  73. for (i, input) in tx.inputs.iter().enumerate() {
  74. // Check merkle roots
  75. let merkle = &input.revealed.merkle_root;
  76. // Merkle is used to know whether this is a coin that existed
  77. // in a previous state.
  78. if !state.is_valid_merkle(merkle) {
  79. return Err(VerifyFailed::InvalidMerkle(i));
  80. }
  81. // The nullifiers should not already exist
  82. // It is double spend protection.
  83. let nullifier = &input.revealed.nullifier;
  84. if state.nullifier_exists(nullifier) {
  85. return Err(VerifyFailed::DuplicateNullifier(i));
  86. }
  87. }
  88. // Check the tx verifies correctly
  89. tx.verify(state.mint_pvk(), state.spend_pvk())?;
  90. let mut nullifiers = vec![];
  91. for input in tx.inputs {
  92. nullifiers.push(input.revealed.nullifier);
  93. }
  94. // Newly created coins for this tx
  95. let mut coins = vec![];
  96. let mut enc_notes = vec![];
  97. for output in tx.outputs {
  98. // Gather all the coins
  99. coins.push(Coin::new(output.revealed.coin));
  100. enc_notes.push(output.enc_note);
  101. }
  102. Ok(StateUpdate {
  103. nullifiers,
  104. coins,
  105. enc_notes,
  106. })
  107. }