Parcourir la source

dnetview: remove unused data structures and cleanup

lunar-mining il y a 4 ans
Parent
commit
fac25736a1
7 fichiers modifiés avec 266 ajouts et 291 suppressions
  1. 3 8
      bin/dnetview/src/main.rs
  2. 18 23
      bin/dnetview/src/view.rs
  3. 15 19
      example/gt.rs
  4. 92 103
      example/lead.rs
  5. 130 129
      src/zk/circuit/lead_contract.rs
  6. 6 8
      src/zk/greater_than.rs
  7. 2 1
      src/zk/vm.rs

+ 3 - 8
bin/dnetview/src/main.rs

@@ -399,20 +399,15 @@ async fn render<B: Backend>(terminal: &mut Terminal<B>, model: Arc<Model>) -> Re
 
 
     terminal.clear()?;
     terminal.clear()?;
 
 
-    let all_ids = IdListView::new(FxHashSet::default());
     let active_ids = IdListView::new(FxHashSet::default());
     let active_ids = IdListView::new(FxHashSet::default());
     let info_list = NodeInfoView::new(FxHashMap::default());
     let info_list = NodeInfoView::new(FxHashMap::default());
     let selectable = FxHashMap::default();
     let selectable = FxHashMap::default();
 
 
-    let mut view = View::new(all_ids.clone(), active_ids.clone(), info_list.clone(), selectable);
-    view.all_ids.state.select(Some(0));
-    view.info_list.index = 0;
+    let mut view = View::new(active_ids.clone(), info_list.clone(), selectable);
+    view.active_ids.state.select(Some(0));
 
 
     loop {
     loop {
-        view.init_ids(model.ids.lock().await.clone());
-        view.init_node_info(model.node_info.lock().await.clone());
-        view.init_active_ids();
-        view.init_selectable(model.select_info.lock().await.clone());
+        view.update(model.node_info.lock().await.clone(), model.select_info.lock().await.clone());
 
 
         terminal.draw(|f| {
         terminal.draw(|f| {
             view.clone().render(f);
             view.clone().render(f);

+ 18 - 23
bin/dnetview/src/view.rs

@@ -1,7 +1,5 @@
 use darkfi::error::{Error, Result};
 use darkfi::error::{Error, Result};
 use fxhash::{FxHashMap, FxHashSet};
 use fxhash::{FxHashMap, FxHashSet};
-use log::debug;
-use serde::{Deserialize, Serialize};
 use tui::widgets::ListState;
 use tui::widgets::ListState;
 
 
 use tui::{
 use tui::{
@@ -13,46 +11,48 @@ use tui::{
     Frame,
     Frame,
 };
 };
 
 
-use crate::model::{ConnectInfo, Model, NodeInfo, SelectableObject, SessionInfo};
+use crate::model::{NodeInfo, SelectableObject};
 
 
 #[derive(Debug, Clone)]
 #[derive(Debug, Clone)]
 pub struct View {
 pub struct View {
-    pub all_ids: IdListView,
     pub active_ids: IdListView,
     pub active_ids: IdListView,
-    pub info_list: NodeInfoView,
+    pub node_info: NodeInfoView,
     pub selectables: FxHashMap<String, SelectableObject>,
     pub selectables: FxHashMap<String, SelectableObject>,
 }
 }
 
 
 impl View {
 impl View {
     pub fn new(
     pub fn new(
-        all_ids: IdListView,
         active_ids: IdListView,
         active_ids: IdListView,
-        info_list: NodeInfoView,
+        node_info: NodeInfoView,
         selectables: FxHashMap<String, SelectableObject>,
         selectables: FxHashMap<String, SelectableObject>,
     ) -> View {
     ) -> View {
-        View { all_ids, active_ids, info_list, selectables }
+        View { active_ids, node_info, selectables }
     }
     }
 
 
-    pub fn init_ids(&mut self, ids: FxHashSet<String>) {
-        for id in ids {
-            self.all_ids.ids.insert(id);
-        }
+    pub fn update(
+        &mut self,
+        nodes: FxHashMap<String, NodeInfo>,
+        selectables: FxHashMap<String, SelectableObject>,
+    ) {
+        self.update_node_info(nodes);
+        self.update_selectable(selectables);
+        self.update_active_ids();
     }
     }
 
 
-    pub fn init_node_info(&mut self, nodes: FxHashMap<String, NodeInfo>) {
+    fn update_node_info(&mut self, nodes: FxHashMap<String, NodeInfo>) {
         for (id, node) in nodes {
         for (id, node) in nodes {
-            self.info_list.infos.insert(id, node);
+            self.node_info.infos.insert(id, node);
         }
         }
     }
     }
 
 
-    pub fn init_selectable(&mut self, selectables: FxHashMap<String, SelectableObject>) {
+    fn update_selectable(&mut self, selectables: FxHashMap<String, SelectableObject>) {
         for (id, obj) in selectables {
         for (id, obj) in selectables {
             self.selectables.insert(id, obj);
             self.selectables.insert(id, obj);
         }
         }
     }
     }
 
 
-    pub fn init_active_ids(&mut self) {
-        for info in self.info_list.infos.values() {
+    fn update_active_ids(&mut self) {
+        for info in self.node_info.infos.values() {
             self.active_ids.ids.insert(info.node_id.to_string());
             self.active_ids.ids.insert(info.node_id.to_string());
             for child in &info.children {
             for child in &info.children {
                 if !child.is_empty == true {
                 if !child.is_empty == true {
@@ -63,11 +63,6 @@ impl View {
                 }
                 }
             }
             }
         }
         }
-        //debug!("ACTIVE IDS VEC: {:?}", self.active_ids.ids);
-    }
-
-    pub fn init_node_list(&mut self) {
-        //
     }
     }
 
 
     pub fn render<B: Backend>(mut self, f: &mut Frame<'_, B>) {
     pub fn render<B: Backend>(mut self, f: &mut Frame<'_, B>) {
@@ -78,7 +73,7 @@ impl View {
         let list_direction = Direction::Horizontal;
         let list_direction = Direction::Horizontal;
         let list_cnstrnts = vec![Constraint::Percentage(50), Constraint::Percentage(50)];
         let list_cnstrnts = vec![Constraint::Percentage(50), Constraint::Percentage(50)];
 
 
-        for info in self.info_list.infos.values() {
+        for info in self.node_info.infos.values() {
             let name_span = Span::raw(&info.node_name);
             let name_span = Span::raw(&info.node_name);
             let lines = vec![Spans::from(name_span)];
             let lines = vec![Spans::from(name_span)];
             let names = ListItem::new(lines);
             let names = ListItem::new(lines);

+ 15 - 19
example/gt.rs

@@ -1,5 +1,5 @@
 use darkfi::zk::{
 use darkfi::zk::{
-    arith_chip::{ArithmeticChipConfig, ArithmeticChip},
+    arith_chip::{ArithmeticChip, ArithmeticChipConfig},
     even_bits::{EvenBitsChip, EvenBitsConfig, EvenBitsLookup},
     even_bits::{EvenBitsChip, EvenBitsConfig, EvenBitsLookup},
     greater_than::{GreaterThanChip, GreaterThanConfig, GreaterThanInstruction},
     greater_than::{GreaterThanChip, GreaterThanConfig, GreaterThanInstruction},
 };
 };
@@ -10,7 +10,7 @@ use halo2_proofs::{
     plonk,
     plonk,
     plonk::{Advice, Circuit, Column, ConstraintSystem, Instance as InstanceColumn},
     plonk::{Advice, Circuit, Column, ConstraintSystem, Instance as InstanceColumn},
 };
 };
-use pasta_curves::{pallas, Fp, vesta, Fq};
+use pasta_curves::{pallas, vesta, Fp, Fq};
 
 
 const WORD_BITS: u32 = 24;
 const WORD_BITS: u32 = 24;
 
 
@@ -20,11 +20,9 @@ struct ZkConfig {
     advices: [Column<Advice>; 3],
     advices: [Column<Advice>; 3],
     evenbits_config: EvenBitsConfig,
     evenbits_config: EvenBitsConfig,
     greaterthan_config: GreaterThanConfig,
     greaterthan_config: GreaterThanConfig,
-    arith_config: ArithmeticChipConfig
+    arith_config: ArithmeticChipConfig,
 }
 }
 
 
-
-
 impl ZkConfig {
 impl ZkConfig {
     fn evenbits_chip(&self) -> EvenBitsChip<pallas::Base, WORD_BITS> {
     fn evenbits_chip(&self) -> EvenBitsChip<pallas::Base, WORD_BITS> {
         EvenBitsChip::construct(self.evenbits_config.clone())
         EvenBitsChip::construct(self.evenbits_config.clone())
@@ -54,7 +52,7 @@ impl Circuit<pallas::Base> for ZkCircuit {
     type FloorPlanner = SimpleFloorPlanner;
     type FloorPlanner = SimpleFloorPlanner;
 
 
     fn without_witnesses(&self) -> Self {
     fn without_witnesses(&self) -> Self {
-        Self { y: None, v: None, f:None }
+        Self { y: None, v: None, f: None }
     }
     }
 
 
     fn configure(meta: &mut ConstraintSystem<pallas::Base>) -> Self::Config {
     fn configure(meta: &mut ConstraintSystem<pallas::Base>) -> Self::Config {
@@ -69,7 +67,11 @@ impl Circuit<pallas::Base> for ZkCircuit {
         }
         }
 
 
         let evenbits_config = EvenBitsChip::<pallas::Base, WORD_BITS>::configure(meta);
         let evenbits_config = EvenBitsChip::<pallas::Base, WORD_BITS>::configure(meta);
-        let greaterthan_config = GreaterThanChip::<pallas::Base, WORD_BITS>::configure(meta, [advices[1], advices[2]], primary);
+        let greaterthan_config = GreaterThanChip::<pallas::Base, WORD_BITS>::configure(
+            meta,
+            [advices[1], advices[2]],
+            primary,
+        );
         let arith_config = ArithmeticChip::configure(meta);
         let arith_config = ArithmeticChip::configure(meta);
 
 
         ZkConfig { primary, advices, evenbits_config, greaterthan_config, arith_config }
         ZkConfig { primary, advices, evenbits_config, greaterthan_config, arith_config }
@@ -91,13 +93,13 @@ impl Circuit<pallas::Base> for ZkCircuit {
         let v = self.load_private(layouter.namespace(|| "Witness v"), config.advices[0], self.v)?;
         let v = self.load_private(layouter.namespace(|| "Witness v"), config.advices[0], self.v)?;
         let f = self.load_private(layouter.namespace(|| "Witness t"), config.advices[0], self.f)?;
         let f = self.load_private(layouter.namespace(|| "Witness t"), config.advices[0], self.f)?;
 
 
-
-        let t = ar_chip.mul(layouter.namespace(|| "target value"),  v, f)?;
+        let t = ar_chip.mul(layouter.namespace(|| "target value"), v, f)?;
 
 
         eb_chip.decompose(layouter.namespace(|| "y range check"), y.clone())?;
         eb_chip.decompose(layouter.namespace(|| "y range check"), y.clone())?;
         eb_chip.decompose(layouter.namespace(|| "t range check"), t.clone())?;
         eb_chip.decompose(layouter.namespace(|| "t range check"), t.clone())?;
 
 
-        let (helper, greater_than) = gt_chip.greater_than(layouter.namespace(|| "y > t"), y.into(), t.into())?;
+        let (helper, greater_than) =
+            gt_chip.greater_than(layouter.namespace(|| "y > t"), y.into(), t.into())?;
 
 
         eb_chip.decompose(layouter.namespace(|| "helper range check"), helper.0)?;
         eb_chip.decompose(layouter.namespace(|| "helper range check"), helper.0)?;
 
 
@@ -113,15 +115,9 @@ fn main() {
     let f = pallas::Base::from(1);
     let f = pallas::Base::from(1);
     //
     //
     let c = pallas::Base::from(0);
     let c = pallas::Base::from(0);
-    let circuit = ZkCircuit {
-        y: Some(y),
-        v: Some(v),
-        f: Some(f),
-    };
-
-    let mut public_inputs : Vec<pallas::Base> = vec![
-          c,
-    ];
+    let circuit = ZkCircuit { y: Some(y), v: Some(v), f: Some(f) };
+
+    let mut public_inputs: Vec<pallas::Base> = vec![c];
 
 
     let prover = MockProver::run(k, &circuit, vec![public_inputs]).unwrap();
     let prover = MockProver::run(k, &circuit, vec![public_inputs]).unwrap();
     assert_eq!(prover.verify(), Ok(()));
     assert_eq!(prover.verify(), Ok(()));

+ 92 - 103
example/lead.rs

@@ -5,74 +5,65 @@ use halo2_gadgets::primitives::{
     poseidon::{ConstantLength, P128Pow5T3},
     poseidon::{ConstantLength, P128Pow5T3},
 };
 };
 
 
-use halo2_proofs::{
-    dev::MockProver,
-};
+use halo2_proofs::dev::MockProver;
 
 
 use rand::{thread_rng, Rng};
 use rand::{thread_rng, Rng};
 
 
 use pasta_curves::{pallas, Fp};
 use pasta_curves::{pallas, Fp};
 
 
 use darkfi::{
 use darkfi::{
-    zk:: {
-        circuit::lead_contract::{LeadContract},
-    },
     crypto::{
     crypto::{
-        merkle_node::MerkleNode,
-        //point_node::PointNode
-        keypair::{Keypair, PublicKey, SecretKey},
-        types::*,
         constants::{
         constants::{
-            NullifierK, OrchardFixedBases, OrchardFixedBasesFull, ValueCommitV, MERKLE_DEPTH_ORCHARD,
+            NullifierK, OrchardFixedBases, OrchardFixedBasesFull, ValueCommitV,
+            MERKLE_DEPTH_ORCHARD,
         },
         },
+        keypair::{Keypair, PublicKey, SecretKey},
+        merkle_node::MerkleNode,
         nullifier::Nullifier,
         nullifier::Nullifier,
         proof::{Proof, ProvingKey, VerifyingKey},
         proof::{Proof, ProvingKey, VerifyingKey},
+        types::*,
         util::{mod_r_p, pedersen_commitment_scalar, pedersen_commitment_u64},
         util::{mod_r_p, pedersen_commitment_scalar, pedersen_commitment_u64},
     },
     },
+    zk::circuit::lead_contract::LeadContract,
 };
 };
 
 
-use pasta_curves::group::Curve;
-use pasta_curves::arithmetic::CurveAffine;
+use pasta_curves::{arithmetic::CurveAffine, group::Curve};
 //use halo2_proofs::arithmetic::CurveAffine;
 //use halo2_proofs::arithmetic::CurveAffine;
-use pasta_curves::group::ff::PrimeField;
-use pasta_curves::group::GroupEncoding;
-
-
-#[derive(Debug,Default,Clone,Copy)]
-pub struct Coin
-{
-    value : Option<pallas::Base>, //stake
-    cm : Option<pallas::Point>,
-    cm2 : Option<pallas::Point>,
-    cm_blind : Option<pallas::Base>,
-    sl : Option<pallas::Base>, //slot id
-    tau : Option<pallas::Base>,
-    nonce : Option<pallas::Base>,
-    nonce_cm : Option<pallas::Point>,
-    sn : Option<pallas::Point>, // coin's serial number
+use pasta_curves::group::{ff::PrimeField, GroupEncoding};
+
+#[derive(Debug, Default, Clone, Copy)]
+pub struct Coin {
+    value: Option<pallas::Base>, //stake
+    cm: Option<pallas::Point>,
+    cm2: Option<pallas::Point>,
+    cm_blind: Option<pallas::Base>,
+    sl: Option<pallas::Base>, //slot id
+    tau: Option<pallas::Base>,
+    nonce: Option<pallas::Base>,
+    nonce_cm: Option<pallas::Point>,
+    sn: Option<pallas::Point>, // coin's serial number
     //sk : Option<SecretKey>,
     //sk : Option<SecretKey>,
-    pk : Option<pallas::Point>,
-    root_cm : Option<pallas::Scalar>,
-    root_sk : Option<pallas::Scalar>,
+    pk: Option<pallas::Point>,
+    root_cm: Option<pallas::Scalar>,
+    root_sk: Option<pallas::Scalar>,
     path: Option<[MerkleNode; MERKLE_DEPTH_ORCHARD]>,
     path: Option<[MerkleNode; MERKLE_DEPTH_ORCHARD]>,
     path_sk: Option<[MerkleNode; MERKLE_DEPTH_ORCHARD]>,
     path_sk: Option<[MerkleNode; MERKLE_DEPTH_ORCHARD]>,
-    opening1 : Option<pallas::Base>,
-    opening2 : Option<pallas::Base>,
+    opening1: Option<pallas::Base>,
+    opening2: Option<pallas::Base>,
 }
 }
 
 
-fn main()
-{
+fn main() {
     let k = 13;
     let k = 13;
     //
     //
-    const LEN : usize = 10;
+    const LEN: usize = 10;
     let mut rng = thread_rng();
     let mut rng = thread_rng();
-    let mut sks : Vec<u64> = vec![];
-    let mut root_sks : Vec<MerkleNode> = vec![];
-    let mut path_sks : Vec<[MerkleNode;MERKLE_DEPTH_ORCHARD]> = vec![];
-    let mut tree  =  BridgeTree::<MerkleNode, 32>::new(LEN);
+    let mut sks: Vec<u64> = vec![];
+    let mut root_sks: Vec<MerkleNode> = vec![];
+    let mut path_sks: Vec<[MerkleNode; MERKLE_DEPTH_ORCHARD]> = vec![];
+    let mut tree = BridgeTree::<MerkleNode, 32>::new(LEN);
     for i in 0..LEN {
     for i in 0..LEN {
-        let tmp : u64 = rng.gen();
-        let mut sk : u64 = tmp;
+        let tmp: u64 = rng.gen();
+        let mut sk: u64 = tmp;
         sks.push(sk.clone());
         sks.push(sk.clone());
         let node = MerkleNode(pallas::Base::from(sk));
         let node = MerkleNode(pallas::Base::from(sk));
         tree.append(&node.clone());
         tree.append(&node.clone());
@@ -81,45 +72,46 @@ fn main()
         root_sks.push(tree.root().clone());
         root_sks.push(tree.root().clone());
         path_sks.push(path.as_slice().try_into().unwrap());
         path_sks.push(path.as_slice().try_into().unwrap());
     }
     }
-    let mut seeds : Vec<u64> = vec![];
+    let mut seeds: Vec<u64> = vec![];
     for i in 0..LEN {
     for i in 0..LEN {
-        let rho : u64 = rng.gen();
+        let rho: u64 = rng.gen();
         seeds.push(rho.clone());
         seeds.push(rho.clone());
     }
     }
     //
     //
-    let yu64 : u64 = rng.gen();
-    let rhou64 : u64 = rng.gen();
-    let mau_y : pallas::Scalar = pallas::Scalar::from(yu64);
-    let mau_rho : pallas::Scalar = pallas::Scalar::from(rhou64);
+    let yu64: u64 = rng.gen();
+    let rhou64: u64 = rng.gen();
+    let mau_y: pallas::Scalar = pallas::Scalar::from(yu64);
+    let mau_rho: pallas::Scalar = pallas::Scalar::from(rhou64);
 
 
     //
     //
-    let mut coins : Vec<Coin> = vec![];
+    let mut coins: Vec<Coin> = vec![];
 
 
     //
     //
     let mut tree_cm = BridgeTree::<MerkleNode, 32>::new(LEN);
     let mut tree_cm = BridgeTree::<MerkleNode, 32>::new(LEN);
-    let zerou64 : u64 = 0;
+    let zerou64: u64 = 0;
 
 
     for i in 0..LEN {
     for i in 0..LEN {
-        let c_v = pallas::Base::from(u64::try_from(i*2).unwrap());
+        let c_v = pallas::Base::from(u64::try_from(i * 2).unwrap());
         //random sampling of the same size of prf,
         //random sampling of the same size of prf,
         //pseudo random sampling that is the size of pederson commitment
         //pseudo random sampling that is the size of pederson commitment
-        let c_sk : u64 = sks[i];
-        let iu64 : u64 = u64::try_from(i).unwrap();
-        let c_sl  = pallas::Base::from(iu64);
+        let c_sk: u64 = sks[i];
+        let iu64: u64 = u64::try_from(i).unwrap();
+        let c_sl = pallas::Base::from(iu64);
 
 
-        let c_tau  = pallas::Base::from(u64::try_from(i).unwrap()); // let's assume it's sl for simplicity
-        let c_root_sk : MerkleNode  = root_sks[i];
+        let c_tau = pallas::Base::from(u64::try_from(i).unwrap()); // let's assume it's sl for simplicity
+        let c_root_sk: MerkleNode = root_sks[i];
 
 
         let c_pk = pedersen_commitment_scalar(mod_r_p(c_tau), mod_r_p(c_root_sk.inner()));
         let c_pk = pedersen_commitment_scalar(mod_r_p(c_tau), mod_r_p(c_root_sk.inner()));
 
 
-        let c_seed  = pallas::Base::from(seeds[i]);
-        let c_sn  = pedersen_commitment_scalar(mod_r_p(c_seed), mod_r_p(c_root_sk.inner()));
+        let c_seed = pallas::Base::from(seeds[i]);
+        let c_sn = pedersen_commitment_scalar(mod_r_p(c_seed), mod_r_p(c_root_sk.inner()));
         let c_pk_pt = c_pk.to_affine().coordinates().unwrap();
         let c_pk_pt = c_pk.to_affine().coordinates().unwrap();
         let c_cm_message = [*c_pk_pt.x(), *c_pk_pt.y(), c_v.clone(), c_seed.clone()];
         let c_cm_message = [*c_pk_pt.x(), *c_pk_pt.y(), c_v.clone(), c_seed.clone()];
-        let c_cm_v = poseidon::Hash::<_,P128Pow5T3, ConstantLength<4>, 3, 2>::init().hash(c_cm_message);
+        let c_cm_v =
+            poseidon::Hash::<_, P128Pow5T3, ConstantLength<4>, 3, 2>::init().hash(c_cm_message);
         let c_cm1_blind = pallas::Base::from(0); //tmp val
         let c_cm1_blind = pallas::Base::from(0); //tmp val
         let c_cm2_blind = pallas::Base::from(0); //tmp val
         let c_cm2_blind = pallas::Base::from(0); //tmp val
-        let c_cm : pallas::Point  = pedersen_commitment_scalar(mod_r_p(c_cm_v), mod_r_p(c_cm1_blind));
+        let c_cm: pallas::Point = pedersen_commitment_scalar(mod_r_p(c_cm_v), mod_r_p(c_cm1_blind));
         //TODO this return run time error! assertion error, it's out of range most likely
         //TODO this return run time error! assertion error, it's out of range most likely
         //let c_cm_base_bytes : [u8; 32] = c_cm.to_bytes();
         //let c_cm_base_bytes : [u8; 32] = c_cm.to_bytes();
         /*
         /*
@@ -138,11 +130,12 @@ fn main()
         let c_seed2 = pedersen_commitment_scalar(mod_r_p(c_seed), mod_r_p(c_root_sk.inner()));
         let c_seed2 = pedersen_commitment_scalar(mod_r_p(c_seed), mod_r_p(c_root_sk.inner()));
         let c_seed2_pt = c_seed2.to_affine().coordinates().unwrap();
         let c_seed2_pt = c_seed2.to_affine().coordinates().unwrap();
         let lead_coin_msg = [*c_pk_pt.x(), *c_pk_pt.y(), c_v, *c_seed2_pt.x(), *c_seed2_pt.y()];
         let lead_coin_msg = [*c_pk_pt.x(), *c_pk_pt.y(), c_v, *c_seed2_pt.x(), *c_seed2_pt.y()];
-        let lead_coin_msg_hash = poseidon::Hash::<_,P128Pow5T3, ConstantLength<5>, 3, 2>::init().hash(lead_coin_msg);
+        let lead_coin_msg_hash =
+            poseidon::Hash::<_, P128Pow5T3, ConstantLength<5>, 3, 2>::init().hash(lead_coin_msg);
         let c_cm2 = pedersen_commitment_scalar(mod_r_p(lead_coin_msg_hash), mod_r_p(c_cm2_blind));
         let c_cm2 = pedersen_commitment_scalar(mod_r_p(lead_coin_msg_hash), mod_r_p(c_cm2_blind));
         let c_root_sk = root_sks[i];
         let c_root_sk = root_sks[i];
         let c_path_sk = path_sks[i];
         let c_path_sk = path_sks[i];
-        let coin  = Coin {
+        let coin = Coin {
             value: Some(c_v),
             value: Some(c_v),
             cm: Some(c_cm),
             cm: Some(c_cm),
             cm2: Some(c_cm2),
             cm2: Some(c_cm2),
@@ -151,7 +144,7 @@ fn main()
             tau: Some(c_tau),
             tau: Some(c_tau),
             nonce: Some(c_seed),
             nonce: Some(c_seed),
             nonce_cm: Some(c_seed2),
             nonce_cm: Some(c_seed2),
-            sn:  Some(c_sn),
+            sn: Some(c_sn),
             //sk: Some(c_sk),
             //sk: Some(c_sk),
             pk: Some(c_pk),
             pk: Some(c_pk),
             root_cm: Some(mod_r_p(c_root_cm.inner())),
             root_cm: Some(mod_r_p(c_root_cm.inner())),
@@ -167,20 +160,12 @@ fn main()
     // ================
     // ================
     // public inputs
     // public inputs
     // ================
     // ================
-    let coin_idx  = 0;
+    let coin_idx = 0;
     let coin = coins[coin_idx];
     let coin = coins[coin_idx];
 
 
+    let po_nonce = coin.nonce_cm.unwrap().to_affine().coordinates().unwrap();
 
 
-    let po_nonce = coin.nonce_cm
-        .unwrap()
-        .to_affine()
-        .coordinates()
-        .unwrap();
-
-    let po_nonce = coin.nonce_cm.unwrap()
-        .to_affine()
-        .coordinates()
-        .unwrap();
+    let po_nonce = coin.nonce_cm.unwrap().to_affine().coordinates().unwrap();
 
 
     let po_tau = pedersen_commitment_scalar(mod_r_p(coin.tau.unwrap()), coin.root_cm.unwrap())
     let po_tau = pedersen_commitment_scalar(mod_r_p(coin.tau.unwrap()), coin.root_cm.unwrap())
         .to_affine()
         .to_affine()
@@ -193,40 +178,44 @@ fn main()
     let po_pk = coin.pk.unwrap().to_affine().coordinates().unwrap();
     let po_pk = coin.pk.unwrap().to_affine().coordinates().unwrap();
     let po_sn = coin.sn.unwrap().to_affine().coordinates().unwrap();
     let po_sn = coin.sn.unwrap().to_affine().coordinates().unwrap();
 
 
-
     let po_path = coin.path.unwrap();
     let po_path = coin.path.unwrap();
 
 
     let po_cmp = pallas::Base::from(0);
     let po_cmp = pallas::Base::from(0);
     // ===============
     // ===============
     let path_sk = path_sks[coin_idx];
     let path_sk = path_sks[coin_idx];
 
 
-   let contract = LeadContract {
-       path: coin.path,
-       root_sk: coin.root_sk,
-       path_sk: Some(path_sk),
-       coin_timestamp: coin.tau, //
-       coin_nonce: coin.nonce,
-       coin_opening_1: Some(mod_r_p(coin.opening1.unwrap())),
-       value: coin.value,
-       coin_opening_2: Some(mod_r_p(coin.opening2.unwrap())),
-       cm_c1_x: Some(*po_cm.x()),
-       cm_c1_y: Some(*po_cm.y()),
-       cm_c2_x: Some(*po_cm2.x()),
-       cm_c2_y: Some(*po_cm2.y()),
-       cm_pos : Some(u32::try_from(coin_idx).unwrap()),
-       //sn_c1: Some(coin.sn.unwrap()),
-       slot: Some(coin.sl.unwrap()),
-       mau_rho: Some(mau_rho.clone()),
-       mau_y: Some(mau_y.clone()),
-       root_cm: Some(coin.root_cm.unwrap()),
-   };
-
-    let mut public_inputs : Vec<pallas::Base> = vec![
-        *po_nonce.x(), *po_nonce.y(),
-        *po_pk.x(), *po_pk.y(),
-        *po_sn.x(), *po_sn.y(),
-        *po_cm.x(), *po_cm.y(),
-        *po_cm2.x(), *po_cm2.y(),
+    let contract = LeadContract {
+        path: coin.path,
+        root_sk: coin.root_sk,
+        path_sk: Some(path_sk),
+        coin_timestamp: coin.tau, //
+        coin_nonce: coin.nonce,
+        coin_opening_1: Some(mod_r_p(coin.opening1.unwrap())),
+        value: coin.value,
+        coin_opening_2: Some(mod_r_p(coin.opening2.unwrap())),
+        cm_c1_x: Some(*po_cm.x()),
+        cm_c1_y: Some(*po_cm.y()),
+        cm_c2_x: Some(*po_cm2.x()),
+        cm_c2_y: Some(*po_cm2.y()),
+        cm_pos: Some(u32::try_from(coin_idx).unwrap()),
+        //sn_c1: Some(coin.sn.unwrap()),
+        slot: Some(coin.sl.unwrap()),
+        mau_rho: Some(mau_rho.clone()),
+        mau_y: Some(mau_y.clone()),
+        root_cm: Some(coin.root_cm.unwrap()),
+    };
+
+    let mut public_inputs: Vec<pallas::Base> = vec![
+        *po_nonce.x(),
+        *po_nonce.y(),
+        *po_pk.x(),
+        *po_pk.y(),
+        *po_sn.x(),
+        *po_sn.y(),
+        *po_cm.x(),
+        *po_cm.y(),
+        *po_cm2.x(),
+        *po_cm2.y(),
         po_path[31].inner(), //TODO (res) how the path is structured assumed root is last node in the path.
         po_path[31].inner(), //TODO (res) how the path is structured assumed root is last node in the path.
         po_cmp,
         po_cmp,
     ];
     ];

+ 130 - 129
src/zk/circuit/lead_contract.rs

@@ -1,7 +1,7 @@
 use halo2_gadgets::{
 use halo2_gadgets::{
     ecc::{
     ecc::{
         chip::{EccChip, EccConfig},
         chip::{EccChip, EccConfig},
-        FixedPoint, FixedPointShort,NonIdentityPoint,Point
+        FixedPoint, FixedPointShort, NonIdentityPoint, Point,
     },
     },
     poseidon::{Hash as PoseidonHash, Pow5Chip as PoseidonChip, Pow5Config as PoseidonConfig},
     poseidon::{Hash as PoseidonHash, Pow5Chip as PoseidonChip, Pow5Config as PoseidonConfig},
     primitives::poseidon::{ConstantLength, P128Pow5T3},
     primitives::poseidon::{ConstantLength, P128Pow5T3},
@@ -18,7 +18,7 @@ use halo2_gadgets::{
 use halo2_proofs::{
 use halo2_proofs::{
     circuit::{AssignedCell, Layouter, SimpleFloorPlanner},
     circuit::{AssignedCell, Layouter, SimpleFloorPlanner},
     plonk,
     plonk,
-    plonk::{Advice, Circuit, Column, ConstraintSystem, Instance as InstanceColumn, Error},
+    plonk::{Advice, Circuit, Column, ConstraintSystem, Error, Instance as InstanceColumn},
 };
 };
 
 
 use pasta_curves::{pallas, Fp};
 use pasta_curves::{pallas, Fp};
@@ -32,47 +32,41 @@ use crate::crypto::{
     merkle_node::MerkleNode,
     merkle_node::MerkleNode,
 };
 };
 
 
-
 use crate::zk::{
 use crate::zk::{
-    arith_chip::{ArithmeticChipConfig, ArithmeticChip},
-    greater_than::{GreaterThanChip, GreaterThanConfig, GreaterThanInstruction},
+    arith_chip::{ArithmeticChip, ArithmeticChipConfig},
     even_bits::{EvenBitsChip, EvenBitsConfig, EvenBitsLookup},
     even_bits::{EvenBitsChip, EvenBitsConfig, EvenBitsLookup},
+    greater_than::{GreaterThanChip, GreaterThanConfig, GreaterThanInstruction},
 };
 };
 
 
-use pasta_curves::group::Curve;
-use pasta_curves::arithmetic::CurveAffine;
+use pasta_curves::{arithmetic::CurveAffine, group::Curve};
 //use halo2_proofs::arithmetic::CurveAffine;
 //use halo2_proofs::arithmetic::CurveAffine;
-use pasta_curves::group::ff::PrimeField;
-use pasta_curves::group::GroupEncoding;
+use pasta_curves::group::{ff::PrimeField, GroupEncoding};
 
 
+const WORD_BITS: u32 = 24;
 
 
-const WORD_BITS : u32 = 24;
-
-#[derive(Clone,Debug)]
-pub struct LeadConfig
-{
+#[derive(Clone, Debug)]
+pub struct LeadConfig {
     primary: Column<InstanceColumn>,
     primary: Column<InstanceColumn>,
-    advices: [Column<Advice>;12],
+    advices: [Column<Advice>; 12],
     ecc_config: EccConfig<OrchardFixedBases>,
     ecc_config: EccConfig<OrchardFixedBases>,
-    poseidon_config: PoseidonConfig<pallas::Base,3,2>,
+    poseidon_config: PoseidonConfig<pallas::Base, 3, 2>,
     merkle_config_1: MerkleConfig<OrchardHashDomains, OrchardCommitDomains, OrchardFixedBases>,
     merkle_config_1: MerkleConfig<OrchardHashDomains, OrchardCommitDomains, OrchardFixedBases>,
     merkle_config_2: MerkleConfig<OrchardHashDomains, OrchardCommitDomains, OrchardFixedBases>,
     merkle_config_2: MerkleConfig<OrchardHashDomains, OrchardCommitDomains, OrchardFixedBases>,
-    sinsemilla_config_1: SinsemillaConfig<OrchardHashDomains, OrchardCommitDomains, OrchardFixedBases>,
-    sinsemilla_config_2: SinsemillaConfig<OrchardHashDomains, OrchardCommitDomains, OrchardFixedBases>,
+    sinsemilla_config_1:
+        SinsemillaConfig<OrchardHashDomains, OrchardCommitDomains, OrchardFixedBases>,
+    sinsemilla_config_2:
+        SinsemillaConfig<OrchardHashDomains, OrchardCommitDomains, OrchardFixedBases>,
     greaterthan_config: GreaterThanConfig,
     greaterthan_config: GreaterThanConfig,
     evenbits_config: EvenBitsConfig,
     evenbits_config: EvenBitsConfig,
     arith_config: ArithmeticChipConfig,
     arith_config: ArithmeticChipConfig,
 }
 }
 
 
-impl LeadConfig
-{
-    fn ecc_chip(&self) -> EccChip<OrchardFixedBases>
-    {
+impl LeadConfig {
+    fn ecc_chip(&self) -> EccChip<OrchardFixedBases> {
         EccChip::construct(self.ecc_config.clone())
         EccChip::construct(self.ecc_config.clone())
     }
     }
 
 
-    fn poseidon_chip(&self) -> PoseidonChip<pallas::Base, 3, 2>
-    {
+    fn poseidon_chip(&self) -> PoseidonChip<pallas::Base, 3, 2> {
         PoseidonChip::construct(self.poseidon_config.clone())
         PoseidonChip::construct(self.poseidon_config.clone())
     }
     }
 
 
@@ -96,7 +90,6 @@ impl LeadConfig
         EvenBitsChip::construct(self.evenbits_config.clone())
         EvenBitsChip::construct(self.evenbits_config.clone())
     }
     }
 
 
-
     fn arith_chip(&self) -> ArithmeticChip {
     fn arith_chip(&self) -> ArithmeticChip {
         ArithmeticChip::construct(self.arith_config.clone())
         ArithmeticChip::construct(self.arith_config.clone())
     }
     }
@@ -108,41 +101,41 @@ const LEAD_COIN_PK_X_OFFSET: usize = 2;
 const LEAD_COIN_PK_Y_OFFSET: usize = 3;
 const LEAD_COIN_PK_Y_OFFSET: usize = 3;
 const LEAD_COIN_SERIAL_NUMBER_X_OFFSET: usize = 4;
 const LEAD_COIN_SERIAL_NUMBER_X_OFFSET: usize = 4;
 const LEAD_COIN_SERIAL_NUMBER_Y_OFFSET: usize = 5;
 const LEAD_COIN_SERIAL_NUMBER_Y_OFFSET: usize = 5;
-const LEAD_COIN_COMMIT_X_OFFSET : usize = 6;
-const LEAD_COIN_COMMIT_Y_OFFSET : usize = 7;
-const LEAD_COIN_COMMIT2_X_OFFSET : usize = 8;
-const LEAD_COIN_COMMIT2_Y_OFFSET : usize = 9;
+const LEAD_COIN_COMMIT_X_OFFSET: usize = 6;
+const LEAD_COIN_COMMIT_Y_OFFSET: usize = 7;
+const LEAD_COIN_COMMIT2_X_OFFSET: usize = 8;
+const LEAD_COIN_COMMIT2_Y_OFFSET: usize = 9;
 const LEAD_COIN_COMMIT_PATH_OFFSET: usize = 10;
 const LEAD_COIN_COMMIT_PATH_OFFSET: usize = 10;
 const LEAD_THRESHOLD_OFFSET: usize = 11;
 const LEAD_THRESHOLD_OFFSET: usize = 11;
 
 
-#[derive(Debug,Default)]
+#[derive(Debug, Default)]
 pub struct LeadContract {
 pub struct LeadContract {
     // witness
     // witness
-    pub path : Option<[MerkleNode;MERKLE_DEPTH_ORCHARD]>,
-    pub root_sk : Option<pallas::Scalar>, // coins merkle tree secret key of coin1
-    pub path_sk : Option<[MerkleNode; MERKLE_DEPTH_ORCHARD]>, // path to the secret key root_sk
+    pub path: Option<[MerkleNode; MERKLE_DEPTH_ORCHARD]>,
+    pub root_sk: Option<pallas::Scalar>, // coins merkle tree secret key of coin1
+    pub path_sk: Option<[MerkleNode; MERKLE_DEPTH_ORCHARD]>, // path to the secret key root_sk
     pub coin_timestamp: Option<pallas::Base>,
     pub coin_timestamp: Option<pallas::Base>,
-    pub coin_nonce : Option<pallas::Base>,
-    pub coin_opening_1 :Option<pallas::Scalar>,
+    pub coin_nonce: Option<pallas::Base>,
+    pub coin_opening_1: Option<pallas::Scalar>,
     pub value: Option<pallas::Base>,
     pub value: Option<pallas::Base>,
-    pub coin_opening_2 :Option<pallas::Scalar>,
+    pub coin_opening_2: Option<pallas::Scalar>,
     // public advices
     // public advices
     //
     //
     //TODO implement two version of load_private one or point, other for base
     //TODO implement two version of load_private one or point, other for base
     // or templated load_private. then you would be able to read (x,y) from cm_c
     // or templated load_private. then you would be able to read (x,y) from cm_c
-    pub cm_c1_x : Option<pallas::Base>,
-    pub cm_c1_y : Option<pallas::Base>,
+    pub cm_c1_x: Option<pallas::Base>,
+    pub cm_c1_y: Option<pallas::Base>,
     //
     //
-    pub cm_c2_x : Option<pallas::Base>,
-    pub cm_c2_y : Option<pallas::Base>,
+    pub cm_c2_x: Option<pallas::Base>,
+    pub cm_c2_y: Option<pallas::Base>,
     //
     //
-    pub cm_pos : Option<u32>,
+    pub cm_pos: Option<u32>,
     //
     //
     //pub sn_c1 : Option<pallas::Base>,
     //pub sn_c1 : Option<pallas::Base>,
-    pub slot : Option<pallas::Base>,
+    pub slot: Option<pallas::Base>,
     pub mau_rho: Option<pallas::Scalar>,
     pub mau_rho: Option<pallas::Scalar>,
     pub mau_y: Option<pallas::Scalar>,
     pub mau_y: Option<pallas::Scalar>,
-    pub root_cm : Option<pallas::Scalar>,
+    pub root_cm: Option<pallas::Scalar>,
     //pub eta : Option<u32>,
     //pub eta : Option<u32>,
     //pub rho : Option<u32>,
     //pub rho : Option<u32>,
     //pub h : Option<u32>, // hash of this data
     //pub h : Option<u32>, // hash of this data
@@ -204,7 +197,12 @@ impl Circuit<pallas::Base> for LeadContract {
         meta.enable_constant(lagrange_coeffs[0]);
         meta.enable_constant(lagrange_coeffs[0]);
         let range_check = LookupRangeCheckConfig::configure(meta, advices[9], table_idx);
         let range_check = LookupRangeCheckConfig::configure(meta, advices[9], table_idx);
 
 
-        let ecc_config = EccChip::<OrchardFixedBases>::configure(meta, advices[0..10].try_into().expect("wrong slice size"), lagrange_coeffs, range_check);
+        let ecc_config = EccChip::<OrchardFixedBases>::configure(
+            meta,
+            advices[0..10].try_into().expect("wrong slice size"),
+            lagrange_coeffs,
+            range_check,
+        );
 
 
         let poseidon_config = PoseidonChip::configure::<P128Pow5T3>(
         let poseidon_config = PoseidonChip::configure::<P128Pow5T3>(
             meta,
             meta,
@@ -241,11 +239,14 @@ impl Circuit<pallas::Base> for LeadContract {
             (sinsemilla_config_2, merkle_config_2)
             (sinsemilla_config_2, merkle_config_2)
         };
         };
 
 
-        let  greaterthan_config = GreaterThanChip::<pallas::Base, WORD_BITS>::configure(meta, advices[10..12].try_into().unwrap(), primary);
+        let greaterthan_config = GreaterThanChip::<pallas::Base, WORD_BITS>::configure(
+            meta,
+            advices[10..12].try_into().unwrap(),
+            primary,
+        );
         let evenbits_config = EvenBitsChip::<pallas::Base, WORD_BITS>::configure(meta);
         let evenbits_config = EvenBitsChip::<pallas::Base, WORD_BITS>::configure(meta);
         let arith_config = ArithmeticChip::configure(meta);
         let arith_config = ArithmeticChip::configure(meta);
 
 
-
         LeadConfig {
         LeadConfig {
             primary,
             primary,
             advices,
             advices,
@@ -261,9 +262,10 @@ impl Circuit<pallas::Base> for LeadContract {
         }
         }
     }
     }
 
 
-    fn synthesize(&self,
-                  config: Self::Config,
-                  mut layouter: impl Layouter<pallas::Base>,
+    fn synthesize(
+        &self,
+        config: Self::Config,
+        mut layouter: impl Layouter<pallas::Base>,
     ) -> Result<(), Error> {
     ) -> Result<(), Error> {
         SinsemillaChip::load(config.sinsemilla_config_1.clone(), &mut layouter)?;
         SinsemillaChip::load(config.sinsemilla_config_1.clone(), &mut layouter)?;
         let ecc_chip = config.ecc_chip();
         let ecc_chip = config.ecc_chip();
@@ -322,32 +324,18 @@ impl Circuit<pallas::Base> for LeadContract {
         )?;
         )?;
          */
          */
 
 
-
         //let cm_c1_point : pallas::Point = pallas::Point::from(1);
         //let cm_c1_point : pallas::Point = pallas::Point::from(1);
         //let cm_c1 : AssignedCell<pallas::Point, pallas::Point> = cm_c1_point;
         //let cm_c1 : AssignedCell<pallas::Point, pallas::Point> = cm_c1_point;
 
 
+        let cm_c1_x =
+            self.load_private(layouter.namespace(|| ""), config.advices[0], self.cm_c1_x)?;
+        let cm_c1_y =
+            self.load_private(layouter.namespace(|| ""), config.advices[0], self.cm_c1_y)?;
 
 
-        let cm_c1_x = self.load_private(
-            layouter.namespace(|| ""),
-            config.advices[0],
-            self.cm_c1_x,
-        )?;
-        let cm_c1_y = self.load_private(
-            layouter.namespace(|| ""),
-            config.advices[0],
-            self.cm_c1_y,
-        )?;
-
-        let cm_c2_x = self.load_private(
-            layouter.namespace(|| ""),
-            config.advices[0],
-            self.cm_c2_x,
-        )?;
-        let cm_c2_y = self.load_private(
-            layouter.namespace(|| ""),
-            config.advices[0],
-            self.cm_c2_y,
-        )?;
+        let cm_c2_x =
+            self.load_private(layouter.namespace(|| ""), config.advices[0], self.cm_c2_x)?;
+        let cm_c2_y =
+            self.load_private(layouter.namespace(|| ""), config.advices[0], self.cm_c2_y)?;
 
 
         /*
         /*
         let cm_pos = self.load_private(
         let cm_pos = self.load_private(
@@ -371,11 +359,7 @@ impl Circuit<pallas::Base> for LeadContract {
         )?;
         )?;
          */
          */
 
 
-        let slot = self.load_private(
-            layouter.namespace(|| ""),
-            config.advices[0],
-            self.slot,
-        )?;
+        let slot = self.load_private(layouter.namespace(|| ""), config.advices[0], self.slot)?;
 
 
         /*
         /*
         let rho = self.load_private(
         let rho = self.load_private(
@@ -432,10 +416,11 @@ impl Circuit<pallas::Base> for LeadContract {
         // coin 2 nonce
         // coin 2 nonce
         // ===============
         // ===============
         // m*G_1
         // m*G_1
-        let (com, _ )  = {
+        let (com, _) = {
             let nonce2_commit_v = ValueCommitV;
             let nonce2_commit_v = ValueCommitV;
             let nonce2_commit_v = FixedPointShort::from_inner(ecc_chip.clone(), nonce2_commit_v);
             let nonce2_commit_v = FixedPointShort::from_inner(ecc_chip.clone(), nonce2_commit_v);
-            nonce2_commit_v.mul(layouter.namespace(|| "coin_pk commit v"), (coin_nonce.clone(), one.clone()))?
+            nonce2_commit_v
+                .mul(layouter.namespace(|| "coin_pk commit v"), (coin_nonce.clone(), one.clone()))?
         };
         };
         // r*G_2
         // r*G_2
         let (blind, _) = {
         let (blind, _) = {
@@ -461,12 +446,12 @@ impl Circuit<pallas::Base> for LeadContract {
         // coin public key constraints derived from the coin timestamp
         // coin public key constraints derived from the coin timestamp
         // ================
         // ================
 
 
-
         // m*G_1
         // m*G_1
-        let (com, _ )  = {
+        let (com, _) = {
             let coin_pk_commit_v = ValueCommitV;
             let coin_pk_commit_v = ValueCommitV;
             let coin_pk_commit_v = FixedPointShort::from_inner(ecc_chip.clone(), coin_pk_commit_v);
             let coin_pk_commit_v = FixedPointShort::from_inner(ecc_chip.clone(), coin_pk_commit_v);
-            coin_pk_commit_v.mul(layouter.namespace(|| "coin_pk commit v"), (coin_timestamp, one.clone()))?
+            coin_pk_commit_v
+                .mul(layouter.namespace(|| "coin_pk commit v"), (coin_timestamp, one.clone()))?
         };
         };
         // r*G_2
         // r*G_2
         let (blind, _) = {
         let (blind, _) = {
@@ -493,15 +478,17 @@ impl Circuit<pallas::Base> for LeadContract {
         // nonce constraints derived from previous coin's nonce
         // nonce constraints derived from previous coin's nonce
         // =================
         // =================
 
 
-
         // =============
         // =============
         // constrain coin c1 serial number
         // constrain coin c1 serial number
         // =============
         // =============
         // m*G_1
         // m*G_1
-        let (com, _ )  = {
+        let (com, _) = {
             let sn_commit_v = ValueCommitV;
             let sn_commit_v = ValueCommitV;
             let sn_commit_v = FixedPointShort::from_inner(ecc_chip.clone(), sn_commit_v);
             let sn_commit_v = FixedPointShort::from_inner(ecc_chip.clone(), sn_commit_v);
-            sn_commit_v.mul(layouter.namespace(|| "coin serial number commit v"), (coin_nonce.clone(), one.clone()))?
+            sn_commit_v.mul(
+                layouter.namespace(|| "coin serial number commit v"),
+                (coin_nonce.clone(), one.clone()),
+            )?
         };
         };
         // r*G_2
         // r*G_2
         let (blind, _) = {
         let (blind, _) = {
@@ -541,10 +528,11 @@ impl Circuit<pallas::Base> for LeadContract {
         //but only single value is in witness.
         //but only single value is in witness.
 
 
         let coin_hash = {
         let coin_hash = {
-            let poseidon_message = [coin_pk_commit.inner().x(),
-                                    coin_pk_commit.inner().y(),
-                                    coin_value.clone(),
-                                    coin_nonce.clone()
+            let poseidon_message = [
+                coin_pk_commit.inner().x(),
+                coin_pk_commit.inner().y(),
+                coin_value.clone(),
+                coin_nonce.clone(),
             ];
             ];
 
 
             let poseidon_hasher = PoseidonHash::<_, _, P128Pow5T3, ConstantLength<4>, 3, 2>::init(
             let poseidon_hasher = PoseidonHash::<_, _, P128Pow5T3, ConstantLength<4>, 3, 2>::init(
@@ -558,7 +546,7 @@ impl Circuit<pallas::Base> for LeadContract {
             let poseidon_output: AssignedCell<Fp, Fp> = poseidon_output;
             let poseidon_output: AssignedCell<Fp, Fp> = poseidon_output;
             poseidon_output
             poseidon_output
         };
         };
-        let (com, _ )  = {
+        let (com, _) = {
             let coin_commit_v = ValueCommitV;
             let coin_commit_v = ValueCommitV;
             let coin_commit_v = FixedPointShort::from_inner(ecc_chip.clone(), coin_commit_v);
             let coin_commit_v = FixedPointShort::from_inner(ecc_chip.clone(), coin_commit_v);
             coin_commit_v.mul(layouter.namespace(|| "coin commit v"), (coin_hash, one.clone()))?
             coin_commit_v.mul(layouter.namespace(|| "coin commit v"), (coin_hash, one.clone()))?
@@ -567,15 +555,18 @@ impl Circuit<pallas::Base> for LeadContract {
         let (blind, _) = {
         let (blind, _) = {
             let coin_commit_r = OrchardFixedBasesFull::ValueCommitR;
             let coin_commit_r = OrchardFixedBasesFull::ValueCommitR;
             let coin_commit_r = FixedPoint::from_inner(ecc_chip.clone(), coin_commit_r);
             let coin_commit_r = FixedPoint::from_inner(ecc_chip.clone(), coin_commit_r);
-            coin_commit_r.mul(layouter.namespace(|| "coin serial number commit R"), self.coin_opening_1)?
+            coin_commit_r
+                .mul(layouter.namespace(|| "coin serial number commit R"), self.coin_opening_1)?
         };
         };
-        let coin_commit  = com.add(layouter.namespace(|| "nonce commit"), &blind)?;
+        let coin_commit = com.add(layouter.namespace(|| "nonce commit"), &blind)?;
 
 
-        let coin_commit_x : AssignedCell<Fp, Fp> = coin_commit.inner().x();
-        let coin_commit_y : AssignedCell<Fp, Fp> = coin_commit.inner().y();
+        let coin_commit_x: AssignedCell<Fp, Fp> = coin_commit.inner().x();
+        let coin_commit_y: AssignedCell<Fp, Fp> = coin_commit.inner().y();
 
 
-        let cm1_zero_out_x = ar_chip.sub(layouter.namespace(|| "sub to zero"), coin_commit_x.clone(), cm_c1_x)?;
-        let cm1_zero_out_y = ar_chip.sub(layouter.namespace(|| "sub to zero"), coin_commit_y.clone(), cm_c1_y)?;
+        let cm1_zero_out_x =
+            ar_chip.sub(layouter.namespace(|| "sub to zero"), coin_commit_x.clone(), cm_c1_x)?;
+        let cm1_zero_out_y =
+            ar_chip.sub(layouter.namespace(|| "sub to zero"), coin_commit_y.clone(), cm_c1_y)?;
 
 
         // constrain coin's pub key x value
         // constrain coin's pub key x value
         layouter.constrain_instance(
         layouter.constrain_instance(
@@ -592,11 +583,12 @@ impl Circuit<pallas::Base> for LeadContract {
 
 
         //
         //
         let coin2_hash = {
         let coin2_hash = {
-            let poseidon_message = [coin_pk_commit.inner().x(),
-                                    coin_pk_commit.inner().y(),
-                                    coin_value.clone(),
-                                    coin2_nonce.inner().x(),
-                                    coin2_nonce.inner().y(),
+            let poseidon_message = [
+                coin_pk_commit.inner().x(),
+                coin_pk_commit.inner().y(),
+                coin_value.clone(),
+                coin2_nonce.inner().x(),
+                coin2_nonce.inner().y(),
             ];
             ];
 
 
             let poseidon_hasher = PoseidonHash::<_, _, P128Pow5T3, ConstantLength<5>, 3, 2>::init(
             let poseidon_hasher = PoseidonHash::<_, _, P128Pow5T3, ConstantLength<5>, 3, 2>::init(
@@ -610,7 +602,7 @@ impl Circuit<pallas::Base> for LeadContract {
             let poseidon_output: AssignedCell<Fp, Fp> = poseidon_output;
             let poseidon_output: AssignedCell<Fp, Fp> = poseidon_output;
             poseidon_output
             poseidon_output
         };
         };
-        let (com, _ )  = {
+        let (com, _) = {
             let coin_commit_v = ValueCommitV;
             let coin_commit_v = ValueCommitV;
             let coin_commit_v = FixedPointShort::from_inner(ecc_chip.clone(), coin_commit_v);
             let coin_commit_v = FixedPointShort::from_inner(ecc_chip.clone(), coin_commit_v);
             coin_commit_v.mul(layouter.namespace(|| "coin commit v"), (coin2_hash, one.clone()))?
             coin_commit_v.mul(layouter.namespace(|| "coin commit v"), (coin2_hash, one.clone()))?
@@ -619,14 +611,16 @@ impl Circuit<pallas::Base> for LeadContract {
         let (blind, _) = {
         let (blind, _) = {
             let coin_commit_r = OrchardFixedBasesFull::ValueCommitR;
             let coin_commit_r = OrchardFixedBasesFull::ValueCommitR;
             let coin_commit_r = FixedPoint::from_inner(ecc_chip.clone(), coin_commit_r);
             let coin_commit_r = FixedPoint::from_inner(ecc_chip.clone(), coin_commit_r);
-            coin_commit_r.mul(layouter.namespace(|| "coin serial number commit R"), self.coin_opening_2)?
+            coin_commit_r
+                .mul(layouter.namespace(|| "coin serial number commit R"), self.coin_opening_2)?
         };
         };
-        let coin2_commit  = com.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();
-        let cm2_zero_out_x = ar_chip.sub(layouter.namespace(|| "sub to zero"), coin2_commit_x, cm_c2_x)?;
-        let cm2_zero_out_y = ar_chip.sub(layouter.namespace(|| "sub to zero"), coin2_commit_y, cm_c2_y)?;
-
+        let coin2_commit = com.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();
+        let cm2_zero_out_x =
+            ar_chip.sub(layouter.namespace(|| "sub to zero"), coin2_commit_x, cm_c2_x)?;
+        let cm2_zero_out_y =
+            ar_chip.sub(layouter.namespace(|| "sub to zero"), coin2_commit_y, cm_c2_y)?;
 
 
         layouter.constrain_instance(
         layouter.constrain_instance(
             cm2_zero_out_x.cell(),
             cm2_zero_out_x.cell(),
@@ -652,7 +646,7 @@ impl Circuit<pallas::Base> for LeadContract {
             path,
             path,
         );
         );
 
 
-        let coin_commit_hash :  AssignedCell<Fp, Fp>  = {
+        let coin_commit_hash: AssignedCell<Fp, Fp> = {
             let poseidon_message = [coin_commit_x.clone(), coin_commit_y.clone()];
             let poseidon_message = [coin_commit_x.clone(), coin_commit_y.clone()];
 
 
             let poseidon_hasher = PoseidonHash::<_, _, P128Pow5T3, ConstantLength<2>, 3, 2>::init(
             let poseidon_hasher = PoseidonHash::<_, _, P128Pow5T3, ConstantLength<2>, 3, 2>::init(
@@ -666,8 +660,8 @@ impl Circuit<pallas::Base> for LeadContract {
             let poseidon_output: AssignedCell<Fp, Fp> = poseidon_output;
             let poseidon_output: AssignedCell<Fp, Fp> = poseidon_output;
             poseidon_output
             poseidon_output
         };
         };
-        let computed_final_root =
-            merkle_inputs.calculate_root(layouter.namespace(|| "calculate root"), coin_commit_hash  )?;
+        let computed_final_root = merkle_inputs
+            .calculate_root(layouter.namespace(|| "calculate root"), coin_commit_hash)?;
 
 
         layouter.constrain_instance(
         layouter.constrain_instance(
             computed_final_root.cell(),
             computed_final_root.cell(),
@@ -675,12 +669,14 @@ impl Circuit<pallas::Base> for LeadContract {
             LEAD_COIN_COMMIT_PATH_OFFSET,
             LEAD_COIN_COMMIT_PATH_OFFSET,
         )?;
         )?;
 
 
-
         let message = {
         let message = {
-            let (com, _ )  = {
+            let (com, _) = {
                 let commit_v = ValueCommitV;
                 let commit_v = ValueCommitV;
                 let commit_v = FixedPointShort::from_inner(ecc_chip.clone(), commit_v);
                 let commit_v = FixedPointShort::from_inner(ecc_chip.clone(), commit_v);
-                commit_v.mul(layouter.namespace(|| "coin commit v"), (coin_nonce.clone(), one.clone()))?
+                commit_v.mul(
+                    layouter.namespace(|| "coin commit v"),
+                    (coin_nonce.clone(), one.clone()),
+                )?
             };
             };
             // r*G_2
             // r*G_2
             let (blind, _) = {
             let (blind, _) = {
@@ -689,17 +685,18 @@ impl Circuit<pallas::Base> for LeadContract {
                 commit_r.mul(layouter.namespace(|| "coin serial number commit R"), self.root_sk)?
                 commit_r.mul(layouter.namespace(|| "coin serial number commit R"), self.root_sk)?
             };
             };
             com.add(layouter.namespace(|| "nonce commit"), &blind)?
             com.add(layouter.namespace(|| "nonce commit"), &blind)?
-
         };
         };
-        let message_sum = ar_chip.add(layouter.namespace(|| "msg x + y"),
-                                      message.inner().x(),
-                                      message.inner().y(),
+        let message_sum = ar_chip.add(
+            layouter.namespace(|| "msg x + y"),
+            message.inner().x(),
+            message.inner().y(),
         )?;
         )?;
 
 
-        let (com, _ )  = {
+        let (com, _) = {
             let y_commit_v = ValueCommitV;
             let y_commit_v = ValueCommitV;
             let y_commit_v = FixedPointShort::from_inner(ecc_chip.clone(), y_commit_v);
             let y_commit_v = FixedPointShort::from_inner(ecc_chip.clone(), y_commit_v);
-            y_commit_v.mul(layouter.namespace(|| "coin commit v"), (message_sum.clone(), one.clone()))?
+            y_commit_v
+                .mul(layouter.namespace(|| "coin commit v"), (message_sum.clone(), one.clone()))?
         };
         };
         // r*G_2
         // r*G_2
         let (blind, _) = {
         let (blind, _) = {
@@ -712,8 +709,9 @@ impl Circuit<pallas::Base> for LeadContract {
         //let y_commit_base  : AssignedCell<Fp,Fp> = pallas::Base::from_repr(y_commit.inner().to_bytes()).unwrap();
         //let y_commit_base  : AssignedCell<Fp,Fp> = pallas::Base::from_repr(y_commit.inner().to_bytes()).unwrap();
         //let y_commit_x  : AssignedCell<Fp,Fp> = y_commit.inner().x();
         //let y_commit_x  : AssignedCell<Fp,Fp> = y_commit.inner().x();
         //let y_commit_x_base   = y_commit.inner().x().value().unwrap();
         //let y_commit_x_base   = y_commit.inner().x().value().unwrap();
-        let y_commit_base_temp   =  pallas::Base::from_repr(y_commit.inner().point().unwrap().to_bytes()).unwrap();
-        let y_commit_base  = self.load_private(
+        let y_commit_base_temp =
+            pallas::Base::from_repr(y_commit.inner().point().unwrap().to_bytes()).unwrap();
+        let y_commit_base = self.load_private(
             layouter.namespace(|| "load coin y commit as pallas::base"),
             layouter.namespace(|| "load coin y commit as pallas::base"),
             config.advices[0],
             config.advices[0],
             Some(y_commit_base_temp),
             Some(y_commit_base_temp),
@@ -722,7 +720,7 @@ impl Circuit<pallas::Base> for LeadContract {
         // ============================
         // ============================
         // constraint rho
         // constraint rho
         // ============================
         // ============================
-        let (com, _ )  = {
+        let (com, _) = {
             let rho_commit_v = ValueCommitV;
             let rho_commit_v = ValueCommitV;
             let rho_commit_v = FixedPointShort::from_inner(ecc_chip.clone(), rho_commit_v);
             let rho_commit_v = FixedPointShort::from_inner(ecc_chip.clone(), rho_commit_v);
             rho_commit_v.mul(layouter.namespace(|| "coin commit v"), (message_sum, one.clone()))?
             rho_commit_v.mul(layouter.namespace(|| "coin commit v"), (message_sum, one.clone()))?
@@ -739,19 +737,22 @@ impl Circuit<pallas::Base> for LeadContract {
         // that the coin value never get past it.
         // that the coin value never get past it.
 
 
         let scalar = self.load_private(
         let scalar = self.load_private(
-            layouter.namespace(||"load scalar "),
+            layouter.namespace(|| "load scalar "),
             config.advices[0],
             config.advices[0],
-            Some(pallas::Base::from(1024))
+            Some(pallas::Base::from(1024)),
         )?;
         )?;
         let c = pallas::Scalar::from(3); // leadership coefficient
         let c = pallas::Scalar::from(3); // leadership coefficient
-        let target : AssignedCell<Fp,Fp> = ar_chip.mul(layouter.namespace(|| "calculate target"), scalar, coin_value)?;
-
+        let target: AssignedCell<Fp, Fp> =
+            ar_chip.mul(layouter.namespace(|| "calculate target"), scalar, coin_value)?;
 
 
         eb_chip.decompose(layouter.namespace(|| "target range check"), target.clone())?;
         eb_chip.decompose(layouter.namespace(|| "target range check"), target.clone())?;
         eb_chip.decompose(layouter.namespace(|| "y_commit  range check"), y_commit_base.clone())?;
         eb_chip.decompose(layouter.namespace(|| "y_commit  range check"), y_commit_base.clone())?;
 
 
-
-        let (helper, is_gt) = greater_than_chip.greater_than(layouter.namespace(||"t>y"), target.into() , y_commit_base.into())?; //note assuming x,y coordinates are true random each?
+        let (helper, is_gt) = greater_than_chip.greater_than(
+            layouter.namespace(|| "t>y"),
+            target.into(),
+            y_commit_base.into(),
+        )?; //note assuming x,y coordinates are true random each?
         eb_chip.decompose(layouter.namespace(|| "helper range check"), helper.0)?;
         eb_chip.decompose(layouter.namespace(|| "helper range check"), helper.0)?;
         layouter.constrain_instance(is_gt.0.cell(), config.primary, LEAD_THRESHOLD_OFFSET)?;
         layouter.constrain_instance(is_gt.0.cell(), config.primary, LEAD_THRESHOLD_OFFSET)?;
         Ok(())
         Ok(())

+ 6 - 8
src/zk/greater_than.rs

@@ -3,13 +3,12 @@ use std::marker::PhantomData;
 use halo2_proofs::{
 use halo2_proofs::{
     arithmetic::FieldExt,
     arithmetic::FieldExt,
     circuit::{AssignedCell, Chip, Layouter, Region},
     circuit::{AssignedCell, Chip, Layouter, Region},
-    plonk::{Advice, Column, Instance, ConstraintSystem, Error, Expression, Selector},
+    plonk::{Advice, Column, ConstraintSystem, Error, Expression, Instance, Selector},
     poly::Rotation,
     poly::Rotation,
 };
 };
 
 
 use pasta_curves::pallas;
 use pasta_curves::pallas;
 
 
-
 #[derive(Clone, Debug)]
 #[derive(Clone, Debug)]
 pub struct GreaterThanConfig {
 pub struct GreaterThanConfig {
     pub advice: [Column<Advice>; 2],
     pub advice: [Column<Advice>; 2],
@@ -17,7 +16,6 @@ pub struct GreaterThanConfig {
     s_gt: Selector,
     s_gt: Selector,
 }
 }
 
 
-
 pub struct GreaterThanChip<F: FieldExt, const WORD_BITS: u32> {
 pub struct GreaterThanChip<F: FieldExt, const WORD_BITS: u32> {
     config: GreaterThanConfig,
     config: GreaterThanConfig,
     _marker: PhantomData<F>,
     _marker: PhantomData<F>,
@@ -98,11 +96,11 @@ impl<F: FieldExt, const WORD_BITS: u32> GreaterThanChip<F, WORD_BITS> {
         GreaterThanConfig { advice, s_gt }
         GreaterThanConfig { advice, s_gt }
     }
     }
      */
      */
-    pub fn configure(meta: &mut ConstraintSystem<F>,
-                     advice : [Column<Advice>; 2],
-                     instance: Column<Instance>) -> <Self as Chip<F>>::Config {
-
-
+    pub fn configure(
+        meta: &mut ConstraintSystem<F>,
+        advice: [Column<Advice>; 2],
+        instance: Column<Instance>,
+    ) -> <Self as Chip<F>>::Config {
         for column in &advice {
         for column in &advice {
             meta.enable_equality(*column);
             meta.enable_equality(*column);
         }
         }

+ 2 - 1
src/zk/vm.rs

@@ -206,7 +206,8 @@ impl Circuit<pallas::Base> for ZkCircuit {
         let evenbits_config = EvenBitsChip::<pallas::Base, 24>::configure(meta);
         let evenbits_config = EvenBitsChip::<pallas::Base, 24>::configure(meta);
 
 
         // Configuration for the GreaterThan chip
         // Configuration for the GreaterThan chip
-        let greaterthan_config = GreaterThanChip::<pallas::Base, 24>::configure(meta, [advices[8], advices[9]], primary);
+        let greaterthan_config =
+            GreaterThanChip::<pallas::Base, 24>::configure(meta, [advices[8], advices[9]], primary);
 
 
         // Configuration for a Sinsemilla hash instantiation and a
         // Configuration for a Sinsemilla hash instantiation and a
         // Merkle hash instantiation using this Sinsemilla instance.
         // Merkle hash instantiation using this Sinsemilla instance.