Skip to content

Commit

Permalink
Changes in accordance with the results of the first round of reviewing.
Browse files Browse the repository at this point in the history
  • Loading branch information
AlekseiVambol committed Dec 23, 2024
1 parent 9bed433 commit 0157ff6
Show file tree
Hide file tree
Showing 7 changed files with 55 additions and 71 deletions.
22 changes: 11 additions & 11 deletions rln-cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ fn main() -> Result<()> {
tree_height,
config,
}) => {
let resources = File::open(&config)?;
let resources = File::open(config)?;
state.rln = Some(RLN::new(*tree_height, resources)?);
Ok(())
}
Expand All @@ -49,7 +49,7 @@ fn main() -> Result<()> {
file.read_exact(&mut buffer)?;
resources.push(buffer);
}
let tree_config_input_file = File::open(&tree_config_input)?;
let tree_config_input_file = File::open(tree_config_input)?;
state.rln = Some(RLN::new_with_params(
*tree_height,
resources[0].clone(),
Expand All @@ -66,31 +66,31 @@ fn main() -> Result<()> {
Ok(())
}
Some(Commands::SetLeaf { index, file }) => {
let input_data = File::open(&file)?;
let input_data = File::open(file)?;
state
.rln
.ok_or(Report::msg("no RLN instance initialized"))?
.set_leaf(*index, input_data)?;
Ok(())
}
Some(Commands::SetMultipleLeaves { index, file }) => {
let input_data = File::open(&file)?;
let input_data = File::open(file)?;
state
.rln
.ok_or(Report::msg("no RLN instance initialized"))?
.set_leaves_from(*index, input_data)?;
Ok(())
}
Some(Commands::ResetMultipleLeaves { file }) => {
let input_data = File::open(&file)?;
let input_data = File::open(file)?;
state
.rln
.ok_or(Report::msg("no RLN instance initialized"))?
.init_tree_with_leaves(input_data)?;
Ok(())
}
Some(Commands::SetNextLeaf { file }) => {
let input_data = File::open(&file)?;
let input_data = File::open(file)?;
state
.rln
.ok_or(Report::msg("no RLN instance initialized"))?
Expand Down Expand Up @@ -121,7 +121,7 @@ fn main() -> Result<()> {
Ok(())
}
Some(Commands::Prove { input }) => {
let input_data = File::open(&input)?;
let input_data = File::open(input)?;
let writer = std::io::stdout();
state
.rln
Expand All @@ -130,15 +130,15 @@ fn main() -> Result<()> {
Ok(())
}
Some(Commands::Verify { file }) => {
let input_data = File::open(&file)?;
let input_data = File::open(file)?;
state
.rln
.ok_or(Report::msg("no RLN instance initialized"))?
.verify(input_data)?;
Ok(())
}
Some(Commands::GenerateProof { input }) => {
let input_data = File::open(&input)?;
let input_data = File::open(input)?;
let writer = std::io::stdout();
state
.rln
Expand All @@ -147,8 +147,8 @@ fn main() -> Result<()> {
Ok(())
}
Some(Commands::VerifyWithRoots { input, roots }) => {
let input_data = File::open(&input)?;
let roots_data = File::open(&roots)?;
let input_data = File::open(input)?;
let roots_data = File::open(roots)?;
state
.rln
.ok_or(Report::msg("no RLN instance initialized"))?
Expand Down
14 changes: 7 additions & 7 deletions rln/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,18 +12,18 @@ git clone https://github.com/vacp2p/zerokit.git
cd zerokit/rln
```

### ~~Build and Test~~
### Build and Test

~~To build and test, run the following commands within the module folder~~
To build and test, run the following commands within the module folder

``` bash
cargo make build
cargo make test
```
### Currently the tests are run as follows:
``` bash
cargo make test_default
cargo make test_**mode**
```
The **mode** placeholder should be replaced with
* **default** for the default tests;
* **arkzkey** for the tests with the arkzkey feature;
* **stateless** for the tests with the stateless feature.

### Compile ZK circuits

Expand Down
Binary file added rln/resources/tree_height_20/rln.wasm
Binary file not shown.
3 changes: 0 additions & 3 deletions rln/src/iden3calc.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,3 @@
#![allow(non_upper_case_globals)]
#![allow(non_camel_case_types)]
#![allow(non_snake_case)]
pub mod graph;
pub mod proto;
pub mod storage;
Expand Down
79 changes: 33 additions & 46 deletions rln/src/iden3calc/graph.rs
Original file line number Diff line number Diff line change
Expand Up @@ -410,7 +410,7 @@ pub fn evaluate(nodes: &[Node], inputs: &[U256], outputs: &[usize]) -> Vec<Fr> {

// Evaluate the graph.
let mut values = Vec::with_capacity(nodes.len());
for (_, &node) in nodes.iter().enumerate() {
for &node in nodes.iter() {
let value = match node {
Node::Constant(c) => Fr::new(c.into()),
Node::MontConstant(c) => c,
Expand All @@ -434,12 +434,10 @@ pub fn evaluate(nodes: &[Node], inputs: &[U256], outputs: &[usize]) -> Vec<Fr> {
/// Constant propagation
pub fn propagate(nodes: &mut [Node]) {
assert_valid(nodes);
let mut constants = 0_usize;
for i in 0..nodes.len() {
if let Node::Op(op, a, b) = nodes[i] {
if let (Node::Constant(va), Node::Constant(vb)) = (nodes[a], nodes[b]) {
nodes[i] = Node::Constant(op.eval(va, vb));
constants += 1;
} else if a == b {
// Not constant but equal
use Operation::*;
Expand All @@ -449,25 +447,20 @@ pub fn propagate(nodes: &mut [Node]) {
_ => None,
} {
nodes[i] = Node::Constant(U256::from(c));
constants += 1;
}
}
} else if let Node::UnoOp(op, a) = nodes[i] {
if let Node::Constant(va) = nodes[a] {
nodes[i] = Node::Constant(op.eval(va));
constants += 1;
}
} else if let Node::TresOp(op, a, b, c) = nodes[i] {
if let (Node::Constant(va), Node::Constant(vb), Node::Constant(vc)) =
(nodes[a], nodes[b], nodes[c])
{
nodes[i] = Node::Constant(op.eval(va, vb, vc));
constants += 1;
}
}
}

eprintln!("Propagated {constants} constants");
}

/// Remove unused nodes
Expand Down Expand Up @@ -502,7 +495,6 @@ pub fn tree_shake(nodes: &mut Vec<Node>, outputs: &mut [usize]) {
let n = nodes.len();
let mut retain = used.iter();
nodes.retain(|_| *retain.next().unwrap());
let removed = n - nodes.len();

// Renumber references.
let mut renumber = vec![None; n];
Expand Down Expand Up @@ -536,12 +528,10 @@ pub fn tree_shake(nodes: &mut Vec<Node>, outputs: &mut [usize]) {
for output in outputs.iter_mut() {
*output = renumber[*output].unwrap();
}

eprintln!("Removed {removed} unused nodes");
}

/// Randomly evaluate the graph
fn random_eval(nodes: &mut Vec<Node>) -> Vec<U256> {
fn random_eval(nodes: &mut [Node]) -> Vec<U256> {
let mut rng = rand::thread_rng();
let mut values = Vec::with_capacity(nodes.len());
let mut inputs = HashMap::new();
Expand Down Expand Up @@ -580,7 +570,7 @@ fn random_eval(nodes: &mut Vec<Node>) -> Vec<U256> {
}

/// Value numbering
pub fn value_numbering(nodes: &mut Vec<Node>, outputs: &mut [usize]) {
pub fn value_numbering(nodes: &mut [Node], outputs: &mut [usize]) {
assert_valid(nodes);

// Evaluate the graph in random field elements.
Expand All @@ -593,10 +583,7 @@ pub fn value_numbering(nodes: &mut Vec<Node>, outputs: &mut [usize]) {
}

// For nodes that are the same, pick the first index.
let mut renumber = Vec::with_capacity(nodes.len());
for value in values {
renumber.push(value_map[&value][0]);
}
let renumber: Vec<_> = values.into_iter().map(|v| value_map[&v][0]).collect();

// Renumber references.
for node in nodes.iter_mut() {
Expand All @@ -616,30 +603,25 @@ pub fn value_numbering(nodes: &mut Vec<Node>, outputs: &mut [usize]) {
for output in outputs.iter_mut() {
*output = renumber[*output];
}

eprintln!("Global value numbering applied");
}

/// Probabilistic constant determination
pub fn constants(nodes: &mut Vec<Node>) {
pub fn constants(nodes: &mut [Node]) {
assert_valid(nodes);

// Evaluate the graph in random field elements.
let values_a = random_eval(nodes);
let values_b = random_eval(nodes);

// Find all nodes with the same value.
let mut constants = 0;
for i in 0..nodes.len() {
if let Node::Constant(_) = nodes[i] {
continue;
}
if values_a[i] == values_b[i] {
nodes[i] = Node::Constant(values_a[i]);
constants += 1;
}
}
eprintln!("Found {} constants", constants);
}

/// Convert to Montgomery form
Expand All @@ -662,7 +644,6 @@ pub fn montgomery_form(nodes: &mut [Node]) {
TresOp(TresOperation::TernCond, ..) => (),
}
}
eprintln!("Converted to Montgomery form");
}

fn shl(a: Fr, b: Fr) -> Fr {
Expand All @@ -678,7 +659,7 @@ fn shl(a: Fr, b: Fr) -> Fr {

let mut a = a.into_bigint();
a.muln(n);
return Fr::from_bigint(a).unwrap();
Fr::from_bigint(a).unwrap()
}

fn shr(a: Fr, b: Fr) -> Fr {
Expand Down Expand Up @@ -721,10 +702,12 @@ fn shr(a: Fr, b: Fr) -> Fr {
fn bit_and(a: Fr, b: Fr) -> Fr {
let a = a.into_bigint();
let b = b.into_bigint();
let mut c: [u64; 4] = [0; 4];
for i in 0..4 {
c[i] = a.0[i] & b.0[i];
}
let c: [u64; 4] = [
a.0[0] & b.0[0],
a.0[1] & b.0[1],
a.0[2] & b.0[2],
a.0[3] & b.0[3],
];
let mut d: BigInt<4> = BigInt::new(c);
if d > Fr::MODULUS {
d.sub_with_borrow(&Fr::MODULUS);
Expand All @@ -736,10 +719,12 @@ fn bit_and(a: Fr, b: Fr) -> Fr {
fn bit_or(a: Fr, b: Fr) -> Fr {
let a = a.into_bigint();
let b = b.into_bigint();
let mut c: [u64; 4] = [0; 4];
for i in 0..4 {
c[i] = a.0[i] | b.0[i];
}
let c: [u64; 4] = [
a.0[0] | b.0[0],
a.0[1] | b.0[1],
a.0[2] | b.0[2],
a.0[3] | b.0[3],
];
let mut d: BigInt<4> = BigInt::new(c);
if d > Fr::MODULUS {
d.sub_with_borrow(&Fr::MODULUS);
Expand All @@ -751,10 +736,12 @@ fn bit_or(a: Fr, b: Fr) -> Fr {
fn bit_xor(a: Fr, b: Fr) -> Fr {
let a = a.into_bigint();
let b = b.into_bigint();
let mut c: [u64; 4] = [0; 4];
for i in 0..4 {
c[i] = a.0[i] ^ b.0[i];
}
let c: [u64; 4] = [
a.0[0] ^ b.0[0],
a.0[1] ^ b.0[1],
a.0[2] ^ b.0[2],
a.0[3] ^ b.0[3],
];
let mut d: BigInt<4> = BigInt::new(c);
if d > Fr::MODULUS {
d.sub_with_borrow(&Fr::MODULUS);
Expand All @@ -764,12 +751,12 @@ fn bit_xor(a: Fr, b: Fr) -> Fr {
}

// M / 2
const halfM: U256 =
const HALF_M: U256 =
uint!(10944121435919637611123202872628637544274182200208017171849102093287904247808_U256);

fn u_gte(a: &U256, b: &U256) -> U256 {
let a_neg = &halfM < a;
let b_neg = &halfM < b;
let a_neg = &HALF_M < a;
let b_neg = &HALF_M < b;

match (a_neg, b_neg) {
(false, false) => U256::from(a >= b),
Expand All @@ -780,8 +767,8 @@ fn u_gte(a: &U256, b: &U256) -> U256 {
}

fn u_lte(a: &U256, b: &U256) -> U256 {
let a_neg = &halfM < a;
let b_neg = &halfM < b;
let a_neg = &HALF_M < a;
let b_neg = &HALF_M < b;

match (a_neg, b_neg) {
(false, false) => U256::from(a <= b),
Expand All @@ -792,8 +779,8 @@ fn u_lte(a: &U256, b: &U256) -> U256 {
}

fn u_gt(a: &U256, b: &U256) -> U256 {
let a_neg = &halfM < a;
let b_neg = &halfM < b;
let a_neg = &HALF_M < a;
let b_neg = &HALF_M < b;

match (a_neg, b_neg) {
(false, false) => U256::from(a > b),
Expand All @@ -804,8 +791,8 @@ fn u_gt(a: &U256, b: &U256) -> U256 {
}

fn u_lt(a: &U256, b: &U256) -> U256 {
let a_neg = &halfM < a;
let b_neg = &halfM < b;
let a_neg = &HALF_M < a;
let b_neg = &HALF_M < b;

match (a_neg, b_neg) {
(false, false) => U256::from(a < b),
Expand Down
2 changes: 1 addition & 1 deletion rln/src/iden3calc/storage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,7 @@ impl From<proto::TresOp> for graph::TresOperation {
pub fn serialize_witnesscalc_graph<T: Write>(
mut w: T,
nodes: &Vec<graph::Node>,
witness_signals: &Vec<usize>,
witness_signals: &[usize],
input_signals: &InputSignalsInfo,
) -> std::io::Result<()> {
let mut ptr = 0usize;
Expand Down
6 changes: 3 additions & 3 deletions rln/src/public.rs
Original file line number Diff line number Diff line change
Expand Up @@ -148,14 +148,14 @@ impl RLN {
/// resources.push(buffer);
/// }
///
/// let tree_config = "{}".to_string();
/// let mut tree_config_input = Buffer::from(tree_config.as_bytes());
/// let tree_config = "".to_string();
/// let tree_config_buffer = &Buffer::from(tree_config.as_bytes());
///
/// let mut rln = RLN::new_with_params(
/// tree_height,
/// resources[0].clone(),
/// resources[1].clone(),
/// tree_config_input,
/// tree_config_buffer,
/// );
/// ```
#[cfg(all(not(target_arch = "wasm32"), not(feature = "stateless")))]
Expand Down

0 comments on commit 0157ff6

Please sign in to comment.