verification.rs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658
  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. blockchain::{block_version, expected_reward},
  21. crypto::{schnorr::SchnorrPublic, PublicKey, CONSENSUS_CONTRACT_ID, MONEY_CONTRACT_ID},
  22. pasta::pallas,
  23. };
  24. use darkfi_serial::{Decodable, Encodable, WriteExt};
  25. use log::{debug, error, warn};
  26. use crate::{
  27. blockchain::{BlockInfo, BlockchainOverlayPtr},
  28. error::TxVerifyFailed,
  29. runtime::vm_runtime::Runtime,
  30. tx::Transaction,
  31. util::time::TimeKeeper,
  32. validator::{
  33. consensus::{Consensus, Fork, Proposal, TXS_CAP},
  34. pow::PoWModule,
  35. validation::validate_block,
  36. },
  37. zk::VerifyingKey,
  38. Error, Result,
  39. };
  40. /// Verify given genesis [`BlockInfo`], and apply it to the provided overlay
  41. pub async fn verify_genesis_block(
  42. overlay: &BlockchainOverlayPtr,
  43. time_keeper: &TimeKeeper,
  44. block: &BlockInfo,
  45. genesis_txs_total: u64,
  46. ) -> Result<()> {
  47. let block_hash = block.hash()?.to_string();
  48. debug!(target: "validator::verification::verify_genesis_block", "Validating genesis block {}", block_hash);
  49. // Check if block already exists
  50. if overlay.lock().unwrap().has_block(block)? {
  51. return Err(Error::BlockAlreadyExists(block_hash))
  52. }
  53. // Block height must be 0
  54. if block.header.height != 0 {
  55. return Err(Error::BlockIsInvalid(block_hash))
  56. }
  57. // Block height must be the same as the time keeper verifying slot
  58. if block.header.height != time_keeper.verifying_slot {
  59. return Err(Error::VerifyingSlotMissmatch())
  60. }
  61. // Check genesis slot exist
  62. if block.slots.len() != 1 {
  63. return Err(Error::BlockIsInvalid(block_hash))
  64. }
  65. // Retrieve genesis slot
  66. let genesis_slot = block.slots.last().unwrap();
  67. // Genesis block slot total token must correspond to the total
  68. // of all genesis transactions public inputs (genesis distribution).
  69. if genesis_slot.total_tokens != genesis_txs_total {
  70. return Err(Error::SlotIsInvalid(genesis_slot.id))
  71. }
  72. // Verify there is no reward
  73. if genesis_slot.reward != 0 {
  74. return Err(Error::SlotIsInvalid(genesis_slot.id))
  75. }
  76. // Verify transactions vector contains at least one(producers) transaction
  77. if block.txs.is_empty() {
  78. return Err(Error::BlockContainsNoTransactions(block_hash))
  79. }
  80. // Insert genesis slot so transactions can be validated against.
  81. // Since an overlay is used, original database is not affected.
  82. overlay.lock().unwrap().slots.insert(&[genesis_slot.clone()])?;
  83. // Genesis transaction must be the Transaction::default() one(empty)
  84. let tx = block.txs.last().unwrap();
  85. if tx != &Transaction::default() {
  86. error!(target: "validator::verification::verify_genesis_block", "Genesis proposal transaction is not default one");
  87. return Err(TxVerifyFailed::ErroneousTxs(vec![tx.clone()]).into())
  88. }
  89. // Verify transactions, exluding producer(last) one
  90. let txs = &block.txs[..block.txs.len() - 1];
  91. let erroneous_txs = verify_transactions(overlay, time_keeper, txs).await?;
  92. if !erroneous_txs.is_empty() {
  93. warn!(target: "validator::verification::verify_genesis_block", "Erroneous transactions found in set");
  94. overlay.lock().unwrap().overlay.lock().unwrap().purge_new_trees()?;
  95. return Err(TxVerifyFailed::ErroneousTxs(erroneous_txs).into())
  96. }
  97. // Insert block
  98. overlay.lock().unwrap().add_block(block)?;
  99. debug!(target: "validator::verification::verify_genesis_block", "Genesis block {} verified successfully", block_hash);
  100. Ok(())
  101. }
  102. /// Verify given [`BlockInfo`], and apply it to the provided overlay
  103. pub async fn verify_block(
  104. overlay: &BlockchainOverlayPtr,
  105. time_keeper: &TimeKeeper,
  106. module: &PoWModule,
  107. block: &BlockInfo,
  108. previous: &BlockInfo,
  109. expected_reward: u64,
  110. testing_mode: bool,
  111. ) -> Result<()> {
  112. let block_hash = block.hash()?.to_string();
  113. debug!(target: "validator::verification::verify_block", "Validating block {}", block_hash);
  114. // Check if block already exists
  115. if overlay.lock().unwrap().has_block(block)? {
  116. return Err(Error::BlockAlreadyExists(block_hash))
  117. }
  118. // Block height must be the same as the time keeper verifying slot
  119. if block.header.height != time_keeper.verifying_slot {
  120. return Err(Error::VerifyingSlotMissmatch())
  121. }
  122. // Block epoch must be the correct one, calculated by the time keeper configuration
  123. if block.header.epoch != time_keeper.slot_epoch(block.header.height) {
  124. return Err(Error::VerifyingSlotMissmatch())
  125. }
  126. // Validate block, using its previous
  127. validate_block(block, previous, expected_reward, module)?;
  128. // Verify transactions vector contains at least one(producers) transaction
  129. if block.txs.is_empty() {
  130. return Err(Error::BlockContainsNoTransactions(block_hash))
  131. }
  132. // Insert last block slot so transactions can be validated against.
  133. // Rest (empty) slots will be inserted along with the block.
  134. // Since an overlay is used, original database is not affected.
  135. overlay.lock().unwrap().slots.insert(&[block.slots.last().unwrap().clone()])?;
  136. // Verify proposal transaction if not in testing mode
  137. if !testing_mode {
  138. let tx = block.txs.last().unwrap();
  139. let public_key =
  140. verify_producer_transaction(overlay, time_keeper, tx, block.header.version).await?;
  141. verify_producer_signature(block, &public_key)?;
  142. }
  143. // Verify transactions, exluding producer(last) one
  144. let txs = &block.txs[..block.txs.len() - 1];
  145. let erroneous_txs = verify_transactions(overlay, time_keeper, txs).await?;
  146. if !erroneous_txs.is_empty() {
  147. warn!(target: "validator::verification::verify_block", "Erroneous transactions found in set");
  148. overlay.lock().unwrap().overlay.lock().unwrap().purge_new_trees()?;
  149. return Err(TxVerifyFailed::ErroneousTxs(erroneous_txs).into())
  150. }
  151. // Insert block
  152. overlay.lock().unwrap().add_block(block)?;
  153. debug!(target: "validator::verification::verify_block", "Block {} verified successfully", block_hash);
  154. Ok(())
  155. }
  156. /// Verify block proposer signature, using the proposal transaction signature as signing key
  157. /// over blocks header hash.
  158. pub fn verify_producer_signature(block: &BlockInfo, public_key: &PublicKey) -> Result<()> {
  159. if !public_key.verify(&block.header.hash()?.as_bytes()[..], &block.signature) {
  160. warn!(target: "validator::verification::verify_producer_signature", "Proposer {} signature could not be verified", public_key);
  161. return Err(Error::InvalidSignature)
  162. }
  163. Ok(())
  164. }
  165. /// Verify WASM execution, signatures, and ZK proofs for a given producer [`Transaction`],
  166. /// and apply it to the provided overlay. Returns transaction signature public key.
  167. pub async fn verify_producer_transaction(
  168. overlay: &BlockchainOverlayPtr,
  169. time_keeper: &TimeKeeper,
  170. tx: &Transaction,
  171. block_version: u8,
  172. ) -> Result<PublicKey> {
  173. let tx_hash = tx.hash()?;
  174. debug!(target: "validator::verification::verify_producer_transaction", "Validating proposal transaction {}", tx_hash);
  175. // Transaction must contain a single call
  176. if tx.calls.len() != 1 {
  177. return Err(TxVerifyFailed::ErroneousTxs(vec![tx.clone()]).into())
  178. }
  179. // Verify call based on version
  180. let call = &tx.calls[0];
  181. match block_version {
  182. 1 => {
  183. // Version 1 blocks must contain a Money::PoWReward(0x08) call
  184. if call.contract_id != *MONEY_CONTRACT_ID || call.data[0] != 0x08 {
  185. return Err(TxVerifyFailed::ErroneousTxs(vec![tx.clone()]).into())
  186. }
  187. }
  188. 2 => {
  189. // Version 2 blocks must contain a Consensus::Proposal(0x02) call
  190. if call.contract_id != *CONSENSUS_CONTRACT_ID || call.data[0] != 0x02 {
  191. return Err(TxVerifyFailed::ErroneousTxs(vec![tx.clone()]).into())
  192. }
  193. }
  194. _ => return Err(Error::BlockVersionIsInvalid(block_version)),
  195. }
  196. // Map of ZK proof verifying keys for the current transaction
  197. let mut verifying_keys: HashMap<[u8; 32], HashMap<String, VerifyingKey>> = HashMap::new();
  198. // Initialize the map
  199. verifying_keys.insert(call.contract_id.to_bytes(), HashMap::new());
  200. // Table of public inputs used for ZK proof verification
  201. let mut zkp_table = vec![];
  202. // Table of public keys used for signature verification
  203. let mut sig_table = vec![];
  204. debug!(target: "validator::verification::verify_producer_transaction", "Executing contract call");
  205. // Write the actual payload data
  206. let mut payload = vec![];
  207. payload.write_u32(0)?; // Call index
  208. tx.calls.encode(&mut payload)?; // Actual call data
  209. debug!(target: "validator::verification::verify_producer_transaction", "Instantiating WASM runtime");
  210. let wasm = overlay.lock().unwrap().wasm_bincode.get(call.contract_id)?;
  211. let mut runtime = Runtime::new(&wasm, overlay.clone(), call.contract_id, time_keeper.clone())?;
  212. debug!(target: "validator::verification::verify_producer_transaction", "Executing \"metadata\" call");
  213. let metadata = runtime.metadata(&payload)?;
  214. // Decode the metadata retrieved from the execution
  215. let mut decoder = Cursor::new(&metadata);
  216. // The tuple is (zkas_ns, public_inputs)
  217. let zkp_pub: Vec<(String, Vec<pallas::Base>)> = Decodable::decode(&mut decoder)?;
  218. let sig_pub: Vec<PublicKey> = Decodable::decode(&mut decoder)?;
  219. // Check that only one ZK proof and signature public key exist
  220. if zkp_pub.len() != 1 || sig_pub.len() != 1 {
  221. error!(target: "validator::verification::verify_producer_transaction", "Proposal contains multiple ZK proofs or signature public keys");
  222. return Err(TxVerifyFailed::ErroneousTxs(vec![tx.clone()]).into())
  223. }
  224. // TODO: Make sure we've read all the bytes above.
  225. debug!(target: "validator::verification::verify_producer_transaction", "Successfully executed \"metadata\" call");
  226. // Here we'll look up verifying keys and insert them into the map.
  227. debug!(target: "validator::verification::verify_producer_transaction", "Performing VerifyingKey lookups from the sled db");
  228. for (zkas_ns, _) in &zkp_pub {
  229. // TODO: verify this is correct behavior
  230. let inner_vk_map = verifying_keys.get_mut(&call.contract_id.to_bytes()).unwrap();
  231. if inner_vk_map.contains_key(zkas_ns.as_str()) {
  232. continue
  233. }
  234. let (_, vk) = overlay.lock().unwrap().contracts.get_zkas(&call.contract_id, zkas_ns)?;
  235. inner_vk_map.insert(zkas_ns.to_string(), vk);
  236. }
  237. zkp_table.push(zkp_pub);
  238. let signature_public_key = *sig_pub.last().unwrap();
  239. sig_table.push(sig_pub);
  240. // After getting the metadata, we run the "exec" function with the same runtime
  241. // and the same payload.
  242. debug!(target: "validator::verification::verify_producer_transaction", "Executing \"exec\" call");
  243. let state_update = runtime.exec(&payload)?;
  244. debug!(target: "validator::verification::verify_producer_transaction", "Successfully executed \"exec\" call");
  245. // If that was successful, we apply the state update in the ephemeral overlay.
  246. debug!(target: "validator::verification::verify_producer_transaction", "Executing \"apply\" call");
  247. runtime.apply(&state_update)?;
  248. debug!(target: "validator::verification::verify_producer_transaction", "Successfully executed \"apply\" call");
  249. // When we're done executing over the tx's contract call, we now move on with verification.
  250. // First we verify the signatures as that's cheaper, and then finally we verify the ZK proofs.
  251. debug!(target: "validator::verification::verify_producer_transaction", "Verifying signatures for transaction {}", tx_hash);
  252. if sig_table.len() != tx.signatures.len() {
  253. error!(target: "validator::verification::verify_producer_transaction", "Incorrect number of signatures in tx {}", tx_hash);
  254. return Err(TxVerifyFailed::MissingSignatures.into())
  255. }
  256. // TODO: Go through the ZK circuits that have to be verified and account for the opcodes.
  257. if let Err(e) = tx.verify_sigs(sig_table) {
  258. error!(target: "validator::verification::verify_producer_transaction", "Signature verification for tx {} failed: {}", tx_hash, e);
  259. return Err(TxVerifyFailed::InvalidSignature.into())
  260. }
  261. debug!(target: "validator::verification::verify_producer_transaction", "Signature verification successful");
  262. debug!(target: "validator::verification::verify_producer_transaction", "Verifying ZK proofs for transaction {}", tx_hash);
  263. if let Err(e) = tx.verify_zkps(&verifying_keys, zkp_table).await {
  264. error!(target: "validator::verification::verify_proposal_transaction", "ZK proof verification for tx {} failed: {}", tx_hash, e);
  265. return Err(TxVerifyFailed::InvalidZkProof.into())
  266. }
  267. debug!(target: "validator::verification::verify_producer_transaction", "ZK proof verification successful");
  268. debug!(target: "validator::verification::verify_producer_transaction", "Proposal transaction {} verified successfully", tx_hash);
  269. Ok(signature_public_key)
  270. }
  271. /// Verify WASM execution, signatures, and ZK proofs for a given [`Transaction`],
  272. /// and apply it to the provided overlay.
  273. pub async fn verify_transaction(
  274. overlay: &BlockchainOverlayPtr,
  275. time_keeper: &TimeKeeper,
  276. tx: &Transaction,
  277. verifying_keys: &mut HashMap<[u8; 32], HashMap<String, VerifyingKey>>,
  278. ) -> Result<()> {
  279. let tx_hash = tx.hash()?;
  280. debug!(target: "validator::verification::verify_transaction", "Validating transaction {}", tx_hash);
  281. // Table of public inputs used for ZK proof verification
  282. let mut zkp_table = vec![];
  283. // Table of public keys used for signature verification
  284. let mut sig_table = vec![];
  285. // Iterate over all calls to get the metadata
  286. for (idx, call) in tx.calls.iter().enumerate() {
  287. // Transaction must not contain a reward call, Money::PoWReward(0x08) or Consensus::Proposal(0x02)
  288. if (call.contract_id == *MONEY_CONTRACT_ID && call.data[0] == 0x08) ||
  289. (call.contract_id == *CONSENSUS_CONTRACT_ID && call.data[0] == 0x02)
  290. {
  291. error!(target: "validator::verification::verify_transaction", "Reward transaction detected");
  292. return Err(TxVerifyFailed::ErroneousTxs(vec![tx.clone()]).into())
  293. }
  294. debug!(target: "validator::verification::verify_transaction", "Executing contract call {}", idx);
  295. // Write the actual payload data
  296. let mut payload = vec![];
  297. payload.write_u32(idx as u32)?; // Call index
  298. tx.calls.encode(&mut payload)?; // Actual call data
  299. debug!(target: "validator::verification::verify_transaction", "Instantiating WASM runtime");
  300. let wasm = overlay.lock().unwrap().wasm_bincode.get(call.contract_id)?;
  301. let mut runtime =
  302. Runtime::new(&wasm, overlay.clone(), call.contract_id, time_keeper.clone())?;
  303. debug!(target: "validator::verification::verify_transaction", "Executing \"metadata\" call");
  304. let metadata = runtime.metadata(&payload)?;
  305. // Decode the metadata retrieved from the execution
  306. let mut decoder = Cursor::new(&metadata);
  307. // The tuple is (zkas_ns, public_inputs)
  308. let zkp_pub: Vec<(String, Vec<pallas::Base>)> = Decodable::decode(&mut decoder)?;
  309. let sig_pub: Vec<PublicKey> = Decodable::decode(&mut decoder)?;
  310. // TODO: Make sure we've read all the bytes above.
  311. debug!(target: "validator::verification::verify_transaction", "Successfully executed \"metadata\" call");
  312. // Here we'll look up verifying keys and insert them into the per-contract map.
  313. debug!(target: "validator::verification::verify_transaction", "Performing VerifyingKey lookups from the sled db");
  314. for (zkas_ns, _) in &zkp_pub {
  315. let inner_vk_map = verifying_keys.get_mut(&call.contract_id.to_bytes()).unwrap();
  316. // TODO: This will be a problem in case of ::deploy, unless we force a different
  317. // namespace and disable updating existing circuit. Might be a smart idea to do
  318. // so in order to have to care less about being able to verify historical txs.
  319. if inner_vk_map.contains_key(zkas_ns.as_str()) {
  320. continue
  321. }
  322. let (_, vk) = overlay.lock().unwrap().contracts.get_zkas(&call.contract_id, zkas_ns)?;
  323. inner_vk_map.insert(zkas_ns.to_string(), vk);
  324. }
  325. zkp_table.push(zkp_pub);
  326. sig_table.push(sig_pub);
  327. // After getting the metadata, we run the "exec" function with the same runtime
  328. // and the same payload.
  329. debug!(target: "validator::verification::verify_transaction", "Executing \"exec\" call");
  330. let state_update = runtime.exec(&payload)?;
  331. debug!(target: "validator::verification::verify_transaction", "Successfully executed \"exec\" call");
  332. // If that was successful, we apply the state update in the ephemeral overlay.
  333. debug!(target: "validator::verification::verify_transaction", "Executing \"apply\" call");
  334. runtime.apply(&state_update)?;
  335. debug!(target: "validator::verification::verify_transaction", "Successfully executed \"apply\" call");
  336. // At this point we're done with the call and move on to the next one.
  337. }
  338. // When we're done looping and executing over the tx's contract calls, we now
  339. // move on with verification. First we verify the signatures as that's cheaper,
  340. // and then finally we verify the ZK proofs.
  341. debug!(target: "validator::verification::verify_transaction", "Verifying signatures for transaction {}", tx_hash);
  342. if sig_table.len() != tx.signatures.len() {
  343. error!(target: "validator::verification::verify_transaction", "Incorrect number of signatures in tx {}", tx_hash);
  344. return Err(TxVerifyFailed::MissingSignatures.into())
  345. }
  346. // TODO: Go through the ZK circuits that have to be verified and account for the opcodes.
  347. if let Err(e) = tx.verify_sigs(sig_table) {
  348. error!(target: "validator::verification::verify_transaction", "Signature verification for tx {} failed: {}", tx_hash, e);
  349. return Err(TxVerifyFailed::InvalidSignature.into())
  350. }
  351. debug!(target: "validator::verification::verify_transaction", "Signature verification successful");
  352. debug!(target: "validator::verification::verify_transaction", "Verifying ZK proofs for transaction {}", tx_hash);
  353. if let Err(e) = tx.verify_zkps(verifying_keys, zkp_table).await {
  354. error!(target: "validator::verification::verify_transaction", "ZK proof verification for tx {} failed: {}", tx_hash, e);
  355. return Err(TxVerifyFailed::InvalidZkProof.into())
  356. }
  357. debug!(target: "validator::verification::verify_transaction", "ZK proof verification successful");
  358. debug!(target: "validator::verification::verify_transaction", "Transaction {} verified successfully", tx_hash);
  359. Ok(())
  360. }
  361. /// Verify a set of [`Transaction`] in sequence and apply them if all are valid.
  362. /// In case any of the transactions fail, they will be returned to the caller.
  363. /// The function takes a boolean called `write` which tells it to actually write
  364. /// the state transitions to the database.
  365. pub async fn verify_transactions(
  366. overlay: &BlockchainOverlayPtr,
  367. time_keeper: &TimeKeeper,
  368. txs: &[Transaction],
  369. ) -> Result<Vec<Transaction>> {
  370. debug!(target: "validator::verification::verify_transactions", "Verifying {} transactions", txs.len());
  371. // Tracker for failed txs
  372. let mut erroneous_txs = vec![];
  373. // Map of ZK proof verifying keys for the current transaction batch
  374. let mut vks: HashMap<[u8; 32], HashMap<String, VerifyingKey>> = HashMap::new();
  375. // Initialize the map
  376. for tx in txs {
  377. for call in &tx.calls {
  378. vks.insert(call.contract_id.to_bytes(), HashMap::new());
  379. }
  380. }
  381. // Iterate over transactions and attempt to verify them
  382. for tx in txs {
  383. overlay.lock().unwrap().checkpoint();
  384. if let Err(e) = verify_transaction(overlay, time_keeper, tx, &mut vks).await {
  385. warn!(target: "validator::verification::verify_transactions", "Transaction verification failed: {}", e);
  386. erroneous_txs.push(tx.clone());
  387. // TODO: verify this works as expected
  388. overlay.lock().unwrap().revert_to_checkpoint()?;
  389. }
  390. }
  391. Ok(erroneous_txs)
  392. }
  393. /// Verify given [`Proposal`] against provided consensus state
  394. pub async fn verify_proposal(
  395. consensus: &Consensus,
  396. proposal: &Proposal,
  397. ) -> Result<(Fork, Option<usize>)> {
  398. // TODO: verify proposal validations work as expected on versions change(cutoff)
  399. match block_version(proposal.block.header.height) {
  400. 1 => verify_pow_proposal(consensus, proposal).await,
  401. 2 => verify_pos_proposal(consensus, proposal).await,
  402. _ => Err(Error::BlockVersionIsInvalid(proposal.block.header.version)),
  403. }
  404. }
  405. /// Verify given PoW [`Proposal`] against provided consensus state,
  406. /// A proposal is considered valid when the following rules apply:
  407. /// 1. Proposal hash matches the actual block one
  408. /// 2. Block transactions don't exceed set limit
  409. /// 3. If proposal extends a known fork, verify block's slot
  410. /// correspond to the fork hot/live/next one
  411. /// 4. Block is valid
  412. /// Additional validity rules can be applied.
  413. pub async fn verify_pow_proposal(
  414. consensus: &Consensus,
  415. proposal: &Proposal,
  416. ) -> Result<(Fork, Option<usize>)> {
  417. // Check if proposal hash matches actual one (1)
  418. let proposal_hash = proposal.block.hash()?;
  419. if proposal.hash != proposal_hash {
  420. warn!(
  421. target: "validator::verification::verify_pow_proposal", "Received proposal contains mismatched hashes: {} - {}",
  422. proposal.hash, proposal_hash
  423. );
  424. return Err(Error::ProposalHashesMissmatchError)
  425. }
  426. // Check that proposal transactions don't exceed limit (2)
  427. if proposal.block.txs.len() > TXS_CAP {
  428. warn!(
  429. target: "validator::verification::verify_pow_proposal", "Received proposal transactions exceed configured cap: {} - {}",
  430. proposal.block.txs.len(),
  431. TXS_CAP
  432. );
  433. return Err(Error::ProposalTxsExceedCapError)
  434. }
  435. // Check if proposal extends any existing forks
  436. let (fork, index) = consensus.find_extended_fork(proposal).await?;
  437. // Verify block's slot correspond to the forks' hot/live/next one (3)
  438. if fork.slots.len() != 1 || fork.slots != proposal.block.slots {
  439. return Err(Error::ProposalContainsUnknownSlots)
  440. }
  441. // Insert block slot so transactions can be validated against.
  442. // Since this fork uses an overlay clone, original overlay is not affected.
  443. fork.overlay.lock().unwrap().slots.insert(&[proposal.block.slots.last().unwrap().clone()])?;
  444. // Grab overlay last block
  445. let previous = fork.overlay.lock().unwrap().last_block()?;
  446. // Retrieve expected reward
  447. let expected_reward = expected_reward(proposal.block.header.height);
  448. // Generate a time keeper for proposal block leight
  449. let mut time_keeper = consensus.time_keeper.current();
  450. time_keeper.verifying_slot = proposal.block.header.height;
  451. // Verify proposal block (4)
  452. if verify_block(
  453. &fork.overlay,
  454. &time_keeper,
  455. &fork.module,
  456. &proposal.block,
  457. &previous,
  458. expected_reward,
  459. consensus.testing_mode,
  460. )
  461. .await
  462. .is_err()
  463. {
  464. error!(target: "validator::verification::verify_pow_proposal", "Erroneous proposal block found");
  465. fork.overlay.lock().unwrap().overlay.lock().unwrap().purge_new_trees()?;
  466. return Err(Error::BlockIsInvalid(proposal.hash.to_string()))
  467. };
  468. Ok((fork, index))
  469. }
  470. /// Verify given PoS [`Proposal`] against provided consensus state,
  471. /// A proposal is considered valid when the following rules apply:
  472. /// 1. Consensus(node) has not started current slot finalization
  473. /// 2. Proposal refers to current slot
  474. /// 3. Proposal hash matches the actual block one
  475. /// 4. Block transactions don't exceed set limit
  476. /// 5. If proposal extends a known fork, verify block slots
  477. /// correspond to the fork hot/live ones
  478. /// 6. Block is valid
  479. /// Additional validity rules can be applied.
  480. pub async fn verify_pos_proposal(
  481. consensus: &Consensus,
  482. proposal: &Proposal,
  483. ) -> Result<(Fork, Option<usize>)> {
  484. // Generate a time keeper for current slot
  485. let time_keeper = consensus.time_keeper.current();
  486. // Node have already checked for finalization in this slot (1)
  487. if time_keeper.verifying_slot <= consensus.checked_finalization {
  488. warn!(target: "validator::verification::verify_pos_proposal", "Proposal received after finalization sync period.");
  489. return Err(Error::ProposalAfterFinalizationError)
  490. }
  491. // Proposal validations
  492. let hdr = &proposal.block.header;
  493. // Ignore proposal if not for current slot (2)
  494. if hdr.height != time_keeper.verifying_slot {
  495. return Err(Error::ProposalNotForCurrentSlotError)
  496. }
  497. // Check if proposal hash matches actual one (3)
  498. let proposal_hash = proposal.block.hash()?;
  499. if proposal.hash != proposal_hash {
  500. warn!(
  501. target: "validator::verification::verify_pos_proposal", "Received proposal contains mismatched hashes: {} - {}",
  502. proposal.hash, proposal_hash
  503. );
  504. return Err(Error::ProposalHashesMissmatchError)
  505. }
  506. // Check that proposal transactions don't exceed limit (4)
  507. if proposal.block.txs.len() > TXS_CAP {
  508. warn!(
  509. target: "validator::verification::verify_pos_proposal", "Received proposal transactions exceed configured cap: {} - {}",
  510. proposal.block.txs.len(),
  511. TXS_CAP
  512. );
  513. return Err(Error::ProposalTxsExceedCapError)
  514. }
  515. // Check if proposal extends any existing forks
  516. let (fork, index) = consensus.find_extended_fork(proposal).await?;
  517. // Verify block slots correspond to the forks' hot/live ones (5)
  518. if !fork.slots.is_empty() && fork.slots != proposal.block.slots {
  519. return Err(Error::ProposalContainsUnknownSlots)
  520. }
  521. // Insert last block slot so transactions can be validated against.
  522. // Rest (empty) slots will be inserted along with the block.
  523. // Since this fork uses an overlay clone, original overlay is not affected.
  524. fork.overlay.lock().unwrap().slots.insert(&[proposal.block.slots.last().unwrap().clone()])?;
  525. // Grab overlay last block
  526. let previous = fork.overlay.lock().unwrap().last_block()?;
  527. // Retrieve expected reward
  528. let expected_reward = expected_reward(time_keeper.verifying_slot);
  529. // Verify proposal block (6)
  530. if verify_block(
  531. &fork.overlay,
  532. &time_keeper,
  533. &fork.module,
  534. &proposal.block,
  535. &previous,
  536. expected_reward,
  537. consensus.testing_mode,
  538. )
  539. .await
  540. .is_err()
  541. {
  542. error!(target: "validator::verification::verify_pos_proposal", "Erroneous proposal block found");
  543. fork.overlay.lock().unwrap().overlay.lock().unwrap().purge_new_trees()?;
  544. return Err(Error::BlockIsInvalid(proposal.hash.to_string()))
  545. };
  546. Ok((fork, index))
  547. }