Просмотр исходного кода

[crypsinous: example/crypsinous] finalize crypsinous sim

mohab metwally 4 лет назад
Родитель
Сommit
3521e84865

+ 5 - 0
Cargo.toml

@@ -323,3 +323,8 @@ required-features = ["node"]
 name = "lessthan"
 path = "example/lessthan.rs"
 required-features = ["node"]
+
+[[example]]
+name = "crypsinous"
+path = "example/crypsinous.rs"
+required-features = ["node"]

+ 0 - 15
bin/crypsinous/Cargo.toml

@@ -1,15 +0,0 @@
-[package]
-name = "crypsinous"
-version = "0.1.0"
-description = "crypsinous blockchain simulation"
-authors = ["mohab-metwally@riseup.net"]
-license = "AGPL-3.0-only"
-edition = "2021"
-
-[dependencies]
-async-std = {version = "1.11.0", features = ["attributes"]}
-darkfi = {path = "../../", features = ["node", "tx"]}
-url = "2.2.2"
-thread = "0.1.0"
-futures = "0.3.21"
-#url = {version = "2.2.2", features = ["serde"], optional = true}

+ 1 - 3
bin/crypsinous/src/main.rs → example/crypsinous.rs

@@ -19,7 +19,6 @@ async fn main()
     /// read n from the cmd
     let n = 3;
     /// initialize n stakeholders
-    //let mut stakeholders = vec!();
     let alice_settings = Settings {
         inbound: Some(Url::parse("tls://127.0.0.1:12002").unwrap()),
         outbound_connections: 4,
@@ -50,7 +49,7 @@ async fn main()
     };
     let k : u32 = 13; //proof's number of rows
     let mut handles = vec!();
