mohab metwally 3 лет назад
Родитель
Сommit
edc735b337

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

@@ -3,3 +3,4 @@ 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 =
 pub(crate) const P: &str =
     "28948022309329048855892746252171976963363056481941560715954676764349967630337";
     "28948022309329048855892746252171976963363056481941560715954676764349967630337";
+pub(crate) const LOTTERY_HEAD_START : u64 = 0;

+ 23 - 17
src/consensus/ouroboros/epoch.rs

@@ -2,17 +2,16 @@ use darkfi_sdk::crypto::{constants::MERKLE_DEPTH_ORCHARD, MerkleNode};
 use halo2_gadgets::poseidon::primitives as poseidon;
 use halo2_gadgets::poseidon::primitives as poseidon;
 use halo2_proofs::arithmetic::Field;
 use halo2_proofs::arithmetic::Field;
 use incrementalmerkletree::{bridgetree::BridgeTree, Tree};
 use incrementalmerkletree::{bridgetree::BridgeTree, Tree};
-use log::debug;
+use log::info;
 use pasta_curves::{
 use pasta_curves::{
     arithmetic::CurveAffine,
     arithmetic::CurveAffine,
     group::{ff::PrimeField, Curve},
     group::{ff::PrimeField, Curve},
     pallas,
     pallas,
 };
 };
 use rand::{thread_rng, Rng};
 use rand::{thread_rng, Rng};
