validator.rs 46 KB

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