Przeglądaj źródła

Port codebase to latest halo2 API.

parazyd 4 lat temu
rodzic
commit
f8c2ee5617

+ 22 - 54
Cargo.lock

@@ -379,28 +379,16 @@ version = "1.3.2"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"
 
-[[package]]
-name = "bitvec"
-version = "0.22.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "5237f00a8c86130a0cc317830e558b966dd7850d48a953d998c813f01a41b527"
-dependencies = [
- "funty 1.2.0",
- "radium 0.6.2",
- "tap",
- "wyz 0.4.0",
-]
-
 [[package]]
 name = "bitvec"
 version = "1.0.0"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "1489fcb93a5bb47da0462ca93ad252ad6af2145cce58d10d46a83931ba9f016b"
 dependencies = [
- "funty 2.0.0",
- "radium 0.7.0",
+ "funty",
+ "radium",
  "tap",
- "wyz 0.5.0",
+ "wyz",
 ]
 
 [[package]]
@@ -1192,7 +1180,7 @@ dependencies = [
  "async-trait",
  "async-tungstenite",
  "bincode",
- "bitvec 1.0.0",
+ "bitvec",
  "blake2b_simd 1.0.0",
  "blake3",
  "bs58",
@@ -1717,11 +1705,11 @@ dependencies = [
 
 [[package]]
 name = "ff"
-version = "0.11.0"
+version = "0.12.0"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b2958d04124b9f27f175eaeb9a9f383d026098aa837eadd8ba22c11f13a05b9e"
+checksum = "df689201f395c6b90dfe87127685f8dbfc083a5e779e613575d8bd7314300c3e"
 dependencies = [
- "bitvec 0.22.3",
+ "bitvec",
  "rand_core 0.6.3",
  "subtle",
 ]
@@ -1831,12 +1819,6 @@ dependencies = [
  "winapi",
 ]
 
-[[package]]
-name = "funty"
-version = "1.2.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "1847abb9cb65d566acd5942e94aea9c8f547ad02c98e1649326fc0e8910b8b1e"
-
 [[package]]
 name = "funty"
 version = "2.0.0"
@@ -2057,9 +2039,9 @@ dependencies = [
 
 [[package]]
 name = "group"
-version = "0.11.0"
+version = "0.12.0"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "bc5ac374b108929de78460075f3dc439fa66df9d8fc77e8f12caa5165fcf0c89"
+checksum = "7391856def869c1c81063a03457c676fbcd419709c3dfb33d8d319de484b154d"
 dependencies = [
  "byteorder",
  "ff",
@@ -2069,11 +2051,12 @@ dependencies = [
 
 [[package]]
 name = "halo2_gadgets"
-version = "0.1.0-beta.3"
-source = "git+https://github.com/parazyd/halo2?branch=clone-impls-keys#a6d7785ddc86e897b917d8450055d0d6b2494b5d"
+version = "0.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "13f3914f58cc4af5e4fe83d48b02d582be18976bc7e96c3151aa2bf1c98e9f60"
 dependencies = [
  "arrayvec 0.7.2",
- "bitvec 0.22.3",
+ "bitvec",
  "ff",
  "group",
  "halo2_proofs",
@@ -2088,12 +2071,12 @@ dependencies = [
 
 [[package]]
 name = "halo2_proofs"
-version = "0.1.0-beta.4"
-source = "git+https://github.com/parazyd/halo2?branch=clone-impls-keys#a6d7785ddc86e897b917d8450055d0d6b2494b5d"
+version = "0.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e925780549adee8364c7f2b685c753f6f3df23bde520c67416e93bf615933760"
 dependencies = [
  "backtrace",
  "blake2b_simd 1.0.0",
- "bumpalo",
  "ff",
  "group",
  "pasta_curves",
@@ -2215,9 +2198,9 @@ dependencies = [
 
 [[package]]
 name = "incrementalmerkletree"
-version = "0.3.0-beta.2"
+version = "0.3.0"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "5812f2cfa06a7694b842402e9a100529d80fdc3022ead65ad98ce0af0bcd3311"
+checksum = "068c5bdd31006d55536655cf1eb0d22d84d28de7c725b419480fd5d005c83216"
 dependencies = [
  "serde",
 ]
@@ -2763,9 +2746,9 @@ dependencies = [
 
 [[package]]
 name = "pasta_curves"
-version = "0.3.1"
+version = "0.4.0"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d10d05f1fdbc8c45f133202559b5ed33704fa1e633e96a5776af474779f2ac3f"
+checksum = "369d7785168ad7ff0cbe467d968ca3e19a927d8536b11ef9c21b4e454b15ba42"
 dependencies = [
  "blake2b_simd 1.0.0",
  "ff",
@@ -3089,12 +3072,6 @@ dependencies = [
  "proc-macro2",
 ]
 
-[[package]]
-name = "radium"
-version = "0.6.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "643f8f41a8ebc4c5dc4515c82bb8abd397b527fc20fd681b7c011c2aee5d44fb"
-
 [[package]]
 name = "radium"
 version = "0.7.0"
@@ -4236,9 +4213,9 @@ checksum = "56dee185309b50d1f11bfedef0fe6d036842e3fb77413abef29f8f8d1c5d4c1c"
 
 [[package]]
 name = "uint"
-version = "0.9.1"
+version = "0.9.3"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "6470ab50f482bde894a037a57064480a246dbfdd5960bd65a44824693f08da5f"
+checksum = "12f03af7ccf01dd611cc450a0d10dbc9b745770d096473e2faf0ca6e2d66d1e0"
 dependencies = [
  "byteorder",
  "crunchy",
@@ -4823,15 +4800,6 @@ dependencies = [
  "winapi",
 ]
 
-[[package]]
-name = "wyz"
-version = "0.4.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "129e027ad65ce1453680623c3fb5163cbf7107bfe1aa32257e7d0e63f9ced188"
-dependencies = [
- "tap",
-]
-
 [[package]]
 name = "wyz"
 version = "0.5.0"

+ 5 - 7
Cargo.toml

@@ -106,16 +106,14 @@ bitvec = {version = "1.0.0", optional = true}
 rand = {version = "0.8.5", optional = true}
 blake3 = {version = "1.3.1", optional = true}
 sha2 = {version = "0.10.2", optional = true}
-group = {version = "0.11.0", optional = true}
+group = {version = "0.12.0", optional = true}
 arrayvec = {version = "0.7.2", optional = true}
 blake2b_simd = {version = "1.0.0", optional = true}
-pasta_curves = {version = "0.3.1", optional = true}
+pasta_curves = {version = "0.4.0", optional = true}
 crypto_api_chachapoly = {version = "0.5.0", optional = true}
-incrementalmerkletree = {version = "0.3.0-beta.2", optional = true}
-#halo2_proofs = {version = "0.1.0-beta.4", features = ["dev-graph", "gadget-traces", "sanity-checks"], optional = true}
-#halo2_gadgets = {version = "0.1.0-beta.3", features = ["dev-graph", "test-dependencies"], optional = true}
-halo2_proofs = {git = "https://github.com/parazyd/halo2", branch = "clone-impls-keys", features = ["dev-graph", "gadget-traces", "sanity-checks"], optional = true}
-halo2_gadgets = {git = "https://github.com/parazyd/halo2", branch = "clone-impls-keys", features = ["dev-graph", "test-dependencies"], optional = true}
+incrementalmerkletree = {version = "0.3.0", optional = true}
+halo2_proofs = {version = "0.1.0", features = ["dev-graph", "gadget-traces", "sanity-checks"], optional = true}
+halo2_gadgets = {version = "0.1.0", features = ["dev-graph", "test-dependencies"], optional = true}
 
 # Smart contract runtime
 drk-sdk = {path = "src/sdk", optional = true}

+ 1 - 1
bin/darkfid/Cargo.toml

@@ -24,7 +24,7 @@ fxhash = "0.2.1"
 lazy-init = "0.5.0"
 log = "0.4.16"
 num-bigint = {version = "0.4.3", features = ["serde"]}
-pasta_curves = "0.3.1"
+pasta_curves = "0.4.0"
 rand = "0.8.5"
 serde_json = "1.0.79"
 simplelog = "0.12.0"

+ 1 - 1
doc/Makefile

@@ -6,7 +6,7 @@ all:
 	echo "# darkfid JSON-RPC API" > $(DARKFID_JSONRPC)
 	for i in blockchain tx wallet misc; do \
 		echo "## $$i methods" >> $(DARKFID_JSONRPC);\
-		./build_jsonrpc.py ../bin/darkfid2/src/rpc_$$i.rs >> $(DARKFID_JSONRPC);\
+		./build_jsonrpc.py ../bin/darkfid/src/rpc_$$i.rs >> $(DARKFID_JSONRPC);\
 	done
 
 	echo "# cashierd JSON-RPC API" > src/clients/cashierd_jsonrpc.md

+ 16 - 26
example/lead.rs

@@ -1,17 +1,14 @@
-use incrementalmerkletree::{bridgetree::BridgeTree, Frontier, Tree};
-
-use halo2_gadgets::primitives::{
-    poseidon,
-    poseidon::{ConstantLength, P128Pow5T3},
+use halo2_proofs::{arithmetic::Field, dev::MockProver};
+use incrementalmerkletree::{bridgetree::BridgeTree, Hashable, Tree};
+use pasta_curves::{
+    arithmetic::CurveAffine,
+    group::{ff::PrimeField, Curve, GroupEncoding},
+    pallas, Fp,
 };
 
-use serde::{Deserialize, Serialize};
-
-use halo2_proofs::dev::MockProver;
-
+use halo2_proofs::{arithmetic::Field, dev::MockProver};
 use rand::{thread_rng, Rng};
-
-use pasta_curves::{pallas, Fp};
+use serde::{Deserialize, Serialize};
 
 use darkfi::{
     crypto::{
@@ -31,15 +28,6 @@ use darkfi::{
     zk::circuit::lead_contract::LeadContract,
 };
 
-use incrementalmerkletree::Hashable;
-
-use pasta_curves::{
-    arithmetic::CurveAffine,
-    group::{ff::PrimeField, Curve, GroupEncoding},
-};
-
-use halo2_proofs::arithmetic::Field;
-
 fn create_coins_sks(len: usize) -> (Vec<MerkleNode>, Vec<[MerkleNode; MERKLE_DEPTH_ORCHARD]>) {
     /*
     at the onset of an epoch, the first slot's coin's secret key
@@ -64,11 +52,12 @@ fn create_coins_sks(len: usize) -> (Vec<MerkleNode>, Vec<[MerkleNode; MERKLE_DEP
         //println!("serialized: {}", serialized);
         tree.append(&node.clone());
         let leaf_position = tree.witness();
+        let root = tree.root(0).unwrap();
         //let (leaf_pos, path) = tree.authentication_path(leaf_position.unwrap()).unwrap();
-        let path = tree.authentication_path(leaf_position.unwrap()).unwrap();
+        let path = tree.authentication_path(leaf_position.unwrap(), &root).unwrap();
         //note root sk is at tree.root()
         //root_sks.push(node);
-        root_sks.push(tree.root());
+        root_sks.push(root);
         path_sks.push(path.as_slice().try_into().unwrap());
     }
     (root_sks, path_sks)
@@ -122,8 +111,8 @@ fn create_coins(
         let c_cm_node = MerkleNode(c_cm_base);
         tree_cm.append(&c_cm_node.clone());
         let leaf_position = tree_cm.witness();
-        let c_cm_path = tree_cm.authentication_path(leaf_position.unwrap()).unwrap();
-        let c_root_cm = tree_cm.root();
+        let c_root_cm = tree_cm.root(0).unwrap();
+        let c_cm_path = tree_cm.authentication_path(leaf_position.unwrap(), &c_root_cm).unwrap();
         // lead coin commitment
         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();
@@ -210,6 +199,7 @@ fn main() {
         coin_pk_x: coin.pk_x,
         coin_pk_y: coin.pk_y,
         root_sk: coin.root_sk,
+        sf_root_sk: Some(mod_r_p(coin.root_sk.unwrap())),
         path_sk: coin.path_sk,
         coin_timestamp: coin.tau, //
         coin_nonce: coin.nonce,
@@ -219,8 +209,8 @@ fn main() {
         cm_pos: Some(coin.idx),
         //sn_c1: Some(coin.sn.unwrap()),
         slot: Some(coin.sl.unwrap()),
-        mau_rho: Some(mau_rho.clone()),
-        mau_y: Some(mau_y.clone()),
+        mau_rho: Some(mod_r_p(mau_rho.clone())),
+        mau_y: Some(mod_r_p(mau_y.clone())),
         root_cm: Some(coin.root_cm.unwrap()),
     };
 

+ 4 - 3
example/tx.rs

@@ -1,5 +1,5 @@
 // Example transaction flow
-use incrementalmerkletree::{bridgetree::BridgeTree, Frontier, Tree};
+use incrementalmerkletree::{bridgetree::BridgeTree, Tree};
 use rand::rngs::OsRng;
 
 use darkfi::{
@@ -90,7 +90,7 @@ impl MemoryState {
             self.tree.append(&node);
 
             // Keep track of all Merkle roots that have existed
-            self.merkle_roots.push(self.tree.root());
+            self.merkle_roots.push(self.tree.root(0).unwrap());
 
             // If it's our own coin, witness it and append to the vector.
             if let Some((note, secret)) = self.try_decrypt_note(enc_note) {
@@ -174,7 +174,8 @@ fn main() -> Result<()> {
     let owncoin = &state.own_coins[0];
     let note = owncoin.note;
     let leaf_position = owncoin.leaf_position;
-    let merkle_path = state.tree.authentication_path(leaf_position).unwrap();
+    let root = state.tree.root(0).unwrap();
+    let merkle_path = state.tree.authentication_path(leaf_position, &root).unwrap();
 
     let builder = TransactionBuilder {
         clear_inputs: vec![],

+ 1 - 6
example/zk.rs

@@ -2,9 +2,8 @@
 
 use darkfi::{
     crypto::{
-        keypair::PublicKey,
         proof::{ProvingKey, VerifyingKey},
-        util::{mod_r_p, pedersen_commitment_scalar, pedersen_commitment_u64},
+        util::{pedersen_commitment_scalar, pedersen_commitment_u64},
         Proof,
     },
     zk::{
@@ -14,10 +13,6 @@ use darkfi::{
     zkas::decoder::ZkBinary,
     Result,
 };
-use halo2_gadgets::primitives::{
-    poseidon,
-    poseidon::{ConstantLength, P128Pow5T3},
-};
 use pasta_curves::{
     arithmetic::CurveAffine,
     group::{ff::Field, Curve},

+ 4 - 1
script/compile_all_bins.sh

@@ -1,9 +1,12 @@
 #!/bin/sh
 set -e
 
+# foo|bar|baz
+skip_bins='cashierd'
+
 find_packages() {
 	find bin -type f -name Cargo.toml | while read line; do
-		if echo "$line" | grep -Eq 'cashierd|darkfid|gatewayd'; then
+		if echo "$line" | grep -Eq "$skip_bins"; then
 			continue
 		fi
 

+ 6 - 6
src/crypto/burn_proof.rs

@@ -1,9 +1,6 @@
 use std::time::Instant;
 
-use halo2_gadgets::primitives::{
-    poseidon,
-    poseidon::{ConstantLength, P128Pow5T3},
-};
+use halo2_gadgets::poseidon::primitives as poseidon;
 use incrementalmerkletree::Hashable;
 use log::debug;
 use pasta_curves::{arithmetic::CurveAffine, group::Curve};
@@ -50,7 +47,8 @@ impl BurnRevealedValues {
     ) -> Self {
         let nullifier = [secret.0, serial];
         let nullifier =
-            poseidon::Hash::<_, P128Pow5T3, ConstantLength<2>, 3, 2>::init().hash(nullifier);
+            poseidon::Hash::<_, poseidon::P128Pow5T3, poseidon::ConstantLength<2>, 3, 2>::init()
+                .hash(nullifier);
 
         let public_key = PublicKey::from_secret(secret);
         let coords = public_key.0.to_affine().coordinates().unwrap();
@@ -58,7 +56,9 @@ impl BurnRevealedValues {
         let messages =
             [*coords.x(), *coords.y(), DrkValue::from(value), token_id, serial, coin_blind];
 
-        let coin = poseidon::Hash::<_, P128Pow5T3, ConstantLength<6>, 3, 2>::init().hash(messages);
+        let coin =
+            poseidon::Hash::<_, poseidon::P128Pow5T3, poseidon::ConstantLength<6>, 3, 2>::init()
+                .hash(messages);
 
         let merkle_root = {
             let position: u64 = leaf_position.into();

+ 0 - 2
src/crypto/constants.rs

@@ -8,8 +8,6 @@ pub const DRK_SCHNORR_DOMAIN: &[u8] = b"DarkFi_Schnorr";
 
 pub const MERKLE_DEPTH_ORCHARD: usize = 32;
 
-pub const L_ORCHARD_MERKLE: usize = 255;
-
 #[allow(dead_code)]
 /// $\ell^\mathsf{Orchard}_\mathsf{base}$
 pub(crate) const L_ORCHARD_BASE: usize = 255;

+ 3 - 3
src/crypto/constants/fixed_bases.rs

@@ -98,7 +98,7 @@ impl FixedPoints<pallas::Affine> for OrchardFixedBases {
 }
 
 impl FixedPoint<pallas::Affine> for OrchardFixedBasesFull {
-    type ScalarKind = FullScalar;
+    type FixedScalarKind = FullScalar;
 
     fn generator(&self) -> pallas::Affine {
         match self {
@@ -129,7 +129,7 @@ impl FixedPoint<pallas::Affine> for OrchardFixedBasesFull {
 }
 
 impl FixedPoint<pallas::Affine> for NullifierK {
-    type ScalarKind = BaseFieldElem;
+    type FixedScalarKind = BaseFieldElem;
 
     fn generator(&self) -> pallas::Affine {
         nullifier_k::generator()
@@ -145,7 +145,7 @@ impl FixedPoint<pallas::Affine> for NullifierK {
 }
 
 impl FixedPoint<pallas::Affine> for ValueCommitV {
-    type ScalarKind = ShortScalar;
+    type FixedScalarKind = ShortScalar;
 
     fn generator(&self) -> pallas::Affine {
         value_commit_v::generator()

+ 1 - 1
src/crypto/constants/fixed_bases/commit_ivk_r.rs

@@ -2935,7 +2935,7 @@ mod tests {
     use group::Curve;
     use halo2_gadgets::{
         ecc::chip::constants::{test_lagrange_coeffs, test_zs_and_us},
-        primitives::sinsemilla::CommitDomain,
+        sinsemilla::primitives::CommitDomain,
     };
     use pasta_curves::{arithmetic::CurveAffine, pallas};
 

+ 1 - 1
src/crypto/constants/fixed_bases/note_commit_r.rs

@@ -2934,7 +2934,7 @@ mod tests {
     };
     use halo2_gadgets::{
         ecc::chip::constants::{test_lagrange_coeffs, test_zs_and_us},
-        primitives::sinsemilla::CommitDomain,
+        sinsemilla::primitives::CommitDomain,
     };
 
     use group::Curve;

+ 0 - 2
src/crypto/constants/load.rs

@@ -1,5 +1,3 @@
-use std::convert::TryInto;
-
 use crate::constants::{self, compute_lagrange_coeffs, H, NUM_WINDOWS, NUM_WINDOWS_SHORT};
 use group::ff::PrimeField;
 use pasta_curves::pallas;

+ 5 - 6
src/crypto/constants/sinsemilla.rs

@@ -19,7 +19,6 @@ pub const INV_TWO_POW_K: [u8; 32] = [
 /// of Pallas.
 pub const C: usize = 253;
 
-#[allow(dead_code)]
 /// $\ell^\mathsf{Orchard}_\mathsf{Merkle}$
 pub(crate) const L_ORCHARD_MERKLE: usize = 255;
 
@@ -135,7 +134,7 @@ mod tests {
         sinsemilla::MERKLE_CRH_PERSONALIZATION,
     };
     use group::{ff::PrimeField, Curve};
-    use halo2_gadgets::primitives::sinsemilla::{CommitDomain, HashDomain};
+    use halo2_gadgets::sinsemilla::primitives::{CommitDomain, HashDomain};
     use halo2_proofs::{arithmetic::CurveAffine, pasta::pallas};
     use rand::{self, rngs::OsRng, Rng};
 
@@ -160,18 +159,18 @@ mod tests {
     #[test]
     fn i2lebsp_k_round_trip() {
         {
-            let bitstring = (0..K).map(|_| rand::random()).collect::<Vec<_>>();
-            assert_eq!(i2lebsp_k(lebs2ip_k(&bitstring) as usize).to_vec(), bitstring);
+            let bitstring = [0; K].map(|_| rand::random());
+            assert_eq!(i2lebsp_k(lebs2ip_k(&bitstring) as usize), bitstring);
         }
 
         {
             let bitstring = [false; K];
-            assert_eq!(i2lebsp_k(lebs2ip_k(&bitstring) as usize).to_vec(), bitstring);
+            assert_eq!(i2lebsp_k(lebs2ip_k(&bitstring) as usize), bitstring);
         }
 
         {
             let bitstring = [true; K];
-            assert_eq!(i2lebsp_k(lebs2ip_k(&bitstring) as usize).to_vec(), bitstring);
+            assert_eq!(i2lebsp_k(lebs2ip_k(&bitstring) as usize), bitstring);
         }
     }
 

+ 4 - 6
src/crypto/lead_proof.rs

@@ -1,9 +1,6 @@
 use std::time::Instant;
 
-use halo2_gadgets::primitives::{
-    poseidon,
-    poseidon::{ConstantLength, P128Pow5T3},
-};
+use halo2_gadgets::poseidon::primitives as poseidon;
 use log::debug;
 use pasta_curves::{arithmetic::CurveAffine, group::Curve, pallas};
 use rand::rngs::OsRng;
@@ -36,6 +33,7 @@ pub fn create_lead_proof(pk: ProvingKey, coin: LeadCoin) -> Result<Proof> {
         coin_pk_x: coin.pk_x,
         coin_pk_y: coin.pk_y,
         root_sk: coin.root_sk,
+        sf_root_sk: Some(mod_r_p(coin.root_sk.unwrap())),
         path_sk: coin.path_sk,
         coin_timestamp: coin.tau, //
         coin_nonce: coin.nonce,
@@ -45,8 +43,8 @@ pub fn create_lead_proof(pk: ProvingKey, coin: LeadCoin) -> Result<Proof> {
         cm_pos: Some(coin.idx),
         //sn_c1: Some(coin.sn.unwrap()),
         slot: Some(coin.sl.unwrap()),
-        mau_rho: Some(mau_rho.clone()),
-        mau_y: Some(mau_y.clone()),
+        mau_rho: Some(mod_r_p(mau_rho.clone())),
+        mau_y: Some(mod_r_p(mau_y.clone())),
         root_cm: Some(coin.root_cm.unwrap()),
     };
 

+ 1 - 5
src/crypto/leadcoin.rs

@@ -1,10 +1,6 @@
 use incrementalmerkletree::{bridgetree::BridgeTree, Frontier, Tree};
 
-use halo2_gadgets::primitives::{
-    poseidon,
-    poseidon::{ConstantLength, P128Pow5T3},
-};
-
+use halo2_gadgets::poseidon::primitives as poseidon;
 use halo2_proofs::dev::MockProver;
 
 use rand::{thread_rng, Rng};

+ 5 - 5
src/crypto/merkle_node.rs

@@ -1,6 +1,6 @@
 use std::{io, iter};
 
-use halo2_gadgets::primitives::sinsemilla::HashDomain;
+use halo2_gadgets::sinsemilla::primitives::HashDomain;
 use incrementalmerkletree::{Altitude, Hashable};
 use lazy_static::lazy_static;
 use pasta_curves::{
@@ -18,8 +18,8 @@ use crate::{
     crypto::{
         coin::Coin,
         constants::{
-            sinsemilla::{i2lebsp_k, MERKLE_CRH_PERSONALIZATION},
-            L_ORCHARD_MERKLE, MERKLE_DEPTH_ORCHARD,
+            sinsemilla::{i2lebsp_k, L_ORCHARD_MERKLE, MERKLE_CRH_PERSONALIZATION},
+            MERKLE_DEPTH_ORCHARD,
         },
     },
     util::serial::{Decodable, Encodable},
@@ -106,8 +106,8 @@ impl Hashable for MerkleNode {
                 .hash(
                     iter::empty()
                         .chain(i2lebsp_k(altitude.into()).iter().copied())
-                        .chain(left.0.to_le_bits().iter().by_val().take(L_ORCHARD_MERKLE))
-                        .chain(right.0.to_le_bits().iter().by_val().take(L_ORCHARD_MERKLE)),
+                        .chain(left.0.to_le_bits().iter().by_vals().take(L_ORCHARD_MERKLE))
+                        .chain(right.0.to_le_bits().iter().by_vals().take(L_ORCHARD_MERKLE)),
                 )
                 .unwrap_or(pallas::Base::zero()),
         )

+ 4 - 5
src/crypto/mint_proof.rs

@@ -1,9 +1,6 @@
 use std::time::Instant;
 
-use halo2_gadgets::primitives::{
-    poseidon,
-    poseidon::{ConstantLength, P128Pow5T3},
-};
+use halo2_gadgets::poseidon::primitives as poseidon;
 use log::debug;
 use pasta_curves::{arithmetic::CurveAffine, group::Curve, pallas};
 use rand::rngs::OsRng;
@@ -45,7 +42,9 @@ impl MintRevealedValues {
         let messages =
             [*coords.x(), *coords.y(), DrkValue::from(value), token_id, serial, coin_blind];
 
-        let coin = poseidon::Hash::<_, P128Pow5T3, ConstantLength<6>, 3, 2>::init().hash(messages);
+        let coin =
+            poseidon::Hash::<_, poseidon::P128Pow5T3, poseidon::ConstantLength<6>, 3, 2>::init()
+                .hash(messages);
 
         MintRevealedValues { value_commit, token_commit, coin: Coin(coin) }
     }

+ 1 - 2
src/crypto/mod.rs

@@ -21,9 +21,8 @@ pub use burn_proof::BurnRevealedValues;
 pub use mint_proof::MintRevealedValues;
 pub use proof::Proof;
 
-pub mod leadcoin;
-
 pub mod lead_proof;
+pub mod leadcoin;
 
 use keypair::SecretKey;
 

+ 3 - 5
src/crypto/nullifier.rs

@@ -1,9 +1,6 @@
 use std::io;
 
-use halo2_gadgets::primitives::{
-    poseidon,
-    poseidon::{ConstantLength, P128Pow5T3},
-};
+use halo2_gadgets::poseidon::primitives as poseidon;
 use pasta_curves::{group::ff::PrimeField, pallas};
 
 use crate::{
@@ -19,7 +16,8 @@ impl Nullifier {
     pub fn new(secret: SecretKey, serial: pallas::Base) -> Self {
         let nullifier = [secret.0, serial];
         let nullifier =
-            poseidon::Hash::<_, P128Pow5T3, ConstantLength<2>, 3, 2>::init().hash(nullifier);
+            poseidon::Hash::<_, poseidon::P128Pow5T3, poseidon::ConstantLength<2>, 3, 2>::init()
+                .hash(nullifier);
         Nullifier(nullifier)
     }
 

+ 2 - 1
src/node/client.rs

@@ -95,7 +95,8 @@ impl Client {
                 }
 
                 let leaf_position = own_coin.leaf_position;
-                let merkle_path = state_m.tree.authentication_path(leaf_position).unwrap();
+                let root = state_m.tree.root(0).unwrap();
+                let merkle_path = state_m.tree.authentication_path(leaf_position, &root).unwrap();
                 inputs_value += own_coin.note.value;
 
                 let input = TransactionBuilderInputInfo {

+ 2 - 2
src/node/memorystate.rs

@@ -1,4 +1,4 @@
-use incrementalmerkletree::{bridgetree::BridgeTree, Frontier};
+use incrementalmerkletree::{bridgetree::BridgeTree, Tree};
 use log::debug;
 
 use super::state::{ProgramState, State, StateUpdate};
@@ -64,7 +64,7 @@ impl MemoryState {
         for coin in update.coins {
             let node = MerkleNode(coin.0);
             self.tree.append(&node);
-            self.merkle_roots.push(self.tree.root());
+            self.merkle_roots.push(self.tree.root(0).unwrap());
         }
 
         debug!(target: "state_apply", "(in-memory) Finished apply() successfully.");

+ 3 - 3
src/node/state.rs

@@ -1,5 +1,5 @@
 use async_std::sync::Arc;
-use incrementalmerkletree::{bridgetree::BridgeTree, Frontier, Tree};
+use incrementalmerkletree::{bridgetree::BridgeTree, Tree};
 use lazy_init::Lazy;
 use log::{debug, error};
 
@@ -158,8 +158,8 @@ impl State {
 
             // Keep track of all Merkle roots that have existed
             debug!("Existing merkle roots: {:#?}", self.merkle_roots.get_all()?);
-            debug!("New merkle root: {:#?}", self.tree.root());
-            self.merkle_roots.insert(&[self.tree.root()])?;
+            debug!("New merkle root: {:#?}", self.tree.root(0).unwrap());
+            self.merkle_roots.insert(&[self.tree.root(0).unwrap()])?;
 
             for secret in secret_keys.iter() {
                 if let Some(note) = State::try_decrypt_note(enc_note, *secret) {

+ 4 - 4
src/wallet/walletdb.rs

@@ -441,7 +441,7 @@ mod tests {
         types::{DrkCoinBlind, DrkSerial, DrkValueBlind},
     };
     use group::ff::Field;
-    use incrementalmerkletree::{Frontier, Tree};
+    use incrementalmerkletree::Tree;
     use pasta_curves::pallas;
     use rand::rngs::OsRng;
 
@@ -511,7 +511,7 @@ mod tests {
         tree1.witness();
 
         // We'll check this merkle root corresponds to the one we'll retrieve.
-        let root1 = tree1.root();
+        let root1 = tree1.root(0).unwrap();
 
         // put_tree()
         wallet.put_tree(&tree1).await?;
@@ -557,13 +557,13 @@ mod tests {
 
         // get_tree()
         let tree2 = wallet.get_tree().await?;
-        let root2 = tree2.root();
+        let root2 = tree2.root(0).unwrap();
         assert_eq!(root1, root2);
 
         // Let's try it once more to test sql replacing.
         wallet.put_tree(&tree2).await?;
         let tree3 = wallet.get_tree().await?;
-        let root3 = tree3.root();
+        let root3 = tree3.root(0).unwrap();
         assert_eq!(root2, root3);
 
         Ok(())

+ 47 - 17
src/zk/circuit/burn_contract.rs

@@ -1,10 +1,12 @@
 use halo2_gadgets::{
     ecc::{
         chip::{EccChip, EccConfig},
-        FixedPoint, FixedPointBaseField, FixedPointShort,
+        FixedPoint, FixedPointBaseField, FixedPointShort, ScalarFixed, ScalarFixedShort,
+    },
+    poseidon::{
+        primitives as poseidon, Hash as PoseidonHash, Pow5Chip as PoseidonChip,
+        Pow5Config as PoseidonConfig,
     },
-    poseidon::{Hash as PoseidonHash, Pow5Chip as PoseidonChip, Pow5Config as PoseidonConfig},
-    primitives::poseidon::{ConstantLength, P128Pow5T3},
     sinsemilla::{
         chip::{SinsemillaChip, SinsemillaConfig},
         merkle::{
@@ -175,7 +177,7 @@ impl Circuit<pallas::Base> for BurnContract {
             EccChip::<OrchardFixedBases>::configure(meta, advices, lagrange_coeffs, range_check);
 
         // Configuration for the Poseidon hash
-        let poseidon_config = PoseidonChip::configure::<P128Pow5T3>(
+        let poseidon_config = PoseidonChip::configure::<poseidon::P128Pow5T3>(
             meta,
             advices[6..9].try_into().unwrap(),
             advices[5],
@@ -259,9 +261,15 @@ impl Circuit<pallas::Base> for BurnContract {
         let hash = {
             let poseidon_message = [secret_key.clone(), serial.clone()];
 
-            let poseidon_hasher = PoseidonHash::<_, _, P128Pow5T3, ConstantLength<2>, 3, 2>::init(
-                config.poseidon_chip(),
-                layouter.namespace(|| "Poseidon init"),
+            let poseidon_hasher = PoseidonHash::<
+                _,
+                _,
+                poseidon::P128Pow5T3,
+                poseidon::ConstantLength<2>,
+                3,
+                2,
+            >::init(
+                config.poseidon_chip(), layouter.namespace(|| "Poseidon init")
             )?;
 
             let poseidon_output =
@@ -305,9 +313,15 @@ impl Circuit<pallas::Base> for BurnContract {
         let coin = {
             let poseidon_message = [pub_x, pub_y, value, token, serial, coin_blind];
 
-            let poseidon_hasher = PoseidonHash::<_, _, P128Pow5T3, ConstantLength<6>, 3, 2>::init(
-                config.poseidon_chip(),
-                layouter.namespace(|| "Poseidon init"),
+            let poseidon_hasher = PoseidonHash::<
+                _,
+                _,
+                poseidon::P128Pow5T3,
+                poseidon::ConstantLength<6>,
+                3,
+                2,
+            >::init(
+                config.poseidon_chip(), layouter.namespace(|| "Poseidon init")
             )?;
 
             let poseidon_output =
@@ -325,8 +339,7 @@ impl Circuit<pallas::Base> for BurnContract {
             self.merkle_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(),
+            [config.merkle_chip_1(), config.merkle_chip_2()],
             OrchardHashDomains::MerkleCrh,
             self.leaf_pos,
             path,
@@ -359,13 +372,21 @@ impl Circuit<pallas::Base> for BurnContract {
         let (commitment, _) = {
             let value_commit_v = ValueCommitV;
             let value_commit_v = FixedPointShort::from_inner(ecc_chip.clone(), value_commit_v);
-            value_commit_v
-                .mul(layouter.namespace(|| "[value] ValueCommitV"), (value, one.clone()))?
+            let value = ScalarFixedShort::new(
+                ecc_chip.clone(),
+                layouter.namespace(|| "value"),
+                (value, one.clone()),
+            )?;
+            value_commit_v.mul(layouter.namespace(|| "[value] ValueCommitV"), value)?
         };
 
         // r_V * G_2
         let (blind, _rcv) = {
-            let rcv = self.value_blind;
+            let rcv = ScalarFixed::new(
+                ecc_chip.clone(),
+                layouter.namespace(|| "value_blind"),
+                self.value_blind,
+            )?;
             let value_commit_r = OrchardFixedBasesFull::ValueCommitR;
             let value_commit_r = FixedPoint::from_inner(ecc_chip.clone(), value_commit_r);
             value_commit_r.mul(layouter.namespace(|| "[value_blind] ValueCommitR"), rcv)?
@@ -395,12 +416,21 @@ impl Circuit<pallas::Base> for BurnContract {
         let (commitment, _) = {
             let token_commit_v = ValueCommitV;
             let token_commit_v = FixedPointShort::from_inner(ecc_chip.clone(), token_commit_v);
-            token_commit_v.mul(layouter.namespace(|| "[token] ValueCommitV"), (token, one))?
+            let token = ScalarFixedShort::new(
+                ecc_chip.clone(),
+                layouter.namespace(|| "token"),
+                (token, one),
+            )?;
+            token_commit_v.mul(layouter.namespace(|| "[token] ValueCommitV"), token)?
         };
 
         // r_A * G_2
         let (blind, _rca) = {
-            let rca = self.token_blind;
+            let rca = ScalarFixed::new(
+                ecc_chip.clone(),
+                layouter.namespace(|| "token_blind"),
+                self.token_blind,
+            )?;
             let token_commit_r = OrchardFixedBasesFull::ValueCommitR;
             let token_commit_r = FixedPoint::from_inner(ecc_chip.clone(), token_commit_r);
             token_commit_r.mul(layouter.namespace(|| "[token_blind] ValueCommitR"), rca)?

+ 106 - 64
src/zk/circuit/lead_contract.rs

@@ -1,10 +1,9 @@
 use halo2_gadgets::{
     ecc::{
         chip::{EccChip, EccConfig},
-        FixedPoint, FixedPointShort,
+        FixedPoint, FixedPointShort, ScalarFixed, ScalarFixedShort,
     },
-    poseidon::{Hash as PoseidonHash, Pow5Chip as PoseidonChip, Pow5Config as PoseidonConfig},
-    primitives::poseidon::{ConstantLength, P128Pow5T3},
+    poseidon::{primitives as poseidon, Pow5Chip as PoseidonChip, Pow5Config as PoseidonConfig},
     sinsemilla::{
         chip::{SinsemillaChip, SinsemillaConfig},
         merkle::{
@@ -20,7 +19,7 @@ use halo2_proofs::{
     plonk::{Advice, Circuit, Column, ConstraintSystem, Error, Instance as InstanceColumn},
 };
 
-use pasta_curves::{pallas, Ep, Fp};
+use pasta_curves::{pallas, Fp};
 
 use crate::crypto::{
     constants::{
@@ -29,7 +28,6 @@ use crate::crypto::{
         OrchardFixedBases, OrchardFixedBasesFull, ValueCommitV, MERKLE_DEPTH_ORCHARD,
     },
     merkle_node::MerkleNode,
-    util::mod_r_p,
 };
 
 use crate::zk::{
@@ -38,10 +36,7 @@ use crate::zk::{
     greater_than::{GreaterThanChip, GreaterThanConfig, GreaterThanInstruction},
 };
 
-use pasta_curves::{
-    arithmetic::CurveAffine,
-    group::{ff::PrimeField, Curve, GroupEncoding},
-};
+use pasta_curves::group::{ff::PrimeField, GroupEncoding};
 //use halo2_proofs::arithmetic::CurveAffine;
 
 const WORD_BITS: u32 = 24;
@@ -120,6 +115,7 @@ pub struct LeadContract {
     pub coin_pk_x: Option<pallas::Base>,
     pub coin_pk_y: Option<pallas::Base>,
     pub root_sk: Option<pallas::Base>, // coins merkle tree secret key of coin1
+    pub sf_root_sk: Option<pallas::Scalar>, // root_sk as pallas::Scalar
     pub path_sk: Option<[MerkleNode; MERKLE_DEPTH_ORCHARD]>, // path to the secret key root_sk
     pub coin_timestamp: Option<pallas::Base>,
     pub coin_nonce: Option<pallas::Base>,
@@ -131,8 +127,8 @@ pub struct LeadContract {
     //
     //pub sn_c1 : Option<pallas::Base>,
     pub slot: Option<pallas::Base>,
-    pub mau_rho: Option<pallas::Base>,
-    pub mau_y: Option<pallas::Base>,
+    pub mau_rho: Option<pallas::Scalar>,
+    pub mau_y: Option<pallas::Scalar>,
     pub root_cm: Option<pallas::Scalar>,
     //pub eta : Option<u32>,
     //pub rho : Option<u32>,
@@ -202,7 +198,7 @@ impl Circuit<pallas::Base> for LeadContract {
             range_check,
         );
 
-        let poseidon_config = PoseidonChip::configure::<P128Pow5T3>(
+        let poseidon_config = PoseidonChip::configure::<poseidon::P128Pow5T3>(
             meta,
             advices[6..9].try_into().unwrap(),
             advices[5],
@@ -278,6 +274,12 @@ impl Circuit<pallas::Base> for LeadContract {
         // load witnesses
         // ===============
 
+        let one = self.load_private(
+            layouter.namespace(|| "one"),
+            config.advices[0],
+            Some(pallas::Base::one()),
+        )?;
+
         // coin_timestamp tau
 
         let coin_timestamp = self.load_private(
@@ -314,12 +316,6 @@ impl Circuit<pallas::Base> for LeadContract {
         let root_sk =
             self.load_private(layouter.namespace(|| ""), config.advices[0], self.root_sk)?;
 
-        let one = self.load_private(
-            layouter.namespace(|| "one"),
-            config.advices[0],
-            Some(pallas::Base::one()),
-        )?;
-
         // ===============
         // coin 2 nonce
         // ===============
@@ -327,17 +323,23 @@ impl Circuit<pallas::Base> for LeadContract {
         let (com, _) = {
             let nonce2_commit_v = ValueCommitV;
             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()))?
+            let coin_nonce = ScalarFixedShort::new(
+                ecc_chip.clone(),
+                layouter.namespace(|| "coin_nonce*1"),
+                (coin_nonce.clone(), one.clone()),
+            )?;
+            nonce2_commit_v.mul(layouter.namespace(|| "coin_pk commit v"), coin_nonce)?
         };
         // r*G_2
         let (blind, _) = {
             let nonce2_commit_r = OrchardFixedBasesFull::ValueCommitR;
             let nonce2_commit_r = FixedPoint::from_inner(ecc_chip.clone(), nonce2_commit_r);
-            nonce2_commit_r.mul(
-                layouter.namespace(|| "nonce2 commit R"),
-                Some(mod_r_p(self.root_sk.unwrap())),
-            )?
+            let root_sk = ScalarFixed::new(
+                ecc_chip.clone(),
+                layouter.namespace(|| "root_sk scalar"),
+                self.sf_root_sk,
+            )?;
+            nonce2_commit_r.mul(layouter.namespace(|| "nonce2 commit R"), root_sk)?
         };
         let coin2_nonce = com.add(layouter.namespace(|| "nonce2 commit"), &blind)?;
 
@@ -361,17 +363,23 @@ impl Circuit<pallas::Base> for LeadContract {
         let (com, _) = {
             let coin_pk_commit_v = ValueCommitV;
             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()))?
+            let coin_timestamp = ScalarFixedShort::new(
+                ecc_chip.clone(),
+                layouter.namespace(|| "coin_timestamp*1"),
+                (coin_timestamp, one.clone()),
+            )?;
+            coin_pk_commit_v.mul(layouter.namespace(|| "coin_pk commit v"), coin_timestamp)?
         };
         // r*G_2
         let (blind, _) = {
             let coin_pk_commit_r = OrchardFixedBasesFull::ValueCommitR;
             let coin_pk_commit_r = FixedPoint::from_inner(ecc_chip.clone(), coin_pk_commit_r);
-            coin_pk_commit_r.mul(
-                layouter.namespace(|| "coin_pk commit R"),
-                Some(mod_r_p(self.root_sk.unwrap())),
-            )?
+            let root_sk = ScalarFixed::new(
+                ecc_chip.clone(),
+                layouter.namespace(|| "root sk scalar"),
+                self.sf_root_sk,
+            )?;
+            coin_pk_commit_r.mul(layouter.namespace(|| "coin_pk commit R"), root_sk)?
         };
         let coin_pk_commit = com.add(layouter.namespace(|| "coin timestamp commit"), &blind)?;
 
@@ -401,19 +409,24 @@ impl Circuit<pallas::Base> for LeadContract {
         let (com, _) = {
             let sn_commit_v = ValueCommitV;
             let sn_commit_v = FixedPointShort::from_inner(ecc_chip.clone(), sn_commit_v);
-            sn_commit_v.mul(
-                layouter.namespace(|| "coin serial number commit v"),
+            let coin_nonce = ScalarFixedShort::new(
+                ecc_chip.clone(),
+                layouter.namespace(|| "coin nonce * 1"),
                 (coin_nonce.clone(), one.clone()),
-            )?
+            )?;
+
+            sn_commit_v.mul(layouter.namespace(|| "coin serial number commit v"), coin_nonce)?
         };
         // r*G_2
         let (blind, _) = {
             let sn_commit_r = OrchardFixedBasesFull::ValueCommitR;
             let sn_commit_r = FixedPoint::from_inner(ecc_chip.clone(), sn_commit_r);
-            sn_commit_r.mul(
-                layouter.namespace(|| "coin serial number commit R"),
-                Some(mod_r_p(self.root_sk.unwrap())),
-            )?
+            let root_sk = ScalarFixed::new(
+                ecc_chip.clone(),
+                layouter.namespace(|| "root sk scalar"),
+                self.sf_root_sk,
+            )?;
+            sn_commit_r.mul(layouter.namespace(|| "coin serial number commit R"), root_sk)?
         };
         //
         let sn_commit = com.add(layouter.namespace(|| "nonce commit"), &blind)?;
@@ -446,7 +459,7 @@ impl Circuit<pallas::Base> for LeadContract {
                 coin_pk_x.clone(),
             ];
 
-            let poseidon_hasher = PoseidonHash::<_, _, P128Pow5T3, ConstantLength<1>, 3, 2>::init(
+            let poseidon_hasher = PoseidonHash::<_, _, poseidon::P128Pow5T3, poseidon::ConstantLength<1>, 3, 2>::init(
                 config.poseidon_chip(),
                 layouter.namespace(|| "Poseidon init"),
             )?;
@@ -470,16 +483,25 @@ impl Circuit<pallas::Base> for LeadContract {
         let (com, _) = {
             let coin_commit_v = ValueCommitV;
             let coin_commit_v = FixedPointShort::from_inner(ecc_chip.clone(), coin_commit_v);
-            coin_commit_v
-                .mul(layouter.namespace(|| "coin commit v"), (coin_val.clone(), one.clone()))?
+            let coin_val = ScalarFixedShort::new(
+                ecc_chip.clone(),
+                layouter.namespace(|| "coin_val*1"),
+                (coin_val.clone(), one.clone()),
+            )?;
+            coin_commit_v.mul(layouter.namespace(|| "coin commit v"), coin_val)?
         };
 
         // r*G_2
         let (blind, _) = {
             let coin_commit_r = OrchardFixedBasesFull::ValueCommitR;
             let coin_commit_r = FixedPoint::from_inner(ecc_chip.clone(), coin_commit_r);
+            let coin_opening_1 = ScalarFixed::new(
+                ecc_chip.clone(),
+                layouter.namespace(|| "coin_opening_1 scalar"),
+                self.coin_opening_1,
+            )?;
             coin_commit_r
-                .mul(layouter.namespace(|| "coin serial number commit R"), self.coin_opening_1)?
+                .mul(layouter.namespace(|| "coin serial number commit R"), coin_opening_1)?
         };
 
         let coin_commit = com.add(layouter.namespace(|| "nonce commit"), &blind)?;
@@ -510,7 +532,7 @@ impl Circuit<pallas::Base> for LeadContract {
                 coin2_nonce.inner().y(),
             ];
 
-            let poseidon_hasher = PoseidonHash::<_, _, P128Pow5T3, ConstantLength<5>, 3, 2>::init(
+            let poseidon_hasher = PoseidonHash::<_, _, poseidon::P128Pow5T3, poseidon::ConstantLength<5>, 3, 2>::init(
                 config.poseidon_chip(),
                 layouter.namespace(|| "Poseidon init"),
             )?;
@@ -539,14 +561,24 @@ impl Circuit<pallas::Base> for LeadContract {
         let (com, _) = {
             let coin_commit_v = ValueCommitV;
             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()))?
+            let coin2_hash = ScalarFixedShort::new(
+                ecc_chip.clone(),
+                layouter.namespace(|| "coin2_hash*1"),
+                (coin2_hash, one.clone()),
+            )?;
+            coin_commit_v.mul(layouter.namespace(|| "coin commit v"), coin2_hash)?
         };
         // r*G_2
         let (blind, _) = {
             let coin_commit_r = OrchardFixedBasesFull::ValueCommitR;
             let coin_commit_r = FixedPoint::from_inner(ecc_chip.clone(), coin_commit_r);
+            let coin_opening_2 = ScalarFixed::new(
+                ecc_chip.clone(),
+                layouter.namespace(|| "coin_opening_2 scalar"),
+                self.coin_opening_2,
+            )?;
             coin_commit_r
-                .mul(layouter.namespace(|| "coin serial number commit R"), self.coin_opening_2)?
+                .mul(layouter.namespace(|| "coin serial number commit R"), coin_opening_2)?
         };
         let coin2_commit = com.add(layouter.namespace(|| "nonce commit"), &blind)?;
         let coin2_commit_x: AssignedCell<Fp, Fp> = coin2_commit.inner().x();
@@ -569,8 +601,7 @@ impl Circuit<pallas::Base> for LeadContract {
             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(),
+            [config.merkle_chip_1(), config.merkle_chip_2()],
             OrchardHashDomains::MerkleCrh,
             self.cm_pos,
             path,
@@ -579,13 +610,11 @@ impl Circuit<pallas::Base> for LeadContract {
         let coin_commit_prod: AssignedCell<Fp, Fp> = {
             let coin_commit_coordinates = coin_commit.inner();
 
-            let res: AssignedCell<Fp, Fp> = ar_chip
-                .mul(
-                    layouter.namespace(|| ""),
-                    coin_commit_coordinates.x(),
-                    coin_commit_coordinates.y(),
-                )
-                .unwrap();
+            let res: AssignedCell<Fp, Fp> = ar_chip.mul(
+                layouter.namespace(|| ""),
+                coin_commit_coordinates.x(),
+                coin_commit_coordinates.y(),
+            )?;
             res
         };
 
@@ -613,17 +642,24 @@ impl Circuit<pallas::Base> for LeadContract {
         let (com, _) = {
             let y_commit_v = ValueCommitV;
             let y_commit_v = FixedPointShort::from_inner(ecc_chip.clone(), y_commit_v);
-            y_commit_v.mul(layouter.namespace(|| "coin commit v"), (y_commit_exp, one.clone()))?
+            let y_commit_exp = ScalarFixedShort::new(
+                ecc_chip.clone(),
+                layouter.namespace(|| "y_commit_exp*1"),
+                (y_commit_exp, one.clone()),
+            )?;
+            y_commit_v.mul(layouter.namespace(|| "coin commit v"), y_commit_exp)?
         };
 
         // r*G_2
         let (blind, _) = {
             let y_commit_r = OrchardFixedBasesFull::ValueCommitR;
             let y_commit_r = FixedPoint::from_inner(ecc_chip.clone(), y_commit_r);
-            y_commit_r.mul(
-                layouter.namespace(|| "coin serial number commit R"),
-                Some(mod_r_p(self.mau_y.unwrap())),
-            )?
+            let mau_y = ScalarFixed::new(
+                ecc_chip.clone(),
+                layouter.namespace(|| "mau_y scalar"),
+                self.mau_y,
+            )?;
+            y_commit_r.mul(layouter.namespace(|| "coin serial number commit R"), mau_y)?
         };
         let mut y_commit = com.add(layouter.namespace(|| "nonce commit"), &blind)?;
 
@@ -647,17 +683,23 @@ impl Circuit<pallas::Base> for LeadContract {
         let (com, _) = {
             let rho_commit_v = ValueCommitV;
             let rho_commit_v = FixedPointShort::from_inner(ecc_chip.clone(), rho_commit_v);
-            rho_commit_v
-                .mul(layouter.namespace(|| "coin commit v"), (y_commit_base.clone(), one.clone()))?
+            let y_commit_base = ScalarFixedShort::new(
+                ecc_chip.clone(),
+                layouter.namespace(|| "y_commit_base*1"),
+                (y_commit_base.clone(), one.clone()),
+            )?;
+            rho_commit_v.mul(layouter.namespace(|| "coin commit v"), y_commit_base)?
         };
         // r*G_2
         let (blind, _) = {
             let rho_commit_r = OrchardFixedBasesFull::ValueCommitR;
             let rho_commit_r = FixedPoint::from_inner(ecc_chip.clone(), rho_commit_r);
-            rho_commit_r.mul(
-                layouter.namespace(|| "coin serial number commit R"),
-                Some(mod_r_p(self.mau_rho.unwrap())),
-            )?
+            let mau_rho = ScalarFixed::new(
+                ecc_chip.clone(),
+                layouter.namespace(|| "mau_rho scalar"),
+                self.mau_rho,
+            )?;
+            rho_commit_r.mul(layouter.namespace(|| "coin serial number commit R"), mau_rho)?
         };
         let rho_commit = com.add(layouter.namespace(|| "nonce commit"), &blind)?;
 

+ 37 - 12
src/zk/circuit/mint_contract.rs

@@ -1,10 +1,12 @@
 use halo2_gadgets::{
     ecc::{
         chip::{EccChip, EccConfig},
-        FixedPoint, FixedPointShort,
+        FixedPoint, FixedPointShort, ScalarFixed, ScalarFixedShort,
+    },
+    poseidon::{
+        primitives as poseidon, Hash as PoseidonHash, Pow5Chip as PoseidonChip,
+        Pow5Config as PoseidonConfig,
     },
-    poseidon::{Hash as PoseidonHash, Pow5Chip as PoseidonChip, Pow5Config as PoseidonConfig},
-    primitives::poseidon::{ConstantLength, P128Pow5T3},
     utilities::{lookup_range_check::LookupRangeCheckConfig, UtilitiesInstructions},
 };
 use halo2_proofs::{
@@ -121,7 +123,7 @@ impl Circuit<pallas::Base> for MintContract {
             EccChip::<OrchardFixedBases>::configure(meta, advices, lagrange_coeffs, range_check);
 
         // Configuration for the Poseidon hash
-        let poseidon_config = PoseidonChip::configure::<P128Pow5T3>(
+        let poseidon_config = PoseidonChip::configure::<poseidon::P128Pow5T3>(
             meta,
             advices[6..9].try_into().unwrap(),
             advices[5],
@@ -175,9 +177,15 @@ impl Circuit<pallas::Base> for MintContract {
         let coin = {
             let poseidon_message = [pub_x, pub_y, value.clone(), token.clone(), serial, coin_blind];
 
-            let poseidon_hasher = PoseidonHash::<_, _, P128Pow5T3, ConstantLength<6>, 3, 2>::init(
-                config.poseidon_chip(),
-                layouter.namespace(|| "Poseidon init"),
+            let poseidon_hasher = PoseidonHash::<
+                _,
+                _,
+                poseidon::P128Pow5T3,
+                poseidon::ConstantLength<6>,
+                3,
+                2,
+            >::init(
+                config.poseidon_chip(), layouter.namespace(|| "Poseidon init")
             )?;
 
             let poseidon_output =
@@ -205,13 +213,21 @@ impl Circuit<pallas::Base> for MintContract {
         let (commitment, _) = {
             let value_commit_v = ValueCommitV;
             let value_commit_v = FixedPointShort::from_inner(ecc_chip.clone(), value_commit_v);
-            value_commit_v
-                .mul(layouter.namespace(|| "[value] ValueCommitV"), (value, one.clone()))?
+            let value = ScalarFixedShort::new(
+                ecc_chip.clone(),
+                layouter.namespace(|| "value"),
+                (value, one.clone()),
+            )?;
+            value_commit_v.mul(layouter.namespace(|| "[value] ValueCommitV"), value)?
         };
 
         // r_V * G_2
         let (blind, _rcv) = {
-            let rcv = self.value_blind;
+            let rcv = ScalarFixed::new(
+                ecc_chip.clone(),
+                layouter.namespace(|| "value_blind"),
+                self.value_blind,
+            )?;
             let value_commit_r = OrchardFixedBasesFull::ValueCommitR;
             let value_commit_r = FixedPoint::from_inner(ecc_chip.clone(), value_commit_r);
             value_commit_r.mul(layouter.namespace(|| "[value_blind] ValueCommitR"), rcv)?
@@ -239,12 +255,21 @@ impl Circuit<pallas::Base> for MintContract {
         let (commitment, _) = {
             let token_commit_v = ValueCommitV;
             let token_commit_v = FixedPointShort::from_inner(ecc_chip.clone(), token_commit_v);
-            token_commit_v.mul(layouter.namespace(|| "[token] ValueCommitV"), (token, one))?
+            let token = ScalarFixedShort::new(
+                ecc_chip.clone(),
+                layouter.namespace(|| "token"),
+                (token, one),
+            )?;
+            token_commit_v.mul(layouter.namespace(|| "[token] ValueCommitV"), token)?
         };
 
         // r_A * G_2
         let (blind, _rca) = {
-            let rca = self.token_blind;
+            let rca = ScalarFixed::new(
+                ecc_chip.clone(),
+                layouter.namespace(|| "token_blind"),
+                self.token_blind,
+            )?;
             let token_commit_r = OrchardFixedBasesFull::ValueCommitR;
             let token_commit_r = FixedPoint::from_inner(ecc_chip, token_commit_r);
             token_commit_r.mul(layouter.namespace(|| "[token_blind] ValueCommitR"), rca)?

+ 29 - 15
src/zk/vm.rs

@@ -1,10 +1,12 @@
 use halo2_gadgets::{
     ecc::{
         chip::{EccChip, EccConfig},
-        FixedPoint, FixedPointBaseField, FixedPointShort, Point,
+        FixedPoint, FixedPointBaseField, FixedPointShort, Point, ScalarFixed, ScalarFixedShort,
+    },
+    poseidon::{
+        primitives as poseidon, Hash as PoseidonHash, Pow5Chip as PoseidonChip,
+        Pow5Config as PoseidonConfig,
     },
-    poseidon::{Hash as PoseidonHash, Pow5Chip as PoseidonChip, Pow5Config as PoseidonConfig},
-    primitives::poseidon::{ConstantLength, P128Pow5T3},
     sinsemilla::{
         chip::{SinsemillaChip, SinsemillaConfig},
         merkle::{
@@ -191,7 +193,7 @@ impl Circuit<pallas::Base> for ZkCircuit {
             EccChip::<OrchardFixedBases>::configure(meta, advices, lagrange_coeffs, range_check);
 
         // Configuration for the Poseidon hash
-        let poseidon_config = PoseidonChip::configure::<P128Pow5T3>(
+        let poseidon_config = PoseidonChip::configure::<poseidon::P128Pow5T3>(
             meta,
             advices[6..9].try_into().unwrap(),
             advices[5],
@@ -398,7 +400,11 @@ impl Circuit<pallas::Base> for ZkCircuit {
                     let lhs: FixedPoint<pallas::Affine, EccChip<OrchardFixedBases>> =
                         stack[args[1]].clone().into();
 
-                    let rhs: Option<pallas::Scalar> = stack[args[0]].clone().into();
+                    let rhs = ScalarFixed::new(
+                        ecc_chip.clone(),
+                        layouter.namespace(|| "EcMul: ScalarFixed::new()"),
+                        stack[args[0]].clone().into(),
+                    )?;
 
                     let (ret, _) = lhs.mul(layouter.namespace(|| "EcMul()"), rhs)?;
 
@@ -428,10 +434,13 @@ impl Circuit<pallas::Base> for ZkCircuit {
                     let lhs: FixedPointShort<pallas::Affine, EccChip<OrchardFixedBases>> =
                         stack[args[1]].clone().into();
 
-                    let rhs: AssignedCell<Fp, Fp> = stack[args[0]].clone().into();
+                    let rhs = ScalarFixedShort::new(
+                        ecc_chip.clone(),
+                        layouter.namespace(|| "EcMulShort: ScalarFixedShort::new()"),
+                        (stack[args[0]].clone().into(), one.clone()),
+                    )?;
 
-                    let (ret, _) =
-                        lhs.mul(layouter.namespace(|| "EcMulShort()"), (rhs, one.clone()))?;
+                    let (ret, _) = lhs.mul(layouter.namespace(|| "EcMulShort()"), rhs)?;
                     debug!("Pushing result to stack index {}", stack.len());
                     stack.push(StackVar::EcPoint(ret));
                 }
@@ -475,11 +484,17 @@ impl Circuit<pallas::Base> for ZkCircuit {
 
                     macro_rules! poseidon_hash {
                         ($len:expr, $hasher:ident, $output:ident, $cell:ident) => {
-                            let $hasher =
-                                PoseidonHash::<_, _, P128Pow5T3, ConstantLength<$len>, 3, 2>::init(
-                                    config.poseidon_chip(),
-                                    layouter.namespace(|| "PoseidonHash init"),
-                                )?;
+                            let $hasher = PoseidonHash::<
+                                _,
+                                _,
+                                poseidon::P128Pow5T3,
+                                poseidon::ConstantLength<$len>,
+                                3,
+                                2,
+                            >::init(
+                                config.poseidon_chip(),
+                                layouter.namespace(|| "PoseidonHash init"),
+                            )?;
 
                             let $output = $hasher.hash(
                                 layouter.namespace(|| "PoseidonHash hash"),
@@ -516,8 +531,7 @@ impl Circuit<pallas::Base> for ZkCircuit {
                     let leaf = stack[args[2]].clone().into();
 
                     let merkle_inputs = MerklePath::construct(
-                        config.merkle_chip_1(),
-                        config.merkle_chip_2(),
+                        [config.merkle_chip_1(), config.merkle_chip_2()],
                         OrchardHashDomains::MerkleCrh,
                         leaf_pos,
                         merkle_path,

+ 9 - 9
tests/burn_proof.rs

@@ -13,11 +13,8 @@ use darkfi::{
     zkas::decoder::ZkBinary,
     Result,
 };
-use halo2_gadgets::primitives::{
-    poseidon,
-    poseidon::{ConstantLength, P128Pow5T3},
-};
-use incrementalmerkletree::{bridgetree::BridgeTree, Frontier, Tree};
+use halo2_gadgets::poseidon::primitives as poseidon;
+use incrementalmerkletree::{bridgetree::BridgeTree, Tree};
 use pasta_curves::{
     arithmetic::CurveAffine,
     group::{ff::Field, Curve},
@@ -51,7 +48,8 @@ fn burn_proof() -> Result<()> {
         let messages =
             [*coords.x(), *coords.y(), pallas::Base::from(value), token_id, serial, coin_blind];
 
-        poseidon::Hash::<_, P128Pow5T3, ConstantLength<6>, 3, 2>::init().hash(messages)
+        poseidon::Hash::<_, poseidon::P128Pow5T3, poseidon::ConstantLength<6>, 3, 2>::init()
+            .hash(messages)
     };
 
     // Fill the merkle tree with some random coins that we want to witness,
@@ -69,7 +67,8 @@ fn burn_proof() -> Result<()> {
     tree.append(&MerkleNode(coin3));
     tree.witness();
 
-    let merkle_path = tree.authentication_path(leaf_pos).unwrap();
+    let root = tree.root(0).unwrap();
+    let merkle_path = tree.authentication_path(leaf_pos, &root).unwrap();
     let leaf_pos: u64 = leaf_pos.into();
 
     let prover_witnesses = vec![
@@ -88,7 +87,8 @@ fn burn_proof() -> Result<()> {
     // Create the public inputs
     let nullifier = [secret.0, serial];
     let nullifier =
-        poseidon::Hash::<_, P128Pow5T3, ConstantLength<2>, 3, 2>::init().hash(nullifier);
+        poseidon::Hash::<_, poseidon::P128Pow5T3, poseidon::ConstantLength<2>, 3, 2>::init()
+            .hash(nullifier);
 
     let value_commit = pedersen_commitment_u64(value, value_blind);
     let value_coords = value_commit.to_affine().coordinates().unwrap();
@@ -99,7 +99,7 @@ fn burn_proof() -> Result<()> {
     let sig_pubkey = PublicKey::from_secret(sig_secret);
     let sig_coords = sig_pubkey.0.to_affine().coordinates().unwrap();
 
-    let merkle_root = tree.root();
+    let merkle_root = tree.root(0).unwrap();
 
     let public_inputs = vec![
         nullifier,

+ 3 - 5
tests/mint_proof.rs

@@ -12,10 +12,7 @@ use darkfi::{
     zkas::decoder::ZkBinary,
     Result,
 };
-use halo2_gadgets::primitives::{
-    poseidon,
-    poseidon::{ConstantLength, P128Pow5T3},
-};
+use halo2_gadgets::poseidon::primitives as poseidon;
 use pasta_curves::{
     arithmetic::CurveAffine,
     group::{ff::Field, Curve},
@@ -56,7 +53,8 @@ fn mint_proof() -> Result<()> {
 
     // Create the public inputs
     let msgs = [*coords.x(), *coords.y(), pallas::Base::from(value), token_id, serial, coin_blind];
-    let coin = poseidon::Hash::<_, P128Pow5T3, ConstantLength<6>, 3, 2>::init().hash(msgs);
+    let coin = poseidon::Hash::<_, poseidon::P128Pow5T3, poseidon::ConstantLength<6>, 3, 2>::init()
+        .hash(msgs);
 
     let value_commit = pedersen_commitment_u64(value, value_blind);
     let value_coords = value_commit.to_affine().coordinates().unwrap();