state.rs 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133
  1. use std::fmt;
  2. use log::debug;
  3. use crate::{
  4. crypto::{coin::Coin, note::EncryptedNote, nullifier::Nullifier, proof::VerifyingKey, schnorr},
  5. tx::Transaction,
  6. types::{DrkCoinBlind, DrkPublicKey, DrkSecretKey, DrkSerial, DrkTokenId, DrkValueBlind},
  7. };
  8. pub trait ProgramState {
  9. fn is_valid_cashier_public_key(&self, public: &schnorr::PublicKey) -> bool;
  10. // TODO: fn is_valid_merkle(&self, merkle: &MerkleNode) -> bool;
  11. fn nullifier_exists(&self, nullifier: &Nullifier) -> bool;
  12. fn mint_pvk(&self) -> &VerifyingKey;
  13. fn spend_pvk(&self) -> &VerifyingKey;
  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 (token commits)")
  57. }
  58. }
  59. }
  60. }
  61. pub fn state_transition<S: ProgramState>(
  62. state: &async_std::sync::MutexGuard<S>,
  63. tx: Transaction,
  64. ) -> VerifyResult<StateUpdate> {
  65. // Check deposits are legit
  66. debug!(target: "STATE TRANSITION", "iterate clear_inputs");
  67. for (i, input) in tx.clear_inputs.iter().enumerate() {
  68. // Check the public key in the clear inputs
  69. // It should be a valid public key for the cashier
  70. if !state.is_valid_cashier_public_key(&input.signature_public) {
  71. log::error!(target: "STATE TRANSITION", "Not valid cashier public key");
  72. return Err(VerifyFailed::InvalidCashierKey(i));
  73. }
  74. }
  75. debug!(target: "STATE TRANSITION", "iterate inputs");
  76. for (i, input) in tx.inputs.iter().enumerate() {
  77. // TODO: Check merkle roots
  78. //let merkle = &input.revealed.merkle_root;
  79. // Merkle is used to know whether this is a coin that existed
  80. // in a previous state.
  81. // if !state.is_valid_merkle(merkle) {
  82. // return Err(VerifyFailed::InvalidMerkle(i));
  83. // }
  84. // The nullifiers should not already exist
  85. // It is double spend protection.
  86. let nullifier = &input.revealed.nullifier;
  87. if state.nullifier_exists(nullifier) {
  88. return Err(VerifyFailed::DuplicateNullifier(i));
  89. }
  90. }
  91. debug!(target: "STATE TRANSITION", "Check the tx Verifies correctly");
  92. // Check the tx verifies correctly
  93. tx.verify(state.mint_pvk(), state.spend_pvk())?;
  94. let mut nullifiers = vec![];
  95. for input in tx.inputs {
  96. nullifiers.push(input.revealed.nullifier);
  97. }
  98. // Newly created coins for this tx
  99. let mut coins = vec![];
  100. let mut enc_notes = vec![];
  101. for output in tx.outputs {
  102. // Gather all the coins
  103. coins.push(Coin(output.revealed.coin.clone()));
  104. enc_notes.push(output.enc_note);
  105. }
  106. Ok(StateUpdate {
  107. nullifiers,
  108. coins,
  109. enc_notes,
  110. })
  111. }