validator.rs 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104
  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 async_std::sync::{Arc, RwLock};
  20. use darkfi_sdk::{
  21. crypto::{
  22. constants::MERKLE_DEPTH,
  23. contract_id::{DAO_CONTRACT_ID, MONEY_CONTRACT_ID},
  24. schnorr::{SchnorrPublic, SchnorrSecret},
  25. MerkleNode, PublicKey, SecretKey,
  26. },
  27. db::SMART_CONTRACT_ZKAS_DB_NAME,
  28. incrementalmerkletree::{bridgetree::BridgeTree, Tree},
  29. pasta::{group::ff::PrimeField, pallas},
  30. };
  31. use darkfi_serial::{deserialize, serialize, Decodable, Encodable, WriteExt};
  32. use halo2_proofs::arithmetic::Field;
  33. use log::{debug, error, info, warn};
  34. use rand::rngs::OsRng;
  35. use serde_json::json;
  36. use super::{
  37. constants,
  38. lead_coin::LeadCoin,
  39. state::{ConsensusState, Fork, SlotCheckpoint, StateCheckpoint},
  40. BlockInfo, BlockProposal, Header, LeadInfo, LeadProof,
  41. };
  42. use crate::{
  43. blockchain::Blockchain,
  44. rpc::jsonrpc::JsonNotification,
  45. runtime::vm_runtime::Runtime,
  46. system::{Subscriber, SubscriberPtr},
  47. tx::Transaction,
  48. util::time::Timestamp,
  49. wallet::WalletPtr,
  50. zk::{
  51. proof::{ProvingKey, VerifyingKey},
  52. vm::ZkCircuit,
  53. vm_stack::empty_witnesses,
  54. },
  55. zkas::ZkBinary,
  56. Error, Result,
  57. };
  58. /// Atomic pointer to validator state.
  59. pub type ValidatorStatePtr = Arc<RwLock<ValidatorState>>;
  60. type VerifyingKeyMap = Arc<RwLock<HashMap<[u8; 32], Vec<(String, VerifyingKey)>>>>;
  61. /// This struct represents the state of a validator node.
  62. pub struct ValidatorState {
  63. /// Leader proof proving key
  64. pub lead_proving_key: Option<ProvingKey>,
  65. /// Leader proof verifying key
  66. pub lead_verifying_key: VerifyingKey,
  67. /// Hot/Live data used by the consensus algorithm
  68. pub consensus: ConsensusState,
  69. /// Canonical (finalized) blockchain
  70. pub blockchain: Blockchain,
  71. /// Pending transactions
  72. pub unconfirmed_txs: Vec<Transaction>,
  73. /// A map of various subscribers exporting live info from the blockchain
  74. /// TODO: Instead of JsonNotification, it can be an enum of internal objects,
  75. /// and then we don't have to deal with json in this module but only
  76. // externally.
  77. pub subscribers: HashMap<&'static str, SubscriberPtr<JsonNotification>>,
  78. /// ZK proof verifying keys for smart contract calls
  79. pub verifying_keys: VerifyingKeyMap,
  80. /// Wallet interface
  81. pub wallet: WalletPtr,
  82. /// Flag to enable single-node mode
  83. pub single_node: bool,
  84. }
  85. impl ValidatorState {
  86. pub async fn new(
  87. db: &sled::Db, // <-- TODO: Avoid this with some wrapping, sled should only be in blockchain
  88. bootstrap_ts: Timestamp,
  89. genesis_ts: Timestamp,
  90. genesis_data: blake3::Hash,
  91. initial_distribution: u64,
  92. wallet: WalletPtr,
  93. faucet_pubkeys: Vec<PublicKey>,
  94. enable_participation: bool,
  95. single_node: bool,
  96. ) -> Result<ValidatorStatePtr> {
  97. debug!(target: "consensus::validator", "Initializing ValidatorState");
  98. debug!(target: "consensus::validator", "Initializing wallet tables for consensus");
  99. // Initialize consensus coin table.
  100. // NOTE: In future this will be redundant as consensus coins will live in the money contract.
  101. if enable_participation {
  102. wallet.exec_sql(include_str!("consensus_coin.sql")).await?;
  103. }
  104. debug!(target: "consensus::validator", "Generating leader proof keys with k: {}", constants::LEADER_PROOF_K);
  105. let bincode = include_bytes!("../../proof/lead.zk.bin");
  106. let zkbin = ZkBinary::decode(bincode)?;
  107. let witnesses = empty_witnesses(&zkbin);
  108. let circuit = ZkCircuit::new(witnesses, zkbin);
  109. let lead_verifying_key = VerifyingKey::build(constants::LEADER_PROOF_K, &circuit);
  110. // We only need this proving key if we're going to participate in the consensus.
  111. let lead_proving_key = if enable_participation {
  112. Some(ProvingKey::build(constants::LEADER_PROOF_K, &circuit))
  113. } else {
  114. None
  115. };
  116. let blockchain = Blockchain::new(db, genesis_ts, genesis_data)?;
  117. let consensus = ConsensusState::new(
  118. wallet.clone(),
  119. blockchain.clone(),
  120. bootstrap_ts,
  121. genesis_ts,
  122. genesis_data,
  123. initial_distribution,
  124. single_node,
  125. )?;
  126. let unconfirmed_txs = vec![];
  127. // -----NATIVE WASM CONTRACTS-----
  128. // This is the current place where native contracts are being deployed.
  129. // When the `Blockchain` object is created, it doesn't care whether it
  130. // already has the contract data or not. If there's existing data, it
  131. // will just open the necessary db and trees, and give back what it has.
  132. // This means that on subsequent runs our native contracts will already
  133. // be in a deployed state, so what we actually do here is a redeployment.
  134. // This kind of operation should only modify the contract's state in case
  135. // it wasn't deployed before (meaning the initial run). Otherwise, it
  136. // shouldn't touch anything, or just potentially update the db schemas or
  137. // whatever is necessary. This logic should be handled in the init function
  138. // of the actual contract, so make sure the native contracts handle this well.
  139. // The faucet pubkeys are pubkeys which are allowed to create clear inputs
  140. // in the money contract.
  141. let money_contract_deploy_payload = serialize(&faucet_pubkeys);
  142. let dao_contract_deploy_payload = vec![];
  143. // In this hashmap, we keep references to ZK proof verifying keys needed
  144. // for the circuits our native contracts provide.
  145. let mut verifying_keys = HashMap::new();
  146. let native_contracts = vec![
  147. (
  148. "Money Contract",
  149. *MONEY_CONTRACT_ID,
  150. include_bytes!("../contract/money/money_contract.wasm").to_vec(),
  151. money_contract_deploy_payload,
  152. ),
  153. (
  154. "DAO Contract",
  155. *DAO_CONTRACT_ID,
  156. include_bytes!("../contract/dao/dao_contract.wasm").to_vec(),
  157. dao_contract_deploy_payload,
  158. ),
  159. ];
  160. info!(target: "consensus::validator", "Deploying native wasm contracts");
  161. for nc in native_contracts {
  162. info!(target: "consensus::validator", "Deploying {} with ContractID {}", nc.0, nc.1);
  163. let mut runtime = Runtime::new(&nc.2[..], blockchain.clone(), nc.1)?;
  164. runtime.deploy(&nc.3)?;
  165. info!(target: "consensus::validator", "Successfully deployed {}", nc.0);
  166. // When deployed, we can do a lookup for the zkas circuits and
  167. // initialize verifying keys for them.
  168. info!(target: "consensus::validator", "Creating ZK verifying keys for {} zkas circuits", nc.0);
  169. info!(target: "consensus::validator", "Looking up zkas db for {} (ContractID: {})", nc.0, nc.1);
  170. let zkas_db = blockchain.contracts.lookup(
  171. &blockchain.sled_db,
  172. &nc.1,
  173. SMART_CONTRACT_ZKAS_DB_NAME,
  174. )?;
  175. let mut vks = vec![];
  176. for i in zkas_db.iter() {
  177. info!(target: "consensus::validator", "Iterating over zkas db");
  178. let (zkas_ns, zkas_bincode) = i?;
  179. info!(target: "consensus::validator", "Deserializing namespace");
  180. let zkas_ns: String = deserialize(&zkas_ns)?;
  181. info!(target: "consensus::validator", "Creating VerifyingKey for zkas circuit with namespace {}", zkas_ns);
  182. let zkbin = ZkBinary::decode(&zkas_bincode)?;
  183. let circuit = ZkCircuit::new(empty_witnesses(&zkbin), zkbin);
  184. // FIXME: This k=13 man...
  185. let vk = VerifyingKey::build(13, &circuit);
  186. vks.push((zkas_ns, vk));
  187. }
  188. info!(target: "consensus::validator", "Finished creating VerifyingKey objects for {} (ContractID: {})", nc.0, nc.1);
  189. verifying_keys.insert(nc.1.to_bytes(), vks);
  190. }
  191. info!(target: "consensus::validator", "Finished deployment of native wasm contracts");
  192. // -----NATIVE WASM CONTRACTS-----
  193. // Here we initialize various subscribers that can export live consensus/blockchain data.
  194. let mut subscribers = HashMap::new();
  195. let block_subscriber = Subscriber::new();
  196. subscribers.insert("blocks", block_subscriber);
  197. let state = Arc::new(RwLock::new(ValidatorState {
  198. lead_proving_key,
  199. lead_verifying_key,
  200. consensus,
  201. blockchain,
  202. unconfirmed_txs,
  203. subscribers,
  204. verifying_keys: Arc::new(RwLock::new(verifying_keys)),
  205. wallet,
  206. single_node,
  207. }));
  208. Ok(state)
  209. }
  210. /// The node retrieves a transaction, validates its state transition,
  211. /// and appends it to the unconfirmed transactions list.
  212. pub async fn append_tx(&mut self, tx: Transaction) -> bool {
  213. let tx_hash = blake3::hash(&serialize(&tx));
  214. let tx_in_txstore = match self.blockchain.transactions.contains(&tx_hash) {
  215. Ok(v) => v,
  216. Err(e) => {
  217. error!(target: "consensus::validator", "append_tx(): Failed querying txstore: {}", e);
  218. return false
  219. }
  220. };
  221. if self.unconfirmed_txs.contains(&tx) || tx_in_txstore {
  222. info!(target: "consensus::validator", "append_tx(): We have already seen this tx.");
  223. return false
  224. }
  225. info!(target: "consensus::validator", "append_tx(): Starting state transition validation");
  226. if let Err(e) = self.verify_transactions(&[tx.clone()], false).await {
  227. error!(target: "consensus::validator", "append_tx(): Failed to verify transaction: {}", e);
  228. return false
  229. };
  230. info!(target: "consensus::validator", "append_tx(): Appended tx to mempool");
  231. self.unconfirmed_txs.push(tx);
  232. true
  233. }
  234. /// Generate a block proposal for the current slot, containing all
  235. /// unconfirmed transactions. Proposal extends the longest fork
  236. /// chain the node is holding.
  237. pub fn propose(
  238. &mut self,
  239. slot: u64,
  240. fork_index: i64,
  241. coin_index: usize,
  242. sigma1: pallas::Base,
  243. sigma2: pallas::Base,
  244. ) -> Result<Option<(BlockProposal, LeadCoin, pallas::Scalar)>> {
  245. let eta = self.consensus.get_eta();
  246. // Check if node can produce proposals
  247. if !self.consensus.proposing {
  248. return Ok(None)
  249. }
  250. // Generate proposal
  251. let unproposed_txs = self.unproposed_txs(fork_index);
  252. let mut tree = BridgeTree::<MerkleNode, MERKLE_DEPTH>::new(100);
  253. // The following is pretty weird, so something better should be done.
  254. for tx in &unproposed_txs {
  255. let mut hash = [0_u8; 32];
  256. hash[0..31].copy_from_slice(&blake3::hash(&serialize(tx)).as_bytes()[0..31]);
  257. tree.append(&MerkleNode::from(pallas::Base::from_repr(hash).unwrap()));
  258. }
  259. let root = tree.root(0).unwrap();
  260. // Checking if extending a fork or canonical
  261. let (prev_hash, coin) = if fork_index == -1 {
  262. (self.blockchain.last()?.1, self.consensus.coins[coin_index].clone())
  263. } else {
  264. let checkpoint = self.consensus.forks[fork_index as usize].sequence.last().unwrap();
  265. (checkpoint.proposal.hash, checkpoint.coins[coin_index].clone())
  266. };
  267. // Generate derived coin blind
  268. let derived_blind = pallas::Scalar::random(&mut OsRng);
  269. // Generating leader proof
  270. let (proof, public_inputs) = coin.create_lead_proof(
  271. sigma1,
  272. sigma2,
  273. eta.clone(),
  274. pallas::Base::from(self.consensus.current_slot()),
  275. self.lead_proving_key.as_ref().unwrap(),
  276. derived_blind,
  277. );
  278. // Signing using coin
  279. let secret_key = coin.coin1_sk;
  280. let header = Header::new(
  281. prev_hash,
  282. self.consensus.slot_epoch(slot),
  283. slot,
  284. Timestamp::current_time(),
  285. root,
  286. );
  287. let signed_proposal =
  288. SecretKey::from(secret_key).sign(&mut OsRng, &header.headerhash().as_bytes()[..]);
  289. let public_key = PublicKey::from_secret(secret_key.into());
  290. let lead_info = LeadInfo::new(
  291. signed_proposal,
  292. public_key,
  293. public_inputs,
  294. coin.slot,
  295. eta,
  296. LeadProof::from(proof?),
  297. *self.consensus.leaders_history.last().unwrap(),
  298. );
  299. Ok(Some((BlockProposal::new(header, unproposed_txs, lead_info), coin, derived_blind)))
  300. }
  301. /// Retrieve all unconfirmed transactions not proposed in previous blocks
  302. /// of provided index chain.
  303. pub fn unproposed_txs(&self, index: i64) -> Vec<Transaction> {
  304. let unproposed_txs = if index == -1 {
  305. // If index is -1 (canonical blockchain) a new fork will be generated,
  306. // therefore all unproposed transactions can be included in the proposal.
  307. self.unconfirmed_txs.clone()
  308. } else {
  309. // We iterate over the fork chain proposals to find already proposed
  310. // transactions and remove them from the local unproposed_txs vector.
  311. let mut filtered_txs = self.unconfirmed_txs.clone();
  312. let chain = &self.consensus.forks[index as usize];
  313. for state_checkpoint in &chain.sequence {
  314. for tx in &state_checkpoint.proposal.block.txs {
  315. if let Some(pos) = filtered_txs.iter().position(|txs| *txs == *tx) {
  316. filtered_txs.remove(pos);
  317. }
  318. }
  319. }
  320. filtered_txs
  321. };
  322. // Check if transactions exceed configured cap
  323. let cap = constants::TXS_CAP;
  324. if unproposed_txs.len() > cap {
  325. return unproposed_txs[0..cap].to_vec()
  326. }
  327. unproposed_txs
  328. }
  329. /// Given a proposal, the node verify its sender (slot leader) and finds which blockchain
  330. /// it extends. If the proposal extends the canonical blockchain, a new fork chain is created.
  331. /// Returns flag to signal if proposal should be broadcasted. Only active consensus participants
  332. /// should broadcast proposals.
  333. pub async fn receive_proposal(
  334. &mut self,
  335. proposal: &BlockProposal,
  336. coin: Option<(usize, LeadCoin, pallas::Scalar)>,
  337. ) -> Result<bool> {
  338. let current = self.consensus.current_slot();
  339. // Node hasn't started participating
  340. match self.consensus.participating {
  341. Some(start) => {
  342. if current < start {
  343. return Ok(false)
  344. }
  345. }
  346. None => return Ok(false),
  347. }
  348. // Node have already checked for finalization in this slot
  349. if current <= self.consensus.checked_finalization {
  350. warn!(target: "consensus::validator", "receive_proposal(): Proposal received after finalization sync period.");
  351. return Err(Error::ProposalAfterFinalizationError)
  352. }
  353. // Proposal validations
  354. let lf = &proposal.block.lead_info;
  355. let hdr = &proposal.block.header;
  356. // Ignore proposal if not for current slot
  357. if hdr.slot != current {
  358. return Err(Error::ProposalNotForCurrentSlotError)
  359. }
  360. // Verify that proposer can produce proposals.
  361. // Nodes that created coins in the bootstrap slot can propose immediately.
  362. // NOTE: Later, this will be enforced via contract, where it will be explicit
  363. // when a node can produce proposals, and after which slot they can be considered as valid.
  364. let elapsed_slots = current - lf.coin_slot;
  365. if lf.coin_slot != self.consensus.bootstrap_slot &&
  366. elapsed_slots <= (constants::EPOCH_LENGTH as u64)
  367. {
  368. warn!(
  369. target: "consensus::validator",
  370. "receive_proposal(): Proposer {} is not eligible to produce proposals",
  371. lf.public_key
  372. );
  373. return Err(Error::ProposalProposerNotEligible)
  374. }
  375. // Check if proposal extends any existing fork chains
  376. let index = self.consensus.find_extended_chain_index(proposal)?;
  377. if index == -2 {
  378. return Err(Error::ExtendedChainIndexNotFound)
  379. }
  380. // Check that proposal transactions don't exceed limit
  381. if proposal.block.txs.len() > constants::TXS_CAP {
  382. warn!(
  383. target: "consensus::validator",
  384. "receive_proposal(): Received proposal transactions exceed configured cap: {} - {}",
  385. proposal.block.txs.len(),
  386. constants::TXS_CAP
  387. );
  388. return Err(Error::ProposalTxsExceedCapError)
  389. }
  390. // Verify proposal signature is valid based on producer public key
  391. // TODO: derive public key from proof
  392. if !lf.public_key.verify(proposal.header.as_bytes(), &lf.signature) {
  393. warn!(target: "consensus::validator", "receive_proposal(): Proposer {} signature could not be verified", lf.public_key);
  394. return Err(Error::InvalidSignature)
  395. }
  396. // Check if proposal hash matches actual one
  397. let proposal_hash = proposal.block.blockhash();
  398. if proposal.hash != proposal_hash {
  399. warn!(
  400. target: "consensus::validator",
  401. "receive_proposal(): Received proposal contains mismatched hashes: {} - {}",
  402. proposal.hash, proposal_hash
  403. );
  404. return Err(Error::ProposalHashesMissmatchError)
  405. }
  406. // Check if proposal header matches actual one
  407. let proposal_header = hdr.headerhash();
  408. if proposal.header != proposal_header {
  409. warn!(
  410. target: "consensus::validator",
  411. "receive_proposal(): Received proposal contains mismatched headers: {} - {}",
  412. proposal.header, proposal_header
  413. );
  414. return Err(Error::ProposalHeadersMissmatchError)
  415. }
  416. // Ignore node coin validations if we oporate in single-node mode
  417. if !self.single_node {
  418. // Verify proposal leader proof
  419. if let Err(e) = lf.proof.verify(&self.lead_verifying_key, &lf.public_inputs) {
  420. error!(target: "consensus::validator", "receive_proposal(): Error during leader proof verification: {}", e);
  421. return Err(Error::LeaderProofVerification)
  422. };
  423. info!(target: "consensus::validator", "receive_proposal(): Leader proof verified successfully!");
  424. // Validate proposal public value against coin creation slot checkpoint
  425. let (mu_y, mu_rho) = LeadCoin::election_seeds_u64(
  426. self.consensus.get_eta(),
  427. self.consensus.current_slot(),
  428. );
  429. // y
  430. let prop_mu_y = lf.public_inputs[constants::PI_MU_Y_INDEX];
  431. if mu_y != prop_mu_y {
  432. error!(
  433. target: "consensus::validator",
  434. "receive_proposal(): Failed to verify mu_y: {:?}, proposed: {:?}",
  435. mu_y, prop_mu_y
  436. );
  437. return Err(Error::ProposalPublicValuesMismatched)
  438. }
  439. // rho
  440. let prop_mu_rho = lf.public_inputs[constants::PI_MU_RHO_INDEX];
  441. if mu_rho != prop_mu_rho {
  442. error!(
  443. target: "consensus::validator",
  444. "receive_proposal(): Failed to verify mu_rho: {:?}, proposed: {:?}",
  445. mu_rho, prop_mu_rho
  446. );
  447. return Err(Error::ProposalPublicValuesMismatched)
  448. }
  449. // Validate proposal coin sigmas against current slot checkpoint
  450. let checkpoint = self.consensus.get_slot_checkpoint(current)?;
  451. // sigma1
  452. let prop_sigma1 = lf.public_inputs[constants::PI_SIGMA1_INDEX];
  453. if checkpoint.sigma1 != prop_sigma1 {
  454. error!(
  455. target: "consensus::validator",
  456. "receive_proposal(): Failed to verify public value sigma1: {:?}, to proposed: {:?}",
  457. checkpoint.sigma1, prop_sigma1
  458. );
  459. }
  460. // sigma2
  461. let prop_sigma2 = lf.public_inputs[constants::PI_SIGMA2_INDEX];
  462. if checkpoint.sigma2 != prop_sigma2 {
  463. error!(
  464. target: "consensus::validator",
  465. "receive_proposal(): Failed to verify public value sigma2: {:?}, to proposed: {:?}",
  466. checkpoint.sigma2, prop_sigma2
  467. );
  468. }
  469. }
  470. // Create corresponding state checkpoint for validations
  471. let mut state_checkpoint = match index {
  472. -1 => {
  473. // Extends canonical
  474. StateCheckpoint::new(
  475. proposal.clone(),
  476. self.consensus.coins.clone(),
  477. self.consensus.coins_tree.clone(),
  478. self.consensus.nullifiers.clone(),
  479. )
  480. }
  481. _ => {
  482. // Extends a fork
  483. let previous = self.consensus.forks[index as usize].sequence.last().unwrap();
  484. StateCheckpoint::new(
  485. proposal.clone(),
  486. previous.coins.clone(),
  487. previous.coins_tree.clone(),
  488. previous.nullifiers.clone(),
  489. )
  490. }
  491. };
  492. // Check if proposal coin nullifiers already exist in the state checkpoint
  493. let prop_sn = lf.public_inputs[constants::PI_NULLIFIER_INDEX];
  494. for sn in &state_checkpoint.nullifiers {
  495. if *sn == prop_sn {
  496. error!(target: "consensus::validator", "receive_proposal(): Proposal nullifiers exist.");
  497. return Err(Error::ProposalIsSpent)
  498. }
  499. }
  500. // Validate state transition against canonical state
  501. // TODO: This should be validated against fork state
  502. info!(target: "consensus::validator", "receive_proposal(): Starting state transition validation");
  503. if let Err(e) = self.verify_transactions(&proposal.block.txs, false).await {
  504. error!(target: "consensus::validator", "receive_proposal(): Transaction verifications failed: {}", e);
  505. return Err(e)
  506. };
  507. // TODO: [PLACEHOLDER] Add rewards validation
  508. // If proposal came fromself, we derive new coin
  509. if let Some((idx, c, derived_blind)) = coin {
  510. info!(target: "consensus::validator", "receive_proposal(): Storing derived coin...");
  511. // Derive coin
  512. let derived = c.derive_coin(&mut state_checkpoint.coins_tree, derived_blind);
  513. // Update consensus coin in wallet
  514. // NOTE: In future this will be redundant as consensus coins will live in the money contract.
  515. // Get a wallet connection
  516. let mut conn = self.wallet.conn.acquire().await?;
  517. let query_str = format!(
  518. "UPDATE {} SET {} = ?1",
  519. constants::CONSENSUS_COIN_TABLE,
  520. constants::CONSENSUS_COIN_COL
  521. );
  522. let mut query = sqlx::query(&query_str);
  523. query = query.bind(serialize(&derived));
  524. query.execute(&mut conn).await?;
  525. state_checkpoint.coins[idx] = derived;
  526. }
  527. // Store proposal coins nullifiers
  528. state_checkpoint.nullifiers.push(prop_sn);
  529. // Extend corresponding chain
  530. match index {
  531. -1 => {
  532. let fork = Fork::new(self.consensus.genesis_block, state_checkpoint);
  533. self.consensus.forks.push(fork);
  534. }
  535. _ => {
  536. self.consensus.forks[index as usize].add(&state_checkpoint);
  537. }
  538. };
  539. Ok(true)
  540. }
  541. /// Remove provided transactions vector from unconfirmed_txs if they exist.
  542. pub fn remove_txs(&mut self, transactions: &Vec<Transaction>) -> Result<()> {
  543. for tx in transactions {
  544. if let Some(pos) = self.unconfirmed_txs.iter().position(|txs| txs == tx) {
  545. self.unconfirmed_txs.remove(pos);
  546. }
  547. }
  548. Ok(())
  549. }
  550. /// Node checks if any of the fork chains can be finalized.
  551. /// Consensus finalization logic:
  552. /// - If the node has observed the creation of a fork chain and no other forks exists at same or greater height,
  553. /// it finalizes (appends to canonical blockchain) all proposals in that fork chain.
  554. /// When fork chain proposals are finalized, the rest of fork chains are removed and all
  555. /// slot checkpoints are apppended to canonical state.
  556. pub async fn chain_finalization(&mut self) -> Result<(Vec<BlockInfo>, Vec<SlotCheckpoint>)> {
  557. let slot = self.consensus.current_slot();
  558. info!(target: "consensus::validator", "chain_finalization(): Started finalization check for slot: {}", slot);
  559. // Set last slot finalization check occured to current slot
  560. self.consensus.checked_finalization = slot;
  561. // First we find longest fork without any other forks at same height
  562. let mut fork_index = -1;
  563. // Use this index to extract leaders count sequence from longest fork
  564. let mut index_for_history = -1;
  565. let mut max_length_for_history = 0;
  566. let mut max_length = 0;
  567. for (index, fork) in self.consensus.forks.iter().enumerate() {
  568. let length = fork.sequence.len();
  569. // Check if greater than max to retain index for history
  570. if length > max_length_for_history {
  571. index_for_history = index as i64;
  572. max_length_for_history = length;
  573. }
  574. // Check if less than max
  575. if length < max_length {
  576. continue
  577. }
  578. // Check if same length as max
  579. if length == max_length {
  580. // Setting fork_index so we know we have multiple
  581. // forks at same length.
  582. fork_index = -2;
  583. continue
  584. }
  585. // Set fork as max
  586. fork_index = index as i64;
  587. max_length = length;
  588. }
  589. // Check if we found any fork to finalize
  590. match fork_index {
  591. -2 => {
  592. info!(target: "consensus::validator", "chain_finalization(): Eligible forks with same height exist, nothing to finalize.");
  593. self.consensus.set_leader_history(index_for_history, slot);
  594. return Ok((vec![], vec![]))
  595. }
  596. -1 => {
  597. info!(target: "consensus::validator", "chain_finalization(): Nothing to finalize.");
  598. }
  599. _ => {
  600. info!(target: "consensus::validator", "chain_finalization(): Chain {} can be finalized!", fork_index)
  601. }
  602. }
  603. if max_length == 0 {
  604. return Ok((vec![], vec![]))
  605. }
  606. // Starting finalization
  607. let fork = self.consensus.forks[fork_index as usize].clone();
  608. // Retrieving proposals to finalize
  609. let mut finalized: Vec<BlockInfo> = vec![];
  610. for state_checkpoint in &fork.sequence {
  611. finalized.push(state_checkpoint.proposal.clone().into());
  612. }
  613. // Adding finalized proposals to canonical
  614. info!(target: "consensus::validator", "consensus: Adding {} finalized block to canonical chain.", finalized.len());
  615. match self.blockchain.add(&finalized) {
  616. Ok(v) => v,
  617. Err(e) => {
  618. error!(target: "consensus::validator", "consensus: Failed appending finalized blocks to canonical chain: {}", e);
  619. return Err(e)
  620. }
  621. };
  622. let blocks_subscriber = self.subscribers.get("blocks").unwrap().clone();
  623. // Validating state transitions
  624. for proposal in &finalized {
  625. // TODO: Is this the right place? We're already doing this in protocol_sync.
  626. // TODO: These state transitions have already been checked. (I wrote this, but where?)
  627. // TODO: FIXME: The state transitions have already been written, they have to be in memory
  628. // until this point.
  629. info!(target: "consensus::validator", "Applying state transition for finalized block");
  630. if let Err(e) = self.verify_transactions(&proposal.txs, true).await {
  631. error!(target: "consensus::validator", "Finalized block transaction verifications failed: {}", e);
  632. return Err(e)
  633. }
  634. // Remove proposal transactions from memory pool
  635. if let Err(e) = self.remove_txs(&proposal.txs) {
  636. error!(target: "consensus::validator", "Removing finalized block transactions failed: {}", e);
  637. return Err(e)
  638. }
  639. // TODO: Don't hardcode this:
  640. let params = json!([bs58::encode(&serialize(proposal)).into_string()]);
  641. let notif = JsonNotification::new("blockchain.subscribe_blocks", params);
  642. info!(target: "consensus::validator", "consensus: Sending notification about finalized block");
  643. blocks_subscriber.notify(notif).await;
  644. }
  645. // Setting leaders history to last proposal leaders count
  646. let last_state_checkpoint = fork.sequence.last().unwrap().clone();
  647. self.consensus.leaders_history =
  648. vec![last_state_checkpoint.proposal.block.lead_info.leaders];
  649. // Setting canonical states from last finalized checkpoint
  650. self.consensus.coins = last_state_checkpoint.coins;
  651. self.consensus.coins_tree = last_state_checkpoint.coins_tree;
  652. self.consensus.nullifiers = last_state_checkpoint.nullifiers;
  653. // Adding finalized slot checkpoints to canonical
  654. let finalized_slot_checkpoints: Vec<SlotCheckpoint> =
  655. self.consensus.slot_checkpoints.clone();
  656. debug!(
  657. target: "consensus::validator",
  658. "consensus: Adding {} finalized slot checkpoints to canonical chain.",
  659. finalized_slot_checkpoints.len()
  660. );
  661. match self.blockchain.add_slot_checkpoints(&finalized_slot_checkpoints) {
  662. Ok(v) => v,
  663. Err(e) => {
  664. error!(
  665. target: "consensus::validator",
  666. "consensus: Failed appending finalized slot checkpoints to canonical chain: {}",
  667. e
  668. );
  669. return Err(e)
  670. }
  671. };
  672. // Resetting forks and slot checkpoints
  673. self.consensus.forks = vec![];
  674. self.consensus.slot_checkpoints = vec![];
  675. Ok((finalized, finalized_slot_checkpoints))
  676. }
  677. // ==========================
  678. // State transition functions
  679. // ==========================
  680. // TODO TESTNET: Write down all cases below
  681. // State transition checks should be happening in the following cases for a sync node:
  682. // 1) When a finalized block is received
  683. // 2) When a transaction is being broadcasted to us
  684. // State transition checks should be happening in the following cases for a consensus participating node:
  685. // 1) When a finalized block is received
  686. // 2) When a transaction is being broadcasted to us
  687. // ==========================
  688. /// Validate and append to canonical state received blocks.
  689. pub async fn receive_blocks(&mut self, blocks: &[BlockInfo]) -> Result<()> {
  690. // Verify state transitions for all blocks and their respective transactions.
  691. info!(target: "consensus::validator", "receive_blocks(): Starting state transition validations");
  692. for block in blocks {
  693. if let Err(e) = self.verify_transactions(&block.txs, true).await {
  694. error!(target: "consensus::validator", "receive_blocks(): Transaction verifications failed: {}", e);
  695. return Err(e)
  696. }
  697. }
  698. info!(target: "consensus::validator", "receive_blocks(): All state transitions passed");
  699. info!(target: "consensus::validator", "receive_blocks(): Appending blocks to ledger");
  700. self.blockchain.add(blocks)?;
  701. Ok(())
  702. }
  703. /// Validate and append to canonical state received finalized block.
  704. /// Returns boolean flag indicating already existing block.
  705. pub async fn receive_finalized_block(&mut self, block: BlockInfo) -> Result<bool> {
  706. match self.blockchain.has_block(&block) {
  707. Ok(v) => {
  708. if v {
  709. info!(target: "consensus::validator", "receive_finalized_block(): Existing block received");
  710. return Ok(false)
  711. }
  712. }
  713. Err(e) => {
  714. error!(target: "consensus::validator", "receive_finalized_block(): failed checking for has_block(): {}", e);
  715. return Ok(false)
  716. }
  717. };
  718. info!(target: "consensus::validator", "receive_finalized_block(): Executing state transitions");
  719. self.receive_blocks(&[block.clone()]).await?;
  720. // TODO: Don't hardcode this:
  721. let blocks_subscriber = self.subscribers.get("blocks").unwrap();
  722. let params = json!([bs58::encode(&serialize(&block)).into_string()]);
  723. let notif = JsonNotification::new("blockchain.subscribe_blocks", params);
  724. info!(target: "consensus::validator", "consensus: Sending notification about finalized block");
  725. blocks_subscriber.notify(notif).await;
  726. info!(target: "consensus::validator", "receive_finalized_block(): Removing block transactions from unconfirmed_txs");
  727. self.remove_txs(&block.txs)?;
  728. Ok(true)
  729. }
  730. /// Validate and append to canonical state received finalized blocks from block sync task.
  731. /// Already existing blocks are ignored.
  732. pub async fn receive_sync_blocks(&mut self, blocks: &[BlockInfo]) -> Result<()> {
  733. let mut new_blocks = vec![];
  734. for block in blocks {
  735. match self.blockchain.has_block(block) {
  736. Ok(v) => {
  737. if v {
  738. info!(target: "consensus::validator", "receive_sync_blocks(): Existing block received");
  739. continue
  740. }
  741. new_blocks.push(block.clone());
  742. }
  743. Err(e) => {
  744. error!(target: "consensus::validator", "receive_sync_blocks(): failed checking for has_block(): {}", e);
  745. continue
  746. }
  747. };
  748. }
  749. if new_blocks.is_empty() {
  750. info!(target: "consensus::validator", "receive_sync_blocks(): no new blocks to append");
  751. return Ok(())
  752. }
  753. info!(target: "consensus::validator", "receive_sync_blocks(): Executing state transitions");
  754. self.receive_blocks(&new_blocks[..]).await?;
  755. // TODO: Don't hardcode this:
  756. let blocks_subscriber = self.subscribers.get("blocks").unwrap();
  757. for block in new_blocks {
  758. let params = json!([bs58::encode(&serialize(&block)).into_string()]);
  759. let notif = JsonNotification::new("blockchain.subscribe_blocks", params);
  760. info!(target: "consensus::validator", "consensus: Sending notification about finalized block");
  761. blocks_subscriber.notify(notif).await;
  762. }
  763. Ok(())
  764. }
  765. /// Validate signatures, wasm execution, and zk proofs for given transactions.
  766. /// If all of those succeed, try to execute a state update for the contract calls.
  767. /// Currently the verifications are sequential, and the function will fail if any
  768. /// of the verifications fail.
  769. /// The function takes a boolean called `write` which tells it to actually write
  770. /// the state transitions to the database.
  771. // TODO: This should be paralellized as if even one tx in the batch fails to verify,
  772. // we can drop everything.
  773. pub async fn verify_transactions(&self, txs: &[Transaction], write: bool) -> Result<()> {
  774. info!(target: "consensus::validator", "Verifying {} transaction(s)", txs.len());
  775. for tx in txs {
  776. let tx_hash = blake3::hash(&serialize(tx));
  777. info!(target: "consensus::validator", "Verifying transaction {}", tx_hash);
  778. // Table of public inputs used for ZK proof verification
  779. let mut zkp_table = vec![];
  780. // Table of public keys used for signature verification
  781. let mut sig_table = vec![];
  782. // State updates produced by contract execcution
  783. let mut updates = vec![];
  784. // Iterate over all calls to get the metadata
  785. for (idx, call) in tx.calls.iter().enumerate() {
  786. info!(target: "consensus::validator", "Executing contract call {}", idx);
  787. let wasm = match self.blockchain.wasm_bincode.get(call.contract_id) {
  788. Ok(v) => {
  789. info!(target: "consensus::validator", "Found wasm bincode for {}", call.contract_id);
  790. v
  791. }
  792. Err(e) => {
  793. error!(
  794. target: "consensus::validator",
  795. "Could not find wasm bincode for contract {}: {}",
  796. call.contract_id, e
  797. );
  798. return Err(Error::ContractNotFound(call.contract_id.to_string()))
  799. }
  800. };
  801. // Write the actual payload data
  802. let mut payload = vec![];
  803. payload.write_u32(idx as u32)?; // Call index
  804. tx.calls.encode(&mut payload)?; // Actual call data
  805. // Instantiate the wasm runtime
  806. let mut runtime =
  807. match Runtime::new(&wasm, self.blockchain.clone(), call.contract_id) {
  808. Ok(v) => v,
  809. Err(e) => {
  810. error!(
  811. target: "consensus::validator",
  812. "Failed to instantiate WASM runtime for contract {}",
  813. call.contract_id
  814. );
  815. return Err(e)
  816. }
  817. };
  818. info!(target: "consensus::validator", "Executing \"metadata\" call");
  819. let metadata = match runtime.metadata(&payload) {
  820. Ok(v) => v,
  821. Err(e) => {
  822. error!(target: "consensus::validator", "Failed to execute \"metadata\" call: {}", e);
  823. return Err(e)
  824. }
  825. };
  826. // Decode the metadata retrieved from the execution
  827. let mut decoder = Cursor::new(&metadata);
  828. let zkp_pub: Vec<(String, Vec<pallas::Base>)> = match Decodable::decode(
  829. &mut decoder,
  830. ) {
  831. Ok(v) => v,
  832. Err(e) => {
  833. error!(target: "consensus::validator", "Failed to decode ZK public inputs from metadata: {}", e);
  834. return Err(e.into())
  835. }
  836. };
  837. let sig_pub: Vec<PublicKey> = match Decodable::decode(&mut decoder) {
  838. Ok(v) => v,
  839. Err(e) => {
  840. error!(target: "consensus::validator", "Failed to decode signature pubkeys from metadata: {}", e);
  841. return Err(e.into())
  842. }
  843. };
  844. // TODO: Make sure we've read all the bytes above.
  845. info!(target: "consensus::validator", "Successfully executed \"metadata\" call");
  846. zkp_table.push(zkp_pub);
  847. sig_table.push(sig_pub);
  848. // After getting the metadata, we run the "exec" function with the same
  849. // runtime and the same payload.
  850. info!(target: "consensus::validator", "Executing \"exec\" call");
  851. match runtime.exec(&payload) {
  852. Ok(v) => {
  853. info!(target: "consensus::validator", "Successfully executed \"exec\" call");
  854. updates.push(v);
  855. }
  856. Err(e) => {
  857. error!(
  858. target: "consensus::validator",
  859. "Failed to execute \"exec\" call for contract id {}: {}",
  860. call.contract_id, e
  861. );
  862. return Err(e)
  863. }
  864. };
  865. // At this point we're done with the call and move on to the next one.
  866. }
  867. // When we're done looping and executing over the tx's contract calls, we
  868. // move on with verification. First we verify the signatures as that's
  869. // cheaper, and then finally we verify the ZK proofs.
  870. info!(target: "consensus::validator", "Verifying signatures for transaction {}", tx_hash);
  871. if sig_table.len() != tx.signatures.len() {
  872. error!(target: "consensus::validator", "Incorrect number of signatures in tx {}", tx_hash);
  873. return Err(Error::InvalidSignature)
  874. }
  875. match tx.verify_sigs(sig_table) {
  876. Ok(()) => {
  877. info!(target: "consensus::validator", "Signatures verification for tx {} successful", tx_hash)
  878. }
  879. Err(e) => {
  880. error!(target: "consensus::validator", "Signature verification for tx {} failed: {}", tx_hash, e);
  881. return Err(e)
  882. }
  883. };
  884. // NOTE: When it comes to the ZK proofs, we first do a lookup of the
  885. // verifying keys, but if we do not find them, we'll generate them
  886. // inside of this function. This can be kinda expensive, so open to
  887. // alternatives.
  888. info!(target: "consensus::validator", "Verifying ZK proofs for transaction {}", tx_hash);
  889. match tx.verify_zkps(self.verifying_keys.clone(), zkp_table).await {
  890. Ok(()) => {
  891. info!(target: "consensus::validator", "ZK proof verification for tx {} successful", tx_hash)
  892. }
  893. Err(e) => {
  894. error!(target: "consensus::validator", "ZK proof verification for tx {} failed: {}", tx_hash, e);
  895. return Err(e)
  896. }
  897. };
  898. // After the verifications stage passes, if we're told to write, we
  899. // apply the state updates.
  900. assert!(tx.calls.len() == updates.len());
  901. if write {
  902. info!(target: "consensus::validator", "Performing state updates");
  903. for (call, update) in tx.calls.iter().zip(updates.iter()) {
  904. // For this we instantiate the runtimes again.
  905. // TODO: Optimize this
  906. // TODO: Sum up the gas costs of previous calls during execution
  907. // and verification and these.
  908. let wasm = match self.blockchain.wasm_bincode.get(call.contract_id) {
  909. Ok(v) => {
  910. info!(target: "consensus::validator", "Found wasm bincode for {}", call.contract_id);
  911. v
  912. }
  913. Err(e) => {
  914. error!(
  915. target: "consensus::validator",
  916. "Could not find wasm bincode for contract {}: {}",
  917. call.contract_id, e
  918. );
  919. return Err(Error::ContractNotFound(call.contract_id.to_string()))
  920. }
  921. };
  922. let mut runtime =
  923. match Runtime::new(&wasm, self.blockchain.clone(), call.contract_id) {
  924. Ok(v) => v,
  925. Err(e) => {
  926. error!(
  927. target: "consensus::validator",
  928. "Failed to instantiate WASM runtime for contract {}",
  929. call.contract_id
  930. );
  931. return Err(e)
  932. }
  933. };
  934. info!(target: "consensus::validator", "Executing \"apply\" call");
  935. match runtime.apply(update) {
  936. // TODO: FIXME: This should be done in an atomic tx/batch
  937. Ok(()) => {
  938. info!(target: "consensus::validator", "State update applied successfully")
  939. }
  940. Err(e) => {
  941. error!(target: "consensus::validator", "Failed to apply state update: {}", e);
  942. return Err(e)
  943. }
  944. };
  945. }
  946. } else {
  947. info!(target: "consensus::validator", "Skipping apply of state updates because write=false");
  948. }
  949. info!(target: "consensus::validator", "Transaction {} verified successfully", tx_hash);
  950. }
  951. Ok(())
  952. }
  953. /// Append to canonical state received finalized slot checkpoints from block sync task.
  954. pub async fn receive_slot_checkpoints(
  955. &mut self,
  956. slot_checkpoints: &[SlotCheckpoint],
  957. ) -> Result<()> {
  958. info!(target: "consensus::validator", "receive_slot_checkpoints(): Appending slot checkpoints to ledger");
  959. self.blockchain.add_slot_checkpoints(slot_checkpoints)?;
  960. Ok(())
  961. }
  962. /// Validate and append to canonical state received finalized slot checkpoint.
  963. /// Returns boolean flag indicating already existing slot checkpoint.
  964. pub async fn receive_finalized_slot_checkpoints(
  965. &mut self,
  966. slot_checkpoint: SlotCheckpoint,
  967. ) -> Result<bool> {
  968. match self.blockchain.has_slot_checkpoint(&slot_checkpoint) {
  969. Ok(v) => {
  970. if v {
  971. info!(
  972. target: "consensus::validator",
  973. "receive_finalized_slot_checkpoints(): Existing slot checkpoint received"
  974. );
  975. return Ok(false)
  976. }
  977. }
  978. Err(e) => {
  979. error!(target: "consensus::validator", "receive_finalized_slot_checkpoints(): failed checking for has_slot_checkpoint(): {}", e);
  980. return Ok(false)
  981. }
  982. };
  983. self.receive_slot_checkpoints(&[slot_checkpoint]).await?;
  984. Ok(true)
  985. }
  986. }