-    let path = "db";
+    let path = "/tmp/db";
     for i in 0..2 {
         let rel_path =  format!("{}{}",path, i.to_string());
 
@@ -69,7 +68,6 @@ async fn main()
         let handle = thread::spawn(move || {
             block_on(stakeholder.background());
         });
-        //stakeholders.push(stakeholder);
         handles.push(handle);
     }
     for handle in handles {

+ 5 - 3
src/blockchain/epoch.rs

@@ -4,6 +4,8 @@ use halo2_gadgets::{
     poseidon::{primitives as poseidon},
 };
 
+use log::debug;
+
 use pasta_curves::{
     arithmetic::CurveAffine,
     group::{ff::PrimeField, Curve},
@@ -142,7 +144,7 @@ impl Epoch {
             };
             let node = MerkleNode::from_bytes(&sk_bytes).unwrap();
             //let serialized = serde_json::to_string(&node).unwrap();
-            //println!("serialized: {}", serialized);
+            //debug!("serialized: {}", serialized);
             tree.append(&node.clone());
             let leaf_position = tree.witness();
             let root = tree.root(0).unwrap();
@@ -271,7 +273,7 @@ impl Epoch {
     /// winning the lottery, in case of success return True
     pub fn is_leader(&self, sl: u64) -> bool {
         let slusize = sl as usize;
-        println!("slot: {}, coin len: {}", sl, self.coins.len());
+        debug!("slot: {}, coin len: {}", sl, self.coins.len());
         assert!(slusize < self.coins.len()  && sl>=0);
         let coin = self.coins[sl as usize];
         let y_exp = [
@@ -283,7 +285,7 @@ impl Epoch {
         let y_x : pallas::Base = *pedersen_commitment_base(coin.y_mu.unwrap(), mod_r_p(y_exp_hash)).to_affine().coordinates().unwrap().x();
         let ord = pallas::Base::from(10241024); //TODO fine tune this scalar.
         let target = ord*coin.value.unwrap();
-        println!("y_x: {:?}, target: {:?}", y_x, target);
+        debug!("y_x: {:?}, target: {:?}", y_x, target);
         //reversed for testing
         target < y_x
     }

+ 2 - 7
src/crypto/lead_proof.rs

@@ -6,6 +6,7 @@ use log::{
     debug,
     error
 };
+
 use pasta_curves::pallas;
 use rand::rngs::OsRng;
 
@@ -22,17 +23,11 @@ use crate::{
 
 use rand::{thread_rng, Rng};
 
-//#[allow(clippy::too_many_arguments)]
+#[allow(clippy::too_many_arguments)]
 pub fn create_lead_proof(pk: &ProvingKey, coin: LeadCoin) -> Result<Proof> {
-    println!("[creating lead proof]");
     let contract = coin.create_contract();
-    //let start = Instant::now();
-    println!("[creating lead proof] public inputs");
     let public_inputs = coin.public_inputs();
-    println!("[creating lead proof] Proof create");
     let proof = Proof::create(&pk, &[contract], &public_inputs, &mut OsRng)?;
-    println!("[creating lead proof] proof successfully created");
-    //debug!("Prove lead: [{:?}]", start.elapsed());
     Ok(proof)
 }
 

+ 14 - 15
src/stakeholder/stakeholder.rs

@@ -125,9 +125,9 @@ impl Stakeholder
     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();
-        println!("opening db");
+        debug!("opening db");
         let db = sled::open(&path)?;
-        println!("opend db");
+        debug!("opend db");
         let ts = Timestamp::current_time();
         let genesis_hash = blake3::hash(b"");
         //TODO lisen and add transactions
@@ -147,7 +147,7 @@ impl Stakeholder
 
         //
         let clock = Clock::new(Some(consensus.get_epoch_len()), Some(consensus.get_slot_len()), Some(consensus.get_tick_len()), settings.peers);
-        println!("stakeholder constructed...");
+        debug!("stakeholder constructed...");
         Ok(Self{blockchain: bc,
                 net: p2p,
                 clock: clock,
@@ -245,21 +245,21 @@ impl Stakeholder
     /// if so add the proof to metadata if stakeholder isn't the lead.
     pub async fn sync_block(&self) {
         let subscription : Subscription<Result<ChannelPtr>> = self.net.subscribe_channel().await;
-        println!("--> channel");
+        debug!("--> channel");
         let chanptr : ChannelPtr =  subscription.receive().await.unwrap();
-        println!("--> received channel");
+        debug!("--> received channel");
         //
         let message_subsytem = chanptr.get_message_subsystem();
-        println!("--> adding dispatcher to msg subsystem");
+        debug!("--> adding dispatcher to msg subsystem");
         message_subsytem.add_dispatch::<BlockInfo>().await;
-        println!("--> added");
+        debug!("--> added");
         //TODO start channel if isn't started yet
         //let info = chanptr.get_info();
-        //println!("channel info: {}", info);
-        println!("--> subscribe msg_sub");
+        //debug!("channel info: {}", info);
+        debug!("--> subscribe msg_sub");
         let msg_sub : MessageSubscription::<BlockInfo> =
             chanptr.subscribe_msg::<BlockInfo>().await.expect("missing blockinfo");
-        println!("--> subscribed");
+        debug!("--> subscribed");
 
         let res = msg_sub.receive().await.unwrap();
         let blk : BlockInfo = (*res).to_owned();
@@ -268,7 +268,7 @@ impl Stakeholder
             //TODO if valid only.
             self.blockchain.add(&[blk.clone()]);
         } else {
-            println!("received block is invalid!");
+            debug!("received block is invalid!");
         }
     }
 
@@ -293,6 +293,7 @@ impl Stakeholder
                     // sync, and validate.
                     // no more transactions to be received/send to the end of slot.
                     if self.workspace.is_leader {
+                        debug!("<<<--- [[[leadership won]]] --->>>");
                         //craete block
                         let (block_info, block_hash) = self.workspace.new_block();
                         //add the block to the blockchain
@@ -326,7 +327,7 @@ impl Stakeholder
     /// in the epoch's gen2esis data.
     fn new_epoch(&mut self)
     {
-        println!("[new epoch] 4 {}", self);
+        debug!("[new epoch] 4 {}", self);
         let eta = self.get_eta();
         let mut epoch = Epoch::new(self.epoch_consensus, self.get_eta());
         epoch.create_coins(); // set epoch interal fields working space with competing coins
@@ -342,7 +343,7 @@ impl Stakeholder
     /// this will encourage each potential leader to play with honesty.
     fn new_slot(&mut self, e: u64, sl: u64)
     {
-        println!("[new slot] 4 {}\ne:{}, sl:{}", self, e, sl);
+        debug!("[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) {
             self.workspace.block.blockhash()
@@ -352,7 +353,6 @@ impl Stakeholder
         let is_leader : bool = self.epoch.is_leader(sl);
         // if is leader create proof
         let proof = if is_leader {
-            println!("<<<--- [[[leadership won]]] --->>>");
             self.epoch.get_proof(sl, &self.pk.clone())
         } else {
             Proof::new(vec![])
@@ -365,7 +365,6 @@ impl Stakeholder
         self.workspace.set_proof(proof.clone());
         //
         if is_leader {
-            println!("<<<--- [[[leadership won]]] --->>>");
             let metadata = Metadata::new(Timestamp::current_time(),
                                          self.get_eta().to_repr(),
                                          TransactionLeadProof::from(proof.clone()));

+ 12 - 12
src/util/clock.rs

@@ -73,7 +73,7 @@ impl Clock {
                 Ok(t)
             },
             e => {
-                println!("ntp request failed: {}", e);
+                debug!("ntp request failed: {}", e);
                 Err(Error::ClockOutOfSync(e.to_string()))
             }
     }
@@ -100,7 +100,7 @@ impl Clock {
     /// return true if the clock is at the begining (before 2/3 of the slot).
     async fn ticking(&self) -> bool {
         let (abs, rel) =  self.tick_time().await;
-        println!("abs ticks: {}, rel ticks: {}", abs, rel);
+        debug!("abs ticks: {}, rel ticks: {}", abs, rel);
         rel < (self.tick_len) /3
     }
 
@@ -115,21 +115,21 @@ impl Clock {
     /// absolute zero based slot index
     async fn slot_abs(&self) -> u64 {
         let sl_abs = self.tick_time().await.0 / self.sl_len;
-        println!("[slot_abs] slot len: {} - slot abs: {}", self.sl_len, sl_abs);
+        debug!("[slot_abs] slot len: {} - slot abs: {}", self.sl_len, sl_abs);
         sl_abs
     }
 
     /// relative zero based slot index
     async fn  slot_relative(&self) -> u64 {
         let e_abs = self.slot_abs().await % self.e_len;
-        println!("[slot_relative] slot len: {} - slot relative: {}", self.sl_len, e_abs);
+        debug!("[slot_relative] slot len: {} - slot relative: {}", self.sl_len, e_abs);
         e_abs
     }
 
     /// absolute zero based epoch index.
     async fn epoch_abs(&self) -> u64 {
         let res = self.slot_abs().await / self.e_len;
-        println!("[epoch_abs] epoch len: {} - epoch abs: {}", self.e_len, res);
+        debug!("[epoch_abs] epoch len: {} - epoch abs: {}", self.e_len, res);
         res
     }
 
@@ -138,34 +138,34 @@ impl Clock {
         let e = self.epoch_abs().await;
         let sl = self.slot_relative().await;
         if self.ticking().await {
-            println!("e/e`: {}/{} sl/sl`: {}/{}, BB_E/BB_SL: {}/{}", e, self.e, sl, self.sl, BB_E, BB_SL);
+            debug!("e/e`: {}/{} sl/sl`: {}/{}, BB_E/BB_SL: {}/{}", e, self.e, sl, self.sl, BB_E, BB_SL);
             if e==self.e&&e==BB_E &&  self.sl==BB_SL {
                 self.sl=sl+1; // 0
                 self.e=e; // 0
-                println!("new genesis");
+                debug!("new genesis");
                 Ticks::GENESIS{e:e, sl:sl}
             } else if e==self.e&&sl==self.sl+1 {
                 self.sl=sl;
-                println!("new slot");
+                debug!("new slot");
                 Ticks::NEWSLOT{e:e, sl:sl}
             } else if e==self.e+1 && sl==0 {
                 self.e=e;
                 self.sl=sl;
-                println!("new epoch");
+                debug!("new epoch");
                 Ticks::NEWEPOCH{e:e, sl:sl}
             }
             else if e==self.e && sl==self.sl {
-                println!("clock is idle");
+                debug!("clock is idle");
                 thread::sleep(Duration::from_millis(100));
                 Ticks::IDLE
             }
             else {
-                println!("clock is out of sync");
+                debug!("clock is out of sync");
                 //clock is out of sync
                 Ticks::OUTOFSYNC
             }
         } else {
-            println!("tocks");
+            debug!("tocks");
             Ticks::TOCKS
         }
     }