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

+ 27 - 34
example/crypsinous.rs

@@ -7,69 +7,62 @@ use  ::darkfi::{
 use futures::executor::block_on;
 use futures::executor::block_on;
 use url::Url;
 use url::Url;
 use std::thread;
 use std::thread;
+use vec;
+use clap::Parser;
+
+#[derive(Parser)]
+struct NetCli {
+    addr: String,
+    path: String,
+    peers: Vec<String>,
+}
+
 
 
 #[async_std::main]
 #[async_std::main]
 async fn main()
 async fn main()
 {
 {
+    let args = NetCli::parse();
+    let addr = vec!(Url::parse(args.addr.as_str()).unwrap());
+    let mut peers = vec![];
+    for i in 0..args.peers.len() {
+        peers.push(Url::parse(args.peers[i].as_str()).unwrap());
+    }
+    let seeds = [Url::parse("tls://irc0.dark.fi:11001").unwrap(),
+                 Url::parse("tls://irc1.dark.fi:11001").unwrap()].to_vec();
     let slots=3;
     let slots=3;
     let epochs=3;
     let epochs=3;
     let ticks=10;
     let ticks=10;
     let reward=1;
     let reward=1;
     let epoch_consensus = EpochConsensus::new(Some(slots), Some(epochs), Some(ticks), Some(reward));
     let epoch_consensus = EpochConsensus::new(Some(slots), Some(epochs), Some(ticks), Some(reward));
-    // read n from the cmd
-    let n = 3;
     // initialize n stakeholders
     // initialize n stakeholders
-    let alice_settings = Settings {
-        inbound: vec!(Url::parse("tls://127.0.0.1:12002").unwrap()),
-        outbound_connections: 4,
-        manual_attempt_limit: 0,
-        seed_query_timeout_seconds: 8,
-        connect_timeout_seconds: 10,
-        channel_handshake_seconds: 4,
-        channel_heartbeat_seconds: 10,
-        external_addr: vec!(Url::parse("tls://127.0.0.1:12002").unwrap()),
-        peers: [Url::parse("tls://127.0.0.1:12003").unwrap()].to_vec(),
-        seeds: [Url::parse("tls://irc0.dark.fi:11001").unwrap(),
-                Url::parse("tls://irc1.dark.fi:11001").unwrap()
-        ].to_vec(),
-        ..Default::default()
-    };
-    let bob_settings = Settings {
-        inbound: vec!(Url::parse("tls://127.0.0.1:12003").unwrap()),
+    let settings = Settings {
+        inbound: addr.clone(),
         outbound_connections: 4,
         outbound_connections: 4,
         manual_attempt_limit: 0,
         manual_attempt_limit: 0,
         seed_query_timeout_seconds: 8,
         seed_query_timeout_seconds: 8,
         connect_timeout_seconds: 10,
         connect_timeout_seconds: 10,
         channel_handshake_seconds: 4,
         channel_handshake_seconds: 4,
         channel_heartbeat_seconds: 10,
         channel_heartbeat_seconds: 10,
-        external_addr: vec!(Url::parse("tls://127.0.0.1:12003").unwrap()),
-        peers: [Url::parse("tls://127.0.0.1:12002").unwrap()].to_vec(),
-        seeds: [Url::parse("tls://irc0.dark.fi:11001").unwrap(),
-                Url::parse("tls://irc1.dark.fi:11001").unwrap()
-        ].to_vec(),
+        external_addr: addr.clone(),
+        peers: peers,
+        seeds: seeds,
         ..Default::default()
         ..Default::default()
     };
     };
     //proof's number of rows
     //proof's number of rows
     let k : u32 = 13;
     let k : u32 = 13;
     let mut handles = vec!();
     let mut handles = vec!();
-    let path = "/tmp/db";
+    let path = args.path;
     for i in 0..2 {
     for i in 0..2 {
         let rel_path =  format!("{}{}",path, i.to_string());
         let rel_path =  format!("{}{}",path, i.to_string());
 
 
         let mut stakeholder = block_on(Stakeholder::new(epoch_consensus.clone(),
         let mut stakeholder = block_on(Stakeholder::new(epoch_consensus.clone(),
-                                                        if i==0 {
-                                                            alice_settings.clone()
-                                                        }
-                                                        else {
-                                                            bob_settings.clone()
-                                                        },
+                                                        settings.clone(),
                                                         &rel_path,
                                                         &rel_path,
                                                         i,
                                                         i,
-                                                        Some(k))
-        ).unwrap();
+                                                        Some(k))).unwrap();
 
 
         let handle = thread::spawn(move || {
         let handle = thread::spawn(move || {
-            block_on(stakeholder.background(Some(5)));
+            block_on(stakeholder.background(Some(9)));
         });
         });
         handles.push(handle);
         handles.push(handle);
     }
     }

+ 7 - 8
src/blockchain/epoch.rs

@@ -1,4 +1,4 @@
-use halo2_proofs::{arithmetic::Field};
+use halo2_proofs::{arithmetic::Field,};
 use incrementalmerkletree::{bridgetree::BridgeTree, Tree};
 use incrementalmerkletree::{bridgetree::BridgeTree, Tree};
 use halo2_gadgets::{
 use halo2_gadgets::{
     poseidon::{primitives as poseidon},
     poseidon::{primitives as poseidon},
@@ -19,7 +19,7 @@ use crate::{
         constants::MERKLE_DEPTH_ORCHARD,
         constants::MERKLE_DEPTH_ORCHARD,
         leadcoin::LeadCoin,
         leadcoin::LeadCoin,
         lead_proof,
         lead_proof,
-        proof::{Proof, ProvingKey},
+        proof::{Proof, ProvingKey,},
         merkle_node::MerkleNode,
         merkle_node::MerkleNode,
         util::{mod_r_p, pedersen_commitment_base, pedersen_commitment_u64},
         util::{mod_r_p, pedersen_commitment_base, pedersen_commitment_u64},
         types::DrkValueBlind,
         types::DrkValueBlind,
@@ -97,19 +97,19 @@ impl Epoch {
         }
         }
     }
     }
     fn create_coins_election_seeds(&self, sl: pallas::Base) -> (pallas::Base, pallas::Base) {
     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);
+        let election_seed_nonce : pallas::Base = pallas::Base::from(3);
+        let election_seed_lead : pallas::Base = pallas::Base::from(22);
 
 
         // mu_rho
         // mu_rho
         let nonce_mu_msg = [
         let nonce_mu_msg = [
-            ELECTION_SEED_NONCE,
+            election_seed_nonce,
             self.eta,
             self.eta,
             sl,
             sl,
         ];
         ];
         let nonce_mu : pallas::Base = poseidon::Hash::<_, poseidon::P128Pow5T3, poseidon::ConstantLength<3>, 3, 2>::init().hash(nonce_mu_msg);
         let nonce_mu : pallas::Base = poseidon::Hash::<_, poseidon::P128Pow5T3, poseidon::ConstantLength<3>, 3, 2>::init().hash(nonce_mu_msg);
         // mu_y
         // mu_y
         let lead_mu_msg = [
         let lead_mu_msg = [
-            ELECTION_SEED_LEAD,
+            election_seed_lead,
             self.eta,
             self.eta,
             sl,
             sl,
         ];
         ];
@@ -166,7 +166,6 @@ impl Epoch {
             seeds.push(rho);
             seeds.push(rho);
         }
         }
         let (root_sks, path_sks) = self.create_coins_sks();
         let (root_sks, path_sks) = self.create_coins_sks();
-        let cm1_val: u64 = rng.gen();
         //random commitment blinding values
         //random commitment blinding values
         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);
@@ -274,7 +273,7 @@ impl Epoch {
     pub fn is_leader(&self, sl: u64) -> bool {
     pub fn is_leader(&self, sl: u64) -> bool {
         let slusize = sl as usize;
         let slusize = sl as usize;
         debug!("slot: {}, coin len: {}", sl, self.coins.len());
         debug!("slot: {}, coin len: {}", sl, self.coins.len());
-        assert!(slusize < self.coins.len()  && sl>=0);
+        assert!(slusize < self.coins.len());
         let coin = self.coins[sl as usize];
         let coin = self.coins[sl as usize];
         let y_exp = [
         let y_exp = [
             coin.root_sk.unwrap(),
             coin.root_sk.unwrap(),

+ 3 - 7
src/blockchain/mod.rs

@@ -2,9 +2,7 @@ use log::debug;
 
 
 use crate::{
 use crate::{
     consensus::{Block, BlockInfo},
     consensus::{Block, BlockInfo},
-    util::{
-        time::Timestamp,
-    },
+    util::time::Timestamp,
     Result,
     Result,
 };
 };
 
 
@@ -83,7 +81,7 @@ impl Blockchain {
 
 
         for block in blocks {
         for block in blocks {
             // Store transactions
             // Store transactions
-            let tx_hashes = self.transactions.insert(&block.txs)?;
+            let _tx_hashes = self.transactions.insert(&block.txs)?;
 
 
             // Store header
             // Store header
             let headerhash = self.headers.insert(&[block.header.clone()])?;
             let headerhash = self.headers.insert(&[block.header.clone()])?;
@@ -131,8 +129,6 @@ impl Blockchain {
 
 
         let headers = self.headers.get(hashes, true)?;
         let headers = self.headers.get(hashes, true)?;
         let blocks = self.blocks.get(hashes, true)?;
         let blocks = self.blocks.get(hashes, true)?;
-        let metadata = self.ouroboros_metadata.get(hashes, true)?;
-
 
 
         for (i, header) in headers.iter().enumerate() {
         for (i, header) in headers.iter().enumerate() {
             let header = header.clone().unwrap();
             let header = header.clone().unwrap();
@@ -174,7 +170,7 @@ impl Blockchain {
     }
     }
 
 
     pub fn get_last_proof_hash(&self) -> Result<blake3::Hash> {
     pub fn get_last_proof_hash(&self) -> Result<blake3::Hash> {
-        let (hash, om) = self.ouroboros_metadata.get_last().unwrap();
+        let (hash, _) = self.ouroboros_metadata.get_last().unwrap();
         Ok(hash)
         Ok(hash)
     }
     }
 
 

+ 2 - 1
src/consensus/block.rs

@@ -1,8 +1,9 @@
 use std::fmt;
 use std::fmt;
+
 use incrementalmerkletree::{bridgetree::BridgeTree, Tree};
 use incrementalmerkletree::{bridgetree::BridgeTree, Tree};
 use log::debug;
 use log::debug;
 use pasta_curves::pallas;
 use pasta_curves::pallas;
-use super::{StakeholderMetadata, StreamletMetadata, OuroborosMetadata, BLOCK_MAGIC_BYTES,BLOCK_VERSION};
+use super::{StakeholderMetadata, StreamletMetadata, OuroborosMetadata, BLOCK_MAGIC_BYTES, BLOCK_VERSION};
 
 
 use crate::{
 use crate::{
     crypto::{
     crypto::{

+ 3 - 1
src/consensus/state.rs

@@ -13,7 +13,9 @@ use log::{debug, error, info, warn};
 use rand::rngs::OsRng;
 use rand::rngs::OsRng;
 
 
 use super::{
 use super::{
-    Block, BlockInfo, BlockProposal, OuroborosMetadata, Participant, ProposalChain, StreamletMetadata, Vote, Header};
+    Block, BlockInfo, BlockProposal, OuroborosMetadata, Participant, ProposalChain, StreamletMetadata, Vote, Header,
+};
+
 use crate::{
 use crate::{
     blockchain::Blockchain,
     blockchain::Blockchain,
     crypto::{
     crypto::{

+ 0 - 4
src/crypto/lead_proof.rs

@@ -1,6 +1,3 @@
-use std::time::Instant;
-
-
 use log::{
 use log::{
     error
     error
 };
 };
@@ -28,7 +25,6 @@ pub fn create_lead_proof(pk: &ProvingKey, coin: LeadCoin) -> Result<Proof> {
 pub fn verify_lead_proof(vk: &VerifyingKey,
 pub fn verify_lead_proof(vk: &VerifyingKey,
                          proof: &Proof,
                          proof: &Proof,
                          public_inputs: &[DrkCircuitField]) -> VerifyResult<()> {
                          public_inputs: &[DrkCircuitField]) -> VerifyResult<()> {
-    let start = Instant::now();
     match proof.verify(vk, public_inputs) {
     match proof.verify(vk, public_inputs) {
         Ok(()) => {Ok(())},
         Ok(()) => {Ok(())},
         Err(e) => {
         Err(e) => {

+ 0 - 1
src/crypto/leadcoin.rs

@@ -75,7 +75,6 @@ impl LeadCoin {
         let po_rho = *po_rho_pt.to_affine().coordinates().unwrap().x();
         let po_rho = *po_rho_pt.to_affine().coordinates().unwrap().x();
 
 
 
 
-        let po_cmp = pallas::Base::from(1);
         let _zero = pallas::Base::from(0);
         let _zero = pallas::Base::from(0);
 
 
         // ===============
         // ===============

+ 36 - 34
src/stakeholder/stakeholder.rs

@@ -1,6 +1,6 @@
 use async_executor::Executor;
 use async_executor::Executor;
 use async_std::sync::Arc;
 use async_std::sync::Arc;
-use log::debug;
+//use log::{debug,info};
 use std::fmt;
 use std::fmt;
 
 
 use rand::rngs::OsRng;
 use rand::rngs::OsRng;
@@ -145,9 +145,9 @@ impl Stakeholder
     pub async fn new(consensus: EpochConsensus, settings: Settings, rel_path: &str, id: u8, k: Option<u32>) -> Result<Self>
     pub async fn new(consensus: EpochConsensus, settings: Settings, rel_path: &str, id: u8, k: Option<u32>) -> Result<Self>
     {
     {
         let path = expand_path(&rel_path).unwrap();
         let path = expand_path(&rel_path).unwrap();
-        debug!("opening db");
+        println!("opening db");
         let db = sled::open(&path)?;
         let db = sled::open(&path)?;
-        debug!("opend db");
+        println!("opend db");
         let ts = Timestamp::current_time();
         let ts = Timestamp::current_time();
         let genesis_hash = blake3::hash(b"");
         let genesis_hash = blake3::hash(b"");
         //TODO lisen and add transactions
         //TODO lisen and add transactions
@@ -168,7 +168,7 @@ impl Stakeholder
         //
         //
         let clock = Clock::new(Some(consensus.get_epoch_len()), Some(consensus.get_slot_len()), Some(consensus.get_tick_len()), settings.peers);
         let clock = Clock::new(Some(consensus.get_epoch_len()), Some(consensus.get_slot_len()), Some(consensus.get_tick_len()), settings.peers);
         let keypair = Keypair::random(&mut OsRng);
         let keypair = Keypair::random(&mut OsRng);
-        debug!("stakeholder constructed...");
+        println!("stakeholder constructed...");
         Ok(Self{blockchain: bc,
         Ok(Self{blockchain: bc,
                 net: p2p,
                 net: p2p,
                 clock: clock,
                 clock: clock,
@@ -220,13 +220,12 @@ impl Stakeholder
     }
     }
     */
     */
 
 
-    fn init_network(&self) -> Result<()>{
-        //TODO initialize exectutor
-        //let exec = Arc<Executor<'_>>;
+    async fn init_network(&self) -> Result<()> {
+        println!("runing p2p net");
         let exec = Arc::new(Executor::new());
         let exec = Arc::new(Executor::new());
-        exec.run(self.net.clone().start(exec.clone()));
-        //self.net(exec);
-
+        self.net.clone().start(exec.clone()).await?;
+        self.net.clone().run(exec).await?;
+        println!("p2p net running...");
         Ok(())
         Ok(())
     }
     }
 
 
@@ -238,7 +237,7 @@ impl Stakeholder
     /// add new blockinfo to the blockchain
     /// add new blockinfo to the blockchain
     pub fn add_block(&self, block: BlockInfo) {
     pub fn add_block(&self, block: BlockInfo) {
         let blocks = [block];
         let blocks = [block];
-        self.blockchain.add(&blocks);
+        let _len = self.blockchain.add(&blocks);
     }
     }
 
 
     pub fn add_tx(&mut self, tx: Transaction)
     pub fn add_tx(&mut self, tx: Transaction)
@@ -251,7 +250,6 @@ impl Stakeholder
     /// converted to pallas base
     /// converted to pallas base
     pub fn get_eta(&self) -> pallas::Base
     pub fn get_eta(&self) -> pallas::Base
     {
     {
-        let last_proof_slot : u64 = 0;
         let proof_tx_hash = self.blockchain.get_last_proof_hash().unwrap();
         let proof_tx_hash = self.blockchain.get_last_proof_hash().unwrap();
         let mut bytes : [u8;32] = *proof_tx_hash.as_bytes();
         let mut bytes : [u8;32] = *proof_tx_hash.as_bytes();
         // read first 254 bits
         // read first 254 bits
@@ -260,7 +258,7 @@ impl Stakeholder
         pallas::Base::from_repr(bytes).unwrap()
         pallas::Base::from_repr(bytes).unwrap()
     }
     }
 
 
-    pub fn valid_block(&self, blk : BlockInfo)  -> bool {
+    pub fn valid_block(&self, _blk : BlockInfo)  -> bool {
         //TODO implement
         //TODO implement
         true
         true
     }
     }
@@ -277,35 +275,37 @@ impl Stakeholder
     /// if so add the proof to metadata if stakeholder isn't the lead.
     /// if so add the proof to metadata if stakeholder isn't the lead.
     pub async fn sync_block(&self) {
     pub async fn sync_block(&self) {
         let subscription : Subscription<Result<ChannelPtr>> = self.net.subscribe_channel().await;
         let subscription : Subscription<Result<ChannelPtr>> = self.net.subscribe_channel().await;
-        debug!("--> channel");
+        println!("--> channel");
         let chanptr : ChannelPtr =  subscription.receive().await.unwrap();
         let chanptr : ChannelPtr =  subscription.receive().await.unwrap();
-        debug!("--> received channel");
+        println!("--> received channel");
         //
         //
         let message_subsytem = chanptr.get_message_subsystem();
         let message_subsytem = chanptr.get_message_subsystem();
-        debug!("--> adding dispatcher to msg subsystem");
+        println!("--> adding dispatcher to msg subsystem");
         message_subsytem.add_dispatch::<BlockInfo>().await;
         message_subsytem.add_dispatch::<BlockInfo>().await;
-        debug!("--> added");
+        println!("--> added");
         //TODO start channel if isn't started yet
         //TODO start channel if isn't started yet
         //let info = chanptr.get_info();
         //let info = chanptr.get_info();
-        //debug!("channel info: {}", info);
-        debug!("--> subscribe msg_sub");
+        //println!("channel info: {}", info);
+        println!("--> subscribe msg_sub");
         let msg_sub : MessageSubscription::<BlockInfo> =
         let msg_sub : MessageSubscription::<BlockInfo> =
             chanptr.subscribe_msg::<BlockInfo>().await.expect("missing blockinfo");
             chanptr.subscribe_msg::<BlockInfo>().await.expect("missing blockinfo");
-        debug!("--> subscribed");
+        println!("--> subscribed");
 
 
         let res = msg_sub.receive().await.unwrap();
         let res = msg_sub.receive().await.unwrap();
         let blk : BlockInfo = (*res).to_owned();
         let blk : BlockInfo = (*res).to_owned();
         //TODO validate the block proof, and transactions.
         //TODO validate the block proof, and transactions.
         if self.valid_block(blk.clone())  {
         if self.valid_block(blk.clone())  {
             //TODO if valid only.
             //TODO if valid only.
-            self.blockchain.add(&[blk.clone()]);
+            let _len = self.blockchain.add(&[blk.clone()]);
         } else {
         } else {
-            debug!("received block is invalid!");
+            println!("received block is invalid!");
         }
         }
     }
     }
 
 
     pub async fn background(&mut self, hardlimit: Option<u8>) {
     pub async fn background(&mut self, hardlimit: Option<u8>) {
-        self.clock.sync().await;
+
+        let _ = self.init_network().await;
+        let _ = self.clock.sync().await;
         let mut c : u8= 0;
         let mut c : u8= 0;
         let lim : u8 = hardlimit.unwrap_or(0);
         let lim : u8 = hardlimit.unwrap_or(0);
         while self.playing {
         while self.playing {
@@ -327,31 +327,33 @@ impl Stakeholder
                 }
                 }
                 Ticks::NEWSLOT{e, sl} => self.new_slot(e, sl),
                 Ticks::NEWSLOT{e, sl} => self.new_slot(e, sl),
                 Ticks::TOCKS => {
                 Ticks::TOCKS => {
+                    println!("tocks");
                     // slot is about to end.
                     // slot is about to end.
                     // sync, and validate.
                     // sync, and validate.
                     // no more transactions to be received/send to the end of slot.
                     // no more transactions to be received/send to the end of slot.
                     if self.workspace.is_leader {
                     if self.workspace.is_leader {
-                        debug!("<<<--- [[[leadership won]]] --->>>");
+                        println!("<<<--- [[[leadership won]]] --->>>");
                         //craete block
                         //craete block
-                        let (block_info, block_hash) = self.workspace.new_block();
+                        let (block_info, _block_hash) = self.workspace.new_block();
                         //add the block to the blockchain
                         //add the block to the blockchain
                         self.add_block(block_info.clone());
                         self.add_block(block_info.clone());
                         let block : Block = Block::from(block_info.clone());
                         let block : Block = Block::from(block_info.clone());
                         // publish the block
                         // publish the block
                         //TODO (fix) before publishing the workspace tx root need to be set.
                         //TODO (fix) before publishing the workspace tx root need to be set.
-                        self.net.broadcast(block);
+                        let _ret = self.net.broadcast(block).await;
                     } else {
                     } else {
                         //
                         //
-                        self.sync_block();
+                        self.sync_block().await;
                     }
                     }
                 },
                 },
                 Ticks::IDLE => {
                 Ticks::IDLE => {
                     continue
                     continue
                 }
                 }
                 Ticks::OUTOFSYNC => {
                 Ticks::OUTOFSYNC => {
+                    println!("out of sync");
                     // clock, and blockchain are out of sync
                     // clock, and blockchain are out of sync
-                    self.clock.sync().await;
-                    self.sync_block();
+                    let _ = self.clock.sync().await;
+                    self.sync_block().await;
                 }
                 }
             }
             }
             thread::sleep(Duration::from_millis(1000));
             thread::sleep(Duration::from_millis(1000));
@@ -367,9 +369,9 @@ impl Stakeholder
     /// in the epoch's gen2esis data.
     /// in the epoch's gen2esis data.
     fn new_epoch(&mut self)
     fn new_epoch(&mut self)
     {
     {
-        debug!("[new epoch] 4 {}", self);
+        println!("[new epoch] 4 {}", self);
         let eta = self.get_eta();
         let eta = self.get_eta();
-        let mut epoch = Epoch::new(self.epoch_consensus, self.get_eta());
+        let mut epoch = Epoch::new(self.epoch_consensus, eta);
         //TODO calculate total stake
         //TODO calculate total stake
         // create coin with absolute slot/epoch.
         // create coin with absolute slot/epoch.
         let num_slots = self.workspace.sl;
         let num_slots = self.workspace.sl;
@@ -392,12 +394,12 @@ impl Stakeholder
     /// this will encourage each potential leader to play with honesty.
     /// this will encourage each potential leader to play with honesty.
     fn new_slot(&mut self, e: u64, sl: u64)
     fn new_slot(&mut self, e: u64, sl: u64)
     {
     {
-        debug!("[new slot] 4 {}\ne:{}, sl:{}", self, e, sl);
-        let EMPTY_PTR = blake3::hash(b"");
+        println!("[new slot] 4 {}\ne:{}, sl:{}", self, e, sl);
+        let empty_ptr = blake3::hash(b"");
         let st : blake3::Hash = if e>0 || (e==0&&sl>0) {
         let st : blake3::Hash = if e>0 || (e==0&&sl>0) {
             self.workspace.block.blockhash()
             self.workspace.block.blockhash()
         } else {
         } else {
-            EMPTY_PTR
+            empty_ptr
         };
         };
         let is_leader : bool = self.epoch.is_leader(sl);
         let is_leader : bool = self.epoch.is_leader(sl);
         // if is leader create proof
         // if is leader create proof

+ 0 - 1
src/tx/mod.rs

@@ -1,5 +1,4 @@
 use std::io;
 use std::io;
-
 use log::error;
 use log::error;
 use pasta_curves::group::Group;
 use pasta_curves::group::Group;
 
 

+ 5 - 14
src/zk/circuit/lead_contract.rs

@@ -1,7 +1,7 @@
 use halo2_gadgets::{
 use halo2_gadgets::{
     ecc::{
     ecc::{
         chip::{EccChip, EccConfig},
         chip::{EccChip, EccConfig},
-        FixedPoint, FixedPointBaseField,  ScalarFixed,
+        FixedPoint, FixedPointBaseField, ScalarFixed,
     },
     },
     poseidon::{primitives as poseidon, Hash as PoseidonHash, Pow5Chip as PoseidonChip, Pow5Config as PoseidonConfig},
     poseidon::{primitives as poseidon, Hash as PoseidonHash, Pow5Chip as PoseidonChip, Pow5Config as PoseidonConfig},
     sinsemilla::{
     sinsemilla::{
@@ -35,7 +35,6 @@ use crate::zk::gadget::{
     native_range_check::{NativeRangeCheckChip},
     native_range_check::{NativeRangeCheckChip},
 };
 };
 
 
-
 const WINDOW_SIZE: usize = 3;
 const WINDOW_SIZE: usize = 3;
 const NUM_OF_BITS: usize = 254;
 const NUM_OF_BITS: usize = 254;
 const NUM_OF_WINDOWS: usize = 85;
 const NUM_OF_WINDOWS: usize = 85;
@@ -301,14 +300,6 @@ impl Circuit<pallas::Base> for LeadContract {
             config.advices[0],
             config.advices[0],
             Value::known(pallas::Base::from(PRF_NULLIFIER_PREFIX)),
             Value::known(pallas::Base::from(PRF_NULLIFIER_PREFIX)),
         )?;
         )?;
-
-        // constant value 0
-        let zero = self.load_private(
-            layouter.namespace(|| "one"),
-            config.advices[0],
-            Value::known(pallas::Base::zero()),
-        )?;
-
         // staking coin timestamp
         // staking coin timestamp
         let coin_timestamp = self.load_private(
         let coin_timestamp = self.load_private(
             layouter.namespace(|| "load coin time stamp"),
             layouter.namespace(|| "load coin time stamp"),
@@ -345,7 +336,7 @@ impl Circuit<pallas::Base> for LeadContract {
         )?;
         )?;
 
 
         // leadership coefficient used for fine-tunning leader election frequency
         // leadership coefficient used for fine-tunning leader election frequency
-        let c = self.load_private(
+        let _c = self.load_private(
             layouter.namespace(|| ""),
             layouter.namespace(|| ""),
             config.advices[0],
             config.advices[0],
             Value::known(pallas::Base::one()), // note! this parameter to be tuned.
             Value::known(pallas::Base::one()), // note! this parameter to be tuned.
@@ -567,10 +558,10 @@ impl Circuit<pallas::Base> for LeadContract {
         let target = ar_chip.mul(layouter.namespace(|| "calculate target"), &sigma_scalar, &stake_plus)?;
         let target = ar_chip.mul(layouter.namespace(|| "calculate target"), &sigma_scalar, &stake_plus)?;
 
 
         let y : Value<pallas::Base> = y_commit_base.value().cloned();
         let y : Value<pallas::Base> = y_commit_base.value().cloned();
-        let T : Value<pallas::Base> = target.value().cloned();
+        let target : Value<pallas::Base> = target.value().cloned();
         less_than_chip.witness_less_than(
         less_than_chip.witness_less_than(
-            layouter.namespace(|| "y < T"),
-            T, //reversed for testing
+            layouter.namespace(|| "y < target"),
+            target, //reversed for testing
             y,
             y,
             0,
             0,
             true
             true