Skip to content

Commit

Permalink
refactor: changed data type in 'MstInclusionProof'
Browse files Browse the repository at this point in the history
  • Loading branch information
sifnoc committed Oct 31, 2023
1 parent 5b2f510 commit 897027a
Show file tree
Hide file tree
Showing 4 changed files with 66 additions and 73 deletions.
31 changes: 13 additions & 18 deletions backend/examples/summa_solvency_flow.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
#![feature(generic_const_exprs)]
use std::{error::Error, fs::File, io::BufReader, io::Write};
use std::{
error::Error,
fs::{remove_file, File},
io::BufReader,
io::Write,
};

use ethers::types::{Bytes, U256};
use ethers::types::U256;
use serde_json::{from_reader, to_string_pretty};

use summa_backend::{
Expand Down Expand Up @@ -103,41 +108,31 @@ async fn main() -> Result<(), Box<dyn Error>> {
let user_name = "dxGaEAii".to_string();
let balances = vec![11888, 41163];

let leaf_hash = public_inputs[0][0];
let leaf_hash = public_inputs[0];
assert_eq!(
leaf_hash,
generate_leaf_hash::<N_ASSETS>(user_name.clone(), balances.clone())
);

// Before verifying `root_hath`, convert type of `proof` and `public_inputs` to the type of `Bytes` and `Vec<U256>`.
let proof: Bytes = Bytes::from(inclusion_proof.get_proof().clone());
let public_inputs: Vec<U256> = inclusion_proof
.get_public_inputs()
.iter()
.flat_map(|input_set| {
input_set.iter().map(|input| {
let mut bytes = input.to_bytes();
bytes.reverse();
U256::from_big_endian(&bytes)
})
})
.collect();

// Get `mst_root` from contract. the `mst_root` is disptached by CEX with specific time `snapshot_time`.
let mst_root = summa_contract.mst_roots(snapshot_time).call().await?;

// Match the `mst_root` with the `root_hash` derived from the proof.
assert_eq!(mst_root, public_inputs[1]);

// Validate the inclusion proof using the contract verifier.
let proof = inclusion_proof.get_proof();
let verification_result = summa_contract
.verify_inclusion_proof(proof, public_inputs, snapshot_time)
.verify_inclusion_proof(proof.clone(), public_inputs.clone(), snapshot_time)
.await?;

println!(
"4. Verifying the proof on contract veirifer for User #{}: {}",
USER_INDEX, verification_result
);

// Wrapping up
remove_file(format!("user_{}_proof.json", USER_INDEX))?;
drop(anvil);
Ok(())
}
31 changes: 21 additions & 10 deletions backend/src/apis/round.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ use halo2_proofs::{
poly::kzg::commitment::ParamsKZG,
};
use serde::{Deserialize, Serialize};
use snark_verifier_sdk::{evm::gen_evm_proof_shplonk, CircuitExt};
use std::error::Error;

use super::csv_parser::parse_asset_csv;
Expand Down Expand Up @@ -46,17 +45,17 @@ impl SolvencyProof {

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MstInclusionProof {
public_inputs: Vec<Vec<Fp>>,
proof: Vec<u8>,
public_inputs: Vec<U256>,
proof_calldata: Bytes,
}

impl MstInclusionProof {
pub fn get_public_inputs(&self) -> &Vec<Vec<Fp>> {
pub fn get_public_inputs(&self) -> &Vec<U256> {
&self.public_inputs
}

pub fn get_proof(&self) -> &Vec<u8> {
&self.proof
pub fn get_proof(&self) -> &Bytes {
&self.proof_calldata
}
}

Expand Down Expand Up @@ -203,16 +202,28 @@ where
MstInclusionCircuit::<LEVELS, N_ASSETS, N_BYTES>::init(self.mst.clone(), user_index);

// Currently, default manner of generating a inclusion proof for solidity-verifier.
let proof = gen_evm_proof_shplonk(
// let proof = gen_evm_proof_shplonk(
// &self.trusted_setup[0].0,
// &self.trusted_setup[0].1,
// circuit.clone(),
// circuit.instances(),
// );

let calldata = gen_proof_solidity_calldata(
&self.trusted_setup[0].0,
&self.trusted_setup[0].1,
circuit.clone(),
circuit.instances(),
);

// println!(
// "proof size in bytes: {:?}",
// Bytes::from(proof.clone()).len()
// );
// println!("proof_calldata size in bytes: {:?}", proof_calldata.0.len());

Ok(MstInclusionProof {
public_inputs: circuit.instances(),
proof,
proof_calldata: calldata.0,
public_inputs: calldata.1,
})
}
}
69 changes: 27 additions & 42 deletions backend/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -102,11 +102,8 @@ pub async fn initialize_test_env() -> (

#[cfg(test)]
mod test {
use ethers::{
abi::AbiEncode,
types::{Bytes, U256},
utils::to_checksum,
};
use ethers::{abi::AbiEncode, types::U256, utils::to_checksum};
use std::error::Error;

use crate::apis::{address_ownership::AddressOwnership, round::Round};
use crate::contracts::generated::summa_contract::{
Expand All @@ -116,7 +113,7 @@ mod test {
use crate::tests::initialize_test_env;

#[tokio::test]
async fn test_round_features() {
async fn test_round_features() -> Result<(), Box<dyn Error>> {
let (anvil, cex_addr_1, cex_addr_2, _, summa_contract) = initialize_test_env().await;

let mut address_ownership_client = AddressOwnership::new(
Expand All @@ -128,21 +125,18 @@ mod test {
)
.unwrap();

let ownership_submitted_result = address_ownership_client
address_ownership_client
.dispatch_proof_of_address_ownership()
.await;

assert!(ownership_submitted_result.is_ok());
.await?;

let logs = summa_contract
let ownership_proof_logs = summa_contract
.address_ownership_proof_submitted_filter()
.query()
.await
.unwrap();
.await?;

assert_eq!(logs.len(), 1);
assert_eq!(ownership_proof_logs.len(), 1);
assert_eq!(
logs[0],
ownership_proof_logs[0],
AddressOwnershipProofSubmittedFilter {
address_ownership_proofs: vec![AddressOwnershipProof {
chain: "ETH".to_string(),
Expand Down Expand Up @@ -179,12 +173,12 @@ mod test {
.unwrap();

// Verify solvency proof
let mut logs = summa_contract
let mut solvency_proof_logs = summa_contract
.solvency_proof_submitted_filter()
.query()
.await
.unwrap();
assert_eq!(logs.len(), 0);
.await?;

assert_eq!(solvency_proof_logs.len(), 0);

// Dispatch solvency proof
let assets = [
Expand All @@ -200,20 +194,19 @@ mod test {
},
];

assert_eq!(round.dispatch_solvency_proof().await.unwrap(), ());
// Send sovlecy proof to contract
round.dispatch_solvency_proof().await?; // .unwrap(), ());
// assert!(result_dispatch_solvency_proof.is_ok());

// After sending transaction of proof of solvency, logs should be updated
logs = summa_contract
solvency_proof_logs = summa_contract
.solvency_proof_submitted_filter()
.query()
.await
.unwrap();

assert_eq!(logs.len(), 1);
.await?;

assert_eq!(logs.len(), 1);
assert_eq!(solvency_proof_logs.len(), 1);
assert_eq!(
logs[0],
solvency_proof_logs[0],
SolvencyProofSubmittedFilter {
timestamp: U256::from(1),
mst_root: "0x2E021D9BF99C5BD7267488B6A7A5CF5F7D00222A41B6A9B971899C44089E0C5"
Expand All @@ -225,27 +218,19 @@ mod test {

// Test inclusion proof
let inclusion_proof = round.get_proof_of_inclusion(0).unwrap();
let proof = Bytes::from(inclusion_proof.get_proof().clone());
let public_inputs: Vec<U256> = inclusion_proof
.get_public_inputs()
.iter()
.flat_map(|input_set| {
input_set.iter().map(|input| {
let mut bytes = input.to_bytes();
bytes.reverse();
U256::from_big_endian(&bytes)
})
})
.collect();

// Verify inclusion proof with onchain function
let verified = summa_contract
.verify_inclusion_proof(proof, public_inputs, U256::from(1))
.await
.unwrap();
.verify_inclusion_proof(
inclusion_proof.get_proof().clone(),
inclusion_proof.get_public_inputs().clone(),
U256::from(1),
)
.await?;

assert_eq!(verified, true);

drop(anvil);
Ok(())
}
}
8 changes: 5 additions & 3 deletions zk_prover/src/merkle_sum_tree/utils/generate_leaf_hash.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
use halo2_proofs::halo2curves::bn256::Fr as Fp;
use ethers::types::U256;
use num_bigint::BigUint;

use crate::merkle_sum_tree::Entry;

pub fn generate_leaf_hash<const N_ASSETS: usize>(user_name: String, balances: Vec<usize>) -> Fp
pub fn generate_leaf_hash<const N_ASSETS: usize>(user_name: String, balances: Vec<usize>) -> U256
where
[usize; N_ASSETS + 1]: Sized,
{
Expand All @@ -13,5 +13,7 @@ where
let entry: Entry<N_ASSETS> =
Entry::new(user_name, balances_big_uint.try_into().unwrap()).unwrap();

entry.compute_leaf().hash
// Convert Fp to U256
let hash_str = format!("{:?}", entry.compute_leaf().hash);
U256::from_str_radix(&hash_str, 16).unwrap()
}

0 comments on commit 897027a

Please sign in to comment.