state.rs 58 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457
  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, time::Duration};
  19. use async_std::sync::{Arc, RwLock};
  20. use chrono::{NaiveDateTime, Utc};
  21. use darkfi_sdk::{
  22. crypto::{
  23. constants::MERKLE_DEPTH,
  24. schnorr::{SchnorrPublic, SchnorrSecret},
  25. ContractId, MerkleNode, PublicKey,
  26. },
  27. db::ZKAS_DB_NAME,
  28. };
  29. use darkfi_serial::{
  30. deserialize, serialize, Decodable, Encodable, SerialDecodable, SerialEncodable, WriteExt,
  31. };
  32. use incrementalmerkletree::{bridgetree::BridgeTree, Tree};
  33. use log::{debug, error, info, warn};
  34. use pasta_curves::{group::ff::PrimeField, pallas};
  35. use rand::{rngs::OsRng, thread_rng, Rng};
  36. use serde_json::json;
  37. use super::{
  38. constants,
  39. leadcoin::{LeadCoin, LeadCoinSecrets},
  40. utils::fbig2base,
  41. Block, BlockInfo, BlockProposal, Float10, Header, LeadInfo, LeadProof, ProposalChain,
  42. };
  43. use crate::{
  44. blockchain::Blockchain,
  45. crypto::proof::{ProvingKey, VerifyingKey},
  46. net,
  47. rpc::jsonrpc::JsonNotification,
  48. runtime::vm_runtime::Runtime,
  49. system::{Subscriber, SubscriberPtr},
  50. tx::Transaction,
  51. util::time::Timestamp,
  52. wallet::WalletPtr,
  53. zk::{vm::ZkCircuit, vm_stack::empty_witnesses},
  54. zkas::ZkBinary,
  55. Error, Result,
  56. };
  57. /// This struct represents the information required by the consensus algorithm
  58. #[derive(Debug)]
  59. pub struct ConsensusState {
  60. /// Genesis block creation timestamp
  61. pub genesis_ts: Timestamp,
  62. /// Genesis block hash
  63. pub genesis_block: blake3::Hash,
  64. /// Participating start slot
  65. pub participating: Option<u64>,
  66. /// Last slot node check for finalization
  67. pub checked_finalization: u64,
  68. /// Slots offset since genesis,
  69. pub offset: Option<u64>,
  70. /// Fork chains containing block proposals
  71. pub proposals: Vec<ProposalChain>,
  72. /// Current epoch
  73. pub epoch: u64,
  74. /// Current epoch eta
  75. pub epoch_eta: pallas::Base,
  76. /// Current epoch competing coins
  77. pub coins: Vec<Vec<LeadCoin>>,
  78. // TODO: Aren't these already in db after finalization?
  79. /// Seen nullifiers from proposals
  80. pub leaders_nullifiers: Vec<pallas::Base>,
  81. /// Seen spent coins from proposals
  82. pub leaders_spent_coins: Vec<(pallas::Base, pallas::Base)>,
  83. /// Leaders count history
  84. pub leaders_history: Vec<u64>,
  85. /// Kp
  86. pub kp: Float10,
  87. /// Previous slot sigma1
  88. pub prev_sigma1: pallas::Base,
  89. /// Previous slot sigma2
  90. pub prev_sigma2: pallas::Base,
  91. }
  92. impl ConsensusState {
  93. pub fn new(genesis_ts: Timestamp, genesis_data: blake3::Hash) -> Result<Self> {
  94. let genesis_block = Block::genesis_block(genesis_ts, genesis_data).blockhash();
  95. Ok(Self {
  96. genesis_ts,
  97. genesis_block,
  98. participating: None,
  99. checked_finalization: 0,
  100. offset: None,
  101. proposals: vec![],
  102. epoch: 0,
  103. epoch_eta: pallas::Base::one(),
  104. coins: vec![],
  105. leaders_nullifiers: vec![],
  106. leaders_spent_coins: vec![],
  107. leaders_history: vec![0],
  108. kp: constants::FLOAT10_TWO.clone() / constants::FLOAT10_NINE.clone(),
  109. prev_sigma1: pallas::Base::zero(),
  110. prev_sigma2: pallas::Base::zero(),
  111. })
  112. }
  113. }
  114. /// Auxiliary structure used for consensus syncing.
  115. #[derive(Debug, SerialEncodable, SerialDecodable)]
  116. pub struct ConsensusRequest {}
  117. impl net::Message for ConsensusRequest {
  118. fn name() -> &'static str {
  119. "consensusrequest"
  120. }
  121. }
  122. /// Auxiliary structure used for consensus syncing.
  123. #[derive(Debug, Clone, SerialEncodable, SerialDecodable)]
  124. pub struct ConsensusResponse {
  125. /// Slots offset since genesis,
  126. pub offset: Option<u64>,
  127. /// Hot/live data used by the consensus algorithm
  128. pub proposals: Vec<ProposalChain>,
  129. /// Pending transactions
  130. pub unconfirmed_txs: Vec<Transaction>,
  131. /// Seen nullifiers from proposals
  132. pub leaders_nullifiers: Vec<pallas::Base>,
  133. /// Seen spent coins from proposals
  134. pub leaders_spent_coins: Vec<(pallas::Base, pallas::Base)>,
  135. }
  136. impl net::Message for ConsensusResponse {
  137. fn name() -> &'static str {
  138. "consensusresponse"
  139. }
  140. }
  141. /// Atomic pointer to validator state.
  142. pub type ValidatorStatePtr = Arc<RwLock<ValidatorState>>;
  143. /// This struct represents the state of a validator node.
  144. pub struct ValidatorState {
  145. /// Leader proof proving key
  146. pub lead_proving_key: Option<ProvingKey>,
  147. /// Leader proof verifying key
  148. pub lead_verifying_key: VerifyingKey,
  149. /// Hot/Live data used by the consensus algorithm
  150. pub consensus: ConsensusState,
  151. /// Canonical (finalized) blockchain
  152. pub blockchain: Blockchain,
  153. /// Pending transactions
  154. pub unconfirmed_txs: Vec<Transaction>,
  155. /// A map of various subscribers exporting live info from the blockchain
  156. /// TODO: Instead of JsonNotification, it can be an enum of internal objects,
  157. /// and then we don't have to deal with json in this module but only
  158. // externally.
  159. pub subscribers: HashMap<&'static str, SubscriberPtr<JsonNotification>>,
  160. /// ZK proof verifying keys for smart contract calls
  161. pub verifying_keys: Arc<RwLock<HashMap<[u8; 32], Vec<(String, VerifyingKey)>>>>,
  162. /// Wallet interface
  163. pub wallet: WalletPtr,
  164. }
  165. impl ValidatorState {
  166. pub async fn new(
  167. db: &sled::Db, // <-- TODO: Avoid this with some wrapping, sled should only be in blockchain
  168. genesis_ts: Timestamp,
  169. genesis_data: blake3::Hash,
  170. wallet: WalletPtr,
  171. faucet_pubkeys: Vec<PublicKey>,
  172. enable_participation: bool,
  173. ) -> Result<ValidatorStatePtr> {
  174. info!("Initializing ValidatorState");
  175. info!("Initializing wallet tables for consensus");
  176. // TODO: TESTNET: The stuff is kept entirely in memory for now, what should we write
  177. // to disk/wallet?
  178. //let consensus_tree_init_query = include_str!("../../script/sql/consensus_tree.sql");
  179. //let consensus_keys_init_query = include_str!("../../script/sql/consensus_keys.sql");
  180. //wallet.exec_sql(consensus_tree_init_query).await?;
  181. //wallet.exec_sql(consensus_keys_init_query).await?;
  182. info!("Generating leader proof keys with k: {}", constants::LEADER_PROOF_K);
  183. let bincode = include_bytes!("../../proof/lead.zk.bin");
  184. let zkbin = ZkBinary::decode(bincode)?;
  185. let witnesses = empty_witnesses(&zkbin);
  186. let circuit = ZkCircuit::new(witnesses, zkbin);
  187. let lead_verifying_key = VerifyingKey::build(constants::LEADER_PROOF_K, &circuit);
  188. // We only need this proving key if we're going to participate in the consensus.
  189. let lead_proving_key = if enable_participation {
  190. Some(ProvingKey::build(constants::LEADER_PROOF_K, &circuit))
  191. } else {
  192. None
  193. };
  194. let consensus = ConsensusState::new(genesis_ts, genesis_data)?;
  195. let blockchain = Blockchain::new(db, genesis_ts, genesis_data)?;
  196. let unconfirmed_txs = vec![];
  197. // -----NATIVE WASM CONTRACTS-----
  198. // This is the current place where native contracts are being deployed.
  199. // When the `Blockchain` object is created, it doesn't care whether it
  200. // already has the contract data or not. If there's existing data, it
  201. // will just open the necessary db and trees, and give back what it has.
  202. // This means that on subsequent runs our native contracts will already
  203. // be in a deployed state, so what we actually do here is a redeployment.
  204. // This kind of operation should only modify the contract's state in case
  205. // it wasn't deployed before (meaning the initial run). Otherwise, it
  206. // shouldn't touch anything, or just potentially update the db schemas or
  207. // whatever is necessary. This logic should be handled in the init function
  208. // of the actual contract, so make sure the native contracts handle this well.
  209. // FIXME: This ID should be something that does not solve the pallas curve equation,
  210. // and/or just hardcoded and forbidden in non-native contract deployment.
  211. let money_contract_id = ContractId::from(pallas::Base::from(u64::MAX - 420));
  212. // The faucet pubkeys are pubkeys which are allowed to create clear inputs
  213. // in the money contract.
  214. let money_contract_deploy_payload = serialize(&faucet_pubkeys);
  215. // In this hashmap, we keep references to ZK proof verifying keys needed
  216. // for the circuits our native contracts provide.
  217. let mut verifying_keys = HashMap::new();
  218. let native_contracts = vec![(
  219. "Money Contract",
  220. money_contract_id,
  221. include_bytes!("../contract/money/money_contract.wasm"),
  222. money_contract_deploy_payload,
  223. )];
  224. info!("Deploying native wasm contracts");
  225. for nc in native_contracts {
  226. info!("Deploying {} with ContractID {}", nc.0, nc.1);
  227. let mut runtime = Runtime::new(&nc.2[..], blockchain.clone(), nc.1)?;
  228. runtime.deploy(&nc.3)?;
  229. info!("Successfully deployed {}", nc.0);
  230. // When deployed, we can do a lookup for the zkas circuits and
  231. // initialize verifying keys for them.
  232. info!("Creating ZK verifying keys for {} zkas circuits", nc.0);
  233. debug!("Looking up zkas db for {} (ContractID: {})", nc.0, nc.1);
  234. let zkas_db = blockchain.contracts.lookup(&blockchain.sled_db, &nc.1, ZKAS_DB_NAME)?;
  235. let mut vks = vec![];
  236. for i in zkas_db.iter() {
  237. debug!("Iterating over zkas db");
  238. let (zkas_ns, zkas_bincode) = i?;
  239. debug!("Deserializing namespace");
  240. let zkas_ns: String = deserialize(&zkas_ns)?;
  241. info!("Creating VerifyingKey for zkas circuit with namespace {}", zkas_ns);
  242. let zkbin = ZkBinary::decode(&zkas_bincode)?;
  243. let circuit = ZkCircuit::new(empty_witnesses(&zkbin), zkbin);
  244. // FIXME: This k=13 man...
  245. let vk = VerifyingKey::build(13, &circuit);
  246. vks.push((zkas_ns, vk));
  247. }
  248. info!("Finished creating VerifyingKey objects for {} (ContractID: {})", nc.0, nc.1);
  249. verifying_keys.insert(nc.1.to_bytes(), vks);
  250. }
  251. info!("Finished deployment of native wasm contracts");
  252. // -----NATIVE WASM CONTRACTS-----
  253. // Here we initialize various subscribers that can export live consensus/blockchain data.
  254. let mut subscribers = HashMap::new();
  255. let block_subscriber = Subscriber::new();
  256. subscribers.insert("blocks", block_subscriber);
  257. let state = Arc::new(RwLock::new(ValidatorState {
  258. lead_proving_key,
  259. lead_verifying_key,
  260. consensus,
  261. blockchain,
  262. unconfirmed_txs,
  263. subscribers,
  264. verifying_keys: Arc::new(RwLock::new(verifying_keys)),
  265. wallet,
  266. }));
  267. Ok(state)
  268. }
  269. /// The node retrieves a transaction, validates its state transition,
  270. /// and appends it to the unconfirmed transactions list.
  271. pub async fn append_tx(&mut self, tx: Transaction) -> bool {
  272. let tx_hash = blake3::hash(&serialize(&tx));
  273. let tx_in_txstore = match self.blockchain.transactions.contains(&tx_hash) {
  274. Ok(v) => v,
  275. Err(e) => {
  276. error!("append_tx(): Failed querying txstore: {}", e);
  277. return false
  278. }
  279. };
  280. if self.unconfirmed_txs.contains(&tx) || tx_in_txstore {
  281. debug!("append_tx(): We have already seen this tx.");
  282. return false
  283. }
  284. debug!("append_tx(): Starting state transition validation");
  285. if let Err(e) = self.verify_transactions(&[tx.clone()], false).await {
  286. error!("append_tx(): Failed to verify transaction: {}", e);
  287. return false
  288. };
  289. debug!("append_tx(): Appended tx to mempool");
  290. self.unconfirmed_txs.push(tx);
  291. true
  292. }
  293. /// Calculates current epoch.
  294. pub fn current_epoch(&self) -> u64 {
  295. self.slot_epoch(self.current_slot())
  296. }
  297. /// Calculates the epoch of the provided slot.
  298. /// Epoch duration is configured using the `EPOCH_LENGTH` value.
  299. pub fn slot_epoch(&self, slot: u64) -> u64 {
  300. slot / constants::EPOCH_LENGTH as u64
  301. }
  302. /// Calculates current slot, based on elapsed time from the genesis block.
  303. /// Slot duration is configured using the `SLOT_TIME` constant.
  304. pub fn current_slot(&self) -> u64 {
  305. self.consensus.genesis_ts.elapsed() / constants::SLOT_TIME
  306. }
  307. /// Calculates the relative number of the provided slot.
  308. pub fn relative_slot(&self, slot: u64) -> u64 {
  309. slot % constants::EPOCH_LENGTH as u64
  310. }
  311. /// Finds the last slot a proposal or block was generated.
  312. pub fn last_slot(&self) -> Result<u64> {
  313. let mut slot = 0;
  314. for chain in &self.consensus.proposals {
  315. for proposal in &chain.proposals {
  316. if proposal.block.header.slot > slot {
  317. slot = proposal.block.header.slot;
  318. }
  319. }
  320. }
  321. // We return here in case proposals exist,
  322. // so we don't query the sled database.
  323. if slot > 0 {
  324. return Ok(slot)
  325. }
  326. let (last_slot, _) = self.blockchain.last()?;
  327. Ok(last_slot)
  328. }
  329. /// Calculates seconds until next Nth slot starting time.
  330. /// Slots duration is configured using the SLOT_TIME constant.
  331. pub fn next_n_slot_start(&self, n: u64) -> Duration {
  332. assert!(n > 0);
  333. let start_time = NaiveDateTime::from_timestamp(self.consensus.genesis_ts.0, 0);
  334. let current_slot = self.current_slot() + n;
  335. let next_slot_start =
  336. (current_slot * constants::SLOT_TIME) + (start_time.timestamp() as u64);
  337. let next_slot_start = NaiveDateTime::from_timestamp(next_slot_start as i64, 0);
  338. let current_time = NaiveDateTime::from_timestamp(Utc::now().timestamp(), 0);
  339. let diff = next_slot_start - current_time;
  340. Duration::new(diff.num_seconds().try_into().unwrap(), 0)
  341. }
  342. /// Calculate slots until next Nth epoch.
  343. /// Epoch duration is configured using the EPOCH_LENGTH value.
  344. pub fn slots_to_next_n_epoch(&self, n: u64) -> u64 {
  345. assert!(n > 0);
  346. let slots_till_next_epoch =
  347. constants::EPOCH_LENGTH as u64 - self.relative_slot(self.current_slot());
  348. ((n - 1) * constants::EPOCH_LENGTH as u64) + slots_till_next_epoch
  349. }
  350. /// Calculates seconds until next Nth epoch starting time.
  351. pub fn next_n_epoch_start(&self, n: u64) -> Duration {
  352. self.next_n_slot_start(self.slots_to_next_n_epoch(n))
  353. }
  354. /// Set participating slot to next.
  355. pub fn set_participating(&mut self) -> Result<()> {
  356. self.consensus.participating = Some(self.current_slot() + 1);
  357. Ok(())
  358. }
  359. /// Check if new epoch has started, to create new epoch coins.
  360. /// Returns flag to signify if epoch has changed and vector of
  361. /// new epoch competing coins.
  362. pub async fn epoch_changed(
  363. &mut self,
  364. sigma1: pallas::Base,
  365. sigma2: pallas::Base,
  366. ) -> Result<bool> {
  367. let epoch = self.current_epoch();
  368. self.consensus.prev_sigma1 = sigma1;
  369. self.consensus.prev_sigma2 = sigma2;
  370. if epoch <= self.consensus.epoch {
  371. return Ok(false)
  372. }
  373. let eta = self.get_eta();
  374. // TODO: slot parameter should be absolute slot, not relative.
  375. // At start of epoch, relative slot is 0.
  376. self.consensus.coins = self.create_epoch_coins(eta, epoch).await?;
  377. self.consensus.epoch = epoch;
  378. self.consensus.epoch_eta = eta;
  379. Ok(true)
  380. }
  381. /// return 2-term target approximation sigma coefficients.
  382. /// `epoch: absolute epoch index
  383. /// `slot: relative slot index
  384. pub fn sigmas(&mut self, epoch: u64, slot: u64) -> (pallas::Base, pallas::Base) {
  385. let f = self.win_prob_with_full_stake();
  386. // Generate sigmas
  387. let total_stake = self.total_stake_plus(epoch, slot); // Only used for fine-tuning
  388. debug!("consensus::sigmas(): epoch: {}", epoch);
  389. debug!("consensus::sigmas(): slot: {}", slot);
  390. debug!("consensus::sigmas(): f: {}", f);
  391. debug!("consensus::sigmas(): stake: {}", total_stake);
  392. let one = constants::FLOAT10_ONE.clone();
  393. let two = constants::FLOAT10_TWO.clone();
  394. let field_p = Float10::from_str_native(constants::P)
  395. .unwrap()
  396. .with_precision(constants::RADIX_BITS)
  397. .value();
  398. let total_sigma =
  399. Float10::try_from(total_stake).unwrap().with_precision(constants::RADIX_BITS).value();
  400. let x = one - f;
  401. let c = x.ln();
  402. let sigma1_fbig = c.clone() / total_sigma.clone() * field_p.clone();
  403. let sigma1 = fbig2base(sigma1_fbig);
  404. let sigma2_fbig = (c / total_sigma).powf(two.clone()) * (field_p / two);
  405. let sigma2 = fbig2base(sigma2_fbig);
  406. (sigma1, sigma2)
  407. }
  408. /// Generate epoch-competing coins
  409. async fn create_epoch_coins(
  410. &self,
  411. eta: pallas::Base,
  412. epoch: u64,
  413. ) -> Result<Vec<Vec<LeadCoin>>> {
  414. info!("Consensus: Creating coins for epoch: {}", epoch);
  415. self.create_coins(eta).await
  416. }
  417. /// Generate coins for provided sigmas.
  418. /// NOTE: The strategy here is having a single competing coin per slot.
  419. async fn create_coins(&self, eta: pallas::Base) -> Result<Vec<Vec<LeadCoin>>> {
  420. let slot = self.current_slot();
  421. let mut rng = thread_rng();
  422. let mut seeds: Vec<u64> = Vec::with_capacity(constants::EPOCH_LENGTH);
  423. for _ in 0..constants::EPOCH_LENGTH {
  424. seeds.push(rng.gen());
  425. }
  426. let epoch_secrets = LeadCoinSecrets::generate();
  427. let mut tree_cm = BridgeTree::<MerkleNode, MERKLE_DEPTH>::new(constants::EPOCH_LENGTH);
  428. // LeadCoin matrix where each row represents a slot and contains its competing coins.
  429. let mut coins: Vec<Vec<LeadCoin>> = Vec::with_capacity(constants::EPOCH_LENGTH);
  430. // TODO: TESTNET: Here we would look into the wallet to find coins we're able to use.
  431. // The wallet has specific tables for consensus coins.
  432. // TODO: TESTNET: Token ID still has to be enforced properly in the consensus.
  433. // Temporarily, we compete with zero stake
  434. for i in 0..constants::EPOCH_LENGTH {
  435. let coin = LeadCoin::new(
  436. eta,
  437. constants::LOTTERY_HEAD_START, // TODO: TESTNET: Why is this constant being used?
  438. slot + i as u64,
  439. epoch_secrets.secret_keys[i].inner(),
  440. epoch_secrets.merkle_roots[i],
  441. i,
  442. epoch_secrets.merkle_paths[i],
  443. seeds[i],
  444. epoch_secrets.secret_keys[i],
  445. &mut tree_cm,
  446. );
  447. coins.push(vec![coin]);
  448. }
  449. Ok(coins)
  450. }
  451. /// leadership reward, assuming constant reward
  452. /// TODO (res) implement reward mechanism with accord to DRK,DARK token-economics
  453. fn reward() -> u64 {
  454. constants::REWARD
  455. }
  456. /// Auxillary function to receive current slot offset.
  457. /// If offset is None, its setted up as last block slot offset.
  458. fn get_current_offset(&mut self) -> u64 {
  459. // This is the case were we restarted our node, didn't receive offset from other nodes,
  460. // so we need to find offset from last block
  461. if self.consensus.offset.is_none() {
  462. let last = self.blockchain.get_last_offset().unwrap();
  463. info!("overall_empty_slots(): Setting slot offset: {}", last);
  464. self.consensus.offset = Some(last);
  465. }
  466. self.consensus.offset.unwrap()
  467. }
  468. /// Auxillary function to calculate overall empty slots.
  469. /// We keep an offset from genesis indicating when the first slot actually started.
  470. /// This offset is shared between nodes.
  471. fn overall_empty_slots(&mut self) -> u64 {
  472. let slot = self.current_slot();
  473. // Retrieve existing blocks excluding genesis
  474. let blocks = (self.blockchain.len() as u64) - 1;
  475. // Setup offset if only have genesis and havent received offset from other nodes
  476. if blocks == 0 && self.consensus.offset.is_none() {
  477. info!(
  478. "overall_empty_slots(): Blockchain contains only genesis, setting slot offset: {}",
  479. slot
  480. );
  481. self.consensus.offset = Some(slot);
  482. }
  483. slot - blocks - self.get_current_offset()
  484. }
  485. /// total stake plus one.
  486. /// assuming constant Reward.
  487. fn total_stake_plus(&mut self, epoch: u64, slot: u64) -> i64 {
  488. ((epoch * constants::EPOCH_LENGTH as u64 + slot + 1 - self.overall_empty_slots()) *
  489. Self::reward()) as i64
  490. }
  491. /// Calculate how many leaders existed in previous slot and appends
  492. /// it to history, to report it if win. On finalization sync period,
  493. /// node replaces its leaders history with the sequence extracted by
  494. /// the longest fork.
  495. fn extend_leaders_history(&mut self) -> Float10 {
  496. let slot = self.current_slot();
  497. let previous_slot = slot - 1;
  498. let mut count = 0;
  499. for chain in &self.consensus.proposals {
  500. // Previous slot proposals exist at end of each fork
  501. if chain.proposals.last().unwrap().block.header.slot == previous_slot {
  502. count += 1;
  503. }
  504. }
  505. self.consensus.leaders_history.push(count);
  506. debug!(
  507. "extend_leaders_history(): Current leaders history: {:?}",
  508. self.consensus.leaders_history
  509. );
  510. Float10::try_from(count as i64).unwrap().with_precision(constants::RADIX_BITS).value()
  511. }
  512. fn f_dif(&mut self) -> Float10 {
  513. let one = constants::FLOAT10_ONE.clone();
  514. one - self.extend_leaders_history()
  515. }
  516. fn f_der(&self) -> Float10 {
  517. let len = self.consensus.leaders_history.len();
  518. let last = Float10::try_from(self.consensus.leaders_history[len - 1] as i64)
  519. .unwrap()
  520. .with_precision(constants::RADIX_BITS)
  521. .value();
  522. let second_to_last = Float10::try_from(self.consensus.leaders_history[len - 2] as i64)
  523. .unwrap()
  524. .with_precision(constants::RADIX_BITS)
  525. .value();
  526. (last - second_to_last) / constants::TD.clone()
  527. }
  528. fn f_int(&self) -> Float10 {
  529. let mut sum = constants::FLOAT10_ZERO.clone();
  530. for f in &self.consensus.leaders_history {
  531. sum += f.clone() * constants::TD.clone();
  532. }
  533. sum
  534. }
  535. /// the probability of winnig lottery having all the stake
  536. /// returns f
  537. fn win_prob_with_full_stake(&mut self) -> Float10 {
  538. let zero = constants::FLOAT10_ZERO.clone();
  539. let one = constants::FLOAT10_ONE.clone();
  540. let p = self.f_dif();
  541. let i = self.f_int();
  542. let d = self.f_der();
  543. let mut f = self.consensus.kp.clone() *
  544. (p.clone() +
  545. one.clone() / constants::TI.clone() * i.clone() +
  546. constants::TD.clone() * d.clone());
  547. while f <= zero.clone() || f >= one.clone() {
  548. let mut clipped_f = f;
  549. if clipped_f >=one {
  550. clipped_f = one - constants::PID_OUT_STEP;
  551. } else if clipped_f<=zero {
  552. clipped_f = zero + constants::PID_OUT_STEP;
  553. }
  554. let clipped_kp = clipped_f /
  555. (p.clone() +
  556. one.clone() / constants::TI.clone() * i.clone() +
  557. constants::TD.clone() * d.clone());
  558. self.consensus.kp = clipped_kp.clone();
  559. f = clipped_kp *
  560. (p.clone() +
  561. one.clone() / constants::TI.clone() * i.clone() +
  562. constants::TD.clone() * d.clone());
  563. info!("Consensus::win_prob_with_full_stake(): f: {}", f);
  564. }
  565. info!("Consensus::win_prob_with_full_stake(): last f: {}", f);
  566. f
  567. }
  568. /// Check that the provided participant/stakeholder coins win the slot lottery.
  569. /// If the stakeholder has multiple competing winning coins, only the highest value
  570. /// coin is selected, since the stakeholder can't give more than one proof per block/slot.
  571. /// * 'sigma1', 'sigma2': slot sigmas
  572. /// Returns: (check: bool, idx: usize) where idx is the winning coin's index
  573. pub fn is_slot_leader(&mut self, sigma1: pallas::Base, sigma2: pallas::Base) -> (bool, usize) {
  574. // Slot relative index
  575. let slot = self.relative_slot(self.current_slot());
  576. // Stakeholder's epoch coins
  577. let coins = &self.consensus.coins;
  578. info!("Consensus::is_leader(): slot: {}, coins len: {}", slot, coins.len());
  579. assert!((slot as usize) < coins.len());
  580. let competing_coins = &coins[slot as usize];
  581. let mut won = false;
  582. let mut highest_stake = 0;
  583. let mut highest_stake_idx = 0;
  584. for (winning_idx, coin) in competing_coins.iter().enumerate() {
  585. let first_winning = coin.is_leader(sigma1, sigma2);
  586. if first_winning && !won {
  587. highest_stake_idx = winning_idx;
  588. }
  589. won |= first_winning;
  590. if won && coin.value > highest_stake {
  591. highest_stake = coin.value;
  592. highest_stake_idx = winning_idx;
  593. }
  594. }
  595. (won, highest_stake_idx)
  596. }
  597. /// Generate a block proposal for the current slot, containing all
  598. /// unconfirmed transactions. Proposal extends the longest fork
  599. /// chain the node is holding.
  600. pub fn propose(
  601. &mut self,
  602. idx: usize,
  603. sigma1: pallas::Base,
  604. sigma2: pallas::Base,
  605. ) -> Result<Option<BlockProposal>> {
  606. let slot = self.current_slot();
  607. let (prev_hash, index) = self.longest_chain_last_hash().unwrap();
  608. let unproposed_txs = self.unproposed_txs(index);
  609. // TODO: [PLACEHOLDER] Create and add rewards transaction
  610. let mut tree = BridgeTree::<MerkleNode, MERKLE_DEPTH>::new(100);
  611. // The following is pretty weird, so something better should be done.
  612. for tx in &unproposed_txs {
  613. let mut hash = [0_u8; 32];
  614. hash[0..31].copy_from_slice(&blake3::hash(&serialize(tx)).as_bytes()[0..31]);
  615. tree.append(&MerkleNode::from(pallas::Base::from_repr(hash).unwrap()));
  616. }
  617. let root = tree.root(0).unwrap();
  618. let eta = self.consensus.epoch_eta;
  619. // Generating leader proof
  620. let relative_slot = self.relative_slot(slot) as usize;
  621. let coin = self.consensus.coins[relative_slot][idx];
  622. let proof =
  623. coin.create_lead_proof(sigma1, sigma2, self.lead_proving_key.as_ref().unwrap())?;
  624. // Signing using coin
  625. let secret_key = coin.secret_key;
  626. let header =
  627. Header::new(prev_hash, self.slot_epoch(slot), slot, Timestamp::current_time(), root);
  628. let signed_proposal = secret_key.sign(&mut OsRng, &header.headerhash().as_bytes()[..]);
  629. let public_key = PublicKey::from_secret(secret_key);
  630. let lead_info = LeadInfo::new(
  631. signed_proposal,
  632. public_key,
  633. coin.public_inputs(sigma1, sigma2),
  634. eta.to_repr(),
  635. LeadProof::from(proof),
  636. self.get_current_offset(),
  637. self.consensus.leaders_history.last().unwrap().clone(),
  638. );
  639. // Replacing old coin with the derived coin
  640. // TODO: do we need that? on next epoch we replace everything
  641. // how is this going to get reused?
  642. self.consensus.coins[relative_slot][idx] = coin.derive_coin();
  643. Ok(Some(BlockProposal::new(header, unproposed_txs, lead_info)))
  644. }
  645. /// Retrieve all unconfirmed transactions not proposed in previous blocks
  646. /// of provided index chain.
  647. pub fn unproposed_txs(&self, index: i64) -> Vec<Transaction> {
  648. let mut unproposed_txs = self.unconfirmed_txs.clone();
  649. // If index is -1 (canonical blockchain) a new fork will be generated,
  650. // therefore all unproposed transactions can be included in the proposal.
  651. if index == -1 {
  652. return unproposed_txs
  653. }
  654. // We iterate over the fork chain proposals to find already proposed
  655. // transactions and remove them from the local unproposed_txs vector.
  656. let chain = &self.consensus.proposals[index as usize];
  657. for proposal in &chain.proposals {
  658. for tx in &proposal.block.txs {
  659. if let Some(pos) = unproposed_txs.iter().position(|txs| *txs == *tx) {
  660. unproposed_txs.remove(pos);
  661. }
  662. }
  663. }
  664. unproposed_txs
  665. }
  666. /// Finds the longest blockchain the node holds and
  667. /// returns the last block hash and the chain index.
  668. pub fn longest_chain_last_hash(&self) -> Result<(blake3::Hash, i64)> {
  669. let mut longest: Option<ProposalChain> = None;
  670. let mut length = 0;
  671. let mut index = -1;
  672. if !self.consensus.proposals.is_empty() {
  673. for (i, chain) in self.consensus.proposals.iter().enumerate() {
  674. if chain.proposals.len() > length {
  675. longest = Some(chain.clone());
  676. length = chain.proposals.len();
  677. index = i as i64;
  678. }
  679. }
  680. }
  681. let hash = match longest {
  682. Some(chain) => chain.proposals.last().unwrap().hash,
  683. None => self.blockchain.last()?.1,
  684. };
  685. Ok((hash, index))
  686. }
  687. /// Given a proposal, the node verify its sender (slot leader) and finds which blockchain
  688. /// it extends. If the proposal extends the canonical blockchain, a new fork chain is created.
  689. pub async fn receive_proposal(&mut self, proposal: &BlockProposal) -> Result<()> {
  690. let current = self.current_slot();
  691. // Node hasn't started participating
  692. match self.consensus.participating {
  693. Some(start) => {
  694. if current < start {
  695. return Ok(())
  696. }
  697. }
  698. None => return Ok(()),
  699. }
  700. // Node have already checked for finalization in this slot
  701. if current <= self.consensus.checked_finalization {
  702. warn!("receive_proposal(): Proposal received after finalization sync period.");
  703. return Err(Error::ProposalAfterFinalizationError)
  704. }
  705. let lf = &proposal.block.lead_info;
  706. let hdr = &proposal.block.header;
  707. // Verify proposal signature is valid based on producer public key
  708. // TODO: derive public key from proof
  709. if !lf.public_key.verify(proposal.header.as_bytes(), &lf.signature) {
  710. warn!("receive_proposal(): Proposer {} signature could not be verified", lf.public_key);
  711. return Err(Error::InvalidSignature)
  712. }
  713. // Check if proposal hash matches actual one
  714. let proposal_hash = proposal.block.blockhash();
  715. if proposal.hash != proposal_hash {
  716. warn!(
  717. "receive_proposal(): Received proposal contains mismatched hashes: {} - {}",
  718. proposal.hash, proposal_hash
  719. );
  720. return Err(Error::ProposalHashesMissmatchError)
  721. }
  722. // Check if proposal header matches actual one
  723. let proposal_header = hdr.headerhash();
  724. if proposal.header != proposal_header {
  725. warn!(
  726. "receive_proposal(): Received proposal contains mismatched headers: {} - {}",
  727. proposal.header, proposal_header
  728. );
  729. return Err(Error::ProposalHeadersMissmatchError)
  730. }
  731. // Verify proposal offset
  732. let offset = self.get_current_offset();
  733. if offset != lf.offset {
  734. warn!(
  735. "receive_proposal(): Received proposal contains different offset: {} - {}",
  736. offset, lf.offset
  737. );
  738. return Err(Error::ProposalDifferentOffsetError)
  739. }
  740. // Verify proposal leader proof
  741. if let Err(e) = lf.proof.verify(&self.lead_verifying_key, &lf.public_inputs) {
  742. error!("receive_proposal(): Error during leader proof verification: {}", e);
  743. return Err(Error::LeaderProofVerification)
  744. };
  745. info!("receive_proposal(): Leader proof verified successfully!");
  746. // Verify proposal public values
  747. let (mu_y, mu_rho) =
  748. LeadCoin::election_seeds_u64(self.consensus.epoch_eta, proposal.block.header.slot);
  749. // y
  750. let prop_mu_y = lf.public_inputs[constants::PI_MU_Y_INDEX];
  751. if mu_y != prop_mu_y {
  752. error!(
  753. "receive_proposal(): Failed to verify mu_y: {:?}, proposed: {:?}",
  754. mu_y, prop_mu_y
  755. );
  756. return Err(Error::ProposalPublicValuesMismatched)
  757. }
  758. // rho
  759. let prop_mu_rho = lf.public_inputs[constants::PI_MU_RHO_INDEX];
  760. if mu_rho != prop_mu_rho {
  761. error!(
  762. "receive_proposal(): Failed to verify mu_rho: {:?}, proposed: {:?}",
  763. mu_rho, prop_mu_rho
  764. );
  765. return Err(Error::ProposalPublicValuesMismatched)
  766. }
  767. // sigma1
  768. let prop_sigma1 = lf.public_inputs[constants::PI_SIGMA1_INDEX];
  769. if self.consensus.prev_sigma1 != prop_sigma1 {
  770. error!(
  771. "receive_proposal(): Failed to verify public value sigma1: {:?}, to proposed: {:?}",
  772. self.consensus.prev_sigma1, prop_sigma1
  773. );
  774. }
  775. // sigma2
  776. let prop_sigma2 = lf.public_inputs[constants::PI_SIGMA2_INDEX];
  777. if self.consensus.prev_sigma2 != prop_sigma2 {
  778. error!(
  779. "receive_proposal(): Failed to verify public value sigma2: {:?}, to proposed: {:?}",
  780. self.consensus.prev_sigma2, prop_sigma2
  781. );
  782. }
  783. // sn
  784. let prop_sn = lf.public_inputs[constants::PI_NULLIFIER_INDEX];
  785. for sn in &self.consensus.leaders_nullifiers {
  786. if *sn == prop_sn {
  787. error!("receive_proposal(): Proposal nullifiers exist.");
  788. return Err(Error::ProposalIsSpent)
  789. }
  790. }
  791. // cm
  792. let prop_cm_x: pallas::Base = lf.public_inputs[constants::PI_COMMITMENT_X_INDEX];
  793. let prop_cm_y: pallas::Base = lf.public_inputs[constants::PI_COMMITMENT_Y_INDEX];
  794. for cm in &self.consensus.leaders_spent_coins {
  795. if *cm == (prop_cm_x, prop_cm_y) {
  796. error!("receive_proposal(): Proposal coin already spent.");
  797. return Err(Error::ProposalIsSpent)
  798. }
  799. }
  800. // Check if proposal extends any existing fork chains
  801. let index = self.find_extended_chain_index(proposal)?;
  802. if index == -2 {
  803. return Err(Error::ExtendedChainIndexNotFound)
  804. }
  805. // Validate state transition against canonical state
  806. // TODO: This should be validated against fork state
  807. debug!("receive_proposal(): Starting state transition validation");
  808. if let Err(e) = self.verify_transactions(&proposal.block.txs, false).await {
  809. error!("receive_proposal(): Transaction verifications failed: {}", e);
  810. return Err(e.into())
  811. };
  812. // TODO: [PLACEHOLDER] Add rewards validation
  813. // Extend corresponding chain
  814. match index {
  815. -1 => {
  816. let pc = ProposalChain::new(self.consensus.genesis_block, proposal.clone());
  817. self.consensus.proposals.push(pc);
  818. }
  819. _ => {
  820. self.consensus.proposals[index as usize].add(proposal);
  821. }
  822. };
  823. // Store proposal coin info
  824. self.consensus.leaders_nullifiers.push(prop_sn);
  825. self.consensus.leaders_spent_coins.push((prop_cm_x, prop_cm_y));
  826. Ok(())
  827. }
  828. /// Given a proposal, find the index of the fork chain it extends.
  829. pub fn find_extended_chain_index(&mut self, proposal: &BlockProposal) -> Result<i64> {
  830. // We iterate through all forks to find which fork to extend
  831. let mut chain_index = -1;
  832. let mut prop_index = 0;
  833. for (c_index, chain) in self.consensus.proposals.iter().enumerate() {
  834. // Traverse proposals in reverse
  835. for (p_index, prop) in chain.proposals.iter().enumerate().rev() {
  836. if proposal.block.header.previous == prop.hash {
  837. chain_index = c_index as i64;
  838. prop_index = p_index;
  839. break
  840. }
  841. }
  842. if chain_index != -1 {
  843. break
  844. }
  845. }
  846. // If no fork was found, we check with canonical
  847. if chain_index == -1 {
  848. let (last_slot, last_block) = self.blockchain.last()?;
  849. if proposal.block.header.previous != last_block ||
  850. proposal.block.header.slot <= last_slot
  851. {
  852. debug!("find_extended_chain_index(): Proposal doesn't extend any known chain");
  853. return Ok(-2)
  854. }
  855. // Proposal extends canonical chain
  856. return Ok(-1)
  857. }
  858. // Found fork chain
  859. let chain = &self.consensus.proposals[chain_index as usize];
  860. // Proposal extends fork at last proposal
  861. if prop_index == (chain.proposals.len() - 1) {
  862. return Ok(chain_index)
  863. }
  864. debug!("find_extended_chain_index(): Proposal to fork a forkchain was received.");
  865. let mut chain = self.consensus.proposals[chain_index as usize].clone();
  866. // We keep all proposals until the one it extends
  867. chain.proposals.drain((prop_index + 1)..);
  868. self.consensus.proposals.push(chain);
  869. Ok(self.consensus.proposals.len() as i64 - 1)
  870. }
  871. /// Search the chains we're holding for the given proposal.
  872. pub fn proposal_exists(&self, input_proposal: &blake3::Hash) -> bool {
  873. for chain in self.consensus.proposals.iter() {
  874. for proposal in chain.proposals.iter() {
  875. if input_proposal == &proposal.hash {
  876. return true
  877. }
  878. }
  879. }
  880. false
  881. }
  882. /// Remove provided transactions vector from unconfirmed_txs if they exist.
  883. pub fn remove_txs(&mut self, transactions: &Vec<Transaction>) -> Result<()> {
  884. for tx in transactions {
  885. if let Some(pos) = self.unconfirmed_txs.iter().position(|txs| txs == tx) {
  886. self.unconfirmed_txs.remove(pos);
  887. }
  888. }
  889. Ok(())
  890. }
  891. /// Auxillary function to set nodes leaders count history to the largest fork sequence
  892. /// of leaders, by using provided index.
  893. fn set_leader_history(&mut self, index: i64) {
  894. // Check if we found longest fork to extract sequence from
  895. match index {
  896. -1 => {
  897. debug!("set_leader_history(): No fork exists.");
  898. }
  899. _ => {
  900. debug!("set_leader_history(): Checking last proposal of fork: {}", index);
  901. let last_proposal =
  902. self.consensus.proposals[index as usize].proposals.last().unwrap();
  903. if last_proposal.block.header.slot == self.current_slot() {
  904. // Replacing our last history element with the leaders one
  905. self.consensus.leaders_history.pop();
  906. self.consensus.leaders_history.push(last_proposal.block.lead_info.leaders);
  907. debug!(
  908. "set_leader_history(): New leaders history: {:?}",
  909. self.consensus.leaders_history
  910. );
  911. return
  912. }
  913. }
  914. }
  915. self.consensus.leaders_history.push(0);
  916. }
  917. /// Node checks if any of the fork chains can be finalized.
  918. /// Consensus finalization logic:
  919. /// - If the node has observed the creation of 3 proposals in a fork chain and no other
  920. /// forks exists at same or greater height, it finalizes (appends to canonical blockchain)
  921. /// all proposals up to the last one.
  922. /// When fork chain proposals are finalized, the rest of fork chains are removed.
  923. pub async fn chain_finalization(&mut self) -> Result<Vec<BlockInfo>> {
  924. let slot = self.current_slot();
  925. debug!("chain_finalization(): Started finalization check for slot: {}", slot);
  926. // Set last slot finalization check occured to current slot
  927. self.consensus.checked_finalization = slot;
  928. // First we find longest chain without any other forks at same height
  929. let mut chain_index = -1;
  930. // Use this index to extract leaders count sequence from longest fork
  931. let mut index_for_history = -1;
  932. let mut max_length = 0;
  933. for (index, chain) in self.consensus.proposals.iter().enumerate() {
  934. let length = chain.proposals.len();
  935. // Check if greater than max to retain index for history
  936. if length > max_length {
  937. index_for_history = index as i64;
  938. }
  939. // Ignore forks with less that 3 blocks
  940. if length < 3 {
  941. continue
  942. }
  943. // Check if less than max
  944. if length < max_length {
  945. continue
  946. }
  947. // Check if same length as max
  948. if length == max_length {
  949. // Setting chain_index so we know we have multiple
  950. // forks at same length.
  951. chain_index = -2;
  952. continue
  953. }
  954. // Set chain as max
  955. chain_index = index as i64;
  956. max_length = length;
  957. }
  958. // Check if we found any fork to finalize
  959. match chain_index {
  960. -2 => {
  961. debug!("chain_finalization(): Eligible forks with same height exist, nothing to finalize.");
  962. self.set_leader_history(index_for_history);
  963. return Ok(vec![])
  964. }
  965. -1 => {
  966. debug!("chain_finalization(): All chains have less than 3 proposals, nothing to finalize.");
  967. self.set_leader_history(index_for_history);
  968. return Ok(vec![])
  969. }
  970. _ => debug!("chain_finalization(): Chain {} can be finalized!", chain_index),
  971. }
  972. // Starting finalization
  973. let mut chain = self.consensus.proposals[chain_index as usize].clone();
  974. // Retrieving proposals to finalize
  975. let bound = max_length - 1;
  976. let mut finalized: Vec<BlockInfo> = vec![];
  977. for proposal in &chain.proposals[..bound] {
  978. finalized.push(proposal.clone().into());
  979. }
  980. // Removing finalized proposals from chain
  981. chain.proposals.drain(..bound);
  982. // Adding finalized proposals to canonical
  983. info!("consensus: Adding {} finalized block to canonical chain.", finalized.len());
  984. match self.blockchain.add(&finalized) {
  985. Ok(v) => v,
  986. Err(e) => {
  987. error!("consensus: Failed appending finalized blocks to canonical chain: {}", e);
  988. return Err(e)
  989. }
  990. };
  991. let blocks_subscriber = self.subscribers.get("blocks").unwrap().clone();
  992. // Validating state transitions
  993. for proposal in &finalized {
  994. // TODO: Is this the right place? We're already doing this in protocol_sync.
  995. // TODO: These state transitions have already been checked. (I wrote this, but where?)
  996. // TODO: FIXME: The state transitions have already been written, they have to be in memory
  997. // until this point.
  998. debug!(target: "consensus", "Applying state transition for finalized block");
  999. if let Err(e) = self.verify_transactions(&proposal.txs, true).await {
  1000. error!(target: "consensus", "Finalized block transaction verifications failed: {}", e);
  1001. return Err(e)
  1002. }
  1003. // Remove proposal transactions from memory pool
  1004. if let Err(e) = self.remove_txs(&proposal.txs) {
  1005. error!(target: "consensus", "Removing finalized block transactions failed: {}", e);
  1006. return Err(e)
  1007. }
  1008. // TODO: Don't hardcode this:
  1009. let params = json!([bs58::encode(&serialize(proposal)).into_string()]);
  1010. let notif = JsonNotification::new("blockchain.subscribe_blocks", params);
  1011. info!("consensus: Sending notification about finalized block");
  1012. blocks_subscriber.notify(notif).await;
  1013. }
  1014. // Setting leaders history to last proposal leaders count
  1015. self.consensus.leaders_history =
  1016. vec![chain.proposals.last().unwrap().block.lead_info.leaders];
  1017. // Removing rest forks
  1018. self.consensus.proposals = vec![];
  1019. self.consensus.proposals.push(chain);
  1020. Ok(finalized)
  1021. }
  1022. /// Utility function to extract leader selection lottery randomness(eta),
  1023. /// defined as the hash of the previous lead proof converted to pallas base.
  1024. fn get_eta(&self) -> pallas::Base {
  1025. let proof_tx_hash = self.blockchain.get_last_proof_hash().unwrap();
  1026. let mut bytes: [u8; 32] = *proof_tx_hash.as_bytes();
  1027. // read first 254 bits
  1028. bytes[30] = 0;
  1029. bytes[31] = 0;
  1030. pallas::Base::from_repr(bytes).unwrap()
  1031. }
  1032. // ==========================
  1033. // State transition functions
  1034. // ==========================
  1035. // TODO TESTNET: Write down all cases below
  1036. // State transition checks should be happening in the following cases for a sync node:
  1037. // 1) When a finalized block is received
  1038. // 2) When a transaction is being broadcasted to us
  1039. // State transition checks should be happening in the following cases for a consensus participating node:
  1040. // 1) When a finalized block is received
  1041. // 2) When a transaction is being broadcasted to us
  1042. // ==========================
  1043. /// Validate and append to canonical state received blocks.
  1044. pub async fn receive_blocks(&mut self, blocks: &[BlockInfo]) -> Result<()> {
  1045. // Verify state transitions for all blocks and their respective transactions.
  1046. debug!("receive_blocks(): Starting state transition validations");
  1047. for block in blocks {
  1048. if let Err(e) = self.verify_transactions(&block.txs, false).await {
  1049. error!("receive_blocks(): Transaction verifications failed: {}", e);
  1050. return Err(e)
  1051. }
  1052. }
  1053. debug!("receive_blocks(): All state transitions passed");
  1054. debug!("receive_blocks(): Appending blocks to ledger");
  1055. self.blockchain.add(blocks)?;
  1056. Ok(())
  1057. }
  1058. /// Validate and append to canonical state received finalized block.
  1059. /// Returns boolean flag indicating already existing block.
  1060. pub async fn receive_finalized_block(&mut self, block: BlockInfo) -> Result<bool> {
  1061. match self.blockchain.has_block(&block) {
  1062. Ok(v) => {
  1063. if v {
  1064. debug!("receive_finalized_block(): Existing block received");
  1065. return Ok(false)
  1066. }
  1067. }
  1068. Err(e) => {
  1069. error!("receive_finalized_block(): failed checking for has_block(): {}", e);
  1070. return Ok(false)
  1071. }
  1072. };
  1073. debug!("receive_finalized_block(): Executing state transitions");
  1074. self.receive_blocks(&[block.clone()]).await?;
  1075. // TODO: Don't hardcode this:
  1076. let blocks_subscriber = self.subscribers.get("blocks").unwrap();
  1077. let params = json!([bs58::encode(&serialize(&block)).into_string()]);
  1078. let notif = JsonNotification::new("blockchain.subscribe_blocks", params);
  1079. info!("consensus: Sending notification about finalized block");
  1080. blocks_subscriber.notify(notif).await;
  1081. debug!("receive_finalized_block(): Removing block transactions from unconfirmed_txs");
  1082. self.remove_txs(&block.txs)?;
  1083. Ok(true)
  1084. }
  1085. /// Validate and append to canonical state received finalized blocks from block sync task.
  1086. /// Already existing blocks are ignored.
  1087. pub async fn receive_sync_blocks(&mut self, blocks: &[BlockInfo]) -> Result<()> {
  1088. let mut new_blocks = vec![];
  1089. for block in blocks {
  1090. match self.blockchain.has_block(block) {
  1091. Ok(v) => {
  1092. if v {
  1093. debug!("receive_sync_blocks(): Existing block received");
  1094. continue
  1095. }
  1096. new_blocks.push(block.clone());
  1097. }
  1098. Err(e) => {
  1099. error!("receive_sync_blocks(): failed checking for has_block(): {}", e);
  1100. continue
  1101. }
  1102. };
  1103. }
  1104. if new_blocks.is_empty() {
  1105. debug!("receive_sync_blocks(): no new blocks to append");
  1106. return Ok(())
  1107. }
  1108. debug!("receive_sync_blocks(): Executing state transitions");
  1109. self.receive_blocks(&new_blocks[..]).await?;
  1110. // TODO: Don't hardcode this:
  1111. let blocks_subscriber = self.subscribers.get("blocks").unwrap();
  1112. for block in new_blocks {
  1113. let params = json!([bs58::encode(&serialize(&block)).into_string()]);
  1114. let notif = JsonNotification::new("blockchain.subscribe_blocks", params);
  1115. info!("consensus: Sending notification about finalized block");
  1116. blocks_subscriber.notify(notif).await;
  1117. }
  1118. Ok(())
  1119. }
  1120. /// Validate signatures, wasm execution, and zk proofs for given transactions.
  1121. /// If all of those succeed, try to execute a state update for the contract calls.
  1122. /// Currently the verifications are sequential, and the function will fail if any
  1123. /// of the verifications fail.
  1124. /// The function takes a boolean called `write` which tells it to actually write
  1125. /// the state transitions to the database.
  1126. // TODO: This should be paralellized as if even one tx in the batch fails to verify,
  1127. // we can drop everything.
  1128. pub async fn verify_transactions(&self, txs: &[Transaction], write: bool) -> Result<()> {
  1129. debug!("Verifying {} transaction(s)", txs.len());
  1130. for tx in txs {
  1131. let tx_hash = blake3::hash(&serialize(tx));
  1132. debug!("Verifying transaction {}", tx_hash);
  1133. // Table of public inputs used for ZK proof verification
  1134. let mut zkp_table = vec![];
  1135. // Table of public keys used for signature verification
  1136. let mut sig_table = vec![];
  1137. // State updates produced by contract execcution
  1138. let mut updates = vec![];
  1139. // Iterate over all calls to get the metadata
  1140. for (idx, call) in tx.calls.iter().enumerate() {
  1141. debug!("Executing contract call {}", idx);
  1142. let wasm = match self.blockchain.wasm_bincode.get(call.contract_id) {
  1143. Ok(v) => {
  1144. debug!("Found wasm bincode for {}", call.contract_id);
  1145. v
  1146. }
  1147. Err(e) => {
  1148. error!(
  1149. "Could not find wasm bincode for contract {}: {}",
  1150. call.contract_id, e
  1151. );
  1152. return Err(Error::ContractNotFound(call.contract_id.to_string()))
  1153. }
  1154. };
  1155. // Write the actual payload data
  1156. let mut payload = vec![];
  1157. payload.write_u32(idx as u32)?; // Call index
  1158. tx.calls.encode(&mut payload)?; // Actual call data
  1159. // Instantiate the wasm runtime
  1160. let mut runtime =
  1161. match Runtime::new(&wasm, self.blockchain.clone(), call.contract_id) {
  1162. Ok(v) => v,
  1163. Err(e) => {
  1164. error!(
  1165. "Failed to instantiate WASM runtime for contract {}",
  1166. call.contract_id
  1167. );
  1168. return Err(e.into())
  1169. }
  1170. };
  1171. debug!("Executing \"metadata\" call");
  1172. let metadata = match runtime.metadata(&payload) {
  1173. Ok(v) => v,
  1174. Err(e) => {
  1175. error!("Failed to execute \"metadata\" call: {}", e);
  1176. return Err(e.into())
  1177. }
  1178. };
  1179. // Decode the metadata retrieved from the execution
  1180. let mut decoder = Cursor::new(&metadata);
  1181. let zkp_pub: Vec<(String, Vec<pallas::Base>)> =
  1182. match Decodable::decode(&mut decoder) {
  1183. Ok(v) => v,
  1184. Err(e) => {
  1185. error!("Failed to decode ZK public inputs from metadata: {}", e);
  1186. return Err(e.into())
  1187. }
  1188. };
  1189. let sig_pub: Vec<PublicKey> = match Decodable::decode(&mut decoder) {
  1190. Ok(v) => v,
  1191. Err(e) => {
  1192. error!("Failed to decode signature pubkeys from metadata: {}", e);
  1193. return Err(e.into())
  1194. }
  1195. };
  1196. // TODO: Make sure we've read all the bytes above.
  1197. debug!("Successfully executed \"metadata\" call");
  1198. zkp_table.push(zkp_pub);
  1199. sig_table.push(sig_pub);
  1200. // After getting the metadata, we run the "exec" function with the same
  1201. // runtime and the same payload.
  1202. debug!("Executing \"exec\" call");
  1203. match runtime.exec(&payload) {
  1204. Ok(v) => {
  1205. debug!("Successfully executed \"exec\" call");
  1206. updates.push(v);
  1207. }
  1208. Err(e) => {
  1209. error!(
  1210. "Failed to execute \"exec\" call for contract id {}: {}",
  1211. call.contract_id, e
  1212. );
  1213. return Err(e.into())
  1214. }
  1215. };
  1216. // At this point we're done with the call and move on to the next one.
  1217. }
  1218. // When we're done looping and executing over the tx's contract calls, we
  1219. // move on with verification. First we verify the signatures as that's
  1220. // cheaper, and then finally we verify the ZK proofs.
  1221. debug!("Verifying signatures for transaction {}", tx_hash);
  1222. match tx.verify_sigs(sig_table) {
  1223. Ok(()) => debug!("Signatures verification for tx {} successful", tx_hash),
  1224. Err(e) => {
  1225. error!("Signature verification for tx {} failed: {}", tx_hash, e);
  1226. return Err(e.into())
  1227. }
  1228. };
  1229. // NOTE: When it comes to the ZK proofs, we first do a lookup of the
  1230. // verifying keys, but if we do not find them, we'll generate them
  1231. // inside of this function. This can be kinda expensive, so open to
  1232. // alternatives.
  1233. debug!("Verifying ZK proofs for transaction {}", tx_hash);
  1234. match tx.verify_zkps(self.verifying_keys.clone(), zkp_table).await {
  1235. Ok(()) => debug!("ZK proof verification for tx {} successful", tx_hash),
  1236. Err(e) => {
  1237. error!("ZK proof verrification for tx {} failed: {}", tx_hash, e);
  1238. return Err(e.into())
  1239. }
  1240. };
  1241. // After the verifications stage passes, if we're told to write, we
  1242. // apply the state updates.
  1243. assert!(tx.calls.len() == updates.len());
  1244. if write {
  1245. debug!("Performing state updates");
  1246. for (call, update) in tx.calls.iter().zip(updates.iter()) {
  1247. // For this we instantiate the runtimes again.
  1248. // TODO: Optimize this
  1249. // TODO: Sum up the gas costs of previous calls during execution
  1250. // and verification and these.
  1251. let wasm = match self.blockchain.wasm_bincode.get(call.contract_id) {
  1252. Ok(v) => {
  1253. debug!("Found wasm bincode for {}", call.contract_id);
  1254. v
  1255. }
  1256. Err(e) => {
  1257. error!(
  1258. "Could not find wasm bincode for contract {}: {}",
  1259. call.contract_id, e
  1260. );
  1261. return Err(Error::ContractNotFound(call.contract_id.to_string()))
  1262. }
  1263. };
  1264. let mut runtime =
  1265. match Runtime::new(&wasm, self.blockchain.clone(), call.contract_id) {
  1266. Ok(v) => v,
  1267. Err(e) => {
  1268. error!(
  1269. "Failed to instantiate WASM runtime for contract {}",
  1270. call.contract_id
  1271. );
  1272. return Err(e.into())
  1273. }
  1274. };
  1275. debug!("Executing \"apply\" call");
  1276. match runtime.apply(&update) {
  1277. // TODO: FIXME: This should be done in an atomic tx/batch
  1278. Ok(()) => debug!("State update applied successfully"),
  1279. Err(e) => {
  1280. error!("Failed to apply state update: {}", e);
  1281. return Err(e.into())
  1282. }
  1283. };
  1284. }
  1285. } else {
  1286. debug!("Skipping apply of state updates because write=false");
  1287. }
  1288. debug!("Transaction {} verified successfully", tx_hash);
  1289. }
  1290. Ok(())
  1291. }
  1292. }