validator.rs 42 KB

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