diff --git a/src/consensus/block.rs b/src/consensus/block.rs index 6327a35a8..c7d74f0da 100644 --- a/src/consensus/block.rs +++ b/src/consensus/block.rs @@ -24,7 +24,10 @@ use incrementalmerkletree::{bridgetree::BridgeTree, Tree}; use log::debug; use pasta_curves::pallas; -use super::{Metadata, BLOCK_MAGIC_BYTES, BLOCK_VERSION}; +use super::{ + constants::{BLOCK_MAGIC_BYTES, BLOCK_VERSION}, + Metadata, +}; use crate::{net, tx::Transaction, util::time::Timestamp}; /// This struct represents a tuple of the form (version, previous, epoch, slot, timestamp, merkle_root). @@ -52,7 +55,7 @@ impl Header { timestamp: Timestamp, root: MerkleNode, ) -> Self { - let version = *BLOCK_VERSION; + let version = BLOCK_VERSION; Self { version, previous, epoch, slot, timestamp, root } } @@ -112,7 +115,7 @@ impl Block { root: MerkleNode, metadata: Metadata, ) -> Self { - let magic = *BLOCK_MAGIC_BYTES; + let magic = BLOCK_MAGIC_BYTES; let timestamp = Timestamp::current_time(); let header = Header::new(previous, epoch, slot, timestamp, root); let header = header.headerhash(); @@ -121,7 +124,7 @@ impl Block { /// Generate the genesis block. pub fn genesis_block(genesis_ts: Timestamp, genesis_data: blake3::Hash) -> Self { - let magic = *BLOCK_MAGIC_BYTES; + let magic = BLOCK_MAGIC_BYTES; let header = Header::genesis_header(genesis_ts, genesis_data); let header = header.headerhash(); let metadata = Metadata::default(); @@ -164,7 +167,7 @@ pub struct BlockInfo { impl Default for BlockInfo { fn default() -> Self { - let magic = *BLOCK_MAGIC_BYTES; + let magic = BLOCK_MAGIC_BYTES; Self { magic, header: Header::default(), txs: vec![], metadata: Metadata::default() } } } @@ -177,7 +180,7 @@ impl net::Message for BlockInfo { impl BlockInfo { pub fn new(header: Header, txs: Vec, metadata: Metadata) -> Self { - let magic = *BLOCK_MAGIC_BYTES; + let magic = BLOCK_MAGIC_BYTES; Self { magic, header, txs, metadata } } diff --git a/src/consensus/coins.rs b/src/consensus/coins.rs index de549b475..806dc7a8e 100644 --- a/src/consensus/coins.rs +++ b/src/consensus/coins.rs @@ -37,8 +37,10 @@ use log::info; use rand::{rngs::OsRng, thread_rng, Rng}; use super::{ - leadcoin::LeadCoin, utils::fbig2base, Float10, EPOCH_LENGTH, LOTTERY_HEAD_START, P, RADIX_BITS, - REWARD, + constants::{EPOCH_LENGTH, LOTTERY_HEAD_START, P, RADIX_BITS, REWARD}, + leadcoin::LeadCoin, + utils::fbig2base, + Float10, }; use crate::{ crypto::{ @@ -55,16 +57,16 @@ const MERKLE_DEPTH: u8 = MERKLE_DEPTH_ORCHARD as u8; /// Retrieve previous epoch competing coins frequency. fn get_frequency() -> Float10 { //TODO: Actually retrieve frequency of coins from the previous epoch. - let one: Float10 = Float10::from_str_native("1").unwrap().with_precision(*RADIX_BITS).value(); - let two: Float10 = Float10::from_str_native("2").unwrap().with_precision(*RADIX_BITS).value(); + let one: Float10 = Float10::from_str_native("1").unwrap().with_precision(RADIX_BITS).value(); + let two: Float10 = Float10::from_str_native("2").unwrap().with_precision(RADIX_BITS).value(); one / two } /// Calculate nodes total stake for specific epoch and slot. fn total_stake(_epoch: u64, _slot: u64) -> u64 { // TODO: fix this - //(epoch * *EPOCH_LENGTH + slot + 1) * *REWARD - *REWARD + //(epoch * EPOCH_LENGTH + slot + 1) * REWARD + REWARD } /// Generate epoch competing coins. @@ -77,16 +79,16 @@ pub fn create_epoch_coins( info!("Creating coins for epoch: {}", epoch); // Retrieve previous epoch competing coins frequency - let frequency = get_frequency().with_precision(*RADIX_BITS).value(); + let frequency = get_frequency().with_precision(RADIX_BITS).value(); info!("Previous epoch frequency: {}", frequency); // Generating sigmas let total_stake = total_stake(epoch, slot); // only used for fine tunning info!("Node total stake: {}", total_stake); - let one: Float10 = Float10::from_str_native("1").unwrap().with_precision(*RADIX_BITS).value(); - let two: Float10 = Float10::from_str_native("2").unwrap().with_precision(*RADIX_BITS).value(); - let field_p = Float10::from_str_native(*P).unwrap().with_precision(*RADIX_BITS).value(); - let total_sigma = Float10::try_from(total_stake).unwrap().with_precision(*RADIX_BITS).value(); + let one: Float10 = Float10::from_str_native("1").unwrap().with_precision(RADIX_BITS).value(); + let two: Float10 = Float10::from_str_native("2").unwrap().with_precision(RADIX_BITS).value(); + let field_p = Float10::from_str_native(P).unwrap().with_precision(RADIX_BITS).value(); + let total_sigma = Float10::try_from(total_stake).unwrap().with_precision(RADIX_BITS).value(); let x = one - frequency; info!("x: {}", x); let c = x.ln(); @@ -113,18 +115,18 @@ fn create_coins( ) -> Vec> { let mut rng = thread_rng(); let mut seeds: Vec = vec![]; - for _i in 0..*EPOCH_LENGTH { + for _i in 0..EPOCH_LENGTH { let rho: u64 = rng.gen(); seeds.push(rho); } let (sks, root_sks, path_sks) = create_coins_sks(); - let mut tree_cm = BridgeTree::::new(*EPOCH_LENGTH as usize); + let mut tree_cm = BridgeTree::::new(EPOCH_LENGTH as usize); // Leadcoins matrix were each row represents a slot and contains its competing coins. let mut coins: Vec> = vec![]; // Use existing stake if !owned.is_empty() { - for i in 0..*EPOCH_LENGTH { + for i in 0..EPOCH_LENGTH { let index = i as usize; let mut slot_coins = vec![]; for elem in owned { @@ -146,14 +148,14 @@ fn create_coins( continue } } else { - for i in 0..*EPOCH_LENGTH { + for i in 0..EPOCH_LENGTH { let index = i as usize; // Compete with zero stake let coin = LeadCoin::new( eta, sigma1, sigma2, - *LOTTERY_HEAD_START, + LOTTERY_HEAD_START, index, root_sks[index], path_sks[index], @@ -178,12 +180,12 @@ fn create_coins( fn create_coins_sks() -> (Vec, Vec, Vec<[MerkleNode; MERKLE_DEPTH_ORCHARD]>) { let mut rng = thread_rng(); - let mut tree = BridgeTree::::new(*EPOCH_LENGTH as usize); + let mut tree = BridgeTree::::new(EPOCH_LENGTH as usize); let mut sks: Vec = vec![]; let mut root_sks: Vec = vec![]; let mut path_sks: Vec<[MerkleNode; MERKLE_DEPTH_ORCHARD]> = vec![]; let mut prev_sk_base: pallas::Base = pallas::Base::one(); - for _i in 0..*EPOCH_LENGTH { + for _i in 0..EPOCH_LENGTH { let base: pallas::Point = if _i == 0 { pedersen_commitment_u64(1, pallas::Scalar::random(&mut rng)) } else { diff --git a/src/consensus/constants.rs b/src/consensus/constants.rs new file mode 100644 index 000000000..b6963e9ed --- /dev/null +++ b/src/consensus/constants.rs @@ -0,0 +1,62 @@ +/* This file is part of DarkFi (https://dark.fi) + * + * Copyright (C) 2020-2022 Dyne.org foundation + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +use lazy_static::lazy_static; + +use crate::util::time::Timestamp; + +lazy_static! { + /// Genesis hash for the mainnet chain + pub static ref MAINNET_GENESIS_HASH_BYTES: blake3::Hash = blake3::hash(b"darkfi_mainnet"); + + /// Genesis timestamp for the mainnet chain + pub static ref MAINNET_GENESIS_TIMESTAMP: Timestamp = Timestamp(1650887115); + + /// Genesis hash for the testnet chain + pub static ref TESTNET_GENESIS_HASH_BYTES: blake3::Hash = blake3::hash(b"darkfi_testnet"); + + /// Genesis timestamp for the testnet chain + pub static ref TESTNET_GENESIS_TIMESTAMP: Timestamp = Timestamp(1650887115); +} + +/// Block version number +pub const BLOCK_VERSION: u8 = 1; + +/// Block magic bytes +pub const BLOCK_MAGIC_BYTES: [u8; 4] = [0x11, 0x6d, 0x75, 0x1f]; + +/// Block info magic bytes +pub const BLOCK_INFO_MAGIC_BYTES: [u8; 4] = [0x90, 0x44, 0xf1, 0xf6]; + +/// Number of slots in one epoch +pub const EPOCH_LENGTH: u64 = 10; + +/// Block leader reward +pub const REWARD: u64 = 420; + +/// `2 * DELTA` represents slot time +pub const DELTA: u64 = 20; + +/// Leader proofs k for zk proof rows (rows=2^k) +pub const LEADER_PROOF_K: u32 = 11; + +// TODO: Describe these constants +pub const RADIX_BITS: usize = 76; +pub const P: &str = "28948022309329048855892746252171976963363056481941560715954676764349967630337"; +pub const LOTTERY_HEAD_START: u64 = 1; +pub const PRF_NULLIFIER_PREFIX: u64 = 0; diff --git a/src/consensus/leadcoin.rs b/src/consensus/leadcoin.rs index 1e20793a0..b63ef1906 100644 --- a/src/consensus/leadcoin.rs +++ b/src/consensus/leadcoin.rs @@ -15,6 +15,7 @@ * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see . */ + use darkfi_sdk::{ crypto::{ pedersen::pedersen_commitment_base, poseidon_hash, util::mod_r_p, MerkleNode, PublicKey, @@ -27,7 +28,7 @@ use incrementalmerkletree::{bridgetree::BridgeTree, Tree}; use log::debug; use rand::rngs::OsRng; -use super::PRF_NULLIFIER_PREFIX; +use super::constants::PRF_NULLIFIER_PREFIX; use crate::{ crypto::{proof::ProvingKey, Proof}, zk::circuit::LeadContract, @@ -130,7 +131,7 @@ impl LeadCoin { // Derive input for the commitment of coin1 let coin1_commit_msg = [ - pallas::Base::from(*PRF_NULLIFIER_PREFIX), + pallas::Base::from(PRF_NULLIFIER_PREFIX), coin_pk_x, coin_pk_y, pallas::Base::from(value), @@ -165,7 +166,7 @@ impl LeadCoin { // Derive input for the commitment of coin2 let coin2_commit_msg = [ - pallas::Base::from(*PRF_NULLIFIER_PREFIX), + pallas::Base::from(PRF_NULLIFIER_PREFIX), coin_pk_x, coin_pk_y, pallas::Base::from(value), @@ -268,7 +269,6 @@ impl LeadCoin { rho: Value::known(rho), }; - let proof = Proof::create(pk, &[circuit], &self.public_inputs(), &mut OsRng)?; - Ok(proof) + Ok(Proof::create(pk, &[circuit], &self.public_inputs(), &mut OsRng)?) } } diff --git a/src/consensus/mod.rs b/src/consensus/mod.rs index 93ce75bbc..a57bd4e8a 100644 --- a/src/consensus/mod.rs +++ b/src/consensus/mod.rs @@ -20,6 +20,9 @@ pub mod block; pub use block::{Block, BlockInfo, BlockProposal, Header, ProposalChain}; +/// Constants +pub mod constants; + /// Consensus metadata pub mod metadata; pub use metadata::{LeadProof, Metadata}; @@ -32,9 +35,6 @@ pub use participant::Participant; pub mod state; pub use state::{ValidatorState, ValidatorStatePtr}; -/// Utility functions and types -use crate::util::time::Timestamp; - /// P2P net protocols pub mod proto; @@ -45,12 +45,12 @@ pub mod task; pub mod clock; pub use clock::{Clock, Ticks}; -/// Ouroboros simulation -pub mod ouroboros; - -/// Ouroboros consensus coins functions +/// Ouroboros Crypsinous consensus coins functions pub mod coins; +/// Consensus participation coin functions and definitions +pub mod leadcoin; + /// Utility types pub mod types; pub use types::Float10; @@ -58,46 +58,5 @@ pub use types::Float10; /// Utility functions pub mod utils; -use lazy_static::lazy_static; -lazy_static! { - /// Genesis hash for the mainnet chain - pub static ref MAINNET_GENESIS_HASH_BYTES: blake3::Hash = blake3::hash(b"darkfi_mainnet"); - - /// Genesis timestamp for the mainnet chain - pub static ref MAINNET_GENESIS_TIMESTAMP: Timestamp = Timestamp(1650887115); - - /// Genesis hash for the testnet chain - pub static ref TESTNET_GENESIS_HASH_BYTES: blake3::Hash = blake3::hash(b"darkfi_testnet"); - - /// Genesis timestamp for the testnet chain - pub static ref TESTNET_GENESIS_TIMESTAMP: Timestamp = Timestamp(1650887115); - - /// Block version number - pub static ref BLOCK_VERSION: u8 = 1; - - /// Block magic bytes - pub static ref BLOCK_MAGIC_BYTES: [u8; 4] = [0x11, 0x6d, 0x75, 0x1f]; - - /// Block info magic bytes - pub static ref BLOCK_INFO_MAGIC_BYTES: [u8; 4] = [0x90, 0x44, 0xf1, 0xf6]; - - // Epoch configuration - /// Slots in an epoch - pub static ref EPOCH_LENGTH: u64 = 10; - - /// Block leader reward - pub static ref REWARD: u64 = 420; - - /// `2 * DELTA` represents slot time - pub static ref DELTA: u64 = 20; - - /// Leader proof rows number - pub static ref LEADER_PROOF_K: u32 = 11; - - // TODO: Describe constants meaning in comment - pub static ref RADIX_BITS: usize = 76; - pub static ref P: &'static str = "28948022309329048855892746252171976963363056481941560715954676764349967630337"; - pub static ref LOTTERY_HEAD_START: u64 = 1; - pub static ref PRF_NULLIFIER_PREFIX: u64 = 0; - -} +// Wallet functions +//pub mod wallet; diff --git a/src/consensus/state.rs b/src/consensus/state.rs index 079957592..cfe7be512 100644 --- a/src/consensus/state.rs +++ b/src/consensus/state.rs @@ -270,18 +270,18 @@ impl ValidatorState { /// Calculates the epoch of the provided slot. /// Epoch duration is configured using the `EPOCH_LENGTH` value. pub fn slot_epoch(&self, slot: u64) -> u64 { - slot / *EPOCH_LENGTH + slot / EPOCH_LENGTH } /// Calculates current slot, based on elapsed time from the genesis block. /// Slot duration is configured using the `DELTA` value. pub fn current_slot(&self) -> u64 { - self.consensus.genesis_ts.elapsed() / (2 * *DELTA) + self.consensus.genesis_ts.elapsed() / (2 * DELTA) } /// Calculates the relative number of the provided slot. pub fn relative_slot(&self, slot: u64) -> u64 { - slot % *EPOCH_LENGTH + slot % EPOCH_LENGTH } /// Finds the last slot a proposal or block was generated. @@ -311,7 +311,7 @@ impl ValidatorState { assert!(n > 0); let start_time = NaiveDateTime::from_timestamp(self.consensus.genesis_ts.0, 0); let current_slot = self.current_slot() + n; - let next_slot_start = (current_slot * (2 * *DELTA)) + (start_time.timestamp() as u64); + let next_slot_start = (current_slot * (2 * DELTA)) + (start_time.timestamp() as u64); let next_slot_start = NaiveDateTime::from_timestamp(next_slot_start as i64, 0); let current_time = NaiveDateTime::from_timestamp(Utc::now().timestamp(), 0); let diff = next_slot_start - current_time; @@ -323,8 +323,8 @@ impl ValidatorState { /// Epoch duration is configured using the EPOCH_LENGTH value. pub fn slots_to_next_n_epoch(&self, n: u64) -> u64 { assert!(n > 0); - let slots_till_next_epoch = *EPOCH_LENGTH - self.relative_slot(self.current_slot()); - ((n - 1) * *EPOCH_LENGTH) + slots_till_next_epoch + let slots_till_next_epoch = EPOCH_LENGTH - self.relative_slot(self.current_slot()); + ((n - 1) * EPOCH_LENGTH) + slots_till_next_epoch } /// Calculates seconds until next Nth epoch starting time.