verification.rs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2023 Dyne.org foundation
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU Affero General Public License as
  7. * published by the Free Software Foundation, either version 3 of the
  8. * License, or (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU Affero General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU Affero General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. */
  18. use std::{collections::HashMap, io::Cursor};
  19. use darkfi_sdk::{
  20. crypto::{PublicKey, CONSENSUS_CONTRACT_ID},
  21. pasta::pallas,
  22. };
  23. use darkfi_serial::{Decodable, Encodable, WriteExt};
  24. use log::{debug, error, warn};
  25. use crate::{
  26. blockchain::{BlockInfo, BlockchainOverlayPtr},
  27. error::TxVerifyFailed,
  28. runtime::vm_runtime::Runtime,
  29. tx::Transaction,
  30. util::time::TimeKeeper,
  31. zk::VerifyingKey,
  32. Error, Result,
  33. };
  34. /// Validate given genesis [`BlockInfo`], and apply it to the provided overlay
  35. pub async fn verify_genesis_block(
  36. overlay: &BlockchainOverlayPtr,
  37. time_keeper: &TimeKeeper,
  38. block: &BlockInfo,
  39. genesis_txs_total: u64,
  40. ) -> Result<()> {
  41. let block_hash = block.blockhash().to_string();
  42. debug!(target: "validator", "Validating genesis block {}", block_hash);
  43. // Check if block already exists
  44. if overlay.lock().unwrap().has_block(block)? {
  45. return Err(Error::BlockAlreadyExists(block_hash))
  46. }
  47. // Block slot must be the same as the time keeper verifying slot
  48. if block.header.slot != time_keeper.verifying_slot {
  49. return Err(Error::VerifyingSlotMissmatch())
  50. }
  51. // Check genesis slot exist
  52. if block.slots.len() != 1 {
  53. return Err(Error::BlockIsInvalid(block_hash))
  54. }
  55. // Retrieve genesis slot
  56. let genesis_slot = block.slots.last().unwrap();
  57. // Genesis block slot total token must correspond to the total
  58. // of all genesis transactions public inputs (genesis distribution).
  59. if genesis_slot.total_tokens != genesis_txs_total {
  60. return Err(Error::SlotIsInvalid(genesis_slot.id))
  61. }
  62. // Verify there is not reward
  63. if genesis_slot.reward != 0 {
  64. return Err(Error::SlotIsInvalid(genesis_slot.id))
  65. }
  66. // Genesis transaction must be the Transaction::default() one (empty)
  67. if block.producer.proposal != Transaction::default() {
  68. error!(target: "validator", "Genesis proposal transaction is not default one");
  69. return Err(TxVerifyFailed::ErroneousTxs(vec![block.producer.proposal.clone()]).into())
  70. }
  71. // Verify transactions
  72. let erroneous_txs = verify_transactions(overlay, time_keeper, &block.txs).await?;
  73. if !erroneous_txs.is_empty() {
  74. warn!(target: "validator", "Erroneous transactions found in set");
  75. overlay.lock().unwrap().overlay.lock().unwrap().purge_new_trees()?;
  76. return Err(TxVerifyFailed::ErroneousTxs(erroneous_txs).into())
  77. }
  78. // Insert block
  79. overlay.lock().unwrap().add_block(block)?;
  80. debug!(target: "validator", "Genesis block {} verified successfully", block_hash);
  81. Ok(())
  82. }
  83. /// Validate given [`BlockInfo`], and apply it to the provided overlay
  84. pub async fn verify_block(
  85. overlay: &BlockchainOverlayPtr,
  86. time_keeper: &TimeKeeper,
  87. block: &BlockInfo,
  88. previous: &BlockInfo,
  89. expected_reward: u64,
  90. testing_mode: bool,
  91. ) -> Result<()> {
  92. let block_hash = block.blockhash().to_string();
  93. debug!(target: "validator", "Validating block {}", block_hash);
  94. // Check if block already exists
  95. if overlay.lock().unwrap().has_block(block)? {
  96. return Err(Error::BlockAlreadyExists(block_hash))
  97. }
  98. // Block slot must be the same as the time keeper verifying slot
  99. if block.header.slot != time_keeper.verifying_slot {
  100. return Err(Error::VerifyingSlotMissmatch())
  101. }
  102. // Validate block, using its previous
  103. block.validate(previous, expected_reward)?;
  104. // Validate proposal transaction if not in testing mode
  105. if !testing_mode {
  106. verify_proposal_transaction(overlay, time_keeper, &block.producer.proposal).await?;
  107. }
  108. // Verify transactions
  109. let erroneous_txs = verify_transactions(overlay, time_keeper, &block.txs).await?;
  110. if !erroneous_txs.is_empty() {
  111. warn!(target: "validator", "Erroneous transactions found in set");
  112. overlay.lock().unwrap().overlay.lock().unwrap().purge_new_trees()?;
  113. return Err(TxVerifyFailed::ErroneousTxs(erroneous_txs).into())
  114. }
  115. // Insert block
  116. overlay.lock().unwrap().add_block(block)?;
  117. debug!(target: "validator", "Block {} verified successfully", block_hash);
  118. Ok(())
  119. }
  120. /// Validate WASM execution, signatures, and ZK proofs for a given proposal [`Transaction`],
  121. /// and apply it to the provided overlay.
  122. pub async fn verify_proposal_transaction(
  123. overlay: &BlockchainOverlayPtr,
  124. time_keeper: &TimeKeeper,
  125. tx: &Transaction,
  126. ) -> Result<()> {
  127. let tx_hash = tx.hash();
  128. debug!(target: "validator", "Validating proposal transaction {}", tx_hash);
  129. // Transaction must contain a single Consensus::Proposal (0x02) call
  130. if tx.calls.len() != 1 ||
  131. (tx.calls[0].contract_id != *CONSENSUS_CONTRACT_ID && tx.calls[0].data[0] != 0x02)
  132. {
  133. error!(target: "validator", "Proposal transaction is malformed");
  134. return Err(TxVerifyFailed::ErroneousTxs(vec![tx.clone()]).into())
  135. }
  136. // Map of ZK proof verifying keys for the current transaction batch
  137. let mut vks: HashMap<[u8; 32], HashMap<String, VerifyingKey>> = HashMap::new();
  138. // Initialize the map
  139. vks.insert(tx.calls[0].contract_id.to_bytes(), HashMap::new());
  140. // TODO: when fee is implemented, differentiate here since this transaction
  141. // won't have fee
  142. verify_transaction(overlay, time_keeper, tx, &mut vks).await?;
  143. debug!(target: "validator", "Proposal transaction {} verified successfully", tx_hash);
  144. Ok(())
  145. }
  146. /// Validate WASM execution, signatures, and ZK proofs for a given [`Transaction`],
  147. /// and apply it to the provided overlay.
  148. pub async fn verify_transaction(
  149. overlay: &BlockchainOverlayPtr,
  150. time_keeper: &TimeKeeper,
  151. tx: &Transaction,
  152. verifying_keys: &mut HashMap<[u8; 32], HashMap<String, VerifyingKey>>,
  153. ) -> Result<()> {
  154. let tx_hash = tx.hash();
  155. debug!(target: "validator", "Validating transaction {}", tx_hash);
  156. // Table of public inputs used for ZK proof verification
  157. let mut zkp_table = vec![];
  158. // Table of public keys used for signature verification
  159. let mut sig_table = vec![];
  160. // Iterate over all calls to get the metadata
  161. for (idx, call) in tx.calls.iter().enumerate() {
  162. debug!(target: "validator", "Executing contract call {}", idx);
  163. // Write the actual payload data
  164. let mut payload = vec![];
  165. payload.write_u32(idx as u32)?; // Call index
  166. tx.calls.encode(&mut payload)?; // Actual call data
  167. debug!(target: "validator", "Instantiating WASM runtime");
  168. let wasm = overlay.lock().unwrap().wasm_bincode.get(call.contract_id)?;
  169. let mut runtime =
  170. Runtime::new(&wasm, overlay.clone(), call.contract_id, time_keeper.clone())?;
  171. debug!(target: "validator", "Executing \"metadata\" call");
  172. let metadata = runtime.metadata(&payload)?;
  173. // Decode the metadata retrieved from the execution
  174. let mut decoder = Cursor::new(&metadata);
  175. // The tuple is (zkasa_ns, public_inputs)
  176. let zkp_pub: Vec<(String, Vec<pallas::Base>)> = Decodable::decode(&mut decoder)?;
  177. let sig_pub: Vec<PublicKey> = Decodable::decode(&mut decoder)?;
  178. // TODO: Make sure we've read all the bytes above.
  179. debug!(target: "validator", "Successfully executed \"metadata\" call");
  180. // Here we'll look up verifying keys and insert them into the per-contract map.
  181. debug!(target: "validator", "Performing VerifyingKey lookups from the sled db");
  182. for (zkas_ns, _) in &zkp_pub {
  183. let inner_vk_map = verifying_keys.get_mut(&call.contract_id.to_bytes()).unwrap();
  184. // TODO: This will be a problem in case of ::deploy, unless we force a different
  185. // namespace and disable updating existing circuit. Might be a smart idea to do
  186. // so in order to have to care less about being able to verify historical txs.
  187. if inner_vk_map.contains_key(zkas_ns.as_str()) {
  188. continue
  189. }
  190. let (_, vk) = overlay.lock().unwrap().contracts.get_zkas(&call.contract_id, zkas_ns)?;
  191. inner_vk_map.insert(zkas_ns.to_string(), vk);
  192. }
  193. zkp_table.push(zkp_pub);
  194. sig_table.push(sig_pub);
  195. // After getting the metadata, we run the "exec" function with the same runtime
  196. // and the same payload.
  197. debug!(target: "validator", "Executing \"exec\" call");
  198. let state_update = runtime.exec(&payload)?;
  199. debug!(target: "validator", "Successfully executed \"exec\" call");
  200. // If that was successful, we apply the state update in the ephemeral overlay.
  201. debug!(target: "validator", "Executing \"apply\" call");
  202. runtime.apply(&state_update)?;
  203. debug!(target: "validator", "Successfully executed \"apply\" call");
  204. // At this point we're done with the call and move on to the next one.
  205. }
  206. // When we're done looping and executing over the tx's contract calls, we now
  207. // move on with verification. First we verify the signatures as that's cheaper,
  208. // and then finally we verify the ZK proofs.
  209. debug!(target: "validator", "Verifying signatures for transaction {}", tx_hash);
  210. if sig_table.len() != tx.signatures.len() {
  211. error!(target: "validator", "Incorrect number of signatures in tx {}", tx_hash);
  212. return Err(TxVerifyFailed::MissingSignatures.into())
  213. }
  214. // TODO: Go through the ZK circuits that have to be verified and account for the opcodes.
  215. if let Err(e) = tx.verify_sigs(sig_table) {
  216. error!(target: "validator", "Signature verification for tx {} failed: {}", tx_hash, e);
  217. return Err(TxVerifyFailed::InvalidSignature.into())
  218. }
  219. debug!(target: "validator", "Signature verification successful");
  220. debug!(target: "validator", "Verifying ZK proofs for transaction {}", tx_hash);
  221. if let Err(e) = tx.verify_zkps(verifying_keys, zkp_table).await {
  222. error!(target: "validator", "ZK proof verification for tx {} failed: {}", tx_hash, e);
  223. return Err(TxVerifyFailed::InvalidZkProof.into())
  224. }
  225. debug!(target: "validator", "ZK proof verification successful");
  226. debug!(target: "validator", "Transaction {} verified successfully", tx_hash);
  227. Ok(())
  228. }
  229. /// Validate a set of [`Transaction`] in sequence and apply them if all are valid.
  230. /// In case any of the transactions fail, they will be returned to the caller.
  231. /// The function takes a boolean called `write` which tells it to actually write
  232. /// the state transitions to the database.
  233. pub async fn verify_transactions(
  234. overlay: &BlockchainOverlayPtr,
  235. time_keeper: &TimeKeeper,
  236. txs: &[Transaction],
  237. ) -> Result<Vec<Transaction>> {
  238. debug!(target: "validator", "Verifying {} transactions", txs.len());
  239. // Tracker for failed txs
  240. let mut erroneous_txs = vec![];
  241. // Map of ZK proof verifying keys for the current transaction batch
  242. let mut vks: HashMap<[u8; 32], HashMap<String, VerifyingKey>> = HashMap::new();
  243. // Initialize the map
  244. for tx in txs {
  245. for call in &tx.calls {
  246. vks.insert(call.contract_id.to_bytes(), HashMap::new());
  247. }
  248. }
  249. // Iterate over transactions and attempt to verify them
  250. for tx in txs {
  251. overlay.lock().unwrap().checkpoint();
  252. if let Err(e) = verify_transaction(overlay, time_keeper, tx, &mut vks).await {
  253. warn!(target: "validator", "Transaction verification failed: {}", e);
  254. erroneous_txs.push(tx.clone());
  255. // TODO: verify this works as expected
  256. overlay.lock().unwrap().revert_to_checkpoint()?;
  257. }
  258. }
  259. Ok(erroneous_txs)
  260. }