Skip to content

Commit

Permalink
feat: create all examples; modified generating inclusion proof fn in …
Browse files Browse the repository at this point in the history
…the Round
  • Loading branch information
sifnoc committed Sep 19, 2023
1 parent 631512d commit c7fd5d5
Show file tree
Hide file tree
Showing 14 changed files with 372 additions and 247 deletions.
4 changes: 0 additions & 4 deletions backend/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,3 @@ bincode = "1.3.3"

[build-dependencies]
ethers = { version = "2.0.7", default-features = false, features = ["ethers-solc"] }

[[example]]
name = "generate_signatures"
path = "examples/generate_signatures/main.rs"
54 changes: 54 additions & 0 deletions backend/examples/generate_inclusion.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
#![feature(generic_const_exprs)]
use serde_json::{json, to_writer};
use std::fs;
use summa_backend::{apis::round::Round, tests::initialize_test_env};

const USER_INDEX: usize = 0;

#[tokio::main]
async fn main() {
// Initialize test environment
let (anvil, _, _, _, summa_contract, mut address_ownership_client) =
initialize_test_env().await;

address_ownership_client
.dispatch_proof_of_address_ownership()
.await
.unwrap();

// Initialize `Round` for submitting proof of solvency.
let asset_csv = "src/apis/csv/assets.csv";
let entry_csv = "../zk_prover/src/merkle_sum_tree/csv/entry_16.csv";
let params_path = "ptau/hermez-raw-11";

let mut round = Round::<4, 2, 14>::new(
"0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80", // anvil account [0]
anvil.chain_id(),
anvil.endpoint().as_str(),
summa_contract.address(),
entry_csv,
asset_csv,
params_path,
1,
)
.unwrap();

// Before generating inclusion proof, CEX must dispatch proof of solvency for updating the root of merkle sum tree.
// Without that, the user may not trust your `root_hash` in the inclusion proof because it is not published on-chain.
round.dispatch_solvency_proof().await.unwrap();

let inclusion_proof = round.get_proof_of_inclusion(USER_INDEX).unwrap();
let public_input_vec = inclusion_proof.get_public_inputs();

let output = json!({
"proof": serde_json::to_string(&inclusion_proof.get_proof()).unwrap(),
"leaf_hash": serde_json::to_string(&public_input_vec[0][0]).unwrap(),
"root_hash": serde_json::to_string(&public_input_vec[0][1]).unwrap()
});

let file =
fs::File::create(format!("user_{}_proof.json", USER_INDEX)).expect("Unable to create file");
to_writer(file, &output).expect("Failed to write JSON to file");

println!("Exported proof to user_{}_proof.json", USER_INDEX);
}
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
#![feature(generic_const_exprs)]
use std::{error::Error, fs::File};

use csv::WriterBuilder;

mod message_signer;
use message_signer::sign_message;
mod mock_signer;
use mock_signer::sign_message;

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
Expand All @@ -23,6 +24,7 @@ async fn main() -> Result<(), Box<dyn Error>> {
}

wtr.flush()?; // This will ensure all bytes are written
println!("Successfully exported signatures to {}", path);

Ok(())
}
25 changes: 25 additions & 0 deletions backend/examples/helpers/inclusion_proof.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
use halo2_proofs::halo2curves::bn256::Fr as Fp;
use num_bigint::BigUint;
use serde::Deserialize;

use summa_solvency::merkle_sum_tree::Entry;

#[derive(Debug, Deserialize)]
pub struct InclusionProof {
pub leaf_hash: String,
pub root_hash: String,
pub proof: String,
}

