validate.rs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  1. use std::any::{Any, TypeId};
  2. use darkfi_sdk::crypto::{MerkleNode, Nullifier};
  3. use darkfi_serial::{Encodable, SerialDecodable, SerialEncodable};
  4. use incrementalmerkletree::Tree;
  5. use log::{debug, error};
  6. use pasta_curves::{group::Group, pallas};
  7. use darkfi::{
  8. crypto::{
  9. coin::Coin,
  10. keypair::PublicKey,
  11. types::{DrkCircuitField, DrkTokenId, DrkValueBlind, DrkValueCommit},
  12. util::{pedersen_commitment_base, pedersen_commitment_u64},
  13. BurnRevealedValues, MintRevealedValues,
  14. },
  15. Error as DarkFiError,
  16. };
  17. use crate::{
  18. contract::{
  19. dao_contract,
  20. money_contract::{state::State, CONTRACT_ID},
  21. },
  22. note::EncryptedNote2,
  23. util::{CallDataBase, StateRegistry, Transaction, UpdateBase},
  24. };
  25. const TARGET: &str = "money_contract::transfer::validate::state_transition()";
  26. /// A struct representing a state update.
  27. /// This gets applied on top of an existing state.
  28. #[derive(Clone)]
  29. pub struct Update {
  30. /// All nullifiers in a transaction
  31. pub nullifiers: Vec<Nullifier>,
  32. /// All coins in a transaction
  33. pub coins: Vec<Coin>,
  34. /// All encrypted notes in a transaction
  35. pub enc_notes: Vec<EncryptedNote2>,
  36. }
  37. impl UpdateBase for Update {
  38. fn apply(mut self: Box<Self>, states: &mut StateRegistry) {
  39. let state = states.lookup_mut::<State>(*CONTRACT_ID).unwrap();
  40. // Extend our list of nullifiers with the ones from the update
  41. state.nullifiers.append(&mut self.nullifiers);
  42. //// Update merkle tree and witnesses
  43. for (coin, enc_note) in self.coins.into_iter().zip(self.enc_notes.into_iter()) {
  44. // Add the new coins to the Merkle tree
  45. let node = MerkleNode::from(coin.0);
  46. state.tree.append(&node);
  47. // Keep track of all Merkle roots that have existed
  48. state.merkle_roots.push(state.tree.root(0).unwrap());
  49. state.wallet_cache.try_decrypt_note(coin, enc_note, &mut state.tree);
  50. }
  51. }
  52. }
  53. pub fn state_transition(
  54. states: &StateRegistry,
  55. func_call_index: usize,
  56. parent_tx: &Transaction,
  57. ) -> Result<Box<dyn UpdateBase + Send>> {
  58. // Check the public keys in the clear inputs to see if they're coming
  59. // from a valid cashier or faucet.
  60. debug!(target: TARGET, "Iterate clear_inputs");
  61. let func_call = &parent_tx.func_calls[func_call_index];
  62. let call_data = func_call.call_data.as_any();
  63. assert_eq!((*call_data).type_id(), TypeId::of::<CallData>());
  64. let call_data = call_data.downcast_ref::<CallData>();
  65. // This will be inside wasm so unwrap is fine.
  66. let call_data = call_data.unwrap();
  67. let state = states.lookup::<State>(*CONTRACT_ID).expect("Return type is not of type State");
  68. // Code goes here
  69. for (i, input) in call_data.clear_inputs.iter().enumerate() {
  70. let pk = &input.signature_public;
  71. // TODO: this depends on the token ID
  72. if !state.is_valid_cashier_public_key(pk) && !state.is_valid_faucet_public_key(pk) {
  73. error!(target: TARGET, "Invalid pubkey for clear input: {:?}", pk);
  74. return Err(Error::VerifyFailed(VerifyFailed::InvalidCashierOrFaucetKey(i)))
  75. }
  76. }
  77. // Nullifiers in the transaction
  78. let mut nullifiers = Vec::with_capacity(call_data.inputs.len());
  79. debug!(target: TARGET, "Iterate inputs");
  80. for (i, input) in call_data.inputs.iter().enumerate() {
  81. let merkle = &input.revealed.merkle_root;
  82. // The Merkle root is used to know whether this is a coin that
  83. // existed in a previous state.
  84. if !state.is_valid_merkle(merkle) {
  85. error!(target: TARGET, "Invalid Merkle root (input {})", i);
  86. debug!(target: TARGET, "root: {:?}", merkle);
  87. return Err(Error::VerifyFailed(VerifyFailed::InvalidMerkle(i)))
  88. }
  89. // Check the spend_hook is satisfied
  90. // The spend_hook says a coin must invoke another contract function when being spent
  91. // If the value is set, then we check the function call exists
  92. let spend_hook = &input.revealed.spend_hook;
  93. if spend_hook != &pallas::Base::from(0) {
  94. // spend_hook is set so we enforce the rules
  95. let mut is_found = false;
  96. for (i, func_call) in parent_tx.func_calls.iter().enumerate() {
  97. // Skip current func_call
  98. if i == func_call_index {
  99. continue
  100. }
  101. // TODO: we need to change these to pallas::Base
  102. // temporary workaround for now
  103. // if func_call.func_id == spend_hook ...
  104. if func_call.func_id == *dao_contract::exec::FUNC_ID {
  105. is_found = true;
  106. break
  107. }
  108. }
  109. if !is_found {
  110. return Err(Error::VerifyFailed(VerifyFailed::SpendHookNotSatisfied))
  111. }
  112. }
  113. // The nullifiers should not already exist.
  114. // It is the double-spend protection.
  115. let nullifier = &input.revealed.nullifier;
  116. if state.nullifier_exists(nullifier) ||
  117. (1..nullifiers.len()).any(|i| nullifiers[i..].contains(&nullifiers[i - 1]))
  118. {
  119. error!(target: TARGET, "Duplicate nullifier found (input {})", i);
  120. debug!(target: TARGET, "nullifier: {:?}", nullifier);
  121. return Err(Error::VerifyFailed(VerifyFailed::NullifierExists(i)))
  122. }
  123. nullifiers.push(input.revealed.nullifier);
  124. }
  125. debug!(target: TARGET, "Verifying call data");
  126. match call_data.verify() {
  127. Ok(()) => {
  128. debug!(target: TARGET, "Verified successfully")
  129. }
  130. Err(e) => {
  131. error!(target: TARGET, "Failed verifying zk proofs: {}", e);
  132. return Err(Error::VerifyFailed(VerifyFailed::ProofVerifyFailed(e.to_string())))
  133. }
  134. }
  135. // Newly created coins for this transaction
  136. let mut coins = Vec::with_capacity(call_data.outputs.len());
  137. let mut enc_notes = Vec::with_capacity(call_data.outputs.len());
  138. for output in &call_data.outputs {
  139. // Gather all the coins
  140. coins.push(output.revealed.coin);
  141. enc_notes.push(output.enc_note.clone());
  142. }
  143. Ok(Box::new(Update { nullifiers, coins, enc_notes }))
  144. }
  145. /// A DarkFi transaction
  146. #[derive(Debug, Clone, PartialEq, Eq, SerialEncodable, SerialDecodable)]
  147. pub struct CallData {
  148. /// Clear inputs
  149. pub clear_inputs: Vec<ClearInput>,
  150. /// Anonymous inputs
  151. pub inputs: Vec<Input>,
  152. /// Anonymous outputs
  153. pub outputs: Vec<Output>,
  154. }
  155. impl CallDataBase for CallData {
  156. fn zk_public_values(&self) -> Vec<(String, Vec<DrkCircuitField>)> {
  157. let mut public_values = Vec::new();
  158. for input in &self.inputs {
  159. public_values.push(("money-transfer-burn".to_string(), input.revealed.make_outputs()));
  160. }
  161. for output in &self.outputs {
  162. public_values.push(("money-transfer-mint".to_string(), output.revealed.make_outputs()));
  163. }
  164. public_values
  165. }
  166. fn as_any(&self) -> &dyn Any {
  167. self
  168. }
  169. fn signature_public_keys(&self) -> Vec<PublicKey> {
  170. let mut signature_public_keys = Vec::new();
  171. for input in self.clear_inputs.clone() {
  172. signature_public_keys.push(input.signature_public);
  173. }
  174. signature_public_keys
  175. }
  176. fn encode_bytes(
  177. &self,
  178. mut writer: &mut dyn std::io::Write,
  179. ) -> core::result::Result<usize, std::io::Error> {
  180. self.encode(&mut writer)
  181. }
  182. }
  183. impl CallData {
  184. /// Verify the transaction
  185. pub fn verify(&self) -> VerifyResult<()> {
  186. // must have minimum 1 clear or anon input, and 1 output
  187. if self.clear_inputs.len() + self.inputs.len() == 0 {
  188. error!("tx::verify(): Missing inputs");
  189. return Err(VerifyFailed::LackingInputs)
  190. }
  191. if self.outputs.is_empty() {
  192. error!("tx::verify(): Missing outputs");
  193. return Err(VerifyFailed::LackingOutputs)
  194. }
  195. // Accumulator for the value commitments
  196. let mut valcom_total = DrkValueCommit::identity();
  197. // Add values from the clear inputs
  198. for input in &self.clear_inputs {
  199. valcom_total += pedersen_commitment_u64(input.value, input.value_blind);
  200. }
  201. // Add values from the inputs
  202. for input in &self.inputs {
  203. valcom_total += &input.revealed.value_commit;
  204. }
  205. // Subtract values from the outputs
  206. for output in &self.outputs {
  207. valcom_total -= &output.revealed.value_commit;
  208. }
  209. // If the accumulator is not back in its initial state,
  210. // there's a value mismatch.
  211. if valcom_total != DrkValueCommit::identity() {
  212. error!("tx::verify(): Missing funds");
  213. return Err(VerifyFailed::MissingFunds)
  214. }
  215. // Verify that the token commitments match
  216. if !self.verify_token_commitments() {
  217. error!("tx::verify(): Token ID mismatch");
  218. return Err(VerifyFailed::TokenMismatch)
  219. }
  220. Ok(())
  221. }
  222. fn verify_token_commitments(&self) -> bool {
  223. assert_ne!(self.outputs.len(), 0);
  224. let token_commit_value = self.outputs[0].revealed.token_commit;
  225. let mut failed =
  226. self.inputs.iter().any(|input| input.revealed.token_commit != token_commit_value);
  227. failed = failed ||
  228. self.outputs.iter().any(|output| output.revealed.token_commit != token_commit_value);
  229. failed = failed ||
  230. self.clear_inputs.iter().any(|input| {
  231. pedersen_commitment_base(input.token_id, input.token_blind) != token_commit_value
  232. });
  233. !failed
  234. }
  235. }
  236. /// A transaction's clear input
  237. #[derive(Debug, Clone, PartialEq, Eq, SerialEncodable, SerialDecodable)]
  238. pub struct ClearInput {
  239. /// Input's value (amount)
  240. pub value: u64,
  241. /// Input's token ID
  242. pub token_id: DrkTokenId,
  243. /// Blinding factor for `value`
  244. pub value_blind: DrkValueBlind,
  245. /// Blinding factor for `token_id`
  246. pub token_blind: DrkValueBlind,
  247. /// Public key for the signature
  248. pub signature_public: PublicKey,
  249. }
  250. /// A transaction's anonymous input
  251. #[derive(Debug, Clone, PartialEq, Eq, SerialEncodable, SerialDecodable)]
  252. pub struct Input {
  253. /// Public inputs for the zero-knowledge proof
  254. pub revealed: BurnRevealedValues,
  255. }
  256. /// A transaction's anonymous output
  257. #[derive(Debug, Clone, PartialEq, Eq, SerialEncodable, SerialDecodable)]
  258. pub struct Output {
  259. /// Public inputs for the zero-knowledge proof
  260. pub revealed: MintRevealedValues,
  261. /// The encrypted note
  262. pub enc_note: EncryptedNote2,
  263. }
  264. #[derive(Debug, Clone, thiserror::Error)]
  265. pub enum Error {
  266. #[error(transparent)]
  267. VerifyFailed(#[from] VerifyFailed),
  268. #[error("DarkFi error: {0}")]
  269. DarkFiError(String),
  270. }
  271. /// Transaction verification errors
  272. #[derive(Debug, Clone, thiserror::Error)]
  273. pub enum VerifyFailed {
  274. #[error("Transaction has no inputs")]
  275. LackingInputs,
  276. #[error("Transaction has no outputs")]
  277. LackingOutputs,
  278. #[error("Invalid cashier/faucet public key for clear input {0}")]
  279. InvalidCashierOrFaucetKey(usize),
  280. #[error("Invalid Merkle root for input {0}")]
  281. InvalidMerkle(usize),
  282. #[error("Spend hook invoking function is not attached")]
  283. SpendHookNotSatisfied,
  284. #[error("Nullifier already exists for input {0}")]
  285. NullifierExists(usize),
  286. #[error("Token commitments in inputs or outputs to not match")]
  287. TokenMismatch,
  288. #[error("Money in does not match money out (value commitments)")]
  289. MissingFunds,
  290. #[error("Failed verifying zk proofs: {0}")]
  291. ProofVerifyFailed(String),
  292. #[error("Internal error: {0}")]
  293. InternalError(String),
  294. #[error("DarkFi error: {0}")]
  295. DarkFiError(String),
  296. }
  297. type Result<T> = std::result::Result<T, Error>;
  298. impl From<Error> for VerifyFailed {
  299. fn from(err: Error) -> Self {
  300. Self::InternalError(err.to_string())
  301. }
  302. }
  303. impl From<DarkFiError> for VerifyFailed {
  304. fn from(err: DarkFiError) -> Self {
  305. Self::DarkFiError(err.to_string())
  306. }
  307. }
  308. impl From<DarkFiError> for Error {
  309. fn from(err: DarkFiError) -> Self {
  310. Self::DarkFiError(err.to_string())
  311. }
  312. }
  313. /// Result type used in transaction verifications
  314. pub type VerifyResult<T> = std::result::Result<T, VerifyFailed>;