Sfoglia il codice sorgente

consensus/ouroboros: fixed tests, fmt, removed db folder

aggstam 3 anni fa
parent
commit
e5bfd44c74

+ 0 - 4
db/conf

@@ -1,4 +0,0 @@
-segment_size: 524288
-use_compression: false
-version: 0.34
-vQÁ

BIN
db/db


+ 2 - 2
example/crypsinous.rs

@@ -1,6 +1,7 @@
 use ::darkfi::{
+    consensus::ouroboros::{EpochConsensus, Stakeholder},
     net::Settings,
-    consensus::ouroboros::{Stakeholder, EpochConsensus},util::time::Timestamp,
+    util::time::Timestamp,
 };
 
 use clap::Parser;
@@ -8,7 +9,6 @@ use futures::executor::block_on;
 use std::thread;
 use url::Url;
 
-
 #[derive(Parser)]
 struct NetCli {
     #[clap(long, value_parser, default_value = "tls://127.0.0.1:12003")]

+ 2 - 6
example/lead.rs

@@ -1,16 +1,14 @@
 use futures::executor::block_on;
 use halo2_proofs::dev::MockProver;
-use log::debug;
 use pasta_curves::pallas;
 use url::Url;
 
 use darkfi::{
+    consensus::ouroboros::{Epoch, EpochConsensus, Stakeholder},
     crypto::leadcoin::{LeadCoin, LEAD_PUBLIC_INPUT_LEN},
     net::Settings,
-    consensus::ouroboros::{Stakeholder, Epoch, EpochConsensus},
 };
 
-
 fn main() {
     env_logger::init();
 
@@ -46,9 +44,7 @@ fn main() {
     let eta: pallas::Base = stakeholder.get_eta();
     let mut epoch = Epoch::new(consensus, eta);
     let sigma = pallas::Base::from(10);
-    let coins: Vec<Vec<LeadCoin>> = epoch.create_coins(sigma.clone(),
-                                                       sigma,
-                                                       vec![]);
+    let coins: Vec<Vec<LeadCoin>> = epoch.create_coins(sigma.clone(), sigma, vec![]);
     let coin = coins[0][0];
     let contract = coin.create_contract();
 

+ 4 - 3
src/consensus/ouroboros/consts.rs

@@ -1,4 +1,5 @@
-pub(crate) const RADIX_BITS : usize = 76;
+pub(crate) const RADIX_BITS: usize = 76;
 pub(crate) const LOG_T: &str = "stakeholder";
-pub(crate)const TREE_LEN: usize = 100;
-pub(crate) const P: &str = "28948022309329048855892746252171976963363056481941560715954676764349967630337";
+pub(crate) const TREE_LEN: usize = 100;
+pub(crate) const P: &str =
+    "28948022309329048855892746252171976963363056481941560715954676764349967630337";

+ 30 - 27
src/consensus/ouroboros/epoch.rs

@@ -13,6 +13,11 @@ use pasta_curves::{
 use rand::{thread_rng, Rng};
 
 use crate::{
+    consensus::ouroboros::{
+        consts::RADIX_BITS,
+        utils::{base2ibig, fbig2ibig},
+        EpochConsensus, Float10,
+    },
     crypto::{
         coin::OwnCoin,
         constants::MERKLE_DEPTH_ORCHARD,
@@ -24,20 +29,11 @@ use crate::{
         types::DrkValueBlind,
         util::{mod_r_p, pedersen_commitment_base, pedersen_commitment_u64},
     },
-    consensus::ouroboros::{
-        EpochConsensus,
-        utils::{fbig2ibig, base2ibig},
-        Float10,
-        consts::{RADIX_BITS},
-    }
 };
 
-
-
 const PRF_NULLIFIER_PREFIX: u64 = 0;
 const MERKLE_DEPTH: u8 = MERKLE_DEPTH_ORCHARD as u8;
 
-
 #[derive(Debug, Default, Clone)]
 pub struct Epoch {
     pub consensus: EpochConsensus,
@@ -138,7 +134,12 @@ impl Epoch {
     }
 
     //note! the strategy here is single competing coin per slot.
-    pub fn create_coins(&mut self, sigma1: pallas::Base, sigma2: pallas::Base, owned: Vec<OwnCoin>) -> Vec<Vec<LeadCoin>> {
+    pub fn create_coins(
+        &mut self,
+        sigma1: pallas::Base,
+        sigma2: pallas::Base,
+        owned: Vec<OwnCoin>,
+    ) -> Vec<Vec<LeadCoin>> {
         let mut rng = thread_rng();
         let mut seeds: Vec<u64> = vec![];
         for _i in 0..self.len() {
@@ -171,14 +172,15 @@ impl Epoch {
             }
             // otherwise compete with zero stake
             else {
-                let coin = self.create_leadcoin(sigma1,
-                                                sigma2,
-                                                0,
-                                                i,
-                                                root_sks[i],
-                                                path_sks[i],
-                                                seeds[i],
-                                                sks[i]
+                let coin = self.create_leadcoin(
+                    sigma1,
+                    sigma2,
+                    0,
+                    i,
+                    root_sks[i],
+                    path_sks[i],
+                    seeds[i],
+                    sks[i],
                 );
                 self.coins.push(vec![coin]);
             }
@@ -296,24 +298,25 @@ impl Epoch {
         for (winning_idx, coin) in competing_coins.iter().enumerate() {
             let y_exp = [coin.root_sk.unwrap(), coin.nonce.unwrap()];
             let y_exp_hash: pallas::Base =
-                poseidon::Hash::<_, poseidon::P128Pow5T3, poseidon::ConstantLength<2>, 3, 2>::init().hash(y_exp);
+                poseidon::Hash::<_, poseidon::P128Pow5T3, poseidon::ConstantLength<2>, 3, 2>::init(
+                )
+                .hash(y_exp);
             //TODO (fix) use the hash of y coordinates, using single coordinate is insecure.
             //  pick x coordinate of y for comparison
             let y_x: pallas::Base =
                 *pedersen_commitment_base(coin.y_mu.unwrap(), mod_r_p(y_exp_hash))
-                .to_affine()
-                .coordinates()
-                .unwrap().x();
-            let val_2ibig = Float10::try_from(coin.value.unwrap())
-                .unwrap()
-                .with_precision(RADIX_BITS)
-                .value();
+                    .to_affine()
+                    .coordinates()
+                    .unwrap()
+                    .x();
+            let val_2ibig =
+                Float10::try_from(coin.value.unwrap()).unwrap().with_precision(RADIX_BITS).value();
             let target = base2ibig(coin.sigma1.unwrap()) * val_2ibig.clone() +
                 base2ibig(coin.sigma2.unwrap()) * val_2ibig.clone() * val_2ibig;
             let target_ibig = fbig2ibig(target);
             let y_ibig = base2ibig(y_x);
             debug!("y_x: {}, target: {}", y_ibig, target_ibig);
-            let iam_leader =  y_ibig < target_ibig ;
+            let iam_leader = y_ibig < target_ibig;
             if iam_leader {
                 if coin.value.unwrap() > highest_stake {
                     highest_stake = coin.value.unwrap();

+ 3 - 3
src/consensus/ouroboros/epochconsensus.rs

@@ -5,9 +5,9 @@
 pub struct EpochConsensus {
     pub sl_len: u64, // length of slot in terms of ticks
     // number of slots per epoch
-    pub e_len: u64, // length of epoch in terms of slots
+    pub e_len: u64,    // length of epoch in terms of slots
     pub tick_len: u64, // length of tick in terms of seconds
-    pub reward: u64, // constant reward value for the slot leader
+    pub reward: u64,   // constant reward value for the slot leader
 }
 
 impl EpochConsensus {
@@ -26,7 +26,7 @@ impl EpochConsensus {
     }
 
     pub fn total_stake(&self, e: u64, sl: u64) -> u64 {
-        (e*self.e_len +  sl+ 1) * self.reward
+        (e * self.e_len + sl + 1) * self.reward
     }
     /// getter for constant stakeholder reward
     /// used for configuring the stakeholder reward value

+ 28 - 49
src/consensus/ouroboros/mod.rs

@@ -1,30 +1,29 @@
-use smol::Executor;
 use async_std::sync::Arc;
 use halo2_proofs::arithmetic::Field;
 use log::{debug, error, info};
+use smol::Executor;
 use std::fmt;
 
 use rand::rngs::OsRng;
 use std::{thread, time::Duration};
 
 use crate::zk::circuit::{BurnContract, LeadContract, MintContract};
-use incrementalmerkletree::{bridgetree::BridgeTree};
+use incrementalmerkletree::bridgetree::BridgeTree;
 
-pub mod types;
 pub mod consts;
+pub mod types;
 pub mod utils;
 
 use crate::{
-    blockchain::{Blockchain},
+    blockchain::Blockchain,
     consensus::{
         clock::{Clock, Ticks},
-        Block, BlockInfo, Metadata,
-        LeadProof,
         ouroboros::{
-            types::{Float10},
-            consts::{RADIX_BITS, LOG_T, TREE_LEN, P},
-            utils::{fbig2base},
+            consts::{LOG_T, P, RADIX_BITS, TREE_LEN},
+            types::Float10,
+            utils::fbig2base,
         },
+        Block, BlockInfo, LeadProof, Metadata,
     },
     crypto::{
         address::Address,
@@ -33,12 +32,11 @@ use crate::{
         keypair::{PublicKey, SecretKey},
         leadcoin::LeadCoin,
         merkle_node::MerkleNode,
-        nullifier::Nullifier,
         proof::{Proof, ProvingKey, VerifyingKey},
-        schnorr::{SchnorrSecret},
+        schnorr::SchnorrSecret,
     },
     net::{MessageSubscription, P2p, Settings, SettingsPtr},
-    node::state::{state_transition, ProgramState},
+    node::state::state_transition,
     tx::{
         builder::{
             TransactionBuilder, TransactionBuilderClearInputInfo, TransactionBuilderOutputInfo,
@@ -46,7 +44,6 @@ use crate::{
         Transaction,
     },
     util::{path::expand_path, time::Timestamp},
-
     Result,
 };
 
@@ -56,11 +53,9 @@ use pasta_curves::pallas;
 
 use group::ff::PrimeField;
 
-
 pub mod epochconsensus;
 pub use epochconsensus::EpochConsensus;
 
-
 pub mod epoch;
 pub use epoch::Epoch;
 
@@ -70,8 +65,6 @@ pub(crate) use workspace::SlotWorkspace;
 pub(crate) mod state;
 pub(crate) use state::StakeholderState;
 
-
-
 pub struct Stakeholder {
     pub blockchain: Blockchain, // stakeholder view of the blockchain
     pub net: Arc<P2p>,
@@ -202,7 +195,6 @@ impl Stakeholder {
         settings.peers.clone()
     }
 
-
     async fn init_network(&self) -> Result<()> {
         info!(target: LOG_T, "init_network()");
         let exec = Arc::new(Executor::new());
@@ -343,15 +335,11 @@ impl Stakeholder {
     fn get_f(&self) -> Float10 {
         //TODO (res) should be function of the average time to end of slot
         // in 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();
-        one/two
+        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
     }
     /// on the onset of the epoch, layout the new the competing coins
     /// assuming static stake during the epoch, enforced by the commitment to competing coins
@@ -368,14 +356,10 @@ impl Stakeholder {
         //
         let f = self.get_f();
         let total_stake = self.epoch.consensus.total_stake(e, sl);
-        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();
         //TODO should set f precision here
         /*
         let f : Float10 =  Float10::try_from(f_val)
@@ -383,35 +367,30 @@ impl Stakeholder {
             .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 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 - f;
         info!("x: {}", x);
         // also ln small x should work normally.
         let c = x.ln();
         info!("c: {}", c);
-        let sigma1_fbig = c.clone()/total_sigma.clone() * field_p.clone();
+        let sigma1_fbig = c.clone() / total_sigma.clone() * field_p.clone();
         info!("sigma1: {}", sigma1_fbig);
 
         //TODO in sigma calculation get rad if exp is neg
-        let sigma1 : pallas::Base = fbig2base(sigma1_fbig);
+        let sigma1: pallas::Base = fbig2base(sigma1_fbig);
         info!("sigma1 base: {:?}", sigma1);
-        let sigma2_fbig = c.clone()/total_sigma.clone() * c.clone()/total_sigma.clone()  * field_p.clone()/two.clone();
+        let sigma2_fbig = c.clone() / total_sigma.clone() * c.clone() / total_sigma.clone() *
+            field_p.clone() /
+            two.clone();
         info!("sigma2: {}", sigma2_fbig);
-        let sigma2 : pallas::Base = fbig2base(sigma2_fbig);
+        let sigma2: pallas::Base = fbig2base(sigma2_fbig);
         info!("sigma2 base: {:?}", sigma2);
         epoch.create_coins(sigma1, sigma2, self.ownedcoins.clone()); // set epoch interal fields working space with competing coins
         self.epoch = epoch.clone();
     }
 
-
-
     /// at the begining of the slot
     /// stakeholder need to play the lottery for the slot.
     /// FIXME if the stakeholder is not winning, staker can try different coins before,

+ 9 - 9
src/consensus/ouroboros/state.rs

@@ -2,16 +2,16 @@ use incrementalmerkletree::{bridgetree::BridgeTree, Tree};
 
 use crate::{
     crypto::{
+        coin::OwnCoin,
         constants::MERKLE_DEPTH,
+        keypair::{PublicKey, SecretKey},
         merkle_node::MerkleNode,
+        note::{EncryptedNote, Note},
         nullifier::Nullifier,
+        proof::VerifyingKey,
         util::poseidon_hash,
-        note::{EncryptedNote, Note},
-        coin::OwnCoin,
-        proof::{VerifyingKey},
-        keypair::{PublicKey, SecretKey},
     },
-    node::state::{state_transition, StateUpdate},
+    node::state::{ProgramState, StateUpdate},
 };
 
 pub struct StakeholderState {
@@ -88,11 +88,11 @@ impl StakeholderState {
                 let leaf_position = self.tree.witness().unwrap();
                 let nullifier = poseidon_hash::<2>([secret.inner(), note.serial]);
                 let own_coin = OwnCoin {
-                    coin: coin,
-                    note: note,
-                    secret: secret,
+                    coin,
+                    note,
+                    secret,
                     nullifier: Nullifier::from(nullifier),
-                    leaf_position: leaf_position
+                    leaf_position,
                 };
                 self.own_coins.push(own_coin);
             }

+ 2 - 2
src/consensus/ouroboros/types.rs

@@ -1,3 +1,3 @@
-use dashu::float::{FBig, round::{mode::{Zero}, }};
+use dashu::float::{round::mode::Zero, FBig};
 
-pub(crate) type Float10 = FBig<Zero,10>;
+pub(crate) type Float10 = FBig<Zero, 10>;

+ 29 - 30
src/consensus/ouroboros/utils.rs

@@ -1,32 +1,27 @@
-use pasta_curves::pallas;
-use group::ff::PrimeField;
+use crate::consensus::ouroboros::types::Float10;
 use dashu::integer::{IBig, Sign, UBig};
-use crate::consensus::ouroboros::Float10;
-use log::{info};
+use group::ff::PrimeField;
+use log::info;
+use pasta_curves::pallas;
 
 pub(crate) fn fbig2ibig(f: Float10) -> IBig {
     info!("fbig -> ibig (f): {}", f);
     let rad = IBig::try_from(10).unwrap();
     let sig = f.repr().significand();
     let exp = f.repr().exponent();
-    let val : IBig = if exp>=0 {
-        sig.clone()*rad.pow(exp as usize)
-    } else {
-        sig.clone()
-    };
+    let val: IBig = if exp >= 0 { sig.clone() * rad.pow(exp as usize) } else { sig.clone() };
     info!("fbig -> ibig (i): {}", val);
     val
 }
 
-
 pub(crate) fn base2ibig(base: pallas::Base) -> IBig {
     //
-    let byts : [u8; 32] = base.to_repr();
-    let words : [u64; 4] = [
+    let byts: [u8; 32] = base.to_repr();
+    let words: [u64; 4] = [
         u64::from_le_bytes(byts[0..8].try_into().expect("")),
         u64::from_le_bytes(byts[8..16].try_into().expect("")),
         u64::from_le_bytes(byts[16..24].try_into().expect("")),
-        u64::from_le_bytes(byts[24..32].try_into().expect(""))
+        u64::from_le_bytes(byts[24..32].try_into().expect("")),
     ];
     let uparts = UBig::from_words(&words);
     //TODO both y, and t are positive, but workout the sign for general use
@@ -36,10 +31,10 @@ pub(crate) fn base2ibig(base: pallas::Base) -> IBig {
 
 pub(crate) fn fbig2base(f: Float10) -> pallas::Base {
     info!("fbig -> base (f): {}", f);
-    let val : IBig = fbig2ibig(f);
+    let val: IBig = fbig2ibig(f);
     let (sign, word) = val.as_sign_words();
     //TODO (res) set pallas base sign, i.e sigma1 is negative.
-    let mut words : [u64;4] = [0,0,0,0];
+    let mut words: [u64; 4] = [0, 0, 0, 0];
     for i in 0..word.len() {
         words[i] = word[i];
     }
@@ -52,18 +47,20 @@ pub(crate) fn fbig2base(f: Float10) -> pallas::Base {
 
 #[cfg(test)]
 mod tests {
-    use crate::stakeholder::utils::{base2ibig, fbig2base, fbig2ibig};
-    use crate::stakeholder::consts::{RADIX_BITS};
+    use dashu::integer::IBig;
     use pasta_curves::pallas;
-    use dashu::integer::{IBig};
-    use crate::stakeholder::Float10;
+
+    use crate::consensus::ouroboros::{
+        consts::RADIX_BITS,
+        types::Float10,
+        utils::{base2ibig, fbig2base, fbig2ibig},
+    };
+
     #[test]
     fn dashu_fbig2ibig() {
-        let f = Float10::from_str_native("234234223.000")
-            .unwrap()
-            .with_precision(RADIX_BITS)
-            .value();
-        let i : IBig = fbig2ibig(f);
+        let f =
+            Float10::from_str_native("234234223.000").unwrap().with_precision(RADIX_BITS).value();
+        let i: IBig = fbig2ibig(f);
         let sig = IBig::from(234234223);
         assert_eq!(i, sig);
     }
@@ -71,13 +68,15 @@ mod tests {
     #[test]
     fn dashu_test_base2ibig() {
         //
-        let fbig : Float10 = Float10::from_str_native("28948022309329048855892746252171976963363056481941560715954676764349967630337")
-            .unwrap()
-            .with_precision(RADIX_BITS)
-            .value();
+        let fbig: Float10 = Float10::from_str_native(
+            "28948022309329048855892746252171976963363056481941560715954676764349967630337",
+        )
+        .unwrap()
+        .with_precision(RADIX_BITS)
+        .value();
         let ibig = fbig2ibig(fbig.clone());
-        let res_base : pallas::Base = fbig2base(fbig.clone());
-        let res_ibig : IBig = base2ibig(res_base);
+        let res_base: pallas::Base = fbig2base(fbig.clone());
+        let res_ibig: IBig = base2ibig(res_base);
         assert_eq!(res_ibig, ibig);
     }
 }

+ 4 - 11
src/consensus/ouroboros/workspace.rs

@@ -1,15 +1,8 @@
 use crate::{
-    consensus::{
-        BlockInfo, Header, Metadata,
-    },
-    tx::{
-        Transaction,
-    },
-    util::{ time::Timestamp},
-    crypto::{
-        merkle_node::MerkleNode,
-        proof::{Proof},
-    }
+    consensus::{BlockInfo, Header, Metadata},
+    crypto::{merkle_node::MerkleNode, proof::Proof},
+    tx::Transaction,
+    util::time::Timestamp,
 };
 use pasta_curves::pallas;
 

+ 2 - 1
src/crypto/leadcoin.rs

@@ -64,7 +64,8 @@ impl LeadCoin {
         let nonce = self.nonce.unwrap();
         let lottery_msg_input = [root_sk, nonce];
         let lottery_msg: pallas::Base =
-            poseidon::Hash::<_, poseidon::P128Pow5T3, poseidon::ConstantLength<2>, 3, 2>::init().hash(lottery_msg_input);
+            poseidon::Hash::<_, poseidon::P128Pow5T3, poseidon::ConstantLength<2>, 3, 2>::init()
+                .hash(lottery_msg_input);
         //
         let po_y_pt: pallas::Point = pedersen_commitment_base(lottery_msg, mod_r_p(y_mu));
         let po_y = *po_y_pt.to_affine().coordinates().unwrap().x();

+ 9 - 7
src/zk/circuit/lead_contract.rs

@@ -270,7 +270,6 @@ impl Circuit<pallas::Base> for LeadContract {
         config: Self::Config,
         mut layouter: impl Layouter<pallas::Base>,
     ) -> Result<(), Error> {
-
         let less_than_chip = config.lessthan_chip();
         NativeRangeCheckChip::<WINDOW_SIZE, NUM_OF_BITS, NUM_OF_WINDOWS>::load_k_table(
             &mut layouter,
@@ -594,19 +593,23 @@ impl Circuit<pallas::Base> for LeadContract {
         let rho_commit = com.add(layouter.namespace(|| "nonce commit"), &blind)?;
         let rho_commit_base = rho_commit.inner().x();
 
+        let term1 =
+            ar_chip.mul(layouter.namespace(|| "calculate term1"), &sigma1, &coin_value.clone())?;
 
-        let term1 = ar_chip.mul(layouter.namespace(|| "calculate term1"), &sigma1, &coin_value.clone())?;
-
-        let term2_1 = ar_chip.mul(layouter.namespace(|| "calculate term2_1"), &sigma2, &coin_value.clone())?;
+        let term2_1 = ar_chip.mul(
+            layouter.namespace(|| "calculate term2_1"),
+            &sigma2,
+            &coin_value.clone(),
+        )?;
 
-        let term2 = ar_chip.mul(layouter.namespace(|| "calculate term2"), &term2_1, &coin_value.clone())?;
+        let term2 =
+            ar_chip.mul(layouter.namespace(|| "calculate term2"), &term2_1, &coin_value.clone())?;
 
         let target = ar_chip.add(layouter.namespace(|| "calculate target"), &term1, &term2)?;
         let target: Value<pallas::Base> = target.value().cloned();
 
         let y: Value<pallas::Base> = y_commit_base.value().cloned();
 
-
         less_than_chip.witness_less_than(
             layouter.namespace(|| "y < target"),
             y,
@@ -671,6 +674,5 @@ impl Circuit<pallas::Base> for LeadContract {
         )?;
 
         Ok(())
-
     }
 }