pub fn generate_leaf_hash<const N_ASSETS: usize>(user_name: String, balances: Vec<usize>) -> Fp
where
[usize; N_ASSETS + 1]: Sized,
{
// Convert usize to BigInt for the `Entry` struct
let balances_big_uint: Vec<BigUint> = balances.into_iter().map(BigUint::from).collect();

let entry: Entry<N_ASSETS> =
Entry::new(user_name, balances_big_uint.try_into().unwrap()).unwrap();

entry.compute_leaf().hash
}
1 change: 1 addition & 0 deletions backend/examples/helpers/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
pub mod inclusion_proof;
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ use ethers::{

use summa_backend::apis::csv_parser::SignatureRecord;

// Separated this function from the `generate_signatures.rs` for clarity on the example.
pub async fn sign_message(message: &str) -> Result<Vec<SignatureRecord>, Box<dyn Error>> {
// Using private keys directly is insecure.
// Instead, consider leveraging hardware wallet support.
Expand Down
26 changes: 6 additions & 20 deletions backend/examples/submit_ownership.rs
Original file line number Diff line number Diff line change
@@ -1,36 +1,22 @@
use std::sync::Arc;

use ethers::{
abi::{encode, Token},
types::{Address, U256},
types::U256,
utils::keccak256,
};

use summa_backend::{
apis::address_ownership::AddressOwnership, contracts::generated::summa_contract::Summa,
tests::initialize_anvil,
};
use summa_backend::{apis::address_ownership::AddressOwnership, tests::initialize_test_env};

// In this example, we will demonstrate how to submit ownership of address to the Summa contract.
#[tokio::main]
async fn main() {
// We have already demonstrated how to generate a CSV file containing the asset ownership proofs, `AddressOwnershipProof`.
// For more details on this, kindly refer to the "generate_signature" example.
//
// For the current demonstration, we'll use the same CSV file produced in `generate_signature` example.
let signature_csv_path = "src/apis/csv/signatures.csv";

// Initialize test environment
let (anvil, _, _, client, _) = initialize_anvil().await;
// Initialize test environment without `address_ownership` instance from `initialize_test_env` function.
let (anvil, _, _, _, summa_contract, _) = initialize_test_env().await;

// Deploy contracts with null addresses for verifier contracts for this example
let summa_contract = Summa::deploy(Arc::clone(&client), (Address::zero(), Address::zero()))
.unwrap()
.send()
.await
.unwrap();

// Initialize `AddressOwnership` client
// For the current demonstration, we'll use the same CSV file produced in `generate_signature` example.
let signature_csv_path = "src/apis/csv/signatures.csv";
let mut address_ownership_client = AddressOwnership::new(
"0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80",
anvil.chain_id(),
Expand Down
56 changes: 10 additions & 46 deletions backend/examples/submit_solvency.rs
Original file line number Diff line number Diff line change
@@ -1,47 +1,11 @@
#![feature(generic_const_exprs)]
use std::sync::Arc;

use ethers::{types::Address, utils::keccak256};

use summa_backend::{
apis::{address_ownership::AddressOwnership, round::Round},
contracts::generated::{solvency_verifier::SolvencyVerifier, summa_contract::Summa},
tests::initialize_anvil,
};
use summa_backend::{apis::round::Round, tests::initialize_test_env};

#[tokio::main]
async fn main() {
// Initialize test environment
let (anvil, _, _, client, _) = initialize_anvil().await;

// In this case, We have to deploy Solvency verifier contract first and then deploy Summa contract.
let solvency_verifer_contract = SolvencyVerifier::deploy(Arc::clone(&client), ())
.unwrap()
.send()
.await
.unwrap();

// We will not use Inclusion verifier contract in this example,
// so we will set null address for the inclusion verifier contract.
let summa_contract = Summa::deploy(
Arc::clone(&client),
(solvency_verifer_contract.address(), Address::zero()),
)
.unwrap()
.send()
.await
.unwrap();

// Initialize `Solvency` client for submitting proof of solvency.
// To verify proof of solvency on the contract, at least one ownership address must be registered on the contract.
let mut address_ownership_client = AddressOwnership::new(
"0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80",
anvil.chain_id(),
anvil.endpoint().as_str(),
summa_contract.address(),
"src/apis/csv/signatures.csv",
)
.unwrap();
let (anvil, _, _, _, summa_contract, mut address_ownership_client) =
initialize_test_env().await;

address_ownership_client
.dispatch_proof_of_address_ownership()
Expand All @@ -65,14 +29,14 @@ async fn main() {
)
.unwrap();

round.dispatch_solvency_proof().await.unwrap();
assert_eq!(round.dispatch_solvency_proof().await.unwrap(), ());

let log = summa_contract
.solvency_proof_submitted_filter()
.query()
.await
.unwrap();
println!("{:?}", log);
// You can also use the `solvency_proof_submitted_filter` method to check if the solvency proof is submitted.
// println!("{:?}", summa_contract
// .solvency_proof_submitted_filter()
// .query()
// .await
// .unwrap(););

println!("Solvency proof is submitted successfully!")
}
105 changes: 0 additions & 105 deletions backend/examples/verify_inclusion.rs

This file was deleted.

Loading

0 comments on commit c7fd5d5

Please sign in to comment.