-
 use crate::{
 use crate::{
     consensus::ouroboros::{
     consensus::ouroboros::{
-        consts::RADIX_BITS,
+        consts::{RADIX_BITS, LOTTERY_HEAD_START},
         utils::{base2ibig, fbig2ibig},
         utils::{base2ibig, fbig2ibig},
         EpochConsensus, Float10,
         EpochConsensus, Float10,
     },
     },
@@ -115,7 +114,7 @@ impl Epoch {
             let sk_bytes = sk_base.to_repr();
             let sk_bytes = sk_base.to_repr();
             let node = MerkleNode::from_bytes(sk_bytes).unwrap();
             let node = MerkleNode::from_bytes(sk_bytes).unwrap();
             //let serialized = serde_json::to_string(&node).unwrap();
             //let serialized = serde_json::to_string(&node).unwrap();
-            //debug!("serialized: {}", serialized);
+            //info!("serialized: {}", serialized);
             tree.append(&node.clone());
             tree.append(&node.clone());
             let leaf_position = tree.witness();
             let leaf_position = tree.witness();
             let root = tree.root(0).unwrap();
             let root = tree.root(0).unwrap();
@@ -171,7 +170,7 @@ impl Epoch {
                 let coin = self.create_leadcoin(
                 let coin = self.create_leadcoin(
                     sigma1,
                     sigma1,
                     sigma2,
                     sigma2,
-                    0,
+                    LOTTERY_HEAD_START,
                     i,
                     i,
                     root_sks[i],
                     root_sks[i],
                     path_sks[i],
                     path_sks[i],
@@ -285,7 +284,7 @@ impl Epoch {
     /// returns true if the stakeholder is a leader for the current slot, else otherwise
     /// returns true if the stakeholder is a leader for the current slot, else otherwise
     pub fn is_leader(&self, sl: u64, idx: &mut usize) -> bool {
     pub fn is_leader(&self, sl: u64, idx: &mut usize) -> bool {
         let slusize = sl as usize;
         let slusize = sl as usize;
-        debug!("slot: {}, coin len: {}", sl, self.coins.len());
+        info!("slot: {}, coin len: {}", sl, self.coins.len());
         assert!(slusize < self.coins.len());
         assert!(slusize < self.coins.len());
         let competing_coins: &Vec<LeadCoin> = &self.coins.clone()[sl as usize];
         let competing_coins: &Vec<LeadCoin> = &self.coins.clone()[sl as usize];
         let mut am_leader = vec![];
         let mut am_leader = vec![];
@@ -299,20 +298,26 @@ impl Epoch {
                 .hash(y_exp);
                 .hash(y_exp);
             //TODO (fix) use the hash of y coordinates, using single coordinate is insecure.
             //TODO (fix) use the hash of y coordinates, using single coordinate is insecure.
             //  pick x coordinate of y for comparison
             //  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 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 val_2ibig =
             let val_2ibig =
                 Float10::try_from(coin.value.unwrap()).unwrap().with_precision(RADIX_BITS).value();
                 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 val_base = pallas::Base::from(coin.value.unwrap());
+            let target_base = coin.sigma1.unwrap() * val_base +
+                coin.sigma2.unwrap() * val_base * val_base;
+            let target_fbig = base2ibig(coin.sigma1.unwrap()) * val_2ibig.clone() + base2ibig(coin.sigma2.unwrap()) * val_2ibig.clone() * val_2ibig;
+            let target_ibig = fbig2ibig(target_fbig);
             let y_ibig = base2ibig(y_x);
             let y_ibig = base2ibig(y_x);
-            debug!("y_x: {}, target: {}", y_ibig, target_ibig);
-            let iam_leader = y_ibig < target_ibig;
+            info!("y_x: {}, target ibig: {}", y_ibig, target_ibig);
+            info!("target base: {:?}", target_base);
+            let iam_leader = y_x < target_base;
             if iam_leader {
             if iam_leader {
                 if coin.value.unwrap() > highest_stake {
                 if coin.value.unwrap() > highest_stake {
                     highest_stake = coin.value.unwrap();
                     highest_stake = coin.value.unwrap();
@@ -331,6 +336,7 @@ impl Epoch {
     /// returns  the of proof of the winning coin of slot `sl` at index `idx` with
     /// returns  the of proof of the winning coin of slot `sl` at index `idx` with
     /// proving key `pk`
     /// proving key `pk`
     pub fn get_proof(&self, sl: u64, idx: usize, pk: &ProvingKey) -> Proof {
     pub fn get_proof(&self, sl: u64, idx: usize, pk: &ProvingKey) -> Proof {
+        info!("get_proof");
         let competing_coins: &Vec<LeadCoin> = &self.coins.clone()[sl as usize];
         let competing_coins: &Vec<LeadCoin> = &self.coins.clone()[sl as usize];
         let coin = competing_coins[idx];
         let coin = competing_coins[idx];
         lead_proof::create_lead_proof(pk, coin).unwrap()
         lead_proof::create_lead_proof(pk, coin).unwrap()

+ 7 - 8
src/consensus/ouroboros/mod.rs

@@ -1,15 +1,19 @@
 use std::{fmt, thread, time::Duration};
 use std::{fmt, thread, time::Duration};
-
 use async_std::sync::Arc;
 use async_std::sync::Arc;
 use darkfi_sdk::crypto::{constants::MERKLE_DEPTH, MerkleNode};
 use darkfi_sdk::crypto::{constants::MERKLE_DEPTH, MerkleNode};
 use halo2_proofs::arithmetic::Field;
 use halo2_proofs::arithmetic::Field;
+use log::{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;
 use log::{debug, error, info};
 use log::{debug, error, info};
 use pasta_curves::{group::ff::PrimeField, pallas};
 use pasta_curves::{group::ff::PrimeField, pallas};
 use rand::rngs::OsRng;
 use rand::rngs::OsRng;
 use smol::Executor;
 use smol::Executor;
 use url::Url;
 use url::Url;
-
 use crate::{
 use crate::{
     blockchain::Blockchain,
     blockchain::Blockchain,
     consensus::{
     consensus::{
@@ -41,20 +45,15 @@ use crate::{
     zk::circuit::{BurnContract, LeadContract, MintContract},
     zk::circuit::{BurnContract, LeadContract, MintContract},
     Result,
     Result,
 };
 };
-
 pub mod consts;
 pub mod consts;
 pub mod types;
 pub mod types;
 pub mod utils;
 pub mod utils;
-
 pub mod epochconsensus;
 pub mod epochconsensus;
 pub use epochconsensus::EpochConsensus;
 pub use epochconsensus::EpochConsensus;
-
 pub mod epoch;
 pub mod epoch;
 pub use epoch::Epoch;
 pub use epoch::Epoch;
-
 pub(crate) mod workspace;
 pub(crate) mod workspace;
 pub(crate) use workspace::SlotWorkspace;
 pub(crate) use workspace::SlotWorkspace;
-
 pub(crate) mod state;
 pub(crate) mod state;
 pub(crate) use state::StakeholderState;
 pub(crate) use state::StakeholderState;
 
 
@@ -119,7 +118,7 @@ impl Stakeholder {
         let faucet_signature_secret = SecretKey::random(&mut OsRng);
         let faucet_signature_secret = SecretKey::random(&mut OsRng);
         let faucet_signature_public = PublicKey::from_secret(faucet_signature_secret);
         let faucet_signature_public = PublicKey::from_secret(faucet_signature_secret);
 
 
-        debug!(target: LOG_T, "stakeholder constructed");
+        info!(target: LOG_T, "stakeholder constructed");
         Ok(Self {
         Ok(Self {
             blockchain: bc,
             blockchain: bc,
             net: p2p,
             net: p2p,

+ 1 - 0
src/crypto/leadcoin.rs

@@ -12,6 +12,7 @@ use crate::{
     zk::circuit::lead_contract::LeadContract,
     zk::circuit::lead_contract::LeadContract,
 };
 };
 
 
+
 pub const LEAD_PUBLIC_INPUT_LEN: usize = 11;
 pub const LEAD_PUBLIC_INPUT_LEN: usize = 11;
 
 
 #[derive(Debug, Default, Clone, Copy)]
 #[derive(Debug, Default, Clone, Copy)]

+ 1 - 1
src/zk/circuit/burn_contract.rs

@@ -94,7 +94,7 @@ const BURN_USERDATA_OFFSET: usize = 6;
 const BURN_SIGKEYX_OFFSET: usize = 7;
 const BURN_SIGKEYX_OFFSET: usize = 7;
 const BURN_SIGKEYY_OFFSET: usize = 8;
 const BURN_SIGKEYY_OFFSET: usize = 8;
 
 
-#[derive(Default, Debug)]
+#[derive(Default, Debug, Clone)]
 pub struct BurnContract {
 pub struct BurnContract {
     pub secret_key: Value<pallas::Base>,
     pub secret_key: Value<pallas::Base>,
     pub serial: Value<pallas::Base>,
     pub serial: Value<pallas::Base>,

+ 1 - 1
src/zk/circuit/mint_contract.rs

@@ -50,7 +50,7 @@ const MINT_VALCOMY_OFFSET: usize = 2;
 const MINT_TOKCOMX_OFFSET: usize = 3;
 const MINT_TOKCOMX_OFFSET: usize = 3;
 const MINT_TOKCOMY_OFFSET: usize = 4;
 const MINT_TOKCOMY_OFFSET: usize = 4;
 
 
-#[derive(Default, Debug)]
+#[derive(Default, Debug, Clone)]
 pub struct MintContract {
 pub struct MintContract {
     /// X coordinate for public key
     /// X coordinate for public key
     pub pub_x: Value<pallas::Base>,
     pub pub_x: Value<pallas::Base>,