Quellcode durchsuchen

crypsinous_playground: moved coins.rs to main repo, consensus::ouroboros: create wrappers to use consensus::coins

aggstam vor 3 Jahren
Ursprung
Commit
28d99d337f

+ 1 - 3
script/research/crypsinous_playground/src/main.rs

@@ -5,6 +5,7 @@ use structopt_toml::{serde::Deserialize, structopt::StructOpt, StructOptToml};
 
 
 use darkfi::{
 use darkfi::{
     async_daemonize, cli_desc,
     async_daemonize, cli_desc,
+    consensus::coins,
     crypto::{
     crypto::{
         lead_proof,
         lead_proof,
         proof::{ProvingKey, VerifyingKey},
         proof::{ProvingKey, VerifyingKey},
@@ -15,9 +16,6 @@ use darkfi::{
     Result,
     Result,
 };
 };
 
 
-mod coins;
-mod utils;
-
 const CONFIG_FILE: &str = "crypsinous_playground_config.toml";
 const CONFIG_FILE: &str = "crypsinous_playground_config.toml";
 const CONFIG_FILE_CONTENTS: &str = include_str!("../crypsinous_playground_config.toml");
 const CONFIG_FILE_CONTENTS: &str = include_str!("../crypsinous_playground_config.toml");
 
 

+ 0 - 48
script/research/crypsinous_playground/src/utils.rs

@@ -1,48 +0,0 @@
-use dashu::{
-    float::{round::mode::Zero, FBig},
-    integer::{IBig, Sign},
-};
-use log::{debug, info};
-use pasta_curves::{group::ff::PrimeField, pallas};
-
-pub type Float10 = FBig<Zero, 10>;
-
-pub fn fbig2ibig(f: Float10) -> IBig {
-    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()
-    };
-    debug!("fbig2ibig (f): {}", f);
-    debug!("fbig2ibig (i): {}", val);
-    val
-}
-
-pub fn fbig2base(f: Float10) -> pallas::Base {
-    info!("fbig -> base (f): {}", 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];
-    for i in 0..word.len() {
-        words[i] = word[i];
-    }
-    let base = match sign {
-        Sign::Positive => pallas::Base::from_raw(words),
-        Sign::Negative => pallas::Base::from_raw(words).neg(),
-    };
-    base
-}
-
-/// Extract leader selection lottery randomness(eta)
-/// using the hash of the previous lead proof, converted to pallas base.
-pub fn get_eta(proof_tx_hash: blake3::Hash) -> pallas::Base {
-    let mut bytes: [u8; 32] = *proof_tx_hash.as_bytes();
-    // read first 254 bits
-    bytes[30] = 0;
-    bytes[31] = 0;
-    pallas::Base::from_repr(bytes).unwrap()
-}

+ 64 - 57
script/research/crypsinous_playground/src/coins.rs → src/consensus/coins.rs

@@ -7,15 +7,18 @@ use pasta_curves::{
     group::{ff::PrimeField, Curve},
     group::{ff::PrimeField, Curve},
     pallas,
     pallas,
 };
 };
-use rand::{thread_rng, Rng, rngs::OsRng};
+use rand::{rngs::OsRng, thread_rng, Rng};
 
 
-use darkfi::{
+use super::{
+    utils::fbig2base, Float10, EPOCH_LENGTH, LOTTERY_HEAD_START, P, PRF_NULLIFIER_PREFIX,
+    RADIX_BITS, REWARD,
+};
+use crate::{
     crypto::{
     crypto::{
         coin::{Coin, OwnCoin},
         coin::{Coin, OwnCoin},
         keypair::{Keypair, SecretKey},
         keypair::{Keypair, SecretKey},
         leadcoin::LeadCoin,
         leadcoin::LeadCoin,
         note::Note,
         note::Note,
-        
         types::{DrkCoinBlind, DrkSerial, DrkTokenId, DrkValueBlind},
         types::{DrkCoinBlind, DrkSerial, DrkTokenId, DrkValueBlind},
         util::{mod_r_p, pedersen_commitment_base, pedersen_commitment_u64, poseidon_hash},
         util::{mod_r_p, pedersen_commitment_base, pedersen_commitment_u64, poseidon_hash},
     },
     },
@@ -24,47 +27,41 @@ use darkfi::{
 };
 };
 use darkfi_sdk::crypto::{constants::MERKLE_DEPTH_ORCHARD, MerkleNode, Nullifier};
 use darkfi_sdk::crypto::{constants::MERKLE_DEPTH_ORCHARD, MerkleNode, Nullifier};
 
 
-use crate::utils::{Float10, fbig2base};
-
-// Epoch configuration
-const EPOCH_LENGTH: u64 = 10;
-const REWARD: u64 = 420;
-
-// TODO: Describe constant meaning in comment
-const RADIX_BITS: usize = 76;
-const P: &str = "28948022309329048855892746252171976963363056481941560715954676764349967630337";
-const LOTTERY_HEAD_START: u64 = 1;
-const PRF_NULLIFIER_PREFIX: u64 = 0;
 const MERKLE_DEPTH: u8 = MERKLE_DEPTH_ORCHARD as u8;
 const MERKLE_DEPTH: u8 = MERKLE_DEPTH_ORCHARD as u8;
 
 
 /// Retrieve previous epoch competing coins frequency.
 /// Retrieve previous epoch competing coins frequency.
 fn get_frequency() -> Float10 {
 fn get_frequency() -> Float10 {
     //TODO: Actually retrieve frequency of coins from the previous epoch.
     //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
     one / two
 }
 }
 
 
 /// Calculate nodes total stake for specific epoch and slot.
 /// Calculate nodes total stake for specific epoch and slot.
-fn total_stake(epoch: u64, slot: u64) -> u64 {    
-    (epoch * EPOCH_LENGTH + slot + 1) * REWARD
+fn total_stake(epoch: u64, slot: u64) -> u64 {
+    (epoch * *EPOCH_LENGTH + slot + 1) * *REWARD
 }
 }
 
 
-/// Generate epoch competing coins. 
-pub fn create_epoch_coins(eta: pallas::Base, owned: &Vec<OwnCoin>, epoch: u64, slot: u64) -> Vec<Vec<LeadCoin>> {
+/// Generate epoch competing coins.
+pub fn create_epoch_coins(
+    eta: pallas::Base,
+    owned: &Vec<OwnCoin>,
+    epoch: u64,
+    slot: u64,
+) -> Vec<Vec<LeadCoin>> {
     info!("Creating coins for epoch: {}", epoch);
     info!("Creating coins for epoch: {}", epoch);
 
 
     // Retrieve previous epoch competing coins frequency
     // 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);
     info!("Previous epoch frequency: {}", frequency);
-    
+
     // Generating sigmas
     // Generating sigmas
     let total_stake = total_stake(epoch, slot); // only used for fine tunning
     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();
+    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 x = one - frequency;
     let x = one - frequency;
     info!("x: {}", x);
     info!("x: {}", x);
     let c = x.ln();
     let c = x.ln();
@@ -73,28 +70,34 @@ pub fn create_epoch_coins(eta: pallas::Base, owned: &Vec<OwnCoin>, epoch: u64, s
     info!("sigma1: {}", sigma1_fbig);
     info!("sigma1: {}", sigma1_fbig);
     let sigma1: pallas::Base = fbig2base(sigma1_fbig);
     let sigma1: pallas::Base = fbig2base(sigma1_fbig);
     info!("sigma1 base: {:?}", sigma1);
     info!("sigma1 base: {:?}", sigma1);
-    let sigma2_fbig = (c.clone() / total_sigma.clone()).powf(two.clone()) * (field_p.clone() / two.clone());
+    let sigma2_fbig =
+        (c.clone() / total_sigma.clone()).powf(two.clone()) * (field_p.clone() / two.clone());
     info!("sigma2: {}", sigma2_fbig);
     info!("sigma2: {}", sigma2_fbig);
     let sigma2: pallas::Base = fbig2base(sigma2_fbig);
     let sigma2: pallas::Base = fbig2base(sigma2_fbig);
     info!("sigma2 base: {:?}", sigma2);
     info!("sigma2 base: {:?}", sigma2);
-    
-    create_coins(eta, owned, sigma1, sigma2)  
+
+    create_coins(eta, owned, sigma1, sigma2)
 }
 }
 
 
 /// Generate coins for provided sigmas.
 /// Generate coins for provided sigmas.
 /// Note: the strategy here is single competing coin per slot.
 /// Note: the strategy here is single competing coin per slot.
-fn create_coins(eta: pallas::Base, owned: &Vec<OwnCoin>, sigma1: pallas::Base, sigma2: pallas::Base) -> Vec<Vec<LeadCoin>> {
+fn create_coins(
+    eta: pallas::Base,
+    owned: &Vec<OwnCoin>,
+    sigma1: pallas::Base,
+    sigma2: pallas::Base,
+) -> Vec<Vec<LeadCoin>> {
     let mut rng = thread_rng();
     let mut rng = thread_rng();
     let mut seeds: Vec<u64> = vec![];
     let mut seeds: Vec<u64> = vec![];
-    for _i in 0..EPOCH_LENGTH {
+    for _i in 0..*EPOCH_LENGTH {
         let rho: u64 = rng.gen();
         let rho: u64 = rng.gen();
         seeds.push(rho);
         seeds.push(rho);
-    }    
+    }
     let (sks, root_sks, path_sks) = create_coins_sks();
     let (sks, root_sks, path_sks) = create_coins_sks();
-    
+
     // Leadcoins matrix were each row represents a slot and contains its competing coins.
     // Leadcoins matrix were each row represents a slot and contains its competing coins.
     let mut coins: Vec<Vec<LeadCoin>> = vec![];
     let mut coins: Vec<Vec<LeadCoin>> = vec![];
-    for i in 0..EPOCH_LENGTH {
+    for i in 0..*EPOCH_LENGTH {
         let index = i as usize;
         let index = i as usize;
         // Use existing stake
         // Use existing stake
         if !owned.is_empty() {
         if !owned.is_empty() {
@@ -116,13 +119,13 @@ fn create_coins(eta: pallas::Base, owned: &Vec<OwnCoin>, sigma1: pallas::Base, s
             coins.push(slot_coins);
             coins.push(slot_coins);
             continue
             continue
         }
         }
-        
+
         // Compete with zero stake
         // Compete with zero stake
         let coin = create_leadcoin(
         let coin = create_leadcoin(
             eta,
             eta,
             sigma1,
             sigma1,
             sigma2,
             sigma2,
-            LOTTERY_HEAD_START,
+            *LOTTERY_HEAD_START,
             index,
             index,
             root_sks[index],
             root_sks[index],
             path_sks[index],
             path_sks[index],
@@ -131,26 +134,27 @@ fn create_coins(eta: pallas::Base, owned: &Vec<OwnCoin>, sigma1: pallas::Base, s
         );
         );
         coins.push(vec![coin]);
         coins.push(vec![coin]);
     }
     }
-    
+
     coins
     coins
 }
 }
 
 
 /// Generate epoch coins secret keys.
 /// Generate epoch coins secret keys.
-/// First slot coin secret key is sampled at random, 
+/// First slot coin secret key is sampled at random,
 /// while the secret keys of the rest slots derive from previous slot secret.
 /// while the secret keys of the rest slots derive from previous slot secret.
 /// Clarification:
 /// Clarification:
 ///     sk[0] -> random,
 ///     sk[0] -> random,
 ///     sk[1] -> derive_function(sk[0]),
 ///     sk[1] -> derive_function(sk[0]),
 ///     ...
 ///     ...
 ///     sk[n] -> derive_function(sk[n-1]),
 ///     sk[n] -> derive_function(sk[n-1]),
-fn create_coins_sks() -> (Vec<SecretKey>, Vec<MerkleNode>, Vec<[MerkleNode; MERKLE_DEPTH_ORCHARD]>) {
+fn create_coins_sks() -> (Vec<SecretKey>, Vec<MerkleNode>, Vec<[MerkleNode; MERKLE_DEPTH_ORCHARD]>)
+{
     let mut rng = thread_rng();
     let mut rng = thread_rng();
-    let mut tree = BridgeTree::<MerkleNode, MERKLE_DEPTH>::new(EPOCH_LENGTH as usize);
+    let mut tree = BridgeTree::<MerkleNode, MERKLE_DEPTH>::new(*EPOCH_LENGTH as usize);
     let mut sks: Vec<SecretKey> = vec![];
     let mut sks: Vec<SecretKey> = vec![];
     let mut root_sks: Vec<MerkleNode> = vec![];
     let mut root_sks: Vec<MerkleNode> = vec![];
     let mut path_sks: Vec<[MerkleNode; MERKLE_DEPTH_ORCHARD]> = vec![];
     let mut path_sks: Vec<[MerkleNode; MERKLE_DEPTH_ORCHARD]> = vec![];
     let mut prev_sk_base: pallas::Base = pallas::Base::one();
     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 {
         let base: pallas::Point = if _i == 0 {
             pedersen_commitment_u64(1, pallas::Scalar::random(&mut rng))
             pedersen_commitment_u64(1, pallas::Scalar::random(&mut rng))
         } else {
         } else {
@@ -160,7 +164,9 @@ fn create_coins_sks() -> (Vec<SecretKey>, Vec<MerkleNode>, Vec<[MerkleNode; MERK
         let sk_x = *coord.x();
         let sk_x = *coord.x();
         let sk_y = *coord.y();
         let sk_y = *coord.y();
         let sk_coord_ar = [sk_x, sk_y];
         let sk_coord_ar = [sk_x, sk_y];
-        let sk_base: pallas::Base = poseidon::Hash::<_, poseidon::P128Pow5T3, poseidon::ConstantLength<2>, 3, 2>::init().hash(sk_coord_ar);
+        let sk_base: pallas::Base =
+            poseidon::Hash::<_, poseidon::P128Pow5T3, poseidon::ConstantLength<2>, 3, 2>::init()
+                .hash(sk_coord_ar);
         sks.push(SecretKey::from(sk_base));
         sks.push(SecretKey::from(sk_base));
         prev_sk_base = sk_base;
         prev_sk_base = sk_base;
         let sk_bytes = sk_base.to_repr();
         let sk_bytes = sk_base.to_repr();
@@ -194,7 +200,7 @@ fn create_leadcoin(
     let one = pallas::Base::one();
     let one = pallas::Base::one();
     let c_cm1_blind: DrkValueBlind = pallas::Scalar::random(&mut rng);
     let c_cm1_blind: DrkValueBlind = pallas::Scalar::random(&mut rng);
     let c_cm2_blind: DrkValueBlind = pallas::Scalar::random(&mut rng);
     let c_cm2_blind: DrkValueBlind = pallas::Scalar::random(&mut rng);
-    let mut tree_cm = BridgeTree::<MerkleNode, MERKLE_DEPTH>::new(EPOCH_LENGTH as usize);
+    let mut tree_cm = BridgeTree::<MerkleNode, MERKLE_DEPTH>::new(*EPOCH_LENGTH as usize);
     let c_v = pallas::Base::from(value);
     let c_v = pallas::Base::from(value);
     // coin relative slot index in the epoch
     // coin relative slot index in the epoch
     let c_sl = pallas::Base::from(u64::try_from(i).unwrap());
     let c_sl = pallas::Base::from(u64::try_from(i).unwrap());
@@ -217,7 +223,7 @@ fn create_leadcoin(
             .hash(sn_msg);
             .hash(sn_msg);
 
 
     let coin_commit_msg_input =
     let coin_commit_msg_input =
-        [pallas::Base::from(PRF_NULLIFIER_PREFIX), *c_pk_x, *c_pk_y, c_v, c_seed, one];
+        [pallas::Base::from(*PRF_NULLIFIER_PREFIX), *c_pk_x, *c_pk_y, c_v, c_seed, one];
     let coin_commit_msg: pallas::Base =
     let coin_commit_msg: pallas::Base =
         poseidon::Hash::<_, poseidon::P128Pow5T3, poseidon::ConstantLength<6>, 3, 2>::init()
         poseidon::Hash::<_, poseidon::P128Pow5T3, poseidon::ConstantLength<6>, 3, 2>::init()
             .hash(coin_commit_msg_input);
             .hash(coin_commit_msg_input);
@@ -236,7 +242,7 @@ fn create_leadcoin(
             .hash(coin_nonce2_msg);
             .hash(coin_nonce2_msg);
 
 
     let coin2_commit_msg_input =
     let coin2_commit_msg_input =
-        [pallas::Base::from(PRF_NULLIFIER_PREFIX), *c_pk_x, *c_pk_y, c_v, c_seed2, one];
+        [pallas::Base::from(*PRF_NULLIFIER_PREFIX), *c_pk_x, *c_pk_y, c_v, c_seed2, one];
     let coin2_commit_msg: pallas::Base =
     let coin2_commit_msg: pallas::Base =
         poseidon::Hash::<_, poseidon::P128Pow5T3, poseidon::ConstantLength<6>, 3, 2>::init()
         poseidon::Hash::<_, poseidon::P128Pow5T3, poseidon::ConstantLength<6>, 3, 2>::init()
             .hash(coin2_commit_msg_input);
             .hash(coin2_commit_msg_input);
@@ -269,7 +275,10 @@ fn create_leadcoin(
     coin
     coin
 }
 }
 
 
-fn create_coins_election_seeds(eta: pallas::Base, slot: pallas::Base) -> (pallas::Base, pallas::Base) {
+fn create_coins_election_seeds(
+    eta: pallas::Base,
+    slot: pallas::Base,
+) -> (pallas::Base, pallas::Base) {
     let election_seed_nonce: pallas::Base = pallas::Base::from(3);
     let election_seed_nonce: pallas::Base = pallas::Base::from(3);
     let election_seed_lead: pallas::Base = pallas::Base::from(22);
     let election_seed_lead: pallas::Base = pallas::Base::from(22);
 
 
@@ -303,9 +312,8 @@ pub fn is_leader(slot: u64, epoch_coins: &Vec<Vec<LeadCoin>>) -> (bool, usize) {
     for (winning_idx, coin) in competing_coins.iter().enumerate() {
     for (winning_idx, coin) in competing_coins.iter().enumerate() {
         let y_exp = [coin.root_sk.unwrap(), coin.nonce.unwrap()];
         let y_exp = [coin.root_sk.unwrap(), coin.nonce.unwrap()];
         let y_exp_hash: pallas::Base =
         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);
         let y_coordinates = pedersen_commitment_base(coin.y_mu.unwrap(), mod_r_p(y_exp_hash))
         let y_coordinates = pedersen_commitment_base(coin.y_mu.unwrap(), mod_r_p(y_exp_hash))
             .to_affine()
             .to_affine()
             .coordinates()
             .coordinates()
@@ -315,9 +323,8 @@ pub fn is_leader(slot: u64, epoch_coins: &Vec<Vec<LeadCoin>>) -> (bool, usize) {
         let y_y: pallas::Base = *y_coordinates.y();
         let y_y: pallas::Base = *y_coordinates.y();
         let y_coord_arr = [y_x, y_y];
         let y_coord_arr = [y_x, y_y];
         let y: pallas::Base =
         let y: pallas::Base =
-            poseidon::Hash::<_, poseidon::P128Pow5T3, poseidon::ConstantLength<2>, 3, 2>::init(
-            )
-            .hash(y_coord_arr);
+            poseidon::Hash::<_, poseidon::P128Pow5T3, poseidon::ConstantLength<2>, 3, 2>::init()
+                .hash(y_coord_arr);
         //
         //
         let val_base = pallas::Base::from(coin.value.unwrap());
         let val_base = pallas::Base::from(coin.value.unwrap());
         let target_base =
         let target_base =
@@ -327,14 +334,14 @@ pub fn is_leader(slot: u64, epoch_coins: &Vec<Vec<LeadCoin>>) -> (bool, usize) {
         if y >= target_base {
         if y >= target_base {
             continue
             continue
         }
         }
-        
-        won = true;        
+
+        won = true;
         if coin.value.unwrap() > highest_stake {
         if coin.value.unwrap() > highest_stake {
             highest_stake = coin.value.unwrap();
             highest_stake = coin.value.unwrap();
             highest_stake_idx = winning_idx;
             highest_stake_idx = winning_idx;
         }
         }
     }
     }
-    
+
     (won, highest_stake_idx)
     (won, highest_stake_idx)
 }
 }
 
 
@@ -358,6 +365,6 @@ pub async fn generate_staking_coins(wallet: &WalletDb) -> Result<Vec<OwnCoin>> {
     let leaf_position: incrementalmerkletree::Position = 0.into();
     let leaf_position: incrementalmerkletree::Position = 0.into();
     let coin = OwnCoin { coin, note, secret: keypair.secret, nullifier, leaf_position };
     let coin = OwnCoin { coin, note, secret: keypair.secret, nullifier, leaf_position };
     wallet.put_own_coin(coin.clone()).await?;
     wallet.put_own_coin(coin.clone()).await?;
-    
+
     Ok(vec![coin])
     Ok(vec![coin])
 }
 }

+ 22 - 0
src/consensus/mod.rs

@@ -27,8 +27,19 @@ pub mod task;
 pub mod clock;
 pub mod clock;
 pub use clock::{Clock, Ticks};
 pub use clock::{Clock, Ticks};
 
 
+/// Ouroboros simulation
 pub mod ouroboros;
 pub mod ouroboros;
 
 
+/// Ouroboros consensus coins functions
+pub mod coins;
+
+/// Utility types
+pub mod types;
+pub use types::Float10;
+
+/// Utility functions
+pub mod utils;
+
 use lazy_static::lazy_static;
 use lazy_static::lazy_static;
 lazy_static! {
 lazy_static! {
     /// Genesis hash for the mainnet chain
     /// Genesis hash for the mainnet chain
@@ -51,4 +62,15 @@ lazy_static! {
 
 
     /// Block info magic bytes
     /// Block info magic bytes
     pub static ref BLOCK_INFO_MAGIC_BYTES: [u8; 4] = [0x90, 0x44, 0xf1, 0xf6];
     pub static ref BLOCK_INFO_MAGIC_BYTES: [u8; 4] = [0x90, 0x44, 0xf1, 0xf6];
+
+    // Epoch configuration
+    pub static ref EPOCH_LENGTH: u64 = 10;
+    pub static ref REWARD: u64 = 420;
+
+    // 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;
+
 }
 }

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

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

+ 8 - 302
src/consensus/ouroboros/epoch.rs

@@ -1,36 +1,14 @@
 use crate::{
 use crate::{
-    consensus::ouroboros::{
-        consts::{LOTTERY_HEAD_START, RADIX_BITS},
-        types::Float10,
-        utils::fbig2ibig,
-        EpochConsensus,
-    },
+    consensus::{coins, ouroboros::EpochConsensus},
     crypto::{
     crypto::{
         coin::OwnCoin,
         coin::OwnCoin,
-        keypair::{Keypair, SecretKey},
         lead_proof,
         lead_proof,
         leadcoin::LeadCoin,
         leadcoin::LeadCoin,
         proof::{Proof, ProvingKey},
         proof::{Proof, ProvingKey},
-        types::DrkValueBlind,
-        util::{mod_r_p, pedersen_commitment_base, pedersen_commitment_u64},
     },
     },
 };
 };
-use darkfi_sdk::crypto::{constants::MERKLE_DEPTH_ORCHARD, MerkleNode};
-use halo2_gadgets::poseidon::primitives as poseidon;
-use halo2_proofs::arithmetic::Field;
-use incrementalmerkletree::{bridgetree::BridgeTree, Tree};
 use log::info;
 use log::info;
-use pasta_curves::{
-    arithmetic::CurveAffine,
-    group::{ff::PrimeField, Curve},
-    pallas,
-};
-use rand::{thread_rng, Rng};
-use incrementalmerkletree::Hashable;
-
-
-const PRF_NULLIFIER_PREFIX: u64 = 0;
-const MERKLE_DEPTH: u8 = MERKLE_DEPTH_ORCHARD as u8;
+use pasta_curves::pallas;
 
 
 #[derive(Debug, Default, Clone)]
 #[derive(Debug, Default, Clone)]
 pub struct Epoch {
 pub struct Epoch {
@@ -71,286 +49,14 @@ impl Epoch {
         }
         }
     }
     }
 
 
-    //
-    fn create_coins_election_seeds(&self, sl: pallas::Base) -> (pallas::Base, pallas::Base) {
-        let election_seed_nonce: pallas::Base = pallas::Base::from(3);
-        let election_seed_lead: pallas::Base = pallas::Base::from(22);
-
-        // mu_rho
-        let nonce_mu_msg = [election_seed_nonce, self.eta, sl];
-        let nonce_mu: pallas::Base =
-            poseidon::Hash::<_, poseidon::P128Pow5T3, poseidon::ConstantLength<3>, 3, 2>::init()
-                .hash(nonce_mu_msg);
-        // mu_y
-        let lead_mu_msg = [election_seed_lead, self.eta, sl];
-        let lead_mu: pallas::Base =
-            poseidon::Hash::<_, poseidon::P128Pow5T3, poseidon::ConstantLength<3>, 3, 2>::init()
-                .hash(lead_mu_msg);
-        (lead_mu, nonce_mu)
-    }
-
-    /// at the onset of an epoch, the first slot's coin's secret key
-    /// is sampled at random, and the rest of the secret keys are derived,
-    /// for sk (secret key) at time i+1 is derived from secret key at time i.
-    ///
-    fn create_coins_sks(
-        &self,
-        sks: &mut Vec<SecretKey>,
-    ) -> (Vec<MerkleNode>, Vec<[MerkleNode; MERKLE_DEPTH_ORCHARD]>) {
-        let mut rng = thread_rng();
-        let mut tree = BridgeTree::<MerkleNode, MERKLE_DEPTH>::new(self.len());
-        let mut root_sks: Vec<MerkleNode> = 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..self.len() {
-            let base: pallas::Point = if _i == 0 {
-                pedersen_commitment_u64(1, pallas::Scalar::random(&mut rng))
-            } else {
-                pedersen_commitment_u64(1, mod_r_p(prev_sk_base))
-            };
-            let coord = base.to_affine().coordinates().unwrap();
-            let sk_x = *coord.x();
-            let sk_y = *coord.y();
-            let sk_coord_ar = [sk_x, sk_y];
-            let sk_base: pallas::Base =
-                poseidon::Hash::<_, poseidon::P128Pow5T3, poseidon::ConstantLength<2>, 3, 2>::init(
-                )
-                .hash(sk_coord_ar);
-            sks.push(SecretKey::from(sk_base));
-            prev_sk_base = sk_base;
-            let sk_bytes = sk_base.to_repr();
-            let node = MerkleNode::from_bytes(sk_bytes).unwrap();
-            //let serialized = serde_json::to_string(&node).unwrap();
-            //info!("serialized: {}", serialized);
-            tree.append(&node.clone());
-            let leaf_position = tree.witness();
-            let root = tree.root(0).unwrap();
-            //let (leaf_pos, path) = tree.authentication_path(leaf_position.unwrap()).unwrap();
-            let path = tree.authentication_path(leaf_position.unwrap(), &root).unwrap();
-            //note root sk is at tree.root()
-            //root_sks.push(node);
-            root_sks.push(root);
-            path_sks.push(path.as_slice().try_into().unwrap());
-        }
-        (root_sks, path_sks)
+    /// Wrapper for coins::create_epoch_coins
+    pub fn create_coins(&mut self, e: u64, sl: u64, owned: &Vec<OwnCoin>) {
+        self.coins = coins::create_epoch_coins(self.eta, owned, e, sl);
     }
     }
 
 
-    //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>> {
-        let mut rng = thread_rng();
-        let mut seeds: Vec<u64> = vec![];
-        for _i in 0..self.len() {
-            let rho: u64 = rng.gen();
-            seeds.push(rho);
-        }
-        let mut sks: Vec<SecretKey> = vec![];
-        let (root_sks, path_sks) = self.create_coins_sks(&mut sks);
-        let mut tree_cm = BridgeTree::<MerkleNode, MERKLE_DEPTH>::new(self.len());
-        // matrix of leadcoins, each row has competing coins per slot.
-        let _coins: Vec<Vec<LeadCoin>> = vec![];
-        for i in 0..self.len() {
-            // if you have any stake used is for competition
-            if !owned.is_empty() {
-                let mut slot_coins = vec![];
-                for elem in &owned {
-                    let coin = self.create_leadcoin(
-                        sigma1,
-                        sigma2,
-                        elem.note.value,
-                        i,
-                        root_sks[i],
-                        path_sks[i],
-                        seeds[i],
-                        sks[i],
-                        &mut tree_cm
-                    );
-                    slot_coins.push(coin);
-                }
-                self.coins.push(slot_coins);
-            }
-            // otherwise compete with zero stake
-            else {
-                let coin = self.create_leadcoin(
-                    sigma1,
-                    sigma2,
-                    LOTTERY_HEAD_START,
-                    i,
-                    root_sks[i],
-                    path_sks[i],
-                    seeds[i],
-                    sks[i],
-                    &mut tree_cm
-                );
-                self.coins.push(vec![coin]);
-            }
-        }
-        self.coins.clone()
-    }
-
-    pub fn create_leadcoin(
-        &self,
-        sigma1: pallas::Base,
-        sigma2: pallas::Base,
-        value: u64,
-        i: usize,
-        c_root_sk: MerkleNode,
-        c_path_sk: [MerkleNode; MERKLE_DEPTH_ORCHARD],
-        seed: u64,
-        sk: SecretKey,
-        tree_cm: &mut BridgeTree::<MerkleNode, MERKLE_DEPTH>,
-    ) -> LeadCoin {
-        // keypair
-        let keypair: Keypair = Keypair::new(sk);
-        //random commitment blinding values
-        let mut rng = thread_rng();
-        let one = pallas::Base::one();
-        let c_cm1_blind: DrkValueBlind = pallas::Scalar::random(&mut rng);
-        let c_cm2_blind: DrkValueBlind = pallas::Scalar::random(&mut rng);
-
-        let c_v = pallas::Base::from(value);
-        // coin relative slot index in the epoch
-        let c_sl = pallas::Base::from(u64::try_from(i).unwrap());
-        //
-        //let's assume it's sl for simplicity
-        let c_tau = pallas::Base::from(u64::try_from(i).unwrap());
-        //
-
-        //let coin_pk_msg = [c_tau, c_root_sk.inner()];
-        //let c_pk: pallas::Base = poseidon::Hash::<_, poseidon::P128Pow5T3, poseidon::ConstantLength<2>, 3, 2>::init().hash(coin_pk_msg);
-        let c_pk: pallas::Point = keypair.public.0;
-        let c_pk_coord = c_pk.to_affine().coordinates().unwrap();
-        let c_pk_x = c_pk_coord.x();
-        let c_pk_y = c_pk_coord.y();
-
-        let c_seed = pallas::Base::from(seed);
-        let sn_msg = [c_seed, c_root_sk.inner()];
-        let c_sn: pallas::Base =
-            poseidon::Hash::<_, poseidon::P128Pow5T3, poseidon::ConstantLength<2>, 3, 2>::init()
-                .hash(sn_msg);
-
-        let coin_commit_msg_input =
-            [pallas::Base::from(PRF_NULLIFIER_PREFIX), *c_pk_x, *c_pk_y, c_v, c_seed, one];
-        let coin_commit_msg: pallas::Base =
-            poseidon::Hash::<_, poseidon::P128Pow5T3, poseidon::ConstantLength<6>, 3, 2>::init()
-                .hash(coin_commit_msg_input);
-        let c_cm: pallas::Point = pedersen_commitment_base(coin_commit_msg, c_cm1_blind);
-        let c_cm_coordinates = c_cm.to_affine().coordinates().unwrap();
-        let c_cm_base: pallas::Base = c_cm_coordinates.x() * c_cm_coordinates.y();
-        let c_cm_node = MerkleNode::from(c_cm_base);
-        tree_cm.append(&c_cm_node.clone());
-        let leaf_position = tree_cm.witness();
-        let c_root_cm = tree_cm.root(0).unwrap();
-        let c_cm_path = tree_cm.authentication_path(leaf_position.unwrap(), &c_root_cm).unwrap();
-        /*
-        let c_root_cm = {
-            let mut current = MerkleNode::from(c_cm_base);
-            let pos = leaf_position.unwrap();
-            for (level, sibling) in c_cm_path.iter().enumerate() {
-                let level = level as u8;
-                current = if pos & (1 << level) == 0 {
-                    MerkleNode::combine(level.into(), &current, sibling)
-                } else {
-                    MerkleNode::combine(level.into(), sibling, &current)
-                };
-            }
-            current
-        };
-        */
-
-        let coin_nonce2_msg = [c_seed, c_root_sk.inner()];
-        let c_seed2: pallas::Base =
-            poseidon::Hash::<_, poseidon::P128Pow5T3, poseidon::ConstantLength<2>, 3, 2>::init()
-                .hash(coin_nonce2_msg);
-
-        let coin2_commit_msg_input =
-            [pallas::Base::from(PRF_NULLIFIER_PREFIX), *c_pk_x, *c_pk_y, c_v, c_seed2, one];
-        let coin2_commit_msg: pallas::Base =
-            poseidon::Hash::<_, poseidon::P128Pow5T3, poseidon::ConstantLength<6>, 3, 2>::init()
-                .hash(coin2_commit_msg_input);
-        let c_cm2 = pedersen_commitment_base(coin2_commit_msg, c_cm2_blind);
-
-        // election seeds
-        let (y_mu, rho_mu) = self.create_coins_election_seeds(c_sl);
-        let coin = LeadCoin {
-            value: Some(value),
-            cm: Some(c_cm),
-            cm2: Some(c_cm2),
-            idx: u32::try_from(i).unwrap(), //TODO should be abs slot
-            sl: Some(c_sl),
-            tau: Some(c_tau),
-            nonce: Some(c_seed),
-            nonce_cm: Some(c_seed2),
-            sn: Some(c_sn),
-            keypair: Some(keypair),
-            root_cm: Some(c_root_cm.inner()),
-            root_sk: Some(c_root_sk.inner()),
-            path: Some(c_cm_path.as_slice().try_into().unwrap()),
-            path_sk: Some(c_path_sk),
-            c1_blind: Some(c_cm1_blind),
-            c2_blind: Some(c_cm2_blind),
-            y_mu: Some(y_mu),
-            rho_mu: Some(rho_mu),
-            sigma1: Some(sigma1),
-            sigma2: Some(sigma2),
-        };
-        coin
-    }
-    /// see if the participant stakeholder of this epoch is
-    /// winning the lottery
-    /// if stakeholder with multiple coins have multiple competing winning coins,
-    /// only the highest values coin is selected, since the stakeholder can't give more
-    /// than a proof per block.
-    /// * `sl` - slot relative index
-    /// * `idx` - index of the highest winning coin
-    /// returns true if the stakeholder is a leader for the current slot, else otherwise
-    pub fn is_leader(&self, sl: u64, idx: &mut usize) -> Vec<bool> {
-        let slusize = sl as usize;
-        info!("slot: {}, coin len: {}", sl, self.coins.len());
-        assert!(slusize < self.coins.len());
-        let competing_coins: &Vec<LeadCoin> = &self.coins.clone()[sl as usize];
-        let mut am_leader = vec![];
-        let mut highest_stake = 0;
-        let mut highest_stake_idx: usize = 0;
-        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);
-            let y_coordinates = pedersen_commitment_base(coin.y_mu.unwrap(), mod_r_p(y_exp_hash))
-                .to_affine()
-                .coordinates()
-                .unwrap();
-            //
-            let y_x: pallas::Base = *y_coordinates.x();
-            let y_y: pallas::Base = *y_coordinates.y();
-            let y_coord_arr = [y_x, y_y];
-            let y: pallas::Base =
-                poseidon::Hash::<_, poseidon::P128Pow5T3, poseidon::ConstantLength<2>, 3, 2>::init(
-                )
-                .hash(y_coord_arr);
-            //
-            let val_base = pallas::Base::from(coin.value.unwrap());
-            let target_base =
-                coin.sigma1.unwrap() * val_base + coin.sigma2.unwrap() * val_base * val_base;
-            info!("y: {:?}", y);
-            info!("T: {:?}", target_base);
-            let iam_leader = y < target_base;
-            if iam_leader {
-                if coin.value.unwrap() > highest_stake {
-                    highest_stake = coin.value.unwrap();
-                    highest_stake_idx = winning_idx;
-                }
-            }
-            am_leader.push(iam_leader);
-        }
-        *idx = highest_stake_idx;
-        am_leader
+    /// Wrapper for coins::is_leader
+    pub fn is_leader(&self, sl: u64) -> (bool, usize) {
+        coins::is_leader(sl, &self.coins)
     }
     }
 
 
     /// * `sl` - relative slot index (zero based)
     /// * `sl` - relative slot index (zero based)

+ 0 - 2
src/consensus/ouroboros/mod.rs

@@ -1,7 +1,5 @@
 pub mod consts;
 pub mod consts;
 pub mod epochconsensus;
 pub mod epochconsensus;
-pub mod types;
-pub mod utils;
 pub use epochconsensus::EpochConsensus;
 pub use epochconsensus::EpochConsensus;
 pub mod epoch;
 pub mod epoch;
 pub use epoch::Epoch;
 pub use epoch::Epoch;

+ 34 - 75
src/consensus/ouroboros/stakeholder.rs

@@ -3,9 +3,7 @@ use crate::{
     consensus::{
     consensus::{
         clock::{Clock, Ticks},
         clock::{Clock, Ticks},
         ouroboros::{
         ouroboros::{
-            consts::{LOG_T, P, RADIX_BITS, TREE_LEN},
-            types::Float10,
-            utils::fbig2base,
+            consts::{LOG_T, TREE_LEN},
             Epoch, EpochConsensus, SlotWorkspace, StakeholderState,
             Epoch, EpochConsensus, SlotWorkspace, StakeholderState,
         },
         },
         BlockInfo, LeadProof, Metadata,
         BlockInfo, LeadProof, Metadata,
@@ -16,7 +14,7 @@ use crate::{
         keypair::{PublicKey, SecretKey},
         keypair::{PublicKey, SecretKey},
         lead_proof,
         lead_proof,
         leadcoin::LeadCoin,
         leadcoin::LeadCoin,
-        proof::{Proof, ProvingKey, VerifyingKey},
+        proof::{ProvingKey, VerifyingKey},
         schnorr::SchnorrSecret,
         schnorr::SchnorrSecret,
     },
     },
     net::{P2p, P2pPtr, Settings, SettingsPtr},
     net::{P2p, P2pPtr, Settings, SettingsPtr},
@@ -308,15 +306,6 @@ impl Stakeholder {
         }
         }
     }
     }
 
 
-    fn get_f(&self) -> Float10 {
-        //TODO (res) should be function of the frequency coins in prev epoch
-        // 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
-    }
     /// on the onset of the epoch, layout the new the competing coins
     /// 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
     /// assuming static stake during the epoch, enforced by the commitment to competing coins
     /// in the epoch's gen2esis data.
     /// in the epoch's gen2esis data.
@@ -324,36 +313,7 @@ impl Stakeholder {
         info!(target: LOG_T, "[new epoch] {}", self);
         info!(target: LOG_T, "[new epoch] {}", self);
         let eta = self.get_eta();
         let eta = self.get_eta();
         let mut epoch = Epoch::new(self.epoch_consensus, eta);
         let mut epoch = Epoch::new(self.epoch_consensus, eta);
-        // total stake
-        // let rel_sl = self.workspace.sl;
-        // let epochs = self.workspace.e;
-        // let epoch_len = self.epoch_consensus.get_epoch_len();
-        // let abs_sl = rel_sl + epochs * epoch_len;
-        //
-        let f = self.get_f().with_precision(RADIX_BITS).value();
-        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 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();
-        info!("sigma1: {}", sigma1_fbig);
-
-        let sigma1: pallas::Base = fbig2base(sigma1_fbig);
-        info!("sigma1 base: {:?}", sigma1);
-        let sigma2_fbig = (c / total_sigma).powf(two.clone()) * (field_p / two);
-        info!("sigma2: {}", 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
+        epoch.create_coins(e, sl, &self.ownedcoins);
         self.epoch = epoch.clone();
         self.epoch = epoch.clone();
     }
     }
 
 
@@ -377,39 +337,38 @@ impl Stakeholder {
         self.workspace.set_sl(sl);
         self.workspace.set_sl(sl);
         self.workspace.set_e(e);
         self.workspace.set_e(e);
         self.workspace.set_st(st);
         self.workspace.set_st(st);
-        let mut winning_coin_idx: usize = 0;
-        let won: Vec<bool> = self.epoch.is_leader(sl, &mut winning_coin_idx);
-        for i in 0..won.len() {
-            let proof = if won[i] {
-                let p = self.epoch.get_proof(sl, i, &self.get_leadprovkingkey());
-                // Sanity check for proof validity)
-                info!("================= Leader proof generated successfully, veryfing... =================");
-                let coin = self.epoch.get_coin(sl as usize, i);
-                match lead_proof::verify_lead_proof(&self.get_leadverifyingkey(), &p, &coin.public_inputs()) {
-                    Ok(_) => info!("================= Proof veryfied succsessfully! ================="),
-                    Err(e) => error!("================= Error during leader proof verification: {} =================", e),
-                }
-                info!("====================================================================================");
-                /////////////////////////////////////////////
-                p
-            } else {
-                Proof::new(vec![])
-            };
-            self.workspace.add_leader(won[i]);
-            self.workspace.set_idx(winning_coin_idx);
-            let coin = self.epoch.get_coin(sl as usize, i);
-            let keypair = coin.keypair.unwrap();
-            let addr = Address::from(keypair.public);
-            let sign = keypair.secret.sign(proof.as_ref());
-            let meta =
-                Metadata::new(sign, addr, self.get_eta().to_repr(), LeadProof::from(proof), vec![]);
-            self.workspace.add_metadata(meta);
-            if won[i] {
-                let owned_coin = self
-                    .finalize_coin(&self.epoch.get_coin(sl as usize, winning_coin_idx as usize));
-                self.ownedcoins.push(owned_coin);
-            }
+
+        let (won, idx) = self.epoch.is_leader(sl);
+        info!("Lottery outcome: {}", won);
+        if !won {
+            return
         }
         }
+        // TODO: Generate rewards transaction
+        info!("Winning coin index: {}", idx);
+        // Generating leader proof
+        let coin = self.epoch.get_coin(sl as usize, idx);
+        let proof = self.epoch.get_proof(sl, idx, &self.get_leadprovkingkey());
+        //Verifying generated proof against winning coin public inputs
+        info!("Leader proof generated successfully, veryfing...");
+        match lead_proof::verify_lead_proof(
+            &self.get_leadverifyingkey(),
+            &proof,
+            &coin.public_inputs(),
+        ) {
+            Ok(_) => info!("Proof veryfied succsessfully!"),
+            Err(e) => error!("Error during leader proof verification: {}", e),
+        }
+
+        self.workspace.add_leader(won);
+        self.workspace.set_idx(idx);
+        let keypair = coin.keypair.unwrap();
+        let addr = Address::from(keypair.public);
+        let sign = keypair.secret.sign(proof.as_ref());
+        let meta =
+            Metadata::new(sign, addr, self.get_eta().to_repr(), LeadProof::from(proof), vec![]);
+        self.workspace.add_metadata(meta);
+        let owned_coin = self.finalize_coin(&self.epoch.get_coin(sl as usize, idx as usize));
+        self.ownedcoins.push(owned_coin);
     }
     }
 
 
     //TODO (res) validate the owncoin is the same winning leadcoin
     //TODO (res) validate the owncoin is the same winning leadcoin

+ 0 - 3
src/consensus/ouroboros/types.rs

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

+ 0 - 1
src/consensus/ouroboros/workspace.rs

@@ -3,7 +3,6 @@ use pasta_curves::pallas;
 
 
 use crate::{
 use crate::{
     consensus::{BlockInfo, Header, Metadata},
     consensus::{BlockInfo, Header, Metadata},
-    crypto::proof::Proof,
     tx::Transaction,
     tx::Transaction,
     util::time::Timestamp,
     util::time::Timestamp,
 };
 };

+ 4 - 0
src/consensus/types.rs

@@ -0,0 +1,4 @@
+//! Type aliases used in the consensus codevbase.
+use dashu::float::{round::mode::Zero, FBig};
+
+pub type Float10 = FBig<Zero, 10>;

+ 8 - 8
src/consensus/ouroboros/utils.rs → src/consensus/utils.rs

@@ -1,11 +1,11 @@
-use crate::consensus::ouroboros::types::Float10;
+use super::Float10;
 use dashu::integer::{IBig, Sign};
 use dashu::integer::{IBig, Sign};
 use log::{debug, info};
 use log::{debug, info};
 use pasta_curves::pallas;
 use pasta_curves::pallas;
 //use pasta_curves::{group::ff::PrimeField};
 //use pasta_curves::{group::ff::PrimeField};
 //use dashu::integer::{UBig};
 //use dashu::integer::{UBig};
 
 
-pub(crate) fn fbig2ibig(f: Float10) -> IBig {
+pub fn fbig2ibig(f: Float10) -> IBig {
     let rad = IBig::try_from(10).unwrap();
     let rad = IBig::try_from(10).unwrap();
     let sig = f.repr().significand();
     let sig = f.repr().significand();
     let exp = f.repr().exponent();
     let exp = f.repr().exponent();
@@ -15,7 +15,7 @@ pub(crate) fn fbig2ibig(f: Float10) -> IBig {
     val
     val
 }
 }
 /*
 /*
-pub(crate) fn base2ibig(base: pallas::Base) -> IBig {
+pub fn base2ibig(base: pallas::Base) -> IBig {
     //
     //
     let byts: [u8; 32] = base.to_repr();
     let byts: [u8; 32] = base.to_repr();
     let words: [u64; 4] = [
     let words: [u64; 4] = [
@@ -30,7 +30,7 @@ pub(crate) fn base2ibig(base: pallas::Base) -> IBig {
     ibig
     ibig
 }
 }
 */
 */
-pub(crate) fn fbig2base(f: Float10) -> pallas::Base {
+pub fn fbig2base(f: Float10) -> pallas::Base {
     info!("fbig -> base (f): {}", f);
     info!("fbig -> base (f): {}", f);
     let val: IBig = fbig2ibig(f);
     let val: IBig = fbig2ibig(f);
     let (sign, word) = val.as_sign_words();
     let (sign, word) = val.as_sign_words();
@@ -51,16 +51,16 @@ mod tests {
     use dashu::integer::IBig;
     use dashu::integer::IBig;
     use pasta_curves::pallas;
     use pasta_curves::pallas;
 
 
-    use crate::consensus::ouroboros::{
-        consts::RADIX_BITS,
+    use crate::consensus::{
         types::Float10,
         types::Float10,
-        utils::{base2ibig, fbig2base, fbig2ibig},
+        utils::{fbig2base, fbig2ibig},
+        RADIX_BITS,
     };
     };
 
 
     #[test]
     #[test]
     fn dashu_fbig2ibig() {
     fn dashu_fbig2ibig() {
         let f =
         let f =
-            Float10::from_str_native("234234223.000").unwrap().with_precision(RADIX_BITS).value();
+            Float10::from_str_native("234234223.000").unwrap().with_precision(*RADIX_BITS).value();
         let i: IBig = fbig2ibig(f);
         let i: IBig = fbig2ibig(f);
         let sig = IBig::from(234234223);
         let sig = IBig::from(234234223);
         assert_eq!(i, sig);
         assert_eq!(i, sig);