Dastan-glitch 3 سال پیش
والد
کامیت
a50de65a78

+ 266 - 275
bin/darkotc/src/main.rs

@@ -2,18 +2,18 @@ use std::{
     io::{stdin, Read},
     process::exit,
     /*
-<<<<<<< HEAD
-    str::FromStr,
-};
+    <<<<<<< HEAD
+        str::FromStr,
+    };
 
-use clap::{Parser, Subcommand};
-use darkfi::crypto::proof::VerifyingKey;
-use halo2_proofs::{arithmetic::Field, pasta::group::ff::PrimeField};
-use rand::rngs::OsRng;
-use serde_json::json;
-use termion::color;
-      =======
-      */
+    use clap::{Parser, Subcommand};
+    use darkfi::crypto::proof::VerifyingKey;
+    use halo2_proofs::{arithmetic::Field, pasta::group::ff::PrimeField};
+    use rand::rngs::OsRng;
+    use serde_json::json;
+    use termion::color;
+          =======
+          */
 };
 
 use clap::{Parser, Subcommand};
@@ -26,25 +26,25 @@ use darkfi::{
     cli_desc,
     crypto::{
         /*
-<<<<<<< HEAD
-        address::Address,
-        burn_proof::{create_burn_proof, verify_burn_proof},
-        keypair::{PublicKey, SecretKey},
-        merkle_node::MerkleNode,
-        mint_proof::{create_mint_proof, verify_mint_proof},
-        proof::ProvingKey,
-        token_id,
-        types::{DrkCoinBlind, DrkSerial, DrkTokenId, DrkValueBlind},
-        util::{pedersen_commitment_base, pedersen_commitment_u64},
-        BurnRevealedValues, MintRevealedValues, OwnCoin, Proof,
-    },
-    rpc::{client::RpcClient, jsonrpc::JsonRequest},
-    util::{
-        cli::progress_bar,
-        encode_base10,
-        serial::{deserialize, serialize, SerialDecodable, SerialEncodable},
-        =======
-            */
+        <<<<<<< HEAD
+                address::Address,
+                burn_proof::{create_burn_proof, verify_burn_proof},
+                keypair::{PublicKey, SecretKey},
+                merkle_node::MerkleNode,
+                mint_proof::{create_mint_proof, verify_mint_proof},
+                proof::ProvingKey,
+                token_id,
+                types::{DrkCoinBlind, DrkSerial, DrkTokenId, DrkValueBlind},
+                util::{pedersen_commitment_base, pedersen_commitment_u64},
+                BurnRevealedValues, MintRevealedValues, OwnCoin, Proof,
+            },
+            rpc::{client::RpcClient, jsonrpc::JsonRequest},
+            util::{
+                cli::progress_bar,
+                encode_base10,
+                serial::{deserialize, serialize, SerialDecodable, SerialEncodable},
+                =======
+                    */
         burn_proof::{create_burn_proof, verify_burn_proof},
         keypair::{PublicKey, SecretKey},
         mint_proof::{create_mint_proof, verify_mint_proof},
@@ -102,144 +102,144 @@ enum Subcmd {
     Init {
         #[clap(short, long)]
         /*
-        <<<<<<< HEAD
-        /// Pair of token IDs to swap: e.g. token_to_send:token_to_recv
-        token_pair: String,
+                <<<<<<< HEAD
+                /// Pair of token IDs to swap: e.g. token_to_send:token_to_recv
+                token_pair: String,
 
-        #[clap(short, long)]
-        /// Pair of values to swap: e.g. value_to_send:value_to_recv
-        value_pair: String,
-    },
-
-    /// Inspect swap data from stdin or file.
-    Inspect,
-}
-
-struct Rpc {
-    pub rpc_client: RpcClient,
-}
-
-impl Rpc {
-    async fn balance_of(&self, token_id: &str) -> Result<u64> {
-        let req = JsonRequest::new("wallet.get_balances", json!([]));
-        let rep = self.rpc_client.request(req).await?;
-
-        if !rep.is_object() {
-            eprintln!("Error: Invalid balance data received from darkfid RPC endpoint.");
-            exit(1);
-        }
-
-        for i in rep.as_object().unwrap().keys() {
-            if i == &token_id {
-                if let Some(balance) = rep[i].as_u64() {
-                    return Ok(balance)
-                }
+                #[clap(short, long)]
+                /// Pair of values to swap: e.g. value_to_send:value_to_recv
+                value_pair: String,
+            },
 
-                eprintln!("Error: Invalid balance data received from darkfid RPC endpoint.");
-                exit(1);
-            }
+            /// Inspect swap data from stdin or file.
+            Inspect,
         }
 
-        Ok(0)
-    }
-
-    async fn wallet_address(&self) -> Result<Address> {
-        let req = JsonRequest::new("wallet.get_addrs", json!([0_i64]));
-        let rep = self.rpc_client.request(req).await?;
-
-        if !rep.is_array() || !rep.as_array().unwrap()[0].is_string() {
-            eprintln!("Error: Invalid wallet address received from darkfid RPC endpoint.");
-            exit(1);
+        struct Rpc {
+            pub rpc_client: RpcClient,
         }
 
-        Address::from_str(rep[0].as_str().unwrap())
-    }
+        impl Rpc {
+            async fn balance_of(&self, token_id: &str) -> Result<u64> {
+                let req = JsonRequest::new("wallet.get_balances", json!([]));
+                let rep = self.rpc_client.request(req).await?;
 
-    async fn get_coins_valtok(&self, value: u64, token_id: &str) -> Result<Vec<OwnCoin>> {
-        let req = JsonRequest::new("wallet.get_coins_valtok", json!([value, token_id, true]));
-        let rep = self.rpc_client.request(req).await?;
+                if !rep.is_object() {
+                    eprintln!("Error: Invalid balance data received from darkfid RPC endpoint.");
+                    exit(1);
+                }
 
-        if !rep.is_array() {
-            eprintln!("Error: Invalid coin data received from darkfid RPC endpoint.");
-            exit(1);
-        }
+                for i in rep.as_object().unwrap().keys() {
+                    if i == &token_id {
+                        if let Some(balance) = rep[i].as_u64() {
+                            return Ok(balance)
+                        }
 
-        let mut ret = vec![];
-        let rep = rep.as_array().unwrap();
+                        eprintln!("Error: Invalid balance data received from darkfid RPC endpoint.");
+                        exit(1);
+                    }
+                }
 
-        for i in rep {
-            if !i.is_string() {
-                eprintln!("Error: Invalid base58 data for OwnCoin");
-                exit(1);
+                Ok(0)
             }
 
-            let data = match bs58::decode(i.as_str().unwrap()).into_vec() {
-                Ok(v) => v,
-                Err(e) => {
-                    eprintln!("Error: Failed decoding base58 for OwnCoin: {}", e);
-                    exit(1);
-                }
-            };
+            async fn wallet_address(&self) -> Result<Address> {
+                let req = JsonRequest::new("wallet.get_addrs", json!([0_i64]));
+                let rep = self.rpc_client.request(req).await?;
 
-            let oc = match deserialize(&data) {
-                Ok(v) => v,
-                Err(e) => {
-                    eprintln!("Error: Failed deserializing OwnCoin: {}", e);
+                if !rep.is_array() || !rep.as_array().unwrap()[0].is_string() {
+                    eprintln!("Error: Invalid wallet address received from darkfid RPC endpoint.");
                     exit(1);
                 }
-            };
 
-            ret.push(oc);
-        }
-
-        Ok(ret)
-    }
+                Address::from_str(rep[0].as_str().unwrap())
+            }
 
-    async fn get_merkle_path(&self, leaf_pos: usize) -> Result<Vec<MerkleNode>> {
-        let req = JsonRequest::new("wallet.get_merkle_path", json!([leaf_pos as u64]));
-        let rep = self.rpc_client.request(req).await?;
+            async fn get_coins_valtok(&self, value: u64, token_id: &str) -> Result<Vec<OwnCoin>> {
+                let req = JsonRequest::new("wallet.get_coins_valtok", json!([value, token_id, true]));
+                let rep = self.rpc_client.request(req).await?;
 
-        if !rep.is_array() {
-            eprintln!("Error: Invalid merkle path data received from darkfid RPC endpoint.");
-            exit(1);
-        }
+                if !rep.is_array() {
+                    eprintln!("Error: Invalid coin data received from darkfid RPC endpoint.");
+                    exit(1);
+                }
 
-        let mut ret = vec![];
-        let rep = rep.as_array().unwrap();
+                let mut ret = vec![];
+                let rep = rep.as_array().unwrap();
+
+                for i in rep {
+                    if !i.is_string() {
+                        eprintln!("Error: Invalid base58 data for OwnCoin");
+                        exit(1);
+                    }
+
+                    let data = match bs58::decode(i.as_str().unwrap()).into_vec() {
+                        Ok(v) => v,
+                        Err(e) => {
+                            eprintln!("Error: Failed decoding base58 for OwnCoin: {}", e);
+                            exit(1);
+                        }
+                    };
+
+                    let oc = match deserialize(&data) {
+                        Ok(v) => v,
+                        Err(e) => {
+                            eprintln!("Error: Failed deserializing OwnCoin: {}", e);
+                            exit(1);
+                        }
+                    };
+
+                    ret.push(oc);
+                }
 
-        for i in rep {
-            if !i.is_string() {
-                eprintln!("Error: Invalid base58 data for MerkleNode");
-                exit(1);
+                Ok(ret)
             }
 
-            let n = i.as_str().unwrap();
-            let n = match bs58::decode(n).into_vec() {
-                Ok(v) => v,
-                Err(e) => {
-                    eprintln!("Error: Failed decoding base58 for MerkleNode: {}", e);
+            async fn get_merkle_path(&self, leaf_pos: usize) -> Result<Vec<MerkleNode>> {
+                let req = JsonRequest::new("wallet.get_merkle_path", json!([leaf_pos as u64]));
+                let rep = self.rpc_client.request(req).await?;
+
+                if !rep.is_array() {
+                    eprintln!("Error: Invalid merkle path data received from darkfid RPC endpoint.");
                     exit(1);
                 }
-            };
 
-            if n.len() != 32 {
-                eprintln!("Error: MerkleNode byte length is not 32");
-                exit(1);
-            }
+                let mut ret = vec![];
+                let rep = rep.as_array().unwrap();
+
+                for i in rep {
+                    if !i.is_string() {
+                        eprintln!("Error: Invalid base58 data for MerkleNode");
+                        exit(1);
+                    }
+
+                    let n = i.as_str().unwrap();
+                    let n = match bs58::decode(n).into_vec() {
+                        Ok(v) => v,
+                        Err(e) => {
+                            eprintln!("Error: Failed decoding base58 for MerkleNode: {}", e);
+                            exit(1);
+                        }
+                    };
+
+                    if n.len() != 32 {
+                        eprintln!("Error: MerkleNode byte length is not 32");
+                        exit(1);
+                    }
+
+                    let n = MerkleNode::from_bytes(&n.try_into().unwrap());
+                    if n.is_some().unwrap_u8() == 0 {
+                        eprintln!("Error: Noncanonical bytes of MerkleNode");
+                        exit(1);
+                    }
+
+                    ret.push(n.unwrap());
+                }
 
-            let n = MerkleNode::from_bytes(&n.try_into().unwrap());
-            if n.is_some().unwrap_u8() == 0 {
-                eprintln!("Error: Noncanonical bytes of MerkleNode");
-                exit(1);
+                Ok(ret)
             }
-
-            ret.push(n.unwrap());
-        }
-
-        Ok(ret)
-    }
-        =======
-        */
+                =======
+                */
         /// Pair of token IDs to swap: token_to_send:token_to_recv
         token_pair: String,
 
@@ -303,17 +303,17 @@ async fn init_swap(
     token_pair: (String, String),
     value_pair: (u64, u64),
     /*
-<<<<<<< HEAD
-) -> Result<()> {
-    let rpc_client = RpcClient::new(endpoint).await?;
-    let rpc = Rpc { rpc_client };
+    <<<<<<< HEAD
+    ) -> Result<()> {
+        let rpc_client = RpcClient::new(endpoint).await?;
+        let rpc = Rpc { rpc_client };
 
-    // TODO: Think about decimals, there has to be some metadata to keep track.
-    let tp = (token_id::parse_b58(&token_pair.0)?, token_id::parse_b58(&token_pair.1)?);
-    let vp: (u64, u64) =
-        (value_pair.0.clone().try_into().unwrap(), value_pair.1.clone().try_into().unwrap());
-    =======
-    */
+        // TODO: Think about decimals, there has to be some metadata to keep track.
+        let tp = (token_id::parse_b58(&token_pair.0)?, token_id::parse_b58(&token_pair.1)?);
+        let vp: (u64, u64) =
+            (value_pair.0.clone().try_into().unwrap(), value_pair.1.clone().try_into().unwrap());
+        =======
+        */
 ) -> Result<PartialSwapData> {
     let rpc_client = RpcClient::new(endpoint).await?;
     let rpc = Rpc { rpc_client };
@@ -327,7 +327,6 @@ async fn init_swap(
     if balance < vp.0 {
         eprintln!(
             "Error: There's not enough balance for token \"{}\" in your wallet.",
-
             token_pair.0
         );
         eprintln!("Available balance is {} ({})", encode_base10(balance, 8), balance);
@@ -335,19 +334,19 @@ async fn init_swap(
     }
 
     /*
-<<<<<<< HEAD
-    // If not enough funds in a single coin, mint a single new coin
-    // with the funds. We do this to minimize the size of the swap
-    // transaction, i.e. 2 inputs and 2 outputs.
-    // TODO: Implement ^
-    // TODO: Maybe this should be done by the user beforehand?
-
-    // Find a coin to spend
-    let coins = rpc.get_coins_valtok(vp.0, &token_pair.0).await?;
-    if coins.is_empty() {
-        eprintln!("Error: Did not manage to find a coin with enough value to spend");
-    =======
-    */
+    <<<<<<< HEAD
+        // If not enough funds in a single coin, mint a single new coin
+        // with the funds. We do this to minimize the size of the swap
+        // transaction, i.e. 2 inputs and 2 outputs.
+        // TODO: Implement ^
+        // TODO: Maybe this should be done by the user beforehand?
+
+        // Find a coin to spend
+        let coins = rpc.get_coins_valtok(vp.0, &token_pair.0).await?;
+        if coins.is_empty() {
+            eprintln!("Error: Did not manage to find a coin with enough value to spend");
+        =======
+        */
     // If there's not enough funds in a single coin, mint a single new coin
     // with the funds. We do this to minimize the size of the swap transaction.
     // i.e. 2 inputs and 2 outputs.
@@ -363,15 +362,15 @@ async fn init_swap(
 
     eprintln!("Initializing swap data for:");
     /*
-<<<<<<< HEAD
-    eprintln!("Send: {} {} tokens", encode_base10(value_pair.0, 8), token_pair.0);
-    eprintln!("Recv: {} {} tokens", encode_base10(value_pair.1, 8), token_pair.1);
+    <<<<<<< HEAD
+        eprintln!("Send: {} {} tokens", encode_base10(value_pair.0, 8), token_pair.0);
+        eprintln!("Recv: {} {} tokens", encode_base10(value_pair.1, 8), token_pair.1);
 
-    // Fetch our default address
-    let our_address = rpc.wallet_address().await?;
-    let our_publickey = match PublicKey::try_from(our_address) {
-    =======
-    */
+        // Fetch our default address
+        let our_address = rpc.wallet_address().await?;
+        let our_publickey = match PublicKey::try_from(our_address) {
+        =======
+        */
     eprintln!("Send: {} {} tokens", encode_base10(vp.0, 8), token_pair.0);
     eprintln!("Recv: {} {} tokens", encode_base10(vp.1, 8), token_pair.1);
 
@@ -386,19 +385,19 @@ async fn init_swap(
     };
 
     /*
-<<<<<<< HEAD
-    // Build proving keys
-    let pb = progress_bar("Building proving key for the mint contract");
-    let mint_pk = ProvingKey::build(8, &MintContract::default());
-    pb.finish();
+    <<<<<<< HEAD
+        // Build proving keys
+        let pb = progress_bar("Building proving key for the mint contract");
+        let mint_pk = ProvingKey::build(8, &MintContract::default());
+        pb.finish();
 
-    let pb = progress_bar("Building proving key for the burn contract");
-    let burn_pk = ProvingKey::build(11, &BurnContract::default());
-    pb.finish();
+        let pb = progress_bar("Building proving key for the burn contract");
+        let burn_pk = ProvingKey::build(11, &BurnContract::default());
+        pb.finish();
 
-    // The coin we want to receive.
-    =======
-    */
+        // The coin we want to receive.
+        =======
+        */
     // Build ZK proving keys
     let pb = progress_bar("Building proving key for the Mint contract");
     let mint_pk = ProvingKey::build(11, &MintContract::default());
@@ -414,11 +413,11 @@ async fn init_swap(
     let recv_token_blind = DrkValueBlind::random(&mut OsRng);
     let recv_coin_blind = DrkCoinBlind::random(&mut OsRng);
     let recv_serial = DrkSerial::random(&mut OsRng);
-/*
-<<<<<<< HEAD
-    let pb = progress_bar("Building mint proof for receiving coin");
-    =======
-    */
+    /*
+    <<<<<<< HEAD
+        let pb = progress_bar("Building mint proof for receiving coin");
+        =======
+        */
     // Spend hook and user data disabled
     let spend_hook = DrkSpendHook::from(0);
     let user_data = DrkUserData::from(0);
@@ -433,28 +432,27 @@ async fn init_swap(
         recv_token_blind,
         recv_serial,
         /*
-<<<<<<< HEAD
-        recv_coin_blind,
-        our_publickey,
-        =======
-        */
+        <<<<<<< HEAD
+                recv_coin_blind,
+                our_publickey,
+                =======
+                */
         spend_hook,
         user_data,
         recv_coin_blind,
         our_pubk,
-
     )?;
     pb.finish();
 
     // The coin we are spending.
     /*
-<<<<<<< HEAD
-    // We'll spend the first one we've found.
-    let coin = coins[0];
+    <<<<<<< HEAD
+        // We'll spend the first one we've found.
+        let coin = coins[0];
 
-    let pb = progress_bar("Building burn proof for spending coin");
-    =======
-    */
+        let pb = progress_bar("Building burn proof for spending coin");
+        =======
+        */
     let coin = coins[0].clone();
 
     let pb = progress_bar("Building Burn proof for the spending coin");
@@ -463,19 +461,16 @@ async fn init_swap(
     let merkle_path = match rpc.get_merkle_path(usize::from(coin.leaf_position)).await {
         Ok(v) => v,
         Err(e) => {
-
             eprintln!("Failed to get Merkle path for our coin from darkfid RPC: {}", e);
             exit(1);
         }
     };
 
-
     // Spend hook and user data disabled
     let spend_hook = DrkSpendHook::from(0);
     let user_data = DrkUserData::from(0);
     let user_data_blind = DrkUserDataBlind::random(&mut OsRng);
 
-
     let (burn_proof, burn_revealed) = create_burn_proof(
         &burn_pk,
         vp.0,
@@ -495,12 +490,12 @@ async fn init_swap(
     pb.finish();
 
     /*
-<<<<<<< HEAD
-    // Pack proofs together with pedersen commitment openings so
-    // counterparty can verify correctness.
-    let swap_data = SwapData {
-    =======
-    */
+    <<<<<<< HEAD
+        // Pack proofs together with pedersen commitment openings so
+        // counterparty can verify correctness.
+        let swap_data = SwapData {
+        =======
+        */
     // Create encrypted note
     let note = Note {
         serial: recv_serial,
@@ -517,7 +512,6 @@ async fn init_swap(
     // Pack proofs together with pedersen commitment openings so
     // counterparty can verify correctness.
     let partial_swap_data = PartialSwapData {
-
         mint_proof,
         mint_revealed,
         mint_value: vp.1,
@@ -531,18 +525,18 @@ async fn init_swap(
         burn_value_blind: coin.note.value_blind,
         burn_token_blind: coin.note.token_blind,
         /*
-<<<<<<< HEAD
-    };
+        <<<<<<< HEAD
+            };
 
-    // Print encoded data.
-    println!("{}", bs58::encode(serialize(&swap_data)).into_string());
+            // Print encoded data.
+            println!("{}", bs58::encode(serialize(&swap_data)).into_string());
 
-    Ok(())
-}
+            Ok(())
+        }
 
-fn inspect(data: &str) -> Result<()> {
-        =======
-        */
+        fn inspect(data: &str) -> Result<()> {
+                =======
+                */
         encrypted_note,
     };
 
@@ -550,7 +544,6 @@ fn inspect(data: &str) -> Result<()> {
 }
 
 fn inspect_partial(data: &str) -> Result<()> {
-
     let mut mint_valid = false;
     let mut burn_valid = false;
     let mut mint_value_valid = false;
@@ -567,13 +560,13 @@ fn inspect_partial(data: &str) -> Result<()> {
     };
 
     /*
-<<<<<<< HEAD
-    let sd: SwapData = match deserialize(&bytes) {
-        Ok(v) => v,
-        Err(e) => {
-            eprintln!("Error: Failed to deserialize swap data into struct: {}", e);
-    =======
-    */
+    <<<<<<< HEAD
+        let sd: SwapData = match deserialize(&bytes) {
+            Ok(v) => v,
+            Err(e) => {
+                eprintln!("Error: Failed to deserialize swap data into struct: {}", e);
+        =======
+        */
     let sd: PartialSwapData = match deserialize(&bytes) {
         Ok(v) => v,
         Err(e) => {
@@ -584,21 +577,21 @@ fn inspect_partial(data: &str) -> Result<()> {
     };
 
     /*
-<<<<<<< HEAD
-    eprintln!("Successfully decoded data into SwapData struct");
+    <<<<<<< HEAD
+        eprintln!("Successfully decoded data into SwapData struct");
 
-    // Build verifying keys
-    let pb = progress_bar("Building verifying key for the mint contract");
-    let mint_vk = VerifyingKey::build(8, &MintContract::default());
-    pb.finish();
+        // Build verifying keys
+        let pb = progress_bar("Building verifying key for the mint contract");
+        let mint_vk = VerifyingKey::build(8, &MintContract::default());
+        pb.finish();
 
-    let pb = progress_bar("Building verifying key for the burn contract");
-    let burn_vk = VerifyingKey::build(11, &BurnContract::default());
-    pb.finish();
+        let pb = progress_bar("Building verifying key for the burn contract");
+        let burn_vk = VerifyingKey::build(11, &BurnContract::default());
+        pb.finish();
 
-    let pb = progress_bar("Verifying burn proof");
-    =======
-    */
+        let pb = progress_bar("Verifying burn proof");
+        =======
+        */
     eprintln!("Successfully decoded partial swap data");
 
     // Build ZK verifying keys
@@ -618,10 +611,10 @@ fn inspect_partial(data: &str) -> Result<()> {
     pb.finish();
 
     /*
-<<<<<<< HEAD
-    let pb = progress_bar("Verifying mint proof");
-    =======
-    */
+    <<<<<<< HEAD
+        let pb = progress_bar("Verifying mint proof");
+        =======
+        */
     let pb = progress_bar("Verifying Mint proof");
 
     if verify_mint_proof(&mint_vk, &sd.mint_proof, &sd.mint_revealed).is_ok() {
@@ -630,13 +623,12 @@ fn inspect_partial(data: &str) -> Result<()> {
     pb.finish();
 
     /*
-<<<<<<< HEAD
-    eprintln!("  Verifying pedersen commitments");
-    =======
-    */
+    <<<<<<< HEAD
+        eprintln!("  Verifying pedersen commitments");
+        =======
+        */
     eprintln!("  Verifying Pedersen commitments");
 
-
     if pedersen_commitment_u64(sd.burn_value, sd.burn_value_blind) == sd.burn_revealed.value_commit
     {
         burn_value_valid = true;
@@ -722,22 +714,22 @@ fn inspect_partial(data: &str) -> Result<()> {
     );
 
     /*
-<<<<<<< HEAD
-    if !valid {
-        eprintln!(
-            "\nThe ZK proofs and commitments inspected are {}NOT VALID{}",
-            color::Fg(color::Red),
-            color::Fg(color::Reset)
-        );
-        exit(1);
-    } else {
-        eprintln!(
-            "\nThe ZK proofs and commitments inspected are {}VALID{}",
-            color::Fg(color::Green),
-            color::Fg(color::Reset)
-        );
-        =======
-            */
+    <<<<<<< HEAD
+        if !valid {
+            eprintln!(
+                "\nThe ZK proofs and commitments inspected are {}NOT VALID{}",
+                color::Fg(color::Red),
+                color::Fg(color::Reset)
+            );
+            exit(1);
+        } else {
+            eprintln!(
+                "\nThe ZK proofs and commitments inspected are {}VALID{}",
+                color::Fg(color::Green),
+                color::Fg(color::Reset)
+            );
+            =======
+                */
     eprint!("\nThe ZK proofs and commitments inspected are ");
     if !valid {
         println!("{}", fg_red("NOT VALID"));
@@ -929,7 +921,6 @@ fn try_sign_tx(note: &Note, tx_data: &[u8]) -> Result<schnorr::Signature> {
     eprintln!("Signing transaction...");
     let signature = secret.sign(tx_data);
     Ok(signature)
-
 }
 
 #[async_std::main]
@@ -941,16 +932,16 @@ async fn main() -> Result<()> {
             let token_pair = parse_token_pair(&token_pair)?;
             let value_pair = parse_value_pair(&value_pair)?;
             /*
-            <<<<<<< HEAD
+                <<<<<<< HEAD
 
-            init_swap(args.endpoint, token_pair, value_pair).await
-        }
-        Subcmd::Inspect => {
-            let mut buf = String::new();
-            stdin().read_to_string(&mut buf)?;
-            inspect(&buf.trim())
-            =======
-            */
+                init_swap(args.endpoint, token_pair, value_pair).await
+            }
+            Subcmd::Inspect => {
+                let mut buf = String::new();
+                stdin().read_to_string(&mut buf)?;
+                inspect(&buf.trim())
+                =======
+                */
             let swap_data = init_swap(args.endpoint, token_pair, value_pair).await?;
 
             println!("{}", bs58::encode(serialize(&swap_data)).into_string());

+ 27 - 27
example/crypsinous.rs

@@ -1,14 +1,10 @@
-use  ::darkfi::{
-    stakeholder::Stakeholder,
-    blockchain::{EpochConsensus,},
-    net::{Settings,},
-};
+use ::darkfi::{blockchain::EpochConsensus, net::Settings, stakeholder::Stakeholder};
 
+use clap::Parser;
 use futures::executor::block_on;
-use url::Url;
 use std::thread;
+use url::Url;
 use vec;
-use clap::Parser;
 
 #[derive(Parser)]
 struct NetCli {
@@ -17,22 +13,23 @@ struct NetCli {
     peers: Vec<String>,
 }
 
-
 #[async_std::main]
-async fn main()
-{
+async fn main() {
     let args = NetCli::parse();
-    let addr = vec!(Url::parse(args.addr.as_str()).unwrap());
+    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 epochs=3;
-    let ticks=10;
-    let reward=1;
+    let seeds = [
+        Url::parse("tls://irc0.dark.fi:11001").unwrap(),
+        Url::parse("tls://irc1.dark.fi:11001").unwrap(),
+    ]
+    .to_vec();
+    let slots = 3;
+    let epochs = 3;
+    let ticks = 10;
+    let reward = 1;
     let epoch_consensus = EpochConsensus::new(Some(slots), Some(epochs), Some(ticks), Some(reward));
     // initialize n stakeholders
     let settings = Settings {
@@ -44,22 +41,25 @@ async fn main()
         channel_handshake_seconds: 4,
         channel_heartbeat_seconds: 10,
         external_addr: addr.clone(),
-        peers: peers,
-        seeds: seeds,
+        peers,
+        seeds,
         ..Default::default()
     };
     //proof's number of rows
-    let k : u32 = 13;
-    let mut handles = vec!();
+    let k: u32 = 13;
+    let mut handles = vec![];
     let path = args.path;
     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(),
-                                                        settings.clone(),
-                                                        &rel_path,
-                                                        i,
-                                                        Some(k))).unwrap();
+        let mut stakeholder = block_on(Stakeholder::new(
+            epoch_consensus.clone(),
+            settings.clone(),
+            &rel_path,
+            i,
+            Some(k),
+        ))
+        .unwrap();
 
         let handle = thread::spawn(move || {
             block_on(stakeholder.background(Some(9)));

+ 21 - 27
example/lead.rs

@@ -8,32 +8,28 @@ use pasta_curves::{
 
 use futures::executor::block_on;
 
-use darkfi::crypto::proof::VerifyingKey;
-use darkfi::crypto::proof::ProvingKey;
+use darkfi::crypto::proof::{ProvingKey, VerifyingKey};
 use url::Url;
 
 use darkfi::{
     blockchain::{
-        Blockchain,
-        EpochConsensus,
-        epoch::{Epoch,EpochItem},
+        epoch::{Epoch, EpochItem},
+        Blockchain, EpochConsensus,
     },
-    stakeholder::stakeholder::{Stakeholder},
-    util::time::{Timestamp},
+    consensus::{BlockInfo, StakeholderMetadata, StreamletMetadata, TransactionLeadProof},
     crypto::{
         constants::MERKLE_DEPTH_ORCHARD,
-        leadcoin::{LeadCoin,LEAD_PUBLIC_INPUT_LEN},
         lead_proof,
+        leadcoin::{LeadCoin, LEAD_PUBLIC_INPUT_LEN},
         merkle_node::MerkleNode,
     },
+    net::{P2p, Settings, SettingsPtr},
+    stakeholder::stakeholder::Stakeholder,
     tx::Transaction,
-    consensus::{TransactionLeadProof, StakeholderMetadata, StreamletMetadata, BlockInfo},
-    net::{P2p,Settings, SettingsPtr,},
+    util::time::Timestamp,
     zk::circuit::lead_contract::LeadContract,
 };
 
-
-
 fn main() {
     let k: u32 = 13;
     //
@@ -44,32 +40,30 @@ fn main() {
         value: 332233,  //static stake value
     };
     //
-    let settings = Settings{
-        inbound: vec!(Url::parse("tls://127.0.0.1:12002").unwrap()),
+    let 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()),
+        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(),
+        seeds: [
+            Url::parse("tls://irc0.dark.fi:11001").unwrap(),
+            Url::parse("tls://irc1.dark.fi:11001").unwrap(),
+        ]
+        .to_vec(),
         ..Default::default()
     };
     let consensus = EpochConsensus::new(Some(22), Some(3), Some(22), Some(0));
 
-    let stakeholder : Stakeholder = block_on(Stakeholder::new(consensus, settings, "db", 0,  Some(k))).unwrap();
+    let stakeholder: Stakeholder =
+        block_on(Stakeholder::new(consensus, settings, "db", 0, Some(k))).unwrap();
 
-    let eta : pallas::Base = stakeholder.get_eta();
-    let mut epoch = Epoch {
-        len: Some(LEN),
-        item: Some(epoch_item),
-        eta: eta,
-        coins: vec![],
-    };
+    let eta: pallas::Base = stakeholder.get_eta();
+    let mut epoch = Epoch { len: Some(LEN), item: Some(epoch_item), eta, coins: vec![] };
     // sigma is nubmer of slots * reward (assuming reward is 1 for simplicity)
     let sigma = pallas::Base::from(10);
     let coins: Vec<LeadCoin> = epoch.create_coins(sigma);
@@ -77,7 +71,7 @@ fn main() {
     let coin = coins[coin_idx];
     let contract = coin.create_contract();
 
-    let public_inputs : [pallas::Base;LEAD_PUBLIC_INPUT_LEN] = coin.public_inputs_as_array();
+    let public_inputs: [pallas::Base; LEAD_PUBLIC_INPUT_LEN] = coin.public_inputs_as_array();
 
     let lead_pk = stakeholder.get_provkingkey();
     let lead_vk = stakeholder.get_verifyingkey();

+ 1 - 1
example/net.rs

@@ -69,7 +69,7 @@ impl ProgramOptions {
 
         let connection_slots = if let Some(connection_slots) = programcli.connect_slots {
             connection_slots
-        } else  {
+        } else {
             0
         };
 

+ 1 - 1
src/blockchain/blockstore.rs

@@ -23,7 +23,7 @@ impl HeaderStore {
         let store = Self(tree);
 
         // In case the store is empty, initialize it with the genesis header.
-            let genesis_header = Header::genesis_header(genesis_ts, genesis_data);
+        let genesis_header = Header::genesis_header(genesis_ts, genesis_data);
         if store.0.is_empty() {
             store.insert(&[genesis_header])?;
         }

+ 93 - 95
src/blockchain/epoch.rs

@@ -1,8 +1,6 @@
-use halo2_proofs::{arithmetic::Field,};
+use halo2_gadgets::poseidon::primitives as poseidon;
+use halo2_proofs::arithmetic::Field;
 use incrementalmerkletree::{bridgetree::BridgeTree, Tree};
-use halo2_gadgets::{
-    poseidon::{primitives as poseidon},
-};
 
 use log::debug;
 
@@ -14,23 +12,21 @@ use pasta_curves::{
 
 use rand::{thread_rng, Rng};
 
-use crate::{
-    crypto::{
-        constants::MERKLE_DEPTH_ORCHARD,
-        leadcoin::LeadCoin,
-        lead_proof,
-        proof::{Proof, ProvingKey,},
-        merkle_node::MerkleNode,
-        util::{mod_r_p, pedersen_commitment_base, pedersen_commitment_u64},
-        types::DrkValueBlind,
-    },
+use crate::crypto::{
+    constants::MERKLE_DEPTH_ORCHARD,
+    lead_proof,
+    leadcoin::LeadCoin,
+    merkle_node::MerkleNode,
+    proof::{Proof, ProvingKey},
+    types::DrkValueBlind,
+    util::{mod_r_p, pedersen_commitment_base, pedersen_commitment_u64},
 };
 
-const PRF_NULLIFIER_PREFIX : u64 = 0;
+const PRF_NULLIFIER_PREFIX: u64 = 0;
 
 const MERKLE_DEPTH: u8 = MERKLE_DEPTH_ORCHARD as u8;
 
-#[derive(Copy,Debug,Default,Clone)]
+#[derive(Copy, Debug, Default, Clone)]
 pub struct EpochItem {
     pub value: u64, // the stake value is static during the epoch.
 }
@@ -38,30 +34,36 @@ pub struct EpochItem {
 /// epoch configuration
 /// this struct need be a singleton,
 /// should be populated from configuration file.
-#[derive(Copy,Debug,Default,Clone)]
+#[derive(Copy, Debug, Default, Clone)]
 pub struct EpochConsensus {
-    pub sl_len : u64, /// number of slots per epoch
-    pub e_len : u64,
+    pub sl_len: u64,
+    /// number of slots per epoch
+    pub e_len: u64,
     pub tick_len: u64,
     pub reward: u64,
 }
 
-impl EpochConsensus{
-    pub fn new(sl_len: Option<u64>, e_len: Option<u64>, tick_len: Option<u64>, reward: Option<u64>) -> Self {
+impl EpochConsensus {
+    pub fn new(
+        sl_len: Option<u64>,
+        e_len: Option<u64>,
+        tick_len: Option<u64>,
+        reward: Option<u64>,
+    ) -> Self {
         Self {
             sl_len: sl_len.unwrap_or(22),
             e_len: e_len.unwrap_or(3),
             tick_len: tick_len.unwrap_or(22),
-            reward: reward.unwrap_or(1)
+            reward: reward.unwrap_or(1),
         }
     }
 
     /// TODO how is the reward derived?
-    pub fn get_reward(&self)  -> u64{
+    pub fn get_reward(&self) -> u64 {
         self.reward
     }
 
-    pub fn get_slot_len(&self)  -> u64{
+    pub fn get_slot_len(&self) -> u64 {
         self.sl_len
     }
 
@@ -74,7 +76,7 @@ impl EpochConsensus{
     }
 }
 
-#[derive(Debug,Default,Clone)]
+#[derive(Debug, Default, Clone)]
 pub struct Epoch {
     // TODO this need to emulate epoch
     // should have ep, slot, current block, etc.
@@ -82,38 +84,33 @@ pub struct Epoch {
     pub len: Option<usize>, // number of slots in the epoch
     //epoch item
     pub item: Option<EpochItem>,
-    pub eta: pallas::Base, // CRS for the leader selection.
+    pub eta: pallas::Base,    // CRS for the leader selection.
     pub coins: Vec<LeadCoin>, // competing coins
 }
 
 impl Epoch {
-
-    pub fn new(consensus: EpochConsensus, true_random:pallas::Base) -> Self
-    {
-        Self {len: Some(consensus.get_slot_len() as usize),
-              item: Some(EpochItem {value: consensus.reward}),
-              eta: true_random,
-              coins:vec!(),
+    pub fn new(consensus: EpochConsensus, true_random: pallas::Base) -> Self {
+        Self {
+            len: Some(consensus.get_slot_len() as usize),
+            item: Some(EpochItem { value: consensus.reward }),
+            eta: true_random,
+            coins: vec![],
         }
     }
     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
-        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);
+        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);
+        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)
     }
 
@@ -127,18 +124,18 @@ impl Epoch {
         let mut tree = BridgeTree::<MerkleNode, MERKLE_DEPTH>::new(self.len.unwrap() as usize);
         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();
+        let mut prev_sk_base: pallas::Base = pallas::Base::one();
         for _i in 0..self.len.unwrap() {
-            let sk_bytes = if _i ==0 {
+            let sk_bytes = if _i == 0 {
                 let base = pedersen_commitment_u64(1, pallas::Scalar::random(&mut rng));
                 let coord = base.to_affine().coordinates().unwrap();
-                let sk_base =  coord.x() * coord.y();
+                let sk_base = coord.x() * coord.y();
                 prev_sk_base = sk_base;
                 sk_base.to_repr()
             } else {
                 let base = pedersen_commitment_u64(1, mod_r_p(prev_sk_base));
                 let coord = base.to_affine().coordinates().unwrap();
-                let sk_base =  coord.x() * coord.y();
+                let sk_base = coord.x() * coord.y();
                 prev_sk_base = sk_base;
                 sk_base.to_repr()
             };
@@ -158,7 +155,7 @@ impl Epoch {
         (root_sks, path_sks)
     }
     //note! the strategy here is single competing coin per slot.
-    pub fn create_coins(& mut self, sigma : pallas::Base) -> Vec<LeadCoin> {
+    pub fn create_coins(&mut self, sigma: pallas::Base) -> Vec<LeadCoin> {
         let mut rng = thread_rng();
         let mut seeds: Vec<u64> = vec![];
         for _i in 0..self.len.unwrap() {
@@ -185,27 +182,25 @@ impl Epoch {
             //
             let c_root_sk: MerkleNode = root_sks[i];
 
-            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 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_seed = pallas::Base::from(seeds[i]);
-            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,
-                c_v,
-                c_seed
-            ];
-            let coin_commit_msg : pallas::Base = poseidon::Hash::<_, poseidon::P128Pow5T3, poseidon::ConstantLength<4>, 3, 2>::init().hash(coin_commit_msg_input);
+            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, c_v, c_seed];
+            let coin_commit_msg: pallas::Base =
+                poseidon::Hash::<_, poseidon::P128Pow5T3, poseidon::ConstantLength<4>, 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();
@@ -213,21 +208,21 @@ impl Epoch {
             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 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,
-                c_v,
-                c_seed2,
-            ];
-            let coin2_commit_msg : pallas::Base = poseidon::Hash::<_, poseidon::P128Pow5T3, poseidon::ConstantLength<4>, 3, 2>::init().hash(coin2_commit_msg_input);
+            let c_cm_path =
+                tree_cm.authentication_path(leaf_position.unwrap(), &c_root_cm).unwrap();
+
+            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, c_v, c_seed2];
+            let coin2_commit_msg: pallas::Base =
+                poseidon::Hash::<_, poseidon::P128Pow5T3, poseidon::ConstantLength<4>, 3, 2>::init(
+                )
+                .hash(coin2_commit_msg_input);
             let c_cm2 = pedersen_commitment_base(coin2_commit_msg, c_cm2_blind);
 
             let c_root_sk = root_sks[i];
@@ -275,15 +270,18 @@ impl Epoch {
         debug!("slot: {}, coin len: {}", sl, self.coins.len());
         assert!(slusize < self.coins.len());
         let coin = self.coins[sl as usize];
-        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_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);
         // pick x coordiante 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_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();
+        let target = ord * coin.value.unwrap();
         debug!("y_x: {:?}, target: {:?}", y_x, target);
         //reversed for testing
         target < y_x
@@ -295,10 +293,10 @@ impl Epoch {
     }
 }
 
-#[derive(Debug,Default,Clone)]
+#[derive(Debug, Default, Clone)]
 pub struct LifeTime {
     //lifetime metadata
     //...
     //lifetime epochs
-    pub epochs : Vec<Epoch>,
+    pub epochs: Vec<Epoch>,
 }

+ 5 - 10
src/blockchain/metadatastore.rs

@@ -1,5 +1,5 @@
 use crate::{
-    consensus::{Block, StreamletMetadata, OuroborosMetadata, TransactionLeadProof},
+    consensus::{Block, OuroborosMetadata, StreamletMetadata, TransactionLeadProof},
     util::{
         serial::{deserialize, serialize},
         time::Timestamp,
@@ -104,7 +104,6 @@ impl StreamletMetadataStore {
     }
 }
 
-
 #[derive(Clone)]
 pub struct OuroborosMetadataStore(sled::Tree);
 
@@ -113,20 +112,16 @@ impl OuroborosMetadataStore {
     pub fn new(db: &sled::Db, genesis_ts: Timestamp, genesis_data: blake3::Hash) -> Result<Self> {
         let tree = db.open_tree(SLED_OUROBOROS_METADATA_TREE)?;
         let store = Self(tree);
-        let eta : [u8;32] = *blake3::hash(b"let there be dark!").as_bytes();
+        let eta: [u8; 32] = *blake3::hash(b"let there be dark!").as_bytes();
         // In case the store is empty, initialize it with the genesis block.
         if store.0.is_empty() {
             let genesis_block = Block::genesis_block(genesis_ts, genesis_data);
             let genesis_hash = blake3::hash(&serialize(&genesis_block));
 
             let empty_lead_proof = TransactionLeadProof::default();
-            let metadata = OuroborosMetadata {
-                eta: eta,
-                lead_proof: empty_lead_proof,
-            };
+            let metadata = OuroborosMetadata { eta, lead_proof: empty_lead_proof };
 
-            store.insert(&[genesis_hash],
-                         &[metadata])?;
+            store.insert(&[genesis_hash], &[metadata])?;
         }
 
         Ok(store)
@@ -199,6 +194,6 @@ impl OuroborosMetadataStore {
     /// Retrive last key/val
     pub fn get_last(&self) -> Result<(blake3::Hash, OuroborosMetadata)> {
         let all = self.get_all().unwrap();
-        Ok(all[all.len()-1].clone())
+        Ok(all[all.len() - 1].clone())
     }
 }

+ 3 - 6
src/blockchain/mod.rs

@@ -7,14 +7,13 @@ use crate::{
 };
 
 pub mod epoch;
-pub use epoch::{Epoch, EpochItem,EpochConsensus};
+pub use epoch::{Epoch, EpochConsensus, EpochItem};
 
 pub mod blockstore;
 pub use blockstore::{BlockOrderStore, BlockStore, HeaderStore};
 
 pub mod metadatastore;
-pub use metadatastore::StreamletMetadataStore;
-pub use metadatastore::OuroborosMetadataStore;
+pub use metadatastore::{OuroborosMetadataStore, StreamletMetadataStore};
 
 pub mod nfstore;
 pub use nfstore::NullifierStore;
@@ -90,7 +89,7 @@ impl Blockchain {
             // Store block
             //let _block = Block::new(headerhash[0], tx_hashes, block.m.clone());
             //self.blocks.insert(&[_block])?;
-            let blk : Block = Block::from(block.clone());
+            let blk: Block = Block::from(block.clone());
             self.blocks.insert(&[blk])?;
 
             // Store block order
@@ -102,7 +101,6 @@ impl Blockchain {
             // Store streamlet metadata
             self.streamlet_metadata.insert(&[headerhash[0]], &[block.sm.clone()])?;
 
-
             // NOTE: The nullifiers and Merkle roots are applied in the state
             // transition apply function.
         }
@@ -173,5 +171,4 @@ impl Blockchain {
         let (hash, _) = self.ouroboros_metadata.get_last().unwrap();
         Ok(hash)
     }
-
 }

+ 24 - 30
src/consensus/block.rs

@@ -1,14 +1,14 @@
 use std::fmt;
 
+use super::{
+    OuroborosMetadata, StakeholderMetadata, StreamletMetadata, BLOCK_MAGIC_BYTES, BLOCK_VERSION,
+};
 use incrementalmerkletree::{bridgetree::BridgeTree, Tree};
 use log::debug;
 use pasta_curves::pallas;
-use super::{StakeholderMetadata, StreamletMetadata, OuroborosMetadata, BLOCK_MAGIC_BYTES, BLOCK_VERSION};
 
 use crate::{
-    crypto::{
-        constants::MERKLE_DEPTH, merkle_node::MerkleNode,
-    },
+    crypto::{constants::MERKLE_DEPTH, merkle_node::MerkleNode},
     net,
     tx::Transaction,
     util::{
@@ -62,7 +62,13 @@ impl Header {
 
 impl Default for Header {
     fn default() -> Self {
-        Header::new(blake3::hash(b""), 0 ,0, Timestamp::current_time(), MerkleNode(pallas::Base::zero()))
+        Header::new(
+            blake3::hash(b""),
+            0,
+            0,
+            Timestamp::current_time(),
+            MerkleNode(pallas::Base::zero()),
+        )
     }
 }
 
@@ -106,13 +112,7 @@ impl Block {
         let ts = Timestamp::current_time();
         let header = Header::new(st, e, sl, ts, root);
         let headerhash = header.headerhash();
-        Self { magic:magic,
-               header: headerhash,
-               txs: txs,
-               m: m,
-               om: om,
-               sm: sm
-        }
+        Self { magic, header: headerhash, txs, m, om, sm }
     }
 
     /// Generate the genesis block.
@@ -124,13 +124,7 @@ impl Block {
         let m = StakeholderMetadata::default();
         let om = OuroborosMetadata::default();
         let sm = StreamletMetadata::default();
-        Self{ magic: magic,
-              header: header.headerhash(),
-              txs: vec![],
-              m: m,
-              om: om,
-              sm: sm
-        }
+        Self { magic, header: header.headerhash(), txs: vec![], m, om, sm }
     }
 
     /// Calculate the block hash
@@ -175,7 +169,7 @@ impl Default for BlockInfo {
     fn default() -> Self {
         let magic = *BLOCK_MAGIC_BYTES;
         Self {
-            magic: magic,
+            magic,
             header: Header::default(),
             txs: vec![],
             m: StakeholderMetadata::default(),
@@ -197,10 +191,10 @@ impl BlockInfo {
         txs: Vec<Transaction>,
         m: StakeholderMetadata,
         om: OuroborosMetadata,
-        sm: StreamletMetadata
+        sm: StreamletMetadata,
     ) -> Self {
         let magic = *BLOCK_MAGIC_BYTES;
-        Self {magic, header, txs, m, om, sm}
+        Self { magic, header, txs, m, om, sm }
     }
 
     /// Calculate the block hash
@@ -213,12 +207,13 @@ impl BlockInfo {
 impl From<BlockInfo> for Block {
     fn from(b: BlockInfo) -> Self {
         let txids = b.txs.iter().map(|x| blake3::hash(&serialize(x))).collect();
-        Self { magic: b.magic,
-               header: b.header.headerhash(),
-               txs: txids,
-               m: b.m,
-               om: b.om,
-               sm: b.sm,
+        Self {
+            magic: b.magic,
+            header: b.header.headerhash(),
+            txs: txids,
+            m: b.m,
+            om: b.om,
+            sm: b.sm,
         }
     }
 }
@@ -259,8 +254,7 @@ impl BlockProposal {
 
 impl PartialEq for BlockProposal {
     fn eq(&self, other: &Self) -> bool {
-        self.block.header == other.block.header &&
-            self.block.txs == other.block.txs
+        self.block.header == other.block.header && self.block.txs == other.block.txs
     }
 }
 

+ 16 - 38
src/consensus/metadata.rs

@@ -2,22 +2,16 @@ use super::{Participant, Vote};
 use rand::rngs::OsRng;
 
 use crate::{
-    util::{
-        serial::{SerialDecodable, SerialEncodable},
-    },
     crypto::{
         address::Address,
-        schnorr::Signature,
-        types::*,
-        proof::{
-            Proof,
-            ProvingKey,
-            VerifyingKey,
-        },
+        keypair::Keypair,
         lead_proof,
         leadcoin::LeadCoin,
-        keypair::Keypair,
+        proof::{Proof, ProvingKey, VerifyingKey},
+        schnorr::Signature,
+        types::*,
     },
+    util::serial::{SerialDecodable, SerialEncodable},
     VerifyResult,
 };
 
@@ -34,24 +28,18 @@ impl Default for StakeholderMetadata {
         let keypair = Keypair::random(&mut OsRng);
         let address = Address::from(keypair.public);
         let sign = Signature::dummy();
-        Self {
-            signature: sign,
-            address: address,
-        }
+        Self { signature: sign, address }
     }
 }
 
 impl StakeholderMetadata {
     pub fn new(signature: Signature, address: Address) -> Self {
-        Self {
-            signature,
-            address
-        }
+        Self { signature, address }
     }
 }
 
 /// wrapper over the Proof, for possiblity any metadata necessary in the future.
-#[derive(Debug, Clone, PartialEq,  SerialEncodable, SerialDecodable)]
+#[derive(Debug, Clone, PartialEq, SerialEncodable, SerialDecodable)]
 pub struct TransactionLeadProof {
     /// leadership proof
     pub lead_proof: Proof,
@@ -59,55 +47,45 @@ pub struct TransactionLeadProof {
 
 impl Default for TransactionLeadProof {
     fn default() -> Self {
-        Self {
-            lead_proof : Proof::default(),
-        }
+        Self { lead_proof: Proof::default() }
     }
 }
 
 impl TransactionLeadProof {
-    pub fn new(pk : &ProvingKey, coin: LeadCoin) -> Self
-    {
+    pub fn new(pk: &ProvingKey, coin: LeadCoin) -> Self {
         let proof = lead_proof::create_lead_proof(pk, coin.clone()).unwrap();
         Self { lead_proof: proof }
     }
 
-    pub fn verify(&self, vk : VerifyingKey, public_inputs: &[DrkCircuitField]) -> VerifyResult<()>
-    {
+    pub fn verify(&self, vk: VerifyingKey, public_inputs: &[DrkCircuitField]) -> VerifyResult<()> {
         lead_proof::verify_lead_proof(&vk, &self.lead_proof, public_inputs)
     }
 }
 
 impl From<Proof> for TransactionLeadProof {
     fn from(proof: Proof) -> Self {
-        Self { lead_proof: proof}
+        Self { lead_proof: proof }
     }
 }
 
-
-
-
 /// This struct represents [`Block`](super::Block) information used by the Ouroboros
 /// Praos consensus protocol.
 #[derive(Debug, Clone, PartialEq, SerialEncodable, SerialDecodable)]
 pub struct OuroborosMetadata {
     /// response of global random oracle, or it's emulation.
-    pub eta: [u8;32],
+    pub eta: [u8; 32],
     /// stakeholder lead NIZK lead proof
-    pub lead_proof : TransactionLeadProof,
+    pub lead_proof: TransactionLeadProof,
 }
 
 impl Default for OuroborosMetadata {
     fn default() -> Self {
-        Self {
-            eta: [0;32],
-            lead_proof: TransactionLeadProof::default(),
-        }
+        Self { eta: [0; 32], lead_proof: TransactionLeadProof::default() }
     }
 }
 
 impl OuroborosMetadata {
-    pub fn new(eta: [u8;32], lead_proof: TransactionLeadProof) -> Self {
+    pub fn new(eta: [u8; 32], lead_proof: TransactionLeadProof) -> Self {
         Self { eta, lead_proof }
     }
 }

+ 3 - 1
src/consensus/mod.rs

@@ -4,7 +4,9 @@ pub use block::{Block, BlockInfo, BlockProposal, Header, ProposalChain};
 
 /// Consensus metadata
 pub mod metadata;
-pub use metadata::{StakeholderMetadata, StreamletMetadata, OuroborosMetadata, TransactionLeadProof};
+pub use metadata::{
+    OuroborosMetadata, StakeholderMetadata, StreamletMetadata, TransactionLeadProof,
+};
 
 /// Consensus participant
 pub mod participant;

+ 9 - 7
src/consensus/state.rs

@@ -13,11 +13,13 @@ use log::{debug, error, info, warn};
 use rand::rngs::OsRng;
 
 use super::{
-    Block, BlockInfo, BlockProposal, OuroborosMetadata, Participant, ProposalChain, StreamletMetadata, Vote, Header,
+    Block, BlockInfo, BlockProposal, Header, OuroborosMetadata, Participant, ProposalChain,
+    StreamletMetadata, Vote,
 };
 
 use crate::{
     blockchain::Blockchain,
+    consensus::StakeholderMetadata,
     crypto::{
         address::Address,
         constants::MERKLE_DEPTH,
@@ -25,7 +27,6 @@ use crate::{
         merkle_node::MerkleNode,
         schnorr::{SchnorrPublic, SchnorrSecret},
     },
-    consensus::{StakeholderMetadata},
     net,
     node::{
         state::{state_transition, ProgramState, StateUpdate},
@@ -303,7 +304,8 @@ impl ValidatorState {
             }
         }
         let root = tree.root(0).unwrap();
-        let header = Header::new(prev_hash, self.slot_epoch(slot), slot, Timestamp::current_time(), root);
+        let header =
+            Header::new(prev_hash, self.slot_epoch(slot), slot, Timestamp::current_time(), root);
 
         let signed_proposal = self.secret.sign(&header.headerhash().as_bytes()[..]);
         let m = StakeholderMetadata::new(signed_proposal, self.address);
@@ -387,10 +389,10 @@ impl ValidatorState {
             return Ok(None)
         }
 
-        if !leader.public_key.verify(
-            proposal.block.header.headerhash().as_bytes(),
-            &proposal.block.m.signature,
-        ) {
+        if !leader
+            .public_key
+            .verify(proposal.block.header.headerhash().as_bytes(), &proposal.block.m.signature)
+        {
             warn!("Proposer ({}) signature could not be verified", proposal.block.m.address);
             return Ok(None)
         }

+ 1 - 1
src/crypto/burn_proof.rs

@@ -18,7 +18,7 @@ use crate::{
             DrkCircuitField, DrkCoinBlind, DrkSerial, DrkSpendHook, DrkTokenId, DrkUserData,
             DrkUserDataBlind, DrkUserDataEnc, DrkValue, DrkValueBlind, DrkValueCommit,
         },
-        util::{poseidon_hash},
+        util::poseidon_hash,
     },
     util::serial::{SerialDecodable, SerialEncodable},
     zk::circuit::burn_contract::BurnContract,

+ 9 - 10
src/crypto/lead_proof.rs

@@ -1,19 +1,16 @@
-use log::{
-    error
-};
+use log::error;
 
 use rand::rngs::OsRng;
 
 use crate::{
     crypto::{
-        types::*,
         leadcoin::LeadCoin,
         proof::{Proof, ProvingKey, VerifyingKey},
+        types::*,
     },
-    Result, VerifyResult, VerifyFailed,
+    Result, VerifyFailed, VerifyResult,
 };
 
-
 #[allow(clippy::too_many_arguments)]
 pub fn create_lead_proof(pk: &ProvingKey, coin: LeadCoin) -> Result<Proof> {
     let contract = coin.create_contract();
@@ -22,11 +19,13 @@ pub fn create_lead_proof(pk: &ProvingKey, coin: LeadCoin) -> Result<Proof> {
     Ok(proof)
 }
 
-pub fn verify_lead_proof(vk: &VerifyingKey,
-                         proof: &Proof,
-                         public_inputs: &[DrkCircuitField]) -> VerifyResult<()> {
+pub fn verify_lead_proof(
+    vk: &VerifyingKey,
+    proof: &Proof,
+    public_inputs: &[DrkCircuitField],
+) -> VerifyResult<()> {
     match proof.verify(vk, public_inputs) {
-        Ok(()) => {Ok(())},
+        Ok(()) => Ok(()),
         Err(e) => {
             error!("lead verification failed: {}", e);
             Err(VerifyFailed::InternalError("lead verification failure".to_string()))

+ 27 - 36
src/crypto/leadcoin.rs

@@ -1,16 +1,14 @@
+use halo2_gadgets::poseidon::primitives as poseidon;
+use halo2_proofs::circuit::Value;
 use pasta_curves::pallas;
-use halo2_proofs::{circuit::Value};
-use halo2_gadgets::{
-    poseidon::{primitives as poseidon},
-};
 
 use crate::{
-    zk::circuit::lead_contract::LeadContract,
     crypto::{
         constants::MERKLE_DEPTH_ORCHARD,
         merkle_node::MerkleNode,
         util::{mod_r_p, pedersen_commitment_base},
-    }
+    },
+    zk::circuit::lead_contract::LeadContract,
 };
 
 use incrementalmerkletree::Hashable;
@@ -19,26 +17,26 @@ use pasta_curves::{arithmetic::CurveAffine, group::Curve};
 
 //use halo2_proofs::arithmetic::CurveAffine;
 
-pub const LEAD_PUBLIC_INPUT_LEN : usize = 10;
+pub const LEAD_PUBLIC_INPUT_LEN: usize = 10;
 
 #[derive(Debug, Default, Clone, Copy)]
 pub struct LeadCoin {
-    pub value: Option<pallas::Base>, // coin stake
-    pub cm: Option<pallas::Point>, // coin commitment
-    pub cm2: Option<pallas::Point>, // poured coin commitment
-    pub idx: u32, // coin idex
-    pub sl: Option<pallas::Base>, // coin slot id
-    pub tau: Option<pallas::Base>, // coin time stamp
-    pub nonce: Option<pallas::Base>, // coin nonce
-    pub nonce_cm: Option<pallas::Base>, // coin nonce's commitment
-    pub sn: Option<pallas::Base>, // coin's serial number
-    pub pk: Option<pallas::Base>, // coin public key
-    pub root_cm: Option<pallas::Scalar>, // root of coin commitment
-    pub root_sk: Option<pallas::Base>, // coin's secret key
-    pub path: Option<[MerkleNode; MERKLE_DEPTH_ORCHARD]>, // path to the coin's commitment
+    pub value: Option<pallas::Base>,                         // coin stake
+    pub cm: Option<pallas::Point>,                           // coin commitment
+    pub cm2: Option<pallas::Point>,                          // poured coin commitment
+    pub idx: u32,                                            // coin idex
+    pub sl: Option<pallas::Base>,                            // coin slot id
+    pub tau: Option<pallas::Base>,                           // coin time stamp
+    pub nonce: Option<pallas::Base>,                         // coin nonce
+    pub nonce_cm: Option<pallas::Base>,                      // coin nonce's commitment
+    pub sn: Option<pallas::Base>,                            // coin's serial number
+    pub pk: Option<pallas::Base>,                            // coin public key
+    pub root_cm: Option<pallas::Scalar>,                     // root of coin commitment
+    pub root_sk: Option<pallas::Base>,                       // coin's secret key
+    pub path: Option<[MerkleNode; MERKLE_DEPTH_ORCHARD]>,    // path to the coin's commitment
     pub path_sk: Option<[MerkleNode; MERKLE_DEPTH_ORCHARD]>, // path to the coin's secret key
-    pub c1_blind: Option<pallas::Scalar>, // coin opening
-    pub c2_blind: Option<pallas::Scalar>, // poured coin opening
+    pub c1_blind: Option<pallas::Scalar>,                    // coin opening
+    pub c2_blind: Option<pallas::Scalar>,                    // poured coin opening
     // election seeds
     pub y_mu: Option<pallas::Base>, // leader election nonce derived from eta at onset of epoch
     pub rho_mu: Option<pallas::Base>, // leader election nonce derived from eta at onset of epoch
@@ -46,7 +44,7 @@ pub struct LeadCoin {
 }
 
 impl LeadCoin {
-    pub fn public_inputs_as_array(&self) -> [pallas::Base;LEAD_PUBLIC_INPUT_LEN] {
+    pub fn public_inputs_as_array(&self) -> [pallas::Base; LEAD_PUBLIC_INPUT_LEN] {
         let po_nonce = self.nonce_cm.unwrap();
         let _po_tau = pedersen_commitment_base(self.tau.unwrap(), self.root_cm.unwrap())
             .to_affine()
@@ -60,13 +58,12 @@ impl LeadCoin {
 
         let y_mu = self.y_mu.unwrap();
         let rho_mu = self.rho_mu.unwrap();
-        let root_sk  = self.root_sk.unwrap();
+        let root_sk = self.root_sk.unwrap();
         let nonce = self.nonce.unwrap();
-        let lottery_msg_input = [
-            root_sk,
-            nonce,
-        ];
-        let lottery_msg : pallas::Base = poseidon::Hash::<_, poseidon::P128Pow5T3, poseidon::ConstantLength<2>, 3, 2>::init().hash(lottery_msg_input);
+        let lottery_msg_input = [root_sk, nonce];
+        let lottery_msg: pallas::Base =
+            poseidon::Hash::<_, poseidon::P128Pow5T3, poseidon::ConstantLength<2>, 3, 2>::init()
+                .hash(lottery_msg_input);
         //
         let po_y_pt: pallas::Point = pedersen_commitment_base(lottery_msg, mod_r_p(y_mu));
         let po_y = *po_y_pt.to_affine().coordinates().unwrap().x();
@@ -74,7 +71,6 @@ impl LeadCoin {
         let po_rho_pt: pallas::Point = pedersen_commitment_base(lottery_msg, mod_r_p(rho_mu));
         let po_rho = *po_rho_pt.to_affine().coordinates().unwrap().x();
 
-
         let _zero = pallas::Base::from(0);
 
         // ===============
@@ -95,20 +91,15 @@ impl LeadCoin {
             }
             current
         };
-        let public_inputs : [pallas::Base;LEAD_PUBLIC_INPUT_LEN] = [
-
+        let public_inputs: [pallas::Base; LEAD_PUBLIC_INPUT_LEN] = [
             *po_cm.x(),
             *po_cm.y(),
-
             *po_cm2.x(),
             *po_cm2.y(),
-
             po_nonce,
             cm_root.0,
-
             po_pk,
             po_sn,
-
             po_y,
             po_rho,
         ];

+ 2 - 1
src/crypto/mint_proof.rs

@@ -11,7 +11,8 @@ use crate::{
         keypair::PublicKey,
         proof::{Proof, ProvingKey, VerifyingKey},
         types::{
-            DrkCircuitField, DrkCoinBlind, DrkSerial, DrkSpendHook, DrkTokenId, DrkUserData, DrkValue, DrkValueBlind, DrkValueCommit,
+            DrkCircuitField, DrkCoinBlind, DrkSerial, DrkSpendHook, DrkTokenId, DrkUserData,
+            DrkValue, DrkValueBlind, DrkValueCommit,
         },
         util::{pedersen_commitment_base, pedersen_commitment_u64, poseidon_hash},
     },

+ 0 - 1
src/crypto/util.rs

@@ -47,7 +47,6 @@ pub fn pedersen_commitment_u64(value: u64, blind: DrkValueBlind) -> DrkValueComm
     V * mod_r_p(DrkValue::from(value)) + R * blind
 }
 
-
 /// Simplified wrapper for poseidon hash function.
 pub fn poseidon_hash<const N: usize>(messages: [pallas::Base; N]) -> pallas::Base {
     poseidon::Hash::<_, poseidon::P128Pow5T3, poseidon::ConstantLength<N>, 3, 2>::init()

+ 0 - 2
src/error.rs

@@ -321,7 +321,6 @@ pub enum Error {
     // ==============
     #[error("Did not find key")]
     UnknownKey,
-
 }
 
 /// Transaction verification errors
@@ -365,7 +364,6 @@ pub enum VerifyFailed {
 
     #[error("Internal error: {0}")]
     InternalError(String),
-
 }
 
 /// Client module errors

+ 115 - 123
src/stakeholder/stakeholder.rs

@@ -4,49 +4,49 @@ use async_std::sync::Arc;
 use std::fmt;
 
 use rand::rngs::OsRng;
-use std::time::Duration;
-use std::thread;
+use std::{thread, time::Duration};
 
 use crate::zk::circuit::LeadContract;
 
 use crate::{
-    consensus::{Block, BlockInfo,OuroborosMetadata, StakeholderMetadata,StreamletMetadata,TransactionLeadProof, Header},
-    util::{
-        time::Timestamp,
-        clock::{Clock,Ticks},
-        expand_path,
+    blockchain::{Blockchain, Epoch, EpochConsensus},
+    consensus::{
+        Block, BlockInfo, Header, OuroborosMetadata, StakeholderMetadata, StreamletMetadata,
+        TransactionLeadProof,
     },
-    system::{Subscription},
     crypto::{
-        proof::{Proof, ProvingKey, VerifyingKey,  },
-        leadcoin::{LeadCoin},
-        schnorr::{Signature,SchnorrSecret, SchnorrPublic},
-        keypair::{Keypair},
-        merkle_node::MerkleNode,
         address::Address,
+        keypair::Keypair,
+        leadcoin::LeadCoin,
+        merkle_node::MerkleNode,
+        proof::{Proof, ProvingKey, VerifyingKey},
+        schnorr::{SchnorrPublic, SchnorrSecret, Signature},
+    },
+    net::{ChannelPtr, MessageSubscription, P2p, Settings, SettingsPtr},
+    system::Subscription,
+    tx::Transaction,
+    util::{
+        clock::{Clock, Ticks},
+        expand_path,
+        time::Timestamp,
     },
-    blockchain::{Blockchain,Epoch,EpochConsensus},
-    net::{P2p,Settings, SettingsPtr, ChannelPtr, MessageSubscription},
-    tx::{Transaction},
     Result,
 };
 
 use url::Url;
 
-use pasta_curves::{
-    pallas,
-};
+use pasta_curves::pallas;
 
 use group::ff::PrimeField;
 
 #[derive(Debug)]
-pub struct SlotWorkspace
-{
-    pub st : blake3::Hash,
-    pub e: u64, // epoch index
-    pub sl: u64, // absolute slot index
+pub struct SlotWorkspace {
+    pub st: blake3::Hash,
+    pub e: u64,                // epoch index
+    pub sl: u64,               // absolute slot index
     pub txs: Vec<Transaction>, // unpublished block transactions
-    pub root: MerkleNode, /// merkle root of txs
+    pub root: MerkleNode,
+    /// merkle root of txs
     pub m: StakeholderMetadata,
     pub om: OuroborosMetadata,
     pub is_leader: bool,
@@ -56,35 +56,31 @@ pub struct SlotWorkspace
 
 impl Default for SlotWorkspace {
     fn default() -> Self {
-        Self {st: blake3::hash(b""),
-              e: 0,
-              sl: 0,
-              txs: vec![],
-              root: MerkleNode(pallas::Base::zero()),
-              is_leader: false,
-              m: StakeholderMetadata::default(),
-              om: OuroborosMetadata::default(),
-              proof: Proof::default(),
-              block: BlockInfo::default(),
+        Self {
+            st: blake3::hash(b""),
+            e: 0,
+            sl: 0,
+            txs: vec![],
+            root: MerkleNode(pallas::Base::zero()),
+            is_leader: false,
+            m: StakeholderMetadata::default(),
+            om: OuroborosMetadata::default(),
+            proof: Proof::default(),
+            block: BlockInfo::default(),
         }
     }
 }
 
 impl SlotWorkspace {
-
     pub fn new_block(&self) -> (BlockInfo, blake3::Hash) {
-        let sm = StreamletMetadata::new(vec!());
+        let sm = StreamletMetadata::new(vec![]);
         let header = Header::new(self.st, self.e, self.sl, Timestamp::current_time(), self.root);
-        let block = BlockInfo::new(header,
-                                   self.txs.clone(),
-                                   self.m.clone(),
-                                   self.om.clone(),
-                                   sm);
+        let block = BlockInfo::new(header, self.txs.clone(), self.m.clone(), self.om.clone(), sm);
         let hash = block.blockhash();
         (block, hash)
     }
 
-    pub fn add_tx(& mut self, tx: Transaction) {
+    pub fn add_tx(&mut self, tx: Transaction) {
         self.txs.push(tx);
     }
 
@@ -92,7 +88,7 @@ impl SlotWorkspace {
         self.root = root;
     }
 
-    pub fn set_stakeholdermetadata(& mut self, meta : StakeholderMetadata) {
+    pub fn set_stakeholdermetadata(&mut self, meta: StakeholderMetadata) {
         self.m = meta;
     }
 
@@ -116,23 +112,22 @@ impl SlotWorkspace {
         self.proof = proof;
     }
 
-    pub fn set_leader(&mut self, alead : bool) {
+    pub fn set_leader(&mut self, alead: bool) {
         self.is_leader = alead;
     }
 }
 
-pub struct Stakeholder
-{
+pub struct Stakeholder {
     pub blockchain: Blockchain, // stakeholder view of the blockchain
-    pub net : Arc<P2p>,
-    pub clock : Clock,
-    pub coins : Vec<LeadCoin>, // owned stakes
-    pub epoch : Epoch, // current epoch
-    pub epoch_consensus : EpochConsensus, // configuration for the epoch
-    pub pk : ProvingKey,
-    pub vk : VerifyingKey,
+    pub net: Arc<P2p>,
+    pub clock: Clock,
+    pub coins: Vec<LeadCoin>,            // owned stakes
+    pub epoch: Epoch,                    // current epoch
+    pub epoch_consensus: EpochConsensus, // configuration for the epoch
+    pub pk: ProvingKey,
+    pub vk: VerifyingKey,
     pub playing: bool,
-    pub workspace : SlotWorkspace,
+    pub workspace: SlotWorkspace,
     pub id: u8,
     pub keypair: Keypair,
     //pub subscription: Subscription<Result<ChannelPtr>>,
@@ -140,10 +135,14 @@ pub struct Stakeholder
     //pub msgsub : MessageSubscription::<BlockInfo>,
 }
 
-impl Stakeholder
-{
-    pub async fn new(consensus: EpochConsensus, settings: Settings, rel_path: &str, id: u8, k: Option<u32>) -> Result<Self>
-    {
+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");
         let db = sled::open(&path)?;
@@ -166,30 +165,35 @@ impl Stakeholder
         let workspace = SlotWorkspace::default();
 
         //
-        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);
         println!("stakeholder constructed...");
-        Ok(Self{blockchain: bc,
-                net: p2p,
-                clock: clock,
-                coins: vec![], //constructed with empty coins for sake of simulation only
-                // but should be populated from wallet db.
-                epoch: epoch,
-                epoch_consensus: consensus,
-                pk: lead_pk,
-                vk: lead_vk,
-                playing: true,
-                workspace: workspace,
-                id: id,
-                keypair: keypair
-                //subscription: subscription,
-                //chanptr: chanptr,
-                //msgsub: msg_sub,
+        Ok(Self {
+            blockchain: bc,
+            net: p2p,
+            clock,
+            coins: vec![], //constructed with empty coins for sake of simulation only
+            // but should be populated from wallet db.
+            epoch,
+            epoch_consensus: consensus,
+            pk: lead_pk,
+            vk: lead_vk,
+            playing: true,
+            workspace,
+            id,
+            keypair, //subscription: subscription,
+                     //chanptr: chanptr,
+                     //msgsub: msg_sub,
         })
     }
 
     /// wrapper on Schnorr signature
-    pub fn sign(&self, message : &[u8]) -> Signature {
+    pub fn sign(&self, message: &[u8]) -> Signature {
         self.keypair.secret.sign(message)
     }
 
@@ -208,7 +212,7 @@ impl Stakeholder
 
     /// get list stakeholder peers on the p2p network for synchronization
     pub fn get_peers(&self) -> Vec<Url> {
-        let settings : SettingsPtr = self.net.settings();
+        let settings: SettingsPtr = self.net.settings();
         settings.peers.clone()
     }
 
@@ -240,32 +244,30 @@ impl Stakeholder
         let _len = self.blockchain.add(&blocks);
     }
 
-    pub fn add_tx(&mut self, tx: Transaction)
-    {
+    pub fn add_tx(&mut self, tx: Transaction) {
         self.workspace.add_tx(tx);
     }
 
     /// extract leader selection lottery randomness \eta
     /// it's the hash of the previous lead proof
     /// converted to pallas base
-    pub fn get_eta(&self) -> pallas::Base
-    {
+    pub fn get_eta(&self) -> pallas::Base {
         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
         bytes[30] = 0;
         bytes[31] = 0;
         pallas::Base::from_repr(bytes).unwrap()
     }
 
-    pub fn valid_block(&self, _blk : BlockInfo)  -> bool {
+    pub fn valid_block(&self, _blk: BlockInfo) -> bool {
         //TODO implement
         true
     }
 
     /// listen to the network,
     /// for new transactions.
-    pub fn sync_tx (&self) {
+    pub fn sync_tx(&self) {
         //TODO
     }
 
@@ -274,9 +276,9 @@ impl Stakeholder
     /// validate the block proof, and the transactions,
     /// 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;
+        let subscription: Subscription<Result<ChannelPtr>> = self.net.subscribe_channel().await;
         println!("--> channel");
-        let chanptr : ChannelPtr =  subscription.receive().await.unwrap();
+        let chanptr: ChannelPtr = subscription.receive().await.unwrap();
         println!("--> received channel");
         //
         let message_subsytem = chanptr.get_message_subsystem();
@@ -287,14 +289,14 @@ impl Stakeholder
         //let info = chanptr.get_info();
         //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");
         println!("--> subscribed");
 
         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.
-        if self.valid_block(blk.clone())  {
+        if self.valid_block(blk.clone()) {
             //TODO if valid only.
             let _len = self.blockchain.add(&[blk.clone()]);
         } else {
@@ -303,29 +305,28 @@ impl Stakeholder
     }
 
     pub async fn background(&mut self, hardlimit: Option<u8>) {
-
         let _ = self.init_network().await;
         let _ = self.clock.sync().await;
-        let mut c : u8= 0;
-        let lim : u8 = hardlimit.unwrap_or(0);
+        let mut c: u8 = 0;
+        let lim: u8 = hardlimit.unwrap_or(0);
         while self.playing {
-            if c>lim && lim>0 {
-                break;
+            if c > lim && lim > 0 {
+                break
             }
             // clock ticks slot begins
             // initialize the epoch if it's the time
             // check for leadership
             match self.clock.ticks().await {
-                Ticks::GENESIS{e, sl} => {
+                Ticks::GENESIS { e, sl } => {
                     //TODO (res) any initialization happening here?
                     self.new_epoch();
                     self.new_slot(e, sl);
                 }
-                Ticks::NEWEPOCH{e, sl} => {
+                Ticks::NEWEPOCH { e, sl } => {
                     self.new_epoch();
                     self.new_slot(e, sl);
                 }
-                Ticks::NEWSLOT{e, sl} => self.new_slot(e, sl),
+                Ticks::NEWSLOT { e, sl } => self.new_slot(e, sl),
                 Ticks::TOCKS => {
                     println!("tocks");
                     // slot is about to end.
@@ -337,7 +338,7 @@ impl Stakeholder
                         let (block_info, _block_hash) = self.workspace.new_block();
                         //add the block to the blockchain
                         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
                         //TODO (fix) before publishing the workspace tx root need to be set.
                         let _ret = self.net.broadcast(block).await;
@@ -345,10 +346,8 @@ impl Stakeholder
                         //
                         self.sync_block().await;
                     }
-                },
-                Ticks::IDLE => {
-                    continue
                 }
+                Ticks::IDLE => continue,
                 Ticks::OUTOFSYNC => {
                     println!("out of sync");
                     // clock, and blockchain are out of sync
@@ -357,7 +356,7 @@ impl Stakeholder
                 }
             }
             thread::sleep(Duration::from_millis(1000));
-            c+=1;
+            c += 1;
         }
     }
 
@@ -367,8 +366,7 @@ impl Stakeholder
     /// 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
     /// in the epoch's gen2esis data.
-    fn new_epoch(&mut self)
-    {
+    fn new_epoch(&mut self) {
         println!("[new epoch] 4 {}", self);
         let eta = self.get_eta();
         let mut epoch = Epoch::new(self.epoch_consensus, eta);
@@ -380,34 +378,26 @@ impl Stakeholder
         // it's value is dependent on the tekonomics,
         // set to one untill then.
         let reward = pallas::Base::one();
-        let sigma : pallas::Base = pallas::Base::from(num_slots)*reward;
+        let sigma: pallas::Base = pallas::Base::from(num_slots) * reward;
         epoch.create_coins(sigma); // set epoch interal fields working space with competing coins
         self.epoch = epoch.clone();
     }
 
-
     /// at the begining of the slot
     /// stakeholder need to play the lottery for the slot.
     /// FIXME if the stakeholder is not winning, staker can try different coins before,
     /// commiting it's coins, to maximize success, thus,
     /// the lottery proof need to be conditioned on the slot itself, and previous proof.
     /// 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) {
         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) {
-            self.workspace.block.blockhash()
-        } else {
-            empty_ptr
-        };
-        let is_leader : bool = self.epoch.is_leader(sl);
+        let st: blake3::Hash =
+            if e > 0 || (e == 0 && sl > 0) { self.workspace.block.blockhash() } else { empty_ptr };
+        let is_leader: bool = self.epoch.is_leader(sl);
         // if is leader create proof
-        let proof = if is_leader {
-            self.epoch.get_proof(sl, &self.pk.clone())
-        } else {
-            Proof::new(vec![])
-        };
+        let proof =
+            if is_leader { self.epoch.get_proof(sl, &self.pk.clone()) } else { Proof::new(vec![]) };
         // set workspace
         self.workspace.set_sl(sl);
         self.workspace.set_e(e);
@@ -419,8 +409,10 @@ impl Stakeholder
             let addr = Address::from(self.keypair.public);
             let sign = self.sign(proof.as_ref());
             let stakeholder_meta = StakeholderMetadata::new(sign, addr);
-            let ouroboros_meta = OuroborosMetadata::new(self.get_eta().to_repr(),
-                                                        TransactionLeadProof::from(proof.clone()));
+            let ouroboros_meta = OuroborosMetadata::new(
+                self.get_eta().to_repr(),
+                TransactionLeadProof::from(proof.clone()),
+            );
             self.workspace.set_stakeholdermetadata(stakeholder_meta);
             self.workspace.set_ouroborosmetadata(ouroboros_meta);
         }
@@ -428,7 +420,7 @@ impl Stakeholder
 }
 
 impl fmt::Display for Stakeholder {
-    fn fmt(&self, formater : &mut fmt::Formatter) ->  fmt::Result {
+    fn fmt(&self, formater: &mut fmt::Formatter) -> fmt::Result {
         formater.write_fmt(format_args!("stakeholder with id: {}", self.id))
     }
 }

+ 1 - 1
src/tx/mod.rs

@@ -1,6 +1,6 @@
-use std::io;
 use log::error;
 use pasta_curves::group::Group;
+use std::io;
 
 use crate::{
     crypto::{

+ 61 - 58
src/util/clock.rs

@@ -1,45 +1,47 @@
-use url::Url;
+use crate::{util::Timestamp, Result};
 use log::debug;
-use std::time::Duration;
-use std::thread;
-use crate::{
-    util::{Timestamp},
-    Result,
-};
+use std::{thread, time::Duration};
+use url::Url;
 
 pub enum Ticks {
-    GENESIS{e: u64, sl: u64}, //genesis epoch
-    NEWSLOT{e: u64, sl: u64}, // new slot
-    NEWEPOCH{e: u64, sl: u64}, // new epoch
-    TOCKS, //tocks, or slot is ending
-    IDLE, // idle clock state
-    OUTOFSYNC, //clock, and blockchain are out of sync
+    GENESIS { e: u64, sl: u64 },  //genesis epoch
+    NEWSLOT { e: u64, sl: u64 },  // new slot
+    NEWEPOCH { e: u64, sl: u64 }, // new epoch
+    TOCKS,                        //tocks, or slot is ending
+    IDLE,                         // idle clock state
+    OUTOFSYNC,                    //clock, and blockchain are out of sync
 }
 
-const BB_SL : u64 = u64::MAX-1; //big bang slot time (need to be negative value)
-const BB_E : u64 = 0; //big bang epoch time.
+const BB_SL: u64 = u64::MAX - 1; //big bang slot time (need to be negative value)
+const BB_E: u64 = 0; //big bang epoch time.
 
 #[derive(Debug)]
 pub struct Clock {
-    pub sl : u64, // relative slot index (zero-based) [0-len[
-    pub e : u64, //epoch index (zero-based) [0-\inf[
+    pub sl: u64,       // relative slot index (zero-based) [0-len[
+    pub e: u64,        //epoch index (zero-based) [0-\inf[
     pub tick_len: u64, // tick length in time
-    pub sl_len: u64, // slot length in ticks
-    pub e_len: u64, // epoch length in slots
+    pub sl_len: u64,   // slot length in ticks
+    pub e_len: u64,    // epoch length in slots
     pub peers: Vec<Url>,
     pub genesis_time: Timestamp,
 }
 
 impl Clock {
-    pub fn new(e_len: Option<u64>, sl_len: Option<u64>, tick_len: Option<u64>, peers: Vec<Url>) -> Self{
-        let gt : Timestamp = Timestamp::current_time();
-        Self { sl: BB_SL, //necessary for genesis slot
-               e: BB_E,
-               tick_len: tick_len.unwrap_or(22), // 22 seconds
-               sl_len: sl_len.unwrap_or(22),// ~8 minutes
-               e_len: e_len.unwrap_or(3), // 24.2 minutes
-               peers: peers,
-               genesis_time: gt,
+    pub fn new(
+        e_len: Option<u64>,
+        sl_len: Option<u64>,
+        tick_len: Option<u64>,
+        peers: Vec<Url>,
+    ) -> Self {
+        let gt: Timestamp = Timestamp::current_time();
+        Self {
+            sl: BB_SL, //necessary for genesis slot
+            e: BB_E,
+            tick_len: tick_len.unwrap_or(22), // 22 seconds
+            sl_len: sl_len.unwrap_or(22),     // ~8 minutes
+            e_len: e_len.unwrap_or(3),        // 24.2 minutes
+            peers,
+            genesis_time: gt,
         }
     }
 
@@ -54,22 +56,22 @@ impl Clock {
     async fn time(&self) -> Result<Timestamp> {
         //TODO (fix) add more than ntp server to time, and take the avg
         /*
-        match time::check_clock(self.peers.clone()).await {
-            Ok(t) => {
-                Ok(time::ntp_request().await?)
-            },
-            Err(e) => {
-                Err(Error::ClockOutOfSync(e.to_string()))
-            }
-    }
-        */
+            match time::check_clock(self.peers.clone()).await {
+                Ok(t) => {
+                    Ok(time::ntp_request().await?)
+                },
+                Err(e) => {
+                    Err(Error::ClockOutOfSync(e.to_string()))
+                }
+        }
+            */
         Ok(Timestamp::current_time())
     }
 
     /// time since genesis
     async fn time_to_genesis(&self) -> Timestamp {
         //TODO this value need to be assigned to kickoff time.
-        let genesis_time : i64 = self.genesis_time.0;
+        let genesis_time: i64 = self.genesis_time.0;
         let abs_time = self.time().await.unwrap();
         Timestamp(abs_time.0 - genesis_time)
     }
@@ -84,12 +86,12 @@ 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;
+        let (abs, rel) = self.tick_time().await;
         debug!("abs ticks: {}, rel ticks: {}", abs, rel);
-        rel < (self.tick_len) /3
+        rel < (self.tick_len) / 3
     }
 
-    pub async fn sync(& mut self) -> Result<()> {
+    pub async fn sync(&mut self) -> Result<()> {
         let e = self.epoch_abs().await;
         let sl = self.slot_relative().await;
         self.sl = sl;
@@ -105,7 +107,7 @@ impl Clock {
     }
 
     /// relative zero based slot index
-    async fn  slot_relative(&self) -> u64 {
+    async fn slot_relative(&self) -> u64 {
         let e_abs = self.slot_abs().await % self.e_len;
         debug!("[slot_relative] slot len: {} - slot relative: {}", self.sl_len, e_abs);
         e_abs
@@ -123,28 +125,29 @@ impl Clock {
         let e = self.epoch_abs().await;
         let sl = self.slot_relative().await;
         if self.ticking().await {
-            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
+            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
                 debug!("new genesis");
-                Ticks::GENESIS{e:e, sl:sl}
-            } else if e==self.e&&sl==self.sl+1 {
-                self.sl=sl;
+                Ticks::GENESIS { e, sl }
+            } else if e == self.e && sl == self.sl + 1 {
+                self.sl = sl;
                 debug!("new slot");
-                Ticks::NEWSLOT{e:e, sl:sl}
-            } else if e==self.e+1 && sl==0 {
-                self.e=e;
-                self.sl=sl;
+                Ticks::NEWSLOT { e, sl }
+            } else if e == self.e + 1 && sl == 0 {
+                self.e = e;
+                self.sl = sl;
                 debug!("new epoch");
-                Ticks::NEWEPOCH{e:e, sl:sl}
-            }
-            else if e==self.e && sl==self.sl {
+                Ticks::NEWEPOCH { e, sl }
+            } else if e == self.e && sl == self.sl {
                 debug!("clock is idle");
                 thread::sleep(Duration::from_millis(100));
                 Ticks::IDLE
-            }
-            else {
+            } else {
                 debug!("clock is out of sync");
                 //clock is out of sync
                 Ticks::OUTOFSYNC

+ 3 - 4
src/util/mod.rs

@@ -4,6 +4,7 @@ pub mod async_serial;
 pub mod async_util;
 
 pub mod cli;
+pub mod clock;
 pub mod endian;
 pub mod file;
 pub mod net_name;
@@ -11,7 +12,6 @@ pub mod parse;
 pub mod path;
 pub mod serial;
 pub mod time;
-pub mod clock;
 
 #[cfg(feature = "async-runtime")]
 pub use async_util::sleep;
@@ -20,10 +20,9 @@ pub use net_name::NetworkName;
 pub use parse::{decode_base10, encode_base10};
 pub use path::{expand_path, join_config_path, load_keypair_to_str};
 
-
-pub use time::{check_clock, unix_timestamp, NanoTimestamp, Timestamp, ntp_request};
-pub use clock::{Clock,Ticks};
+pub use clock::{Clock, Ticks};
 use rand::{distributions::Alphanumeric, thread_rng, Rng};
+pub use time::{check_clock, ntp_request, unix_timestamp, NanoTimestamp, Timestamp};
 pub fn gen_id(len: usize) -> String {
     thread_rng().sample_iter(&Alphanumeric).take(len).map(char::from).collect()
 }

+ 111 - 95
src/zk/circuit/lead_contract.rs

@@ -1,9 +1,20 @@
+use crate::crypto::{
+    constants::{
+        sinsemilla::{OrchardCommitDomains, OrchardHashDomains},
+        util::gen_const_array,
+        NullifierK, OrchardFixedBases, OrchardFixedBasesFull, MERKLE_DEPTH_ORCHARD,
+    },
+    merkle_node::MerkleNode,
+};
 use halo2_gadgets::{
     ecc::{
         chip::{EccChip, EccConfig},
         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::{
         chip::{SinsemillaChip, SinsemillaConfig},
         merkle::{
@@ -15,31 +26,22 @@ use halo2_gadgets::{
 };
 use halo2_proofs::{
     circuit::{AssignedCell, Layouter, SimpleFloorPlanner, Value},
-    plonk::{Advice, Circuit, Column, ConstraintSystem, Error, Instance as InstanceColumn,},
+    plonk::{Advice, Circuit, Column, ConstraintSystem, Error, Instance as InstanceColumn},
 };
 use pasta_curves::{pallas, Fp};
-use crate::crypto::{
-    constants::{
-        sinsemilla::{OrchardCommitDomains, OrchardHashDomains},
-        util::gen_const_array,
-        OrchardFixedBases, OrchardFixedBasesFull, MERKLE_DEPTH_ORCHARD, NullifierK,
-    },
-    merkle_node::MerkleNode,
-};
 
 use crate::zk::gadget::{
     arithmetic::{ArithChip, ArithConfig, ArithInstruction},
     //even_bits::{EvenBitsChip, EvenBitsConfig, EvenBitsLookup},
-
-    less_than::{ LessThanConfig, LessThanChip},
-    native_range_check::{NativeRangeCheckChip},
+    less_than::{LessThanChip, LessThanConfig},
+    native_range_check::NativeRangeCheckChip,
 };
 
 const WINDOW_SIZE: usize = 3;
 const NUM_OF_BITS: usize = 254;
 const NUM_OF_WINDOWS: usize = 85;
 
-const PRF_NULLIFIER_PREFIX : u64 = 0;
+const PRF_NULLIFIER_PREFIX: u64 = 0;
 
 #[derive(Clone, Debug)]
 pub struct LeadConfig {
@@ -54,7 +56,7 @@ pub struct LeadConfig {
     _sinsemilla_config_2:
         SinsemillaConfig<OrchardHashDomains, OrchardCommitDomains, OrchardFixedBases>,
 
-    lessthan_config: LessThanConfig<WINDOW_SIZE,NUM_OF_BITS,NUM_OF_WINDOWS>,
+    lessthan_config: LessThanConfig<WINDOW_SIZE, NUM_OF_BITS, NUM_OF_WINDOWS>,
 
     arith_config: ArithConfig,
 }
@@ -80,18 +82,15 @@ impl LeadConfig {
         MerkleChip::construct(self.merkle_config_2.clone())
     }
 
-
-    fn lessthan_chip(&self) -> LessThanChip<WINDOW_SIZE,NUM_OF_BITS,NUM_OF_WINDOWS> {
+    fn lessthan_chip(&self) -> LessThanChip<WINDOW_SIZE, NUM_OF_BITS, NUM_OF_WINDOWS> {
         LessThanChip::construct(self.lessthan_config.clone())
     }
 
     fn arith_chip(&self) -> ArithChip {
         ArithChip::construct(self.arith_config.clone())
-     }
+    }
 }
 
-
-
 const LEAD_COIN_COMMIT_X_OFFSET: usize = 0;
 const LEAD_COIN_COMMIT_Y_OFFSET: usize = 1;
 const LEAD_COIN_COMMIT2_X_OFFSET: usize = 2;
@@ -101,13 +100,12 @@ const LEAD_COIN_COMMIT_PATH_OFFSET: usize = 5;
 const LEAD_COIN_PK_OFFSET: usize = 6;
 const LEAD_COIN_SERIAL_NUMBER_OFFSET: usize = 7;
 const LEAD_Y_COMMIT_BASE_OFFSET: usize = 8;
-const LEAD_RHO_COMMIT_BASE_OFFSET: usize =9;
+const LEAD_RHO_COMMIT_BASE_OFFSET: usize = 9;
 
 pub fn concat_u8(lhs: &[u8], rhs: &[u8]) -> Vec<u8> {
     [lhs, rhs].concat()
 }
 
-
 #[derive(Default, Debug)]
 pub struct LeadContract {
     // witness
@@ -231,7 +229,6 @@ impl Circuit<pallas::Base> for LeadContract {
 
         let k_values_table = meta.lookup_table_column();
 
-
         let lessthan_config = {
             let a = meta.advice_column();
             let b = meta.advice_column();
@@ -247,7 +244,6 @@ impl Circuit<pallas::Base> for LeadContract {
                 a_offset,
                 k_values_table,
             )
-
         };
 
         let arith_config = ArithChip::configure(meta, advices[7], advices[8], advices[6]);
@@ -266,12 +262,11 @@ impl Circuit<pallas::Base> for LeadContract {
         }
     }
 
-    fn synthesize (
+    fn synthesize(
         &self,
         config: Self::Config,
         mut layouter: impl Layouter<pallas::Base>,
     ) -> Result<(), Error> {
-
         let less_than_chip = config.lessthan_chip();
         NativeRangeCheckChip::<WINDOW_SIZE, NUM_OF_BITS, NUM_OF_WINDOWS>::load_k_table(
             &mut layouter,
@@ -322,11 +317,8 @@ impl Circuit<pallas::Base> for LeadContract {
         )?;
 
         // staking coin secret key
-        let _root_sk = self.load_private(
-            layouter.namespace(|| ""),
-            config.advices[0],
-            self.root_sk
-        )?;
+        let _root_sk =
+            self.load_private(layouter.namespace(|| ""), config.advices[0], self.root_sk)?;
 
         // sigma scalar is 2^254/(total network stake + epsilon)
         let sigma_scalar = self.load_private(
@@ -345,14 +337,17 @@ impl Circuit<pallas::Base> for LeadContract {
         // coin public key pk=PRF_{root_sk}(tau)
         // coin public key is pseudo random hash of concatenation of the following:
         // coin timestamp, and root of coin's secret key.
-        let coin_pk_commit : AssignedCell<Fp,Fp> = {
-            let poseidon_message = [
-                coin_timestamp.clone(),
-                _root_sk.clone(),
-            ];
-            let poseidon_hasher = PoseidonHash::<_, _, poseidon::P128Pow5T3, poseidon::ConstantLength<2>, 3, 2>::init(
-                config.poseidon_chip(),
-                layouter.namespace(|| "Poseidon init"),
+        let coin_pk_commit: AssignedCell<Fp, Fp> = {
+            let poseidon_message = [coin_timestamp.clone(), _root_sk.clone()];
+            let poseidon_hasher = PoseidonHash::<
+                _,
+                _,
+                poseidon::P128Pow5T3,
+                poseidon::ConstantLength<2>,
+                3,
+                2,
+            >::init(
+                config.poseidon_chip(), layouter.namespace(|| "Poseidon init")
             )?;
 
             let poseidon_output =
@@ -361,18 +356,20 @@ impl Circuit<pallas::Base> for LeadContract {
             poseidon_output
         };
 
-
         // coin c1 serial number sn=PRF_{root_sk}(nonce)
         // coin's serial number is derived from coin nonce (sampled at random)
         // and root of the coin's secret key sampled an random.
-        let sn_commit : AssignedCell<Fp,Fp> = {
-            let poseidon_message = [
-                coin_nonce.clone(),
-                _root_sk.clone()
-            ];
-            let poseidon_hasher = PoseidonHash::<_, _, poseidon::P128Pow5T3, poseidon::ConstantLength<2>, 3, 2>::init(
-                config.poseidon_chip(),
-                layouter.namespace(|| "Poseidon init"),
+        let sn_commit: AssignedCell<Fp, Fp> = {
+            let poseidon_message = [coin_nonce.clone(), _root_sk.clone()];
+            let poseidon_hasher = PoseidonHash::<
+                _,
+                _,
+                poseidon::P128Pow5T3,
+                poseidon::ConstantLength<2>,
+                3,
+                2,
+            >::init(
+                config.poseidon_chip(), layouter.namespace(|| "Poseidon init")
             )?;
 
             let poseidon_output =
@@ -386,19 +383,27 @@ impl Circuit<pallas::Base> for LeadContract {
         let com = {
             // coin c1 nullifier is a commitment of the following
             // nullifier input
-            let nullifier_msg : AssignedCell<Fp,Fp> = {
-                let poseidon_message =  [
+            let nullifier_msg: AssignedCell<Fp, Fp> = {
+                let poseidon_message = [
                     prf_nullifier_prefix_base.clone(),
                     coin_pk_commit.clone(),
                     coin_value.clone(),
                     coin_nonce.clone(),
                 ];
-                let poseidon_hasher = PoseidonHash::<_, _, poseidon::P128Pow5T3, poseidon::ConstantLength<4>, 3, 2>::init(
+                let poseidon_hasher = PoseidonHash::<
+                    _,
+                    _,
+                    poseidon::P128Pow5T3,
+                    poseidon::ConstantLength<4>,
+                    3,
+                    2,
+                >::init(
                     config.poseidon_chip(),
                     layouter.namespace(|| "Poseidon init"),
                 )?;
 
-                let poseidon_output = poseidon_hasher.hash(layouter.namespace(|| "Poseidon hash"), poseidon_message)?;
+                let poseidon_output = poseidon_hasher
+                    .hash(layouter.namespace(|| "Poseidon hash"), poseidon_message)?;
                 let poseidon_output: AssignedCell<Fp, Fp> = poseidon_output;
                 poseidon_output
             };
@@ -413,7 +418,8 @@ impl Circuit<pallas::Base> for LeadContract {
                 layouter.namespace(|| "coin1 blind scalar"),
                 self.coin1_blind,
             )?;
-            let coin_commit_r = FixedPoint::from_inner(ecc_chip.clone(), OrchardFixedBasesFull::ValueCommitR);
+            let coin_commit_r =
+                FixedPoint::from_inner(ecc_chip.clone(), OrchardFixedBasesFull::ValueCommitR);
             coin_commit_r.mul(layouter.namespace(|| "coin serial number commit R"), rcv)?
         };
 
@@ -424,14 +430,17 @@ impl Circuit<pallas::Base> for LeadContract {
         // nonce2  =  PRF_{root_sk}(coin_nonce)
         // poured coin derived nonce as a poseidon of the previous nonce, and
         // root of secret key.
-        let coin2_nonce : AssignedCell<Fp,Fp> = {
-            let poseidon_message = [
-                coin_nonce.clone(),
-                _root_sk.clone()
-            ];
-            let poseidon_hasher = PoseidonHash::<_, _, poseidon::P128Pow5T3, poseidon::ConstantLength<2>, 3, 2>::init(
-                config.poseidon_chip(),
-                layouter.namespace(|| "Poseidon init"),
+        let coin2_nonce: AssignedCell<Fp, Fp> = {
+            let poseidon_message = [coin_nonce.clone(), _root_sk.clone()];
+            let poseidon_hasher = PoseidonHash::<
+                _,
+                _,
+                poseidon::P128Pow5T3,
+                poseidon::ConstantLength<2>,
+                3,
+                2,
+            >::init(
+                config.poseidon_chip(), layouter.namespace(|| "Poseidon init")
             )?;
 
             let poseidon_output =
@@ -445,23 +454,30 @@ impl Circuit<pallas::Base> for LeadContract {
         let com2 = {
             // coin2's commitment input body as a poseidon of input concatenation of
             // public key, stake, and poured coin's nonce.
-            let nullifier2_msg : AssignedCell<Fp,Fp> = {
+            let nullifier2_msg: AssignedCell<Fp, Fp> = {
                 let poseidon_message = [
                     prf_nullifier_prefix_base.clone(),
                     coin_pk_commit.clone(),
                     coin_value.clone(),
                     coin2_nonce.clone(),
                 ];
-                let poseidon_hasher = PoseidonHash::<_, _, poseidon::P128Pow5T3, poseidon::ConstantLength<4>, 3, 2>::init(
+                let poseidon_hasher = PoseidonHash::<
+                    _,
+                    _,
+                    poseidon::P128Pow5T3,
+                    poseidon::ConstantLength<4>,
+                    3,
+                    2,
+                >::init(
                     config.poseidon_chip(),
                     layouter.namespace(|| "Poseidon init"),
                 )?;
 
-                let poseidon_output =
-                    poseidon_hasher.hash(layouter.namespace(|| "Poseidon hash"), poseidon_message)?;
+                let poseidon_output = poseidon_hasher
+                    .hash(layouter.namespace(|| "Poseidon hash"), poseidon_message)?;
                 let poseidon_output: AssignedCell<Fp, Fp> = poseidon_output;
                 poseidon_output
-        };
+            };
             let coin_commit_v = FixedPointBaseField::from_inner(ecc_chip.clone(), NullifierK);
             coin_commit_v.mul(layouter.namespace(|| "coin commit v"), nullifier2_msg)?
         };
@@ -472,16 +488,17 @@ impl Circuit<pallas::Base> for LeadContract {
                 layouter.namespace(|| "coin2 blind scalar"),
                 self.coin2_blind,
             )?;
-            let coin_commit_r = FixedPoint::from_inner(ecc_chip.clone(), OrchardFixedBasesFull::ValueCommitR);
+            let coin_commit_r =
+                FixedPoint::from_inner(ecc_chip.clone(), OrchardFixedBasesFull::ValueCommitR);
             coin_commit_r.mul(layouter.namespace(|| "coin serial number commit R"), coin2_blind)?
         };
         let coin2_commit = com2.add(layouter.namespace(|| "nonce commit"), &blind)?;
         let coin2_commit_x: AssignedCell<Fp, Fp> = coin2_commit.inner().x();
         let coin2_commit_y: AssignedCell<Fp, Fp> = coin2_commit.inner().y();
 
-
         // path is valid path to staked coin's commitment
-        let path : Value<[pallas::Base;MERKLE_DEPTH_ORCHARD]> = self.path.map(|typed_path| gen_const_array(|i| typed_path[i].inner()));
+        let path: Value<[pallas::Base; MERKLE_DEPTH_ORCHARD]> =
+            self.path.map(|typed_path| gen_const_array(|i| typed_path[i].inner()));
 
         let merkle_inputs = MerklePath::construct(
             [config.merkle_chip_1(), config.merkle_chip_2()],
@@ -500,20 +517,24 @@ impl Circuit<pallas::Base> for LeadContract {
             )?;
             res
         };
-        let computed_final_root = merkle_inputs .calculate_root(layouter.namespace(|| "calculate root"), coin_commit_prod)?;
+        let computed_final_root = merkle_inputs
+            .calculate_root(layouter.namespace(|| "calculate root"), coin_commit_prod)?;
 
         // lhs of the leader election lottery
         // *  y as COMIT(root_sk||nonce, mau_y)
         // beging the commitment to the coin's secret key, coin's nonce, and
         // random value deriven from the epoch sampled random eta.
-        let lottery_commit_msg : AssignedCell<Fp,Fp> = {
-            let poseidon_message = [
-                _root_sk.clone(),
-                coin_nonce.clone(),
-            ];
-            let poseidon_hasher = PoseidonHash::<_, _, poseidon::P128Pow5T3, poseidon::ConstantLength<2>, 3, 2>::init(
-                config.poseidon_chip(),
-                layouter.namespace(|| "Poseidon init"),
+        let lottery_commit_msg: AssignedCell<Fp, Fp> = {
+            let poseidon_message = [_root_sk.clone(), coin_nonce.clone()];
+            let poseidon_hasher = PoseidonHash::<
+                _,
+                _,
+                poseidon::P128Pow5T3,
+                poseidon::ConstantLength<2>,
+                3,
+                2,
+            >::init(
+                config.poseidon_chip(), layouter.namespace(|| "Poseidon init")
             )?;
 
             let poseidon_output =
@@ -523,7 +544,7 @@ impl Circuit<pallas::Base> for LeadContract {
         };
 
         let com = {
-            let y_commit_v = FixedPointBaseField::from_inner(ecc_chip.clone(),  NullifierK);
+            let y_commit_v = FixedPointBaseField::from_inner(ecc_chip.clone(), NullifierK);
             y_commit_v.mul(layouter.namespace(|| "coin commit v"), lottery_commit_msg)?
         };
 
@@ -534,7 +555,8 @@ impl Circuit<pallas::Base> for LeadContract {
                 layouter.namespace(|| "mau_y scalar"),
                 self.mau_y,
             )?;
-            let y_commit_r = FixedPoint::from_inner(ecc_chip.clone(), OrchardFixedBasesFull::ValueCommitR);
+            let y_commit_r =
+                FixedPoint::from_inner(ecc_chip.clone(), OrchardFixedBasesFull::ValueCommitR);
             y_commit_r.mul(layouter.namespace(|| "coin serial number commit R"), mau_y)?
         };
         let y_commit = com.add(layouter.namespace(|| "nonce commit"), &blind)?;
@@ -546,25 +568,27 @@ impl Circuit<pallas::Base> for LeadContract {
             let mau_rho = ScalarFixed::new(
                 ecc_chip.clone(),
                 layouter.namespace(|| "mau_rho scalar"),
-                self.mau_rho
+                self.mau_rho,
             )?;
-            let rho_commit_r = FixedPoint::from_inner(ecc_chip.clone(), OrchardFixedBasesFull::ValueCommitR);
+            let rho_commit_r =
+                FixedPoint::from_inner(ecc_chip.clone(), OrchardFixedBasesFull::ValueCommitR);
             rho_commit_r.mul(layouter.namespace(|| "coin serial number commit R"), mau_rho)?
         };
         let rho_commit = com.add(layouter.namespace(|| "nonce commit"), &blind)?;
         let rho_commit_base = rho_commit.inner().x();
         // stakeholder absolute stake + 1 (epsilon)
         let stake_plus = ar_chip.add(layouter.namespace(|| ""), &one, &coin_value.clone())?;
-        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 target : Value<pallas::Base> = target.value().cloned();
+        let y: Value<pallas::Base> = y_commit_base.value().cloned();
+        let target: Value<pallas::Base> = target.value().cloned();
         less_than_chip.witness_less_than(
             layouter.namespace(|| "y < target"),
             target, //reversed for testing
             y,
             0,
-            true
+            true,
         )?;
 
         layouter.constrain_instance(
@@ -580,7 +604,6 @@ impl Circuit<pallas::Base> for LeadContract {
             LEAD_COIN_COMMIT_Y_OFFSET,
         )?;
 
-
         layouter.constrain_instance(
             coin2_commit_x.cell(),
             config.primary,
@@ -593,26 +616,19 @@ impl Circuit<pallas::Base> for LeadContract {
             LEAD_COIN_COMMIT2_Y_OFFSET,
         )?;
 
-
         layouter.constrain_instance(
             coin2_nonce.clone().cell(),
             config.primary,
             LEAD_COIN_NONCE2_OFFSET,
         )?;
 
-
         layouter.constrain_instance(
             computed_final_root.cell(),
             config.primary,
             LEAD_COIN_COMMIT_PATH_OFFSET,
         )?;
 
-
-        layouter.constrain_instance(
-        coin_pk_commit.cell(),
-        config.primary,
-        LEAD_COIN_PK_OFFSET,
-        )?;
+        layouter.constrain_instance(coin_pk_commit.cell(), config.primary, LEAD_COIN_PK_OFFSET)?;
 
         // constrain coin's pub key x value
         layouter.constrain_instance(

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

@@ -389,7 +389,6 @@ mod tests {
         let spend_hook = pallas::Base::random(&mut OsRng);
         let user_data = pallas::Base::random(&mut OsRng);
 
-
         let msg = [
             *coords.x(),
             *coords.y(),

+ 0 - 1
src/zk/gadget/less_than.rs

@@ -130,7 +130,6 @@ impl<const WINDOW_SIZE: usize, const NUM_OF_BITS: usize, const NUM_OF_WINDOWS: u
         Ok(())
     }
 
-
     /*
     pub fn witness_less_than2(
         &self,

+ 0 - 1
src/zk/gadget/mod.rs

@@ -1,7 +1,6 @@
 /// Base field arithmetic gadget
 pub mod arithmetic;
 
-
 /// Small range check, 0..8 bits
 pub mod small_range_check;
 

+ 0 - 1
src/zk/mod.rs

@@ -8,7 +8,6 @@ pub mod circuit;
 /// ZK gadget implementations
 pub mod gadget;
 
-
 use halo2_proofs::{
     arithmetic::Field,
     circuit::{AssignedCell, Layouter, Value},

+ 0 - 3
src/zk/vm.rs

@@ -24,7 +24,6 @@ use halo2_proofs::{
 };
 use log::{debug, error};
 
-
 pub use super::vm_stack::{StackVar, Witness};
 use super::{
     assign_free_advice,
@@ -63,7 +62,6 @@ pub struct VmConfig {
     native_253_range_check_config: NativeRangeCheckConfig<3, 253, 85>,
     lessthan_config: LessThanConfig<3, 253, 85>,
     boolcheck_config: SmallRangeCheckConfig,
-
 }
 
 impl VmConfig {
@@ -255,7 +253,6 @@ impl Circuit<pallas::Base> for ZkCircuit {
             native_253_range_check_config,
             lessthan_config,
             boolcheck_config,
-
         }
     }