Compare commits

...

16 Commits

Author SHA1 Message Date
vinhtc27
ae96766b09 chore: cleanup Cargo.lock 2026-01-06 22:24:47 +07:00
vinhtc27
b6d017e22e chore: cleanup Cargo.lock 2026-01-06 22:24:31 +07:00
Ekaterina Broslavskaya
2071346174 Release v1.0.0 (#361) 2025-12-18 13:55:37 +03:00
Vinh Trịnh
c0769395bd feat(rln-wasm): seperate rln wasm parallel package (#360) 2025-12-18 16:48:10 +07:00
Vinh Trịnh
2fc079d633 fix(ci): nightly build failed due to import paths for zerokit_utils::merkle_tree in poseidon_tree.rs file (#359) 2025-12-18 12:38:27 +07:00
Vinh Trịnh
0ebeea50fd feat(rln): extend error handling for rln module (#358)
Changes:
- Unified error types (`PoseidonError`, `HashError`, etc.) across
hashing, keygen, witness calculation, and serialization for consistent
and descriptive error handling.
- Refactored tests and examples to use `unwrap()` where safe, and
limited `expect()` in library code to non-panicking cases with clear
messaging.
- Improved witness and proof generation by removing panicking code paths
and enforcing proper error propagation.
- Cleaned up outdated imports, removed unused operations in `graph.rs`,
and updated public API documentation.
- Updated C, Nim, and WASM FFI bindings with more robust serialization
and clearer error log messages.
- Added keywords to package.json and update dependencies in
Makefile.toml and Nightly CI.
2025-12-17 19:27:07 +07:00
Vinh Trịnh
c890bc83ad fix(ci): nightly build failed due to incorrect config flag for pm_tree_adapter (#357)
Success build:
https://github.com/vacp2p/zerokit/actions/runs/20063084959
https://github.com/vacp2p/zerokit/actions/runs/20063354977
2025-12-09 19:40:14 +07:00
Vinh Trịnh
77a8d28965 feat: unify RLN types, refactor public APIs, add full (de)serialization, align FFI/WASM/APIs, simplify errors, update docs/examples, and clean up zerokit (#355)
# Changes

- Unified the `RLN` struct and core protocol types across public, FFI,
and WASM so everything works consistently.
- Fully refactored `protocol.rs` and `public.rs` to clean up the API
surface and make the flow easier to work with.
- Added (de)serialization for `RLN_Proof` and `RLN_ProofValues`, and
matched all C, Nim, WASM, and Node.js examples.
- Aligned FFI and WASM behavior, added missing APIs, and standardized
how witness are created and passed around.
- Reworked the error types, added clearer verification messages, and
simplified the overall error structure.
- Updated variable names, README, Rust docs, and examples across the
repo, updated outdated RLN RFC link.
- Refactored `rln-cli` to use the new public API, removed
serialize-based cli example, and dropped the `eyre` crate.
- Bumped dependencies, fixed CI, fixed `+atomic` flags for latest
nightly Rust and added `Clippy.toml` for better fmt.
- Added a `prelude.rs` file for easier use, cleaned up public access for
types and types import across zerokit modules.
- Separated keygen, proof handling, slashing logic, and witness into
protocol folder.
2025-12-09 19:03:04 +07:00
Vinh Trịnh
5c73af1130 feat(wasm): rework rln-wasm and rln-wasm-utils modules, remove buffer-based serialization, and update public.rs and protocol.rs accordingly (#352) 2025-12-01 17:33:46 +07:00
Vinh Trịnh
c74ab11c82 fix(rln): resolve memory leak in calc_witness and improve FFI memory deallocation pattern (#354) 2025-11-20 17:27:52 +07:00
Sydhds
a52cf84f46 feat(rln): rework FFI module with new functional APIs and remove buffer-based serialization (#337)
Co-authored-by: vinhtc27 <vinhtc27@gmail.com>
Co-authored-by: seemenkina <seemenkina@gmail.com>
Co-authored-by: sydhds < sydhds@gmail.com>
2025-11-05 23:51:49 +07:00
Jakub Sokołowski
3160d9504d nix: add our own binary cache to flake
Signed-off-by: Jakub Sokołowski <jakub@status.im>
2025-11-04 00:11:44 +01:00
Jakub Sokołowski
0b30ba112f nix: bump nixpkgs to same commit as status-go
Signed-off-by: Jakub Sokołowski <jakub@status.im>
2025-11-04 00:11:41 +01:00
Sydhds
a2f9aaeeee Set ruint dependency with fewer features (#349)
Use only the required features for ruint dependency.
2025-10-31 17:12:52 +01:00
Vinh Trịnh
a198960cf3 chore: use rust nightly-2025-09-24 until patch version release (#351)
To avoid CI blocking other PR's CI:
+ https://github.com/vacp2p/zerokit/pull/337
+ https://github.com/vacp2p/zerokit/pull/346
+ https://github.com/vacp2p/zerokit/pull/349
2025-10-31 22:07:10 +07:00
Sydhds
7f6f66bb13 Update zerokit-utils to version 0.7.0 in utils/README.md file (#348) 2025-10-21 10:24:44 +02:00
107 changed files with 12907 additions and 9011 deletions

View File

@@ -9,7 +9,6 @@ on:
- "!rln/src/**"
- "!rln/resources/**"
- "!utils/src/**"
- "!rln-wasm-utils/**"
pull_request:
types: [opened, synchronize, reopened, ready_for_review]
paths-ignore:
@@ -19,7 +18,6 @@ on:
- "!rln/src/**"
- "!rln/resources/**"
- "!utils/src/**"
- "!rln-wasm-utils/**"
name: CI
@@ -135,36 +133,14 @@ jobs:
run: cargo make test_parallel --release
working-directory: ${{ matrix.crate }}
rln-wasm-utils-test:
# skip tests on draft PRs
if: github.event_name == 'push' || (github.event_name == 'pull_request' && !github.event.pull_request.draft)
strategy:
matrix:
platform: [ubuntu-latest, macos-latest]
crate: [rln-wasm-utils]
runs-on: ${{ matrix.platform }}
timeout-minutes: 60
name: Test - ${{ matrix.crate }} - ${{ matrix.platform }}
steps:
- uses: actions/checkout@v4
- name: Install stable toolchain
uses: dtolnay/rust-toolchain@stable
- uses: Swatinem/rust-cache@v2
- name: Install dependencies
run: make installdeps
- name: Test rln-wasm-utils
run: cargo make test --release
working-directory: ${{ matrix.crate }}
lint:
# run on both ready and draft PRs
if: github.event_name == 'push' || (github.event_name == 'pull_request' && !github.event.pull_request.draft)
strategy:
matrix:
# we run lint tests only on ubuntu
# run lint tests only on ubuntu
platform: [ubuntu-latest]
crate: [rln, rln-wasm, rln-wasm-utils, utils]
crate: [rln, rln-wasm, utils]
runs-on: ${{ matrix.platform }}
timeout-minutes: 60
@@ -176,6 +152,9 @@ jobs:
uses: dtolnay/rust-toolchain@stable
with:
components: rustfmt, clippy
- name: Install wasm32 target
if: matrix.crate == 'rln-wasm'
run: rustup target add wasm32-unknown-unknown
- uses: Swatinem/rust-cache@v2
- name: Install dependencies
run: make installdeps
@@ -183,18 +162,27 @@ jobs:
if: success() || failure()
run: cargo fmt -- --check
working-directory: ${{ matrix.crate }}
- name: Check clippy
if: success() || failure()
- name: Check clippy wasm target
if: (success() || failure()) && (matrix.crate == 'rln-wasm')
run: |
cargo clippy --all-targets --release -- -D warnings
cargo clippy --target wasm32-unknown-unknown --tests --release -- -D warnings
working-directory: ${{ matrix.crate }}
- name: Check clippy default feature
if: (success() || failure()) && (matrix.crate != 'rln-wasm')
run: |
cargo clippy --all-targets --tests --release -- -D warnings
- name: Check clippy stateless feature
if: (success() || failure()) && (matrix.crate == 'rln')
run: |
cargo clippy --all-targets --tests --release --features=stateless --no-default-features -- -D warnings
working-directory: ${{ matrix.crate }}
benchmark-utils:
# run only on ready pull requests
# run only on ready PRs
if: github.event_name == 'pull_request' && !github.event.pull_request.draft
strategy:
matrix:
# we run benchmark tests only on ubuntu
# run benchmark tests only on ubuntu
platform: [ubuntu-latest]
crate: [utils]
runs-on: ${{ matrix.platform }}
@@ -211,11 +199,11 @@ jobs:
cwd: ${{ matrix.crate }}
benchmark-rln:
# run only on ready pull requests
# run only on ready PRs
if: github.event_name == 'pull_request' && !github.event.pull_request.draft
strategy:
matrix:
# we run benchmark tests only on ubuntu
# run benchmark tests only on ubuntu
platform: [ubuntu-latest]
crate: [rln]
feature: ["default"]

View File

@@ -97,6 +97,7 @@ jobs:
feature:
- "default"
- "parallel"
- "utils"
steps:
- name: Checkout sources
uses: actions/checkout@v4
@@ -114,18 +115,21 @@ jobs:
run: make installdeps
- name: Build rln-wasm package
run: |
if [[ ${{ matrix.feature }} == *parallel* ]]; then
env RUSTFLAGS="-C target-feature=+atomics,+bulk-memory,+mutable-globals" \
if [[ ${{ matrix.feature }} == "parallel" ]]; then
env CARGO_TARGET_WASM32_UNKNOWN_UNKNOWN_RUSTFLAGS="-C target-feature=+atomics,+bulk-memory,+mutable-globals -C link-arg=--shared-memory -C link-arg=--max-memory=1073741824 -C link-arg=--import-memory -C link-arg=--export=__wasm_init_tls -C link-arg=--export=__tls_size -C link-arg=--export=__tls_align -C link-arg=--export=__tls_base" \
rustup run nightly wasm-pack build --release --target web --scope waku \
--features ${{ matrix.feature }} -Z build-std=panic_abort,std
--features parallel -Z build-std=panic_abort,std
sed -i.bak 's/rln-wasm/zerokit-rln-wasm-parallel/g' pkg/package.json && rm pkg/package.json.bak
elif [[ ${{ matrix.feature }} == "utils" ]]; then
wasm-pack build --release --target web --scope waku --no-default-features --features utils
sed -i.bak 's/rln-wasm/zerokit-rln-wasm-utils/g' pkg/package.json && rm pkg/package.json.bak
else
wasm-pack build --release --target web --scope waku
sed -i.bak 's/rln-wasm/zerokit-rln-wasm/g' pkg/package.json && rm pkg/package.json.bak
fi
sed -i.bak 's/rln-wasm/zerokit-rln-wasm/g' pkg/package.json && rm pkg/package.json.bak
wasm-opt pkg/rln_wasm_bg.wasm -Oz --strip-debug --strip-dwarf \
--remove-unused-module-elements --vacuum -o pkg/rln_wasm_bg.wasm
jq '. + {keywords: ["zerokit", "rln", "wasm"]}' pkg/package.json > pkg/package.json.tmp && \
mv pkg/package.json.tmp pkg/package.json
mkdir release
cp -r pkg/* release/
@@ -138,42 +142,9 @@ jobs:
path: rln-wasm/rln-wasm-${{ matrix.feature }}.tar.gz
retention-days: 2
rln-wasm-utils:
name: Build rln-wasm-utils
runs-on: ubuntu-latest
steps:
- name: Checkout sources
uses: actions/checkout@v4
- name: Install stable toolchain
uses: dtolnay/rust-toolchain@stable
with:
targets: wasm32-unknown-unknown
- uses: Swatinem/rust-cache@v2
- name: Install dependencies
run: make installdeps
- name: Build rln-wasm-utils package
run: |
wasm-pack build --release --target web --scope waku
sed -i.bak 's/rln-wasm-utils/zerokit-rln-wasm-utils/g' pkg/package.json && rm pkg/package.json.bak
wasm-opt pkg/rln_wasm_utils_bg.wasm -Oz --strip-debug --strip-dwarf \
--remove-unused-module-elements --vacuum -o pkg/rln_wasm_utils_bg.wasm
mkdir release
cp -r pkg/* release/
tar -czvf rln-wasm-utils.tar.gz release/
working-directory: rln-wasm-utils
- name: Upload archive artifact
uses: actions/upload-artifact@v4
with:
name: rln-wasm-utils-archive
path: rln-wasm-utils/rln-wasm-utils.tar.gz
retention-days: 2
prepare-prerelease:
name: Prepare pre-release
needs: [linux, macos, rln-wasm, rln-wasm-utils]
needs: [linux, macos, rln-wasm]
runs-on: ubuntu-latest
steps:
- name: Checkout code

15
.gitignore vendored
View File

@@ -7,9 +7,6 @@ tmp/
# Generated by Cargo will have compiled files and executables
/target
# Generated by rln-cli
rln-cli/database
# Generated by Nix
result
@@ -18,3 +15,15 @@ result
# MSVC Windows builds of rustc generate these, which store debugging information
*.pdb
# FFI C examples
rln/ffi_c_examples/main
rln/ffi_c_examples/rln.h
rln/ffi_c_examples/database
# FFI Nim examples
rln/ffi_nim_examples/main
rln/ffi_nim_examples/database
# Vscode
.vscode

View File

@@ -1,29 +0,0 @@
# CHANGE LOG
## 2023-02-28 v0.2
This release contains:
- Improved code quality
- Allows consumers of zerokit RLN to set leaves to the Merkle Tree from an arbitrary index. Useful for batching updates to the Merkle Tree.
- Improved performance for proof generation and verification
- rln_wasm which allows for the consumption of RLN through a WebAssembly interface
- Refactored to generate Semaphore-compatible credentials
- Dual License under Apache 2.0 and MIT
- RLN compiles as a static library, which can be consumed through a C FFI
## 2022-09-19 v0.1
Initial beta release.
This release contains:
- RLN Module with API to manage, compute and verify [RLN](https://rfc.vac.dev/spec/32/) zkSNARK proofs and RLN primitives.
- This can be consumed either as a Rust API or as a C FFI. The latter means it can be easily consumed through other environments, such as [Go](https://github.com/status-im/go-zerokit-rln/blob/master/rln/librln.h) or [Nim](https://github.com/status-im/nwaku/blob/4745c7872c69b5fd5c6ddab36df9c5c3d55f57c3/waku/v2/protocol/waku_rln_relay/waku_rln_relay_types.nim).
It also contains the following examples and experiments:
- Basic [example wrapper](https://github.com/vacp2p/zerokit/tree/master/multiplier) around a simple Circom circuit to show Circom integration through ark-circom and FFI.
- Experimental [Semaphore wrapper](https://github.com/vacp2p/zerokit/tree/master/semaphore).
Feedback welcome! You can either [open an issue](https://github.com/vacp2p/zerokit/issues) or come talk to us in our [Vac Discord](https://discord.gg/PQFdubGt6d) #zerokit channel.

View File

@@ -13,7 +13,7 @@ Following these guidelines definitely helps us in accepting your contributions.
2. Create a feature branch: `git checkout -b fix/your-bug-fix` or `git checkout -b feat/your-feature-name`
3. Make your changes following our guidelines
4. Ensure relevant tests pass (see [testing guidelines](#building-and-testing))
5. Commit your changes (signed commits are highly encouraged - see [commit guidelines](#commits))
5. Commit your changes (signed commits are highly encouraged - see [commit guidelines](#commits))
6. Push and create a Pull Request
## Development Setup
@@ -47,13 +47,6 @@ cd rln-wasm && cargo make test_browser # Test in browser headless mode
cd rln-wasm && cargo make test_parallel # Test parallel features
```
Choose the appropriate test commands based on your changes:
- Core RLN changes: `make test`
- Stateless features: `cargo make test_stateless`
- WASM/browser features: `cargo make test_browser`
- Parallel computation: `cargo make test_parallel`
### Tools
We recommend using the [markdownlint extension](https://marketplace.visualstudio.com/items?itemName=DavidAnson.vscode-markdownlint)
@@ -107,7 +100,6 @@ Use scopes to improve the Changelog:
- `rln` - Core RLN implementation
- `rln-cli` - Command-line interface
- `rln-wasm` - WebAssembly bindings
- `rln-wasm-utils` - WebAssembly utilities
- `utils` - Cryptographic utilities (Merkle trees, Poseidon hash)
- `ci` - Continuous integration
@@ -186,7 +178,7 @@ chore(ci): update rust toolchain version
## Roadmap Alignment
Please refer to our [project roadmap](https://roadmap.vac.dev/) for current development priorities.
Consider how your changes align with these strategic goals, when contributing.
Consider how your changes align with these strategic goals when contributing.
## Getting Help

981
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,10 +1,10 @@
[workspace]
members = ["rln", "utils"]
exclude = ["rln-cli", "rln-wasm", "rln-wasm-utils"]
exclude = ["rln-cli", "rln-wasm"]
resolver = "2"
# Compilation profile for any non-workspace member.
# Dependencies are optimized, even in a dev build. This improves dev performance
# while having neglible impact on incremental build times.
# Dependencies are optimized, even in a dev build.
# This improves dev performance while having negligible impact on incremental build times.
[profile.dev.package."*"]
opt-level = 3

View File

@@ -13,12 +13,13 @@ endif
installdeps: .pre-build
ifeq ($(shell uname),Darwin)
@brew install ninja binaryen
@brew install ninja
else ifeq ($(shell uname),Linux)
@if [ -f /etc/os-release ] && grep -q "ID=nixos" /etc/os-release; then \
echo "Detected NixOS, skipping apt-get installation."; \
echo "Detected NixOS, skipping apt installation."; \
else \
sudo apt-get install -y cmake ninja-build binaryen; \
sudo apt update; \
sudo apt install -y cmake ninja-build; \
fi
endif
@which wasm-pack > /dev/null && wasm-pack --version | grep -q "0.13.1" || cargo install wasm-pack --version=0.13.1

View File

@@ -13,15 +13,16 @@ Zerokit provides zero-knowledge cryptographic primitives with a focus on perform
The current focus is on Rate-Limiting Nullifier [RLN](https://github.com/Rate-Limiting-Nullifier) implementation.
Current implementation is based on the following
[specification](https://github.com/vacp2p/rfc-index/blob/main/vac/raw/rln-v2.md)
[specification](https://rfc.vac.dev/vac/raw/rln-v2)
and focused on RLNv2 which allows to set a rate limit for the number of messages that can be sent by a user.
## Features
- **RLN Implementation**: Efficient Rate-Limiting Nullifier using zkSNARKs
- **RLN Implementation**: Efficient Rate-Limiting Nullifier using zkSNARK
- **Circom Compatibility**: Uses Circom-based circuits for RLN
- **Cross-Platform**: Support for multiple architectures (see compatibility note below)
- **Cross-Platform**: Support for multiple architectures with cross-compilation
- **FFI-Friendly**: Easy to integrate with other languages
- **WASM Support**: Can be compiled to WebAssembly for web applications
## Architecture

8
flake.lock generated
View File

@@ -2,17 +2,17 @@
"nodes": {
"nixpkgs": {
"locked": {
"lastModified": 1740603184,
"narHash": "sha256-t+VaahjQAWyA+Ctn2idyo1yxRIYpaDxMgHkgCNiMJa4=",
"lastModified": 1757590060,
"narHash": "sha256-EWwwdKLMZALkgHFyKW7rmyhxECO74+N+ZO5xTDnY/5c=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "f44bd8ca21e026135061a0a57dcf3d0775b67a49",
"rev": "0ef228213045d2cdb5a169a95d63ded38670b293",
"type": "github"
},
"original": {
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "f44bd8ca21e026135061a0a57dcf3d0775b67a49",
"rev": "0ef228213045d2cdb5a169a95d63ded38670b293",
"type": "github"
}
},

View File

@@ -1,9 +1,14 @@
{
description = "A flake for building zerokit";
nixConfig = {
extra-substituters = [ "https://nix-cache.status.im/" ];
extra-trusted-public-keys = [ "nix-cache.status.im-1:x/93lOfLU+duPplwMSBR+OlY4+mo+dCN7n0mr4oPwgY=" ];
};
inputs = {
# Version 24.11
nixpkgs.url = "github:NixOS/nixpkgs?rev=f44bd8ca21e026135061a0a57dcf3d0775b67a49";
nixpkgs.url = "github:NixOS/nixpkgs?rev=0ef228213045d2cdb5a169a95d63ded38670b293";
rust-overlay = {
url = "github:oxalica/rust-overlay";
inputs.nixpkgs.follows = "nixpkgs";
@@ -19,11 +24,20 @@
"i686-windows"
];
forAllSystems = nixpkgs.lib.genAttrs stableSystems;
overlays = [
(import rust-overlay)
(f: p: { inherit rust-overlay; })
];
pkgsFor = forAllSystems (system: import nixpkgs { inherit system overlays; });
pkgsFor = forAllSystems (
system: import nixpkgs {
inherit system;
config = {
android_sdk.accept_license = true;
allowUnfree = true;
};
overlays = [
(import rust-overlay)
(f: p: { inherit rust-overlay; })
];
}
);
in rec
{
packages = forAllSystems (system: let

View File

@@ -6,10 +6,9 @@ tmp/
# Generated by Cargo will have compiled files and executables
/target
Cargo.lock
# Generated by rln-wasm
pkg/
# Generated by rln-cli
/database
# Generated by Nix
result

1647
rln-cli/Cargo.lock generated Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -13,13 +13,15 @@ path = "src/examples/stateless.rs"
required-features = ["stateless"]
[dependencies]
rln = { path = "../rln", version = "0.9.0", default-features = false }
zerokit_utils = { path = "../utils", version = "0.7.0", default-features = false }
clap = { version = "4.5.41", features = ["cargo", "derive", "env"] }
color-eyre = "0.6.5"
serde_json = "1.0.141"
serde = { version = "1.0", features = ["derive"] }
rln = { path = "../rln", version = "1.0.0", default-features = false }
zerokit_utils = { path = "../utils", version = "1.0.0", default-features = false }
clap = { version = "4.5.53", features = ["cargo", "derive", "env"] }
serde_json = "1.0.145"
serde = { version = "1.0.228", features = ["derive"] }
[features]
default = ["rln/pmtree-ft", "rln/parallel"]
stateless = ["rln/stateless", "rln/parallel"]
[package.metadata.docs.rs]
all-features = true

View File

@@ -1,35 +1,10 @@
# Zerokit RLN-CLI
The Zerokit RLN-CLI provides a command-line interface for interacting with the public API of the [Zerokit RLN Module](../rln/README.md).
It also contain:
+ [Relay Example](#relay-example) to demonstrate the use of the RLN module for spam prevention.
+ [Stateless Example](#stateless-example) to demonstrate the use of the RLN module for stateless features.
## Configuration
The CLI can be configured using a JSON configuration file (see the [example](example.config.json)).
You can specify the configuration file path using the `RLN_CONFIG_PATH` environment variable:
```bash
export RLN_CONFIG_PATH=example.config.json
```
Alternatively, you can provide the configuration file path as an argument for each command:
```bash
RLN_CONFIG_PATH=example.config.json cargo run -- <SUBCOMMAND> [OPTIONS]
```
If the configuration file is empty, default settings will be used, but the tree data folder will be temporary and not saved to the preconfigured path.
We recommend using the example config, as all commands (except `new` and `create-with-params`) require an initialized RLN instance.
The Zerokit RLN-CLI provides a command-line interface examples on how to use public API of the [Zerokit RLN Module](../rln/README.md).
## Relay Example
The following [Example](src/examples/relay.rs) demonstrates how RLN enables spam prevention in anonymous environments for multple users.
The following [Relay Example](src/examples/relay.rs) demonstrates how RLN enables spam prevention in anonymous environments for multple users.
You can run the example using the following command:
@@ -43,7 +18,7 @@ The customize **TREE_DEPTH** constant differs from the default value of `20` sho
## Stateless Example
The following [Example](src/examples/stateless.rs) demonstrates how RLN can be used for stateless features by creating the Merkle tree outside of RLN instance.
The following [Stateless Example](src/examples/stateless.rs) demonstrates how RLN can be used for stateless features by creating the Merkle tree outside of RLN instance.
This example function similarly to the [Relay Example](#relay-example) but uses a stateless RLN and seperate Merkle tree.
@@ -52,97 +27,3 @@ You can run the example using the following command:
```bash
cargo run --example stateless --no-default-features --features stateless
```
## CLI Commands
### Instance Management
To initialize a new RLN instance:
```bash
cargo run new --tree-depth <DEPTH>
```
To initialize an RLN instance with custom parameters:
```bash
cargo run new-with-params --resources-path <PATH> --tree-depth <DEPTH>
```
To update the Merkle tree depth:
```bash
cargo run set-tree --tree-depth <DEPTH>
```
### Leaf Operations
To set a single leaf:
```bash
cargo run set-leaf --index <INDEX> --input <INPUT_PATH>
```
To set multiple leaves:
```bash
cargo run set-multiple-leaves --index <START_INDEX> --input <INPUT_PATH>
```
To reset multiple leaves:
```bash
cargo run reset-multiple-leaves --input <INPUT_PATH>
```
To set the next available leaf:
```bash
cargo run set-next-leaf --input <INPUT_PATH>
```
To delete a specific leaf:
```bash
cargo run delete-leaf --index <INDEX>
```
### Proof Operations
To generate a proof:
```bash
cargo run prove --input <INPUT_PATH>
```
To generate an RLN proof:
```bash
cargo run generate-proof --input <INPUT_PATH>
```
To verify a proof:
```bash
cargo run verify --input <PROOF_PATH>
```
To verify a proof with multiple Merkle roots:
```bash
cargo run verify-with-roots --input <INPUT_PATH> --roots <ROOTS_PATH>
```
### Tree Information
To retrieve the current Merkle root:
```bash
cargo run get-root
```
To obtain a Merkle proof for a specific index:
```bash
cargo run get-proof --index <INDEX>
```

View File

@@ -1,69 +0,0 @@
use std::path::PathBuf;
use clap::Subcommand;
use rln::circuit::TEST_TREE_DEPTH;
#[derive(Subcommand)]
pub(crate) enum Commands {
New {
#[arg(short, long, default_value_t = TEST_TREE_DEPTH)]
tree_depth: usize,
},
NewWithParams {
#[arg(short, long, default_value_t = TEST_TREE_DEPTH)]
tree_depth: usize,
#[arg(short, long, default_value = "../rln/resources/tree_depth_20")]
resources_path: PathBuf,
},
SetTree {
#[arg(short, long, default_value_t = TEST_TREE_DEPTH)]
tree_depth: usize,
},
SetLeaf {
#[arg(short, long)]
index: usize,
#[arg(short, long)]
input: PathBuf,
},
SetMultipleLeaves {
#[arg(short, long)]
index: usize,
#[arg(short, long)]
input: PathBuf,
},
ResetMultipleLeaves {
#[arg(short, long)]
input: PathBuf,
},
SetNextLeaf {
#[arg(short, long)]
input: PathBuf,
},
DeleteLeaf {
#[arg(short, long)]
index: usize,
},
GetRoot,
GetProof {
#[arg(short, long)]
index: usize,
},
Prove {
#[arg(short, long)]
input: PathBuf,
},
Verify {
#[arg(short, long)]
input: PathBuf,
},
GenerateProof {
#[arg(short, long)]
input: PathBuf,
},
VerifyWithRoots {
#[arg(short, long)]
input: PathBuf,
#[arg(short, long)]
roots: PathBuf,
},
}

View File

@@ -1,31 +0,0 @@
use std::{fs::File, io::Read, path::PathBuf};
use color_eyre::Result;
use serde::{Deserialize, Serialize};
use serde_json::Value;
pub const RLN_CONFIG_PATH: &str = "RLN_CONFIG_PATH";
#[derive(Serialize, Deserialize)]
pub(crate) struct Config {
pub tree_config: Option<String>,
}
impl Config {
pub(crate) fn load_config() -> Result<Config> {
match std::env::var(RLN_CONFIG_PATH) {
Ok(env) => {
let path = PathBuf::from(env);
let mut file = File::open(path)?;
let mut contents = String::new();
file.read_to_string(&mut contents)?;
let tree_config: Value = serde_json::from_str(&contents)?;
println!("Initializing RLN with custom config");
Ok(Config {
tree_config: Some(tree_config.to_string()),
})
}
Err(_) => Ok(Config { tree_config: None }),
}
}
}

View File

@@ -1,24 +1,23 @@
use std::{
collections::HashMap,
fs::File,
io::{stdin, stdout, Cursor, Read, Write},
io::{stdin, stdout, Read, Write},
path::{Path, PathBuf},
};
use clap::{Parser, Subcommand};
use color_eyre::{eyre::eyre, Report, Result};
use rln::{
circuit::Fr,
hashers::{hash_to_field_le, poseidon_hash},
protocol::{keygen, prepare_prove_input, prepare_verify_input},
public::RLN,
utils::{fr_to_bytes_le, generate_input_buffer, IdSecret},
use rln::prelude::{
hash_to_field_le, keygen, poseidon_hash, recover_id_secret, Fr, IdSecret, PmtreeConfigBuilder,
RLNProofValues, RLNWitnessInput, RLN,
};
use zerokit_utils::pm_tree::Mode;
const MESSAGE_LIMIT: u32 = 1;
const TREE_DEPTH: usize = 20;
type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;
#[derive(Parser)]
#[command(author, version, about, long_about = None)]
struct Cli {
@@ -44,15 +43,15 @@ enum Commands {
#[derive(Debug, Clone)]
struct Identity {
identity_secret_hash: IdSecret,
identity_secret: IdSecret,
id_commitment: Fr,
}
impl Identity {
fn new() -> Self {
let (identity_secret_hash, id_commitment) = keygen();
let (identity_secret, id_commitment) = keygen().unwrap();
Identity {
identity_secret_hash,
identity_secret,
id_commitment,
}
}
@@ -60,7 +59,7 @@ impl Identity {
struct RLNSystem {
rln: RLN,
used_nullifiers: HashMap<[u8; 32], Vec<u8>>,
used_nullifiers: HashMap<Fr, RLNProofValues>,
local_identities: HashMap<usize, Identity>,
}
@@ -77,11 +76,19 @@ impl RLNSystem {
file.read_exact(&mut output_buffer)?;
resources.push(output_buffer);
}
let tree_config = PmtreeConfigBuilder::new()
.path("./database")
.temporary(false)
.cache_capacity(1073741824)
.flush_every_ms(500)
.mode(Mode::HighThroughput)
.use_compression(false)
.build()?;
let rln = RLN::new_with_params(
TREE_DEPTH,
resources[0].clone(),
resources[1].clone(),
generate_input_buffer(),
tree_config,
)?;
println!("RLN instance initialized successfully");
Ok(RLNSystem {
@@ -100,8 +107,8 @@ impl RLNSystem {
println!("Registered users:");
for (index, identity) in &self.local_identities {
println!("User Index: {index}");
println!("+ Identity Secret Hash: {}", *identity.identity_secret_hash);
println!("+ Identity Commitment: {}", identity.id_commitment);
println!("+ Identity secret: {}", *identity.identity_secret);
println!("+ Identity commitment: {}", identity.id_commitment);
println!();
}
}
@@ -110,13 +117,13 @@ impl RLNSystem {
let index = self.rln.leaves_set();
let identity = Identity::new();
let rate_commitment = poseidon_hash(&[identity.id_commitment, Fr::from(MESSAGE_LIMIT)]);
let mut buffer = Cursor::new(fr_to_bytes_le(&rate_commitment));
match self.rln.set_next_leaf(&mut buffer) {
let rate_commitment =
poseidon_hash(&[identity.id_commitment, Fr::from(MESSAGE_LIMIT)]).unwrap();
match self.rln.set_next_leaf(rate_commitment) {
Ok(_) => {
println!("Registered User Index: {index}");
println!("+ Identity secret hash: {}", *identity.identity_secret_hash);
println!("+ Identity commitment: {},", identity.id_commitment);
println!("+ Identity secret: {}", *identity.identity_secret);
println!("+ Identity commitment: {}", identity.id_commitment);
self.local_identities.insert(index, identity);
}
Err(_) => {
@@ -127,104 +134,84 @@ impl RLNSystem {
Ok(index)
}
fn generate_proof(
fn generate_and_verify_proof(
&mut self,
user_index: usize,
message_id: u32,
signal: &str,
external_nullifier: Fr,
) -> Result<Vec<u8>> {
) -> Result<RLNProofValues> {
let identity = match self.local_identities.get(&user_index) {
Some(identity) => identity,
None => return Err(eyre!("user index {user_index} not found")),
None => return Err(format!("user index {user_index} not found").into()),
};
let serialized = prepare_prove_input(
identity.identity_secret_hash.clone(),
user_index,
let (path_elements, identity_path_index) = self.rln.get_merkle_proof(user_index)?;
let x = hash_to_field_le(signal.as_bytes())?;
let witness = RLNWitnessInput::new(
identity.identity_secret.clone(),
Fr::from(MESSAGE_LIMIT),
Fr::from(message_id),
path_elements,
identity_path_index,
x,
external_nullifier,
signal.as_bytes(),
);
let mut input_buffer = Cursor::new(serialized);
let mut output_buffer = Cursor::new(Vec::new());
self.rln
.generate_rln_proof(&mut input_buffer, &mut output_buffer)?;
)?;
let (proof, proof_values) = self.rln.generate_rln_proof(&witness)?;
println!("Proof generated successfully:");
println!("+ User Index: {user_index}");
println!("+ Message ID: {message_id}");
println!("+ Signal: {signal}");
Ok(output_buffer.into_inner())
let verified = self.rln.verify_rln_proof(&proof, &proof_values, &x)?;
if verified {
println!("Proof verified successfully");
}
Ok(proof_values)
}
fn verify_proof(&mut self, proof_data: Vec<u8>, signal: &str) -> Result<()> {
let proof_with_signal = prepare_verify_input(proof_data.clone(), signal.as_bytes());
let mut input_buffer = Cursor::new(proof_with_signal);
match self.rln.verify_rln_proof(&mut input_buffer) {
Ok(true) => {
let nullifier = &proof_data[256..288];
let nullifier_key: [u8; 32] = nullifier.try_into()?;
if let Some(previous_proof) = self.used_nullifiers.get(&nullifier_key) {
self.handle_duplicate_message_id(previous_proof.clone(), proof_data)?;
return Ok(());
}
self.used_nullifiers.insert(nullifier_key, proof_data);
println!("Message verified and accepted");
}
Ok(false) => {
println!("Verification failed: message_id must be unique within the epoch and satisfy 0 <= message_id < MESSAGE_LIMIT: {MESSAGE_LIMIT}");
}
Err(err) => return Err(Report::new(err)),
fn check_nullifier(&mut self, proof_values: RLNProofValues) -> Result<()> {
if let Some(&previous_proof_values) = self.used_nullifiers.get(&proof_values.nullifier) {
self.handle_duplicate_message_id(previous_proof_values, proof_values)?;
return Ok(());
}
self.used_nullifiers
.insert(proof_values.nullifier, proof_values);
println!("Message verified and accepted");
Ok(())
}
fn handle_duplicate_message_id(
&mut self,
previous_proof: Vec<u8>,
current_proof: Vec<u8>,
previous_proof_values: RLNProofValues,
current_proof_values: RLNProofValues,
) -> Result<()> {
let x = &current_proof[192..224];
let y = &current_proof[224..256];
let prev_x = &previous_proof[192..224];
let prev_y = &previous_proof[224..256];
if x == prev_x && y == prev_y {
return Err(eyre!("this exact message and signal has already been sent"));
if previous_proof_values.x == current_proof_values.x
&& previous_proof_values.y == current_proof_values.y
{
return Err("this exact message and signal has already been sent".into());
}
let mut proof1 = Cursor::new(previous_proof);
let mut proof2 = Cursor::new(current_proof);
let mut output = Cursor::new(Vec::new());
match self
.rln
.recover_id_secret(&mut proof1, &mut proof2, &mut output)
{
Ok(_) => {
let output_data = output.into_inner();
let (leaked_identity_secret_hash, _) = IdSecret::from_bytes_le(&output_data);
match recover_id_secret(&previous_proof_values, &current_proof_values) {
Ok(leaked_identity_secret) => {
if let Some((user_index, identity)) = self
.local_identities
.iter()
.find(|(_, identity)| {
identity.identity_secret_hash == leaked_identity_secret_hash
})
.find(|(_, identity)| identity.identity_secret == leaked_identity_secret)
.map(|(index, identity)| (*index, identity))
{
let real_identity_secret_hash = identity.identity_secret_hash.clone();
if leaked_identity_secret_hash != real_identity_secret_hash {
Err(eyre!("identity secret hash mismatch: leaked_identity_secret_hash != real_identity_secret_hash"))
let real_identity_secret = identity.identity_secret.clone();
if leaked_identity_secret != real_identity_secret {
Err("Identity secret mismatch: leaked_identity_secret != real_identity_secret".into())
} else {
println!(
"DUPLICATE message ID detected! Reveal identity secret hash: {}",
*leaked_identity_secret_hash
"DUPLICATE message ID detected! Reveal identity secret: {}",
*leaked_identity_secret
);
self.local_identities.remove(&user_index);
self.rln.delete_leaf(user_index)?;
@@ -232,10 +219,10 @@ impl RLNSystem {
Ok(())
}
} else {
Err(eyre!("user identity secret hash ******** not found"))
Err("user identity secret ******** not found".into())
}
}
Err(err) => Err(eyre!("Failed to recover identity secret: {err}")),
Err(err) => Err(format!("Failed to recover identity secret: {err}").into()),
}
}
}
@@ -244,9 +231,9 @@ fn main() -> Result<()> {
println!("Initializing RLN instance...");
print!("\x1B[2J\x1B[1;1H");
let mut rln_system = RLNSystem::new()?;
let rln_epoch = hash_to_field_le(b"epoch");
let rln_identifier = hash_to_field_le(b"rln-identifier");
let external_nullifier = poseidon_hash(&[rln_epoch, rln_identifier]);
let rln_epoch = hash_to_field_le(b"epoch")?;
let rln_identifier = hash_to_field_le(b"rln-identifier")?;
let external_nullifier = poseidon_hash(&[rln_epoch, rln_identifier]).unwrap();
println!("RLN Relay Example:");
println!("Message Limit: {MESSAGE_LIMIT}");
println!("----------------------------------");
@@ -273,15 +260,15 @@ fn main() -> Result<()> {
message_id,
signal,
} => {
match rln_system.generate_proof(
match rln_system.generate_and_verify_proof(
user_index,
message_id,
&signal,
external_nullifier,
) {
Ok(proof) => {
if let Err(err) = rln_system.verify_proof(proof, &signal) {
println!("Verification error: {err}");
Ok(proof_values) => {
if let Err(err) = rln_system.check_nullifier(proof_values) {
println!("Check nullifier error: {err}");
};
}
Err(err) => {

View File

@@ -2,22 +2,19 @@
use std::{
collections::HashMap,
io::{stdin, stdout, Cursor, Write},
io::{stdin, stdout, Write},
};
use clap::{Parser, Subcommand};
use color_eyre::{eyre::eyre, Result};
use rln::{
circuit::{Fr, TEST_TREE_DEPTH},
hashers::{hash_to_field_le, poseidon_hash, PoseidonHash},
protocol::{keygen, prepare_verify_input, rln_witness_from_values, serialize_witness},
public::RLN,
utils::{fr_to_bytes_le, IdSecret},
use rln::prelude::{
hash_to_field_le, keygen, poseidon_hash, recover_id_secret, Fr, IdSecret, OptimalMerkleTree,
PoseidonHash, RLNProofValues, RLNWitnessInput, ZerokitMerkleProof, ZerokitMerkleTree,
DEFAULT_TREE_DEPTH, RLN,
};
use zerokit_utils::{OptimalMerkleTree, ZerokitMerkleProof, ZerokitMerkleTree};
const MESSAGE_LIMIT: u32 = 1;
type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;
type ConfigOf<T> = <T as ZerokitMerkleTree>::Config;
#[derive(Parser)]
@@ -45,15 +42,15 @@ enum Commands {
#[derive(Debug, Clone)]
struct Identity {
identity_secret_hash: IdSecret,
identity_secret: IdSecret,
id_commitment: Fr,
}
impl Identity {
fn new() -> Self {
let (identity_secret_hash, id_commitment) = keygen();
let (identity_secret, id_commitment) = keygen().unwrap();
Identity {
identity_secret_hash,
identity_secret,
id_commitment,
}
}
@@ -62,7 +59,7 @@ impl Identity {
struct RLNSystem {
rln: RLN,
tree: OptimalMerkleTree<PoseidonHash>,
used_nullifiers: HashMap<[u8; 32], Vec<u8>>,
used_nullifiers: HashMap<Fr, RLNProofValues>,
local_identities: HashMap<usize, Identity>,
}
@@ -71,7 +68,7 @@ impl RLNSystem {
let rln = RLN::new()?;
let default_leaf = Fr::from(0);
let tree: OptimalMerkleTree<PoseidonHash> = OptimalMerkleTree::new(
TEST_TREE_DEPTH,
DEFAULT_TREE_DEPTH,
default_leaf,
ConfigOf::<OptimalMerkleTree<PoseidonHash>>::default(),
)
@@ -94,8 +91,8 @@ impl RLNSystem {
println!("Registered users:");
for (index, identity) in &self.local_identities {
println!("User Index: {index}");
println!("+ Identity Secret Hash: {}", *identity.identity_secret_hash);
println!("+ Identity Commitment: {}", identity.id_commitment);
println!("+ Identity secret: {}", *identity.identity_secret);
println!("+ Identity commitment: {}", identity.id_commitment);
println!();
}
}
@@ -104,138 +101,117 @@ impl RLNSystem {
let index = self.tree.leaves_set();
let identity = Identity::new();
let rate_commitment = poseidon_hash(&[identity.id_commitment, Fr::from(MESSAGE_LIMIT)]);
let rate_commitment =
poseidon_hash(&[identity.id_commitment, Fr::from(MESSAGE_LIMIT)]).unwrap();
self.tree.update_next(rate_commitment)?;
println!("Registered User Index: {index}");
println!("+ Identity secret hash: {}", *identity.identity_secret_hash);
println!("+ Identity secret: {}", *identity.identity_secret);
println!("+ Identity commitment: {}", identity.id_commitment);
self.local_identities.insert(index, identity);
Ok(index)
}
fn generate_proof(
fn generate_and_verify_proof(
&mut self,
user_index: usize,
message_id: u32,
signal: &str,
external_nullifier: Fr,
) -> Result<Vec<u8>> {
) -> Result<RLNProofValues> {
let identity = match self.local_identities.get(&user_index) {
Some(identity) => identity,
None => return Err(eyre!("user index {user_index} not found")),
None => return Err(format!("user index {user_index} not found").into()),
};
let merkle_proof = self.tree.proof(user_index)?;
let x = hash_to_field_le(signal.as_bytes());
let x = hash_to_field_le(signal.as_bytes())?;
let rln_witness = rln_witness_from_values(
identity.identity_secret_hash.clone(),
let witness = RLNWitnessInput::new(
identity.identity_secret.clone(),
Fr::from(MESSAGE_LIMIT),
Fr::from(message_id),
merkle_proof.get_path_elements(),
merkle_proof.get_path_index(),
x,
external_nullifier,
Fr::from(MESSAGE_LIMIT),
Fr::from(message_id),
)?;
let serialized = serialize_witness(&rln_witness)?;
let mut input_buffer = Cursor::new(serialized);
let mut output_buffer = Cursor::new(Vec::new());
self.rln
.generate_rln_proof_with_witness(&mut input_buffer, &mut output_buffer)?;
let (proof, proof_values) = self.rln.generate_rln_proof(&witness)?;
println!("Proof generated successfully:");
println!("+ User Index: {user_index}");
println!("+ Message ID: {message_id}");
println!("+ Signal: {signal}");
Ok(output_buffer.into_inner())
let tree_root = self.tree.root();
let verified = self
.rln
.verify_with_roots(&proof, &proof_values, &x, &[tree_root])?;
if verified {
println!("Proof verified successfully");
}
Ok(proof_values)
}
fn verify_proof(&mut self, proof_data: Vec<u8>, signal: &str) -> Result<()> {
let proof_with_signal = prepare_verify_input(proof_data.clone(), signal.as_bytes());
let mut input_buffer = Cursor::new(proof_with_signal);
fn check_nullifier(&mut self, proof_values: RLNProofValues) -> Result<()> {
let tree_root = self.tree.root();
let root = self.tree.root();
let roots_serialized = fr_to_bytes_le(&root);
let mut roots_buffer = Cursor::new(roots_serialized);
match self
.rln
.verify_with_roots(&mut input_buffer, &mut roots_buffer)
{
Ok(true) => {
let nullifier = &proof_data[256..288];
let nullifier_key: [u8; 32] = nullifier.try_into()?;
if let Some(previous_proof) = self.used_nullifiers.get(&nullifier_key) {
self.handle_duplicate_message_id(previous_proof.clone(), proof_data)?;
return Ok(());
}
self.used_nullifiers.insert(nullifier_key, proof_data);
println!("Message verified and accepted");
}
Ok(false) => {
println!("Verification failed: message_id must be unique within the epoch and satisfy 0 <= message_id < MESSAGE_LIMIT: {MESSAGE_LIMIT}");
}
Err(err) => return Err(err.into()),
if proof_values.root != tree_root {
println!("Check nullifier failed: invalid root");
return Ok(());
}
if let Some(&previous_proof_values) = self.used_nullifiers.get(&proof_values.nullifier) {
self.handle_duplicate_message_id(previous_proof_values, proof_values)?;
return Ok(());
}
self.used_nullifiers
.insert(proof_values.nullifier, proof_values);
println!("Message verified and accepted");
Ok(())
}
fn handle_duplicate_message_id(
&mut self,
previous_proof: Vec<u8>,
current_proof: Vec<u8>,
previous_proof_values: RLNProofValues,
current_proof_values: RLNProofValues,
) -> Result<()> {
let x = &current_proof[192..224];
let y = &current_proof[224..256];
let prev_x = &previous_proof[192..224];
let prev_y = &previous_proof[224..256];
if x == prev_x && y == prev_y {
return Err(eyre!("this exact message and signal has already been sent"));
if previous_proof_values.x == current_proof_values.x
&& previous_proof_values.y == current_proof_values.y
{
return Err("this exact message and signal has already been sent".into());
}
let mut proof1 = Cursor::new(previous_proof);
let mut proof2 = Cursor::new(current_proof);
let mut output = Cursor::new(Vec::new());
match self
.rln
.recover_id_secret(&mut proof1, &mut proof2, &mut output)
{
Ok(_) => {
let output_data = output.into_inner();
let (leaked_identity_secret_hash, _) = IdSecret::from_bytes_le(&output_data);
match recover_id_secret(&previous_proof_values, &current_proof_values) {
Ok(leaked_identity_secret) => {
if let Some((user_index, identity)) = self
.local_identities
.iter()
.find(|(_, identity)| {
identity.identity_secret_hash == leaked_identity_secret_hash
})
.find(|(_, identity)| identity.identity_secret == leaked_identity_secret)
.map(|(index, identity)| (*index, identity))
{
let real_identity_secret_hash = identity.identity_secret_hash.clone();
if leaked_identity_secret_hash != real_identity_secret_hash {
Err(eyre!("identity secret hash mismatch: leaked_identity_secret_hash != real_identity_secret_hash"))
let real_identity_secret = identity.identity_secret.clone();
if leaked_identity_secret != real_identity_secret {
Err("Identity secret mismatch: leaked_identity_secret != real_identity_secret".into())
} else {
println!(
"DUPLICATE message ID detected! Reveal identity secret hash: ********"
"DUPLICATE message ID detected! Reveal identity secret: {}",
*leaked_identity_secret
);
self.local_identities.remove(&user_index);
println!("User index {user_index} has been SLASHED");
Ok(())
}
} else {
Err(eyre!("user identity secret hash ******** not found"))
Err("user identity secret ******** not found".into())
}
}
Err(err) => Err(eyre!("Failed to recover identity secret: {err}")),
Err(err) => Err(format!("Failed to recover identity secret: {err}").into()),
}
}
}
@@ -244,9 +220,9 @@ fn main() -> Result<()> {
println!("Initializing RLN instance...");
print!("\x1B[2J\x1B[1;1H");
let mut rln_system = RLNSystem::new()?;
let rln_epoch = hash_to_field_le(b"epoch");
let rln_identifier = hash_to_field_le(b"rln-identifier");
let external_nullifier = poseidon_hash(&[rln_epoch, rln_identifier]);
let rln_epoch = hash_to_field_le(b"epoch")?;
let rln_identifier = hash_to_field_le(b"rln-identifier")?;
let external_nullifier = poseidon_hash(&[rln_epoch, rln_identifier]).unwrap();
println!("RLN Stateless Relay Example:");
println!("Message Limit: {MESSAGE_LIMIT}");
println!("----------------------------------");
@@ -274,15 +250,15 @@ fn main() -> Result<()> {
message_id,
signal,
} => {
match rln_system.generate_proof(
match rln_system.generate_and_verify_proof(
user_index,
message_id,
&signal,
external_nullifier,
) {
Ok(proof) => {
if let Err(err) = rln_system.verify_proof(proof, &signal) {
println!("Verification error: {err}");
Ok(proof_values) => {
if let Err(err) = rln_system.check_nullifier(proof_values) {
println!("Check nullifier error: {err}");
};
}
Err(err) => {

View File

@@ -1,195 +0,0 @@
use std::{
fs::File,
io::{Cursor, Read},
path::Path,
};
use clap::Parser;
use color_eyre::{eyre::Report, Result};
use commands::Commands;
use config::Config;
use rln::{
public::RLN,
utils::{bytes_le_to_fr, bytes_le_to_vec_fr},
};
use serde_json::json;
use state::State;
mod commands;
mod config;
mod state;
#[derive(Parser)]
#[command(author, version, about, long_about = None)]
struct Cli {
#[command(subcommand)]
command: Option<Commands>,
}
fn main() -> Result<()> {
let cli = Cli::parse();
let mut state = match &cli.command {
Some(Commands::New { .. }) | Some(Commands::NewWithParams { .. }) => State::default(),
_ => State::load_state()?,
};
match cli.command {
Some(Commands::New { tree_depth }) => {
let config = Config::load_config()?;
state.rln = if let Some(tree_config) = config.tree_config {
println!("Initializing RLN with custom config");
Some(RLN::new(tree_depth, Cursor::new(tree_config.as_bytes()))?)
} else {
println!("Initializing RLN with default config");
Some(RLN::new(tree_depth, Cursor::new(json!({}).to_string()))?)
};
Ok(())
}
Some(Commands::NewWithParams {
tree_depth,
resources_path,
}) => {
let mut resources: Vec<Vec<u8>> = Vec::new();
let filenames = ["rln_final.arkzkey", "graph.bin"];
for filename in filenames {
let fullpath = resources_path.join(Path::new(filename));
let mut file = File::open(&fullpath)?;
let metadata = std::fs::metadata(&fullpath)?;
let mut buffer = vec![0; metadata.len() as usize];
file.read_exact(&mut buffer)?;
resources.push(buffer);
}
let config = Config::load_config()?;
if let Some(tree_config) = config.tree_config {
println!("Initializing RLN with custom config");
state.rln = Some(RLN::new_with_params(
tree_depth,
resources[0].clone(),
resources[1].clone(),
Cursor::new(tree_config.to_string().as_bytes()),
)?)
} else {
println!("Initializing RLN with default config");
state.rln = Some(RLN::new_with_params(
tree_depth,
resources[0].clone(),
resources[1].clone(),
Cursor::new(json!({}).to_string()),
)?)
};
Ok(())
}
Some(Commands::SetTree { tree_depth }) => {
state
.rln
.ok_or(Report::msg("no RLN instance initialized"))?
.set_tree(tree_depth)?;
Ok(())
}
Some(Commands::SetLeaf { index, input }) => {
let input_data = File::open(input)?;
state
.rln
.ok_or(Report::msg("no RLN instance initialized"))?
.set_leaf(index, input_data)?;
Ok(())
}
Some(Commands::SetMultipleLeaves { index, input }) => {
let input_data = File::open(input)?;
state
.rln
.ok_or(Report::msg("no RLN instance initialized"))?
.set_leaves_from(index, input_data)?;
Ok(())
}
Some(Commands::ResetMultipleLeaves { input }) => {
let input_data = File::open(input)?;
state
.rln
.ok_or(Report::msg("no RLN instance initialized"))?
.init_tree_with_leaves(input_data)?;
Ok(())
}
Some(Commands::SetNextLeaf { input }) => {
let input_data = File::open(input)?;
state
.rln
.ok_or(Report::msg("no RLN instance initialized"))?
.set_next_leaf(input_data)?;
Ok(())
}
Some(Commands::DeleteLeaf { index }) => {
state
.rln
.ok_or(Report::msg("no RLN instance initialized"))?
.delete_leaf(index)?;
Ok(())
}
Some(Commands::Prove { input }) => {
let input_data = File::open(input)?;
let mut output_buffer = Cursor::new(Vec::<u8>::new());
state
.rln
.ok_or(Report::msg("no RLN instance initialized"))?
.prove(input_data, &mut output_buffer)?;
let proof = output_buffer.into_inner();
println!("proof: {proof:?}");
Ok(())
}
Some(Commands::Verify { input }) => {
let input_data = File::open(input)?;
let verified = state
.rln
.ok_or(Report::msg("no RLN instance initialized"))?
.verify(input_data)?;
println!("verified: {verified:?}");
Ok(())
}
Some(Commands::GenerateProof { input }) => {
let input_data = File::open(input)?;
let mut output_buffer = Cursor::new(Vec::<u8>::new());
state
.rln
.ok_or(Report::msg("no RLN instance initialized"))?
.generate_rln_proof(input_data, &mut output_buffer)?;
let proof = output_buffer.into_inner();
println!("proof: {proof:?}");
Ok(())
}
Some(Commands::VerifyWithRoots { input, roots }) => {
let input_data = File::open(input)?;
let roots_data = File::open(roots)?;
state
.rln
.ok_or(Report::msg("no RLN instance initialized"))?
.verify_with_roots(input_data, roots_data)?;
Ok(())
}
Some(Commands::GetRoot) => {
let mut output_buffer = Cursor::new(Vec::<u8>::new());
state
.rln
.ok_or(Report::msg("no RLN instance initialized"))?
.get_root(&mut output_buffer)
.unwrap();
let (root, _) = bytes_le_to_fr(&output_buffer.into_inner());
println!("root: {root}");
Ok(())
}
Some(Commands::GetProof { index }) => {
let mut output_buffer = Cursor::new(Vec::<u8>::new());
state
.rln
.ok_or(Report::msg("no RLN instance initialized"))?
.get_proof(index, &mut output_buffer)?;
let output_buffer_inner = output_buffer.into_inner();
let (path_elements, _) = bytes_le_to_vec_fr(&output_buffer_inner)?;
for (index, element) in path_elements.iter().enumerate() {
println!("path element {index}: {element}");
}
Ok(())
}
None => Ok(()),
}
}

View File

@@ -1,31 +0,0 @@
use std::io::Cursor;
use color_eyre::Result;
use rln::{circuit::TEST_TREE_DEPTH, public::RLN};
use serde_json::Value;
use crate::config::Config;
#[derive(Default)]
pub(crate) struct State {
pub rln: Option<RLN>,
}
impl State {
pub(crate) fn load_state() -> Result<State> {
let config = Config::load_config()?;
let rln = if let Some(tree_config) = config.tree_config {
let config_json: Value = serde_json::from_str(&tree_config)?;
let tree_depth = config_json["tree_depth"]
.as_u64()
.unwrap_or(TEST_TREE_DEPTH as u64);
Some(RLN::new(
tree_depth as usize,
Cursor::new(tree_config.as_bytes()),
)?)
} else {
None
};
Ok(State { rln })
}
}

View File

@@ -1,35 +0,0 @@
[package]
name = "rln-wasm-utils"
version = "0.1.0"
edition = "2024"
[lib]
crate-type = ["cdylib", "rlib"]
[dependencies]
# TODO: remove this once we have a proper release
rln = { path = "../rln", version = "0.9.0", default-features = false, features = ["stateless"] }
js-sys = "0.3.77"
wasm-bindgen = "0.2.100"
rand = "0.8.5"
# The `console_error_panic_xhook` crate provides better debugging of panics by
# logging them with `console.error`. This is great for development, but requires
# all the `std::fmt` and `std::panicking` infrastructure, so isn't great for
# code size when deploying.
console_error_panic_hook = { version = "0.1.7", optional = true }
[target.'cfg(target_arch = "wasm32")'.dependencies]
getrandom = { version = "0.2.16", features = ["js"] }
[dev-dependencies]
wasm-bindgen-test = "0.3.50"
web-sys = { version = "0.3.77", features = ["console"] }
ark-std = { version = "0.5.0", default-features = false }
[features]
default = ["console_error_panic_hook"]
[package.metadata.docs.rs]
all-features = true

View File

@@ -1,36 +0,0 @@
[tasks.build]
clear = true
dependencies = ["pack_build", "pack_rename", "pack_resize"]
[tasks.pack_build]
command = "wasm-pack"
args = ["build", "--release", "--target", "web", "--scope", "waku"]
[tasks.pack_rename]
script = "sed -i.bak 's/rln-wasm-utils/zerokit-rln-wasm-utils/g' pkg/package.json && rm pkg/package.json.bak"
[tasks.pack_resize]
command = "wasm-opt"
args = [
"pkg/rln_wasm_utils_bg.wasm",
"-Oz",
"--strip-debug",
"--strip-dwarf",
"--remove-unused-module-elements",
"--vacuum",
"-o",
"pkg/rln_wasm_utils_bg.wasm",
]
[tasks.test]
command = "wasm-pack"
args = [
"test",
"--release",
"--node",
"--target",
"wasm32-unknown-unknown",
"--",
"--nocapture",
]
dependencies = ["build"]

View File

@@ -1,206 +0,0 @@
# RLN WASM Utils
[![npm version](https://badge.fury.io/js/@waku%2Fzerokit-rln-wasm.svg)](https://badge.fury.io/js/@waku%2Fzerokit-rln-wasm-utils)
[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/MIT)
[![License: Apache 2.0](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0)
The Zerokit RLN WASM Utils Module provides WebAssembly bindings for Rate-Limiting Nullifier [RLN](https://rfc.vac.dev/spec/32/) cryptographic primitives.
This module offers comprehensive functionality for identity generation and hashing needed for RLN applications.
## Features
### Identity Generation
- **Random Identity Generation**: Generate cryptographically secure random identities
- **Seeded Identity Generation**: Generate deterministic identities from seeds
- **Extended Identity Generation**: Generate extended identities with additional parameters
- **Seeded Extended Identity Generation**: Generate deterministic extended identities from seeds
- **Endianness Support**: Both little-endian and big-endian serialization support
### Hashing
- **Standard Hashing**: Hash arbitrary data to field elements
- **Poseidon Hashing**: Advanced cryptographic hashing using Poseidon hash function
- **Endianness Support**: Both little-endian and big-endian serialization support
## API Reference
### Identity Generation Functions
#### `generateMembershipKey(isLittleEndian: boolean): Uint8Array`
Generates a random membership key pair (identity secret and commitment).
**Inputs:**
- `isLittleEndian`: Boolean indicating endianness for serialization
**Outputs:** Serialized identity pair as `Uint8Array` in corresponding endianness
#### `generateExtendedMembershipKey(isLittleEndian: boolean): Uint8Array`
Generates an extended membership key with additional parameters.
**Inputs:**
- `isLittleEndian`: Boolean indicating endianness for serialization
**Outputs:** Serialized extended identity tuple as `Uint8Array` in corresponding endianness
#### `generateSeededMembershipKey(seed: Uint8Array, isLittleEndian: boolean): Uint8Array`
Generates a deterministic membership key from a seed.
**Inputs:**
- `seed`: Seed data as `Uint8Array`
- `isLittleEndian`: Boolean indicating endianness for serialization
**Outputs:** Serialized identity pair as `Uint8Array` in corresponding endianness
#### `generateSeededExtendedMembershipKey(seed: Uint8Array, isLittleEndian: boolean): Uint8Array`
Generates a deterministic extended membership key from a seed.
**Inputs:**
- `seed`: Seed data as `Uint8Array`
- `isLittleEndian`: Boolean indicating endianness for serialization
**Outputs:** Serialized extended identity tuple as `Uint8Array` in corresponding endianness
### Hashing Functions
#### `hash(input: Uint8Array, isLittleEndian: boolean): Uint8Array`
Hashes input data to a field element.
**Inputs:**
- `input`: Input data as `Uint8Array`
- `isLittleEndian`: Boolean indicating endianness for serialization
**Outputs:** Serialized hash result as `Uint8Array` in corresponding endianness
#### `poseidonHash(input: Uint8Array, isLittleEndian: boolean): Uint8Array`
Computes Poseidon hash of input field elements.
**Inputs:**
- `input`: Serialized field elements as `Uint8Array` (format: length + field elements)
- `isLittleEndian`: Boolean indicating endianness for serialization
**Outputs:** Serialized hash result as `Uint8Array` in corresponding endianness
## Usage Examples
### JavaScript/TypeScript
```javascript
import init, {
generateMembershipKey,
generateSeededMembershipKey,
hash,
poseidonHash
} from '@waku/zerokit-rln-wasm-utils';
// Initialize the WASM module
await init();
// Generate a random membership key
const membershipKey = generateMembershipKey(true); // little-endian
console.log('Membership key:', membershipKey);
// Generate a deterministic membership key from seed
const seed = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
const seededKey = generateSeededMembershipKey(seed, true);
console.log('Seeded key:', seededKey);
// Hash some data
const input = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
const hashResult = hash(input, true);
console.log('Hash result:', hashResult);
// Poseidon hash with field elements
const fieldElements = new Uint8Array([
// Length (8 bytes) + field elements (32 bytes each)
1, 0, 0, 0, 0, 0, 0, 0, // length = 1
// field element data...
]);
const poseidonResult = poseidonHash(fieldElements, true);
console.log('Poseidon hash:', poseidonResult);
```
## Install Dependencies
> [!NOTE]
> This project requires the following tools:
>
> - `wasm-pack` - for compiling Rust to WebAssembly
> - `cargo-make` - for running build commands
> - `nvm` - to install and manage Node.js
>
> Ensure all dependencies are installed before proceeding.
### Manually
#### Install `wasm-pack`
```bash
cargo install wasm-pack --version=0.13.1
```
#### Install `cargo-make`
```bash
cargo install cargo-make
```
#### Install `Node.js`
If you don't have `nvm` (Node Version Manager), install it by following
the [installation instructions](https://github.com/nvm-sh/nvm?tab=readme-ov-file#install--update-script).
After installing `nvm`, install and use Node.js `v22.14.0`:
```bash
nvm install 22.14.0
nvm use 22.14.0
nvm alias default 22.14.0
```
If you already have Node.js installed,
check your version with `node -v` command — the version must be strictly greater than 22.
### Or install everything
You can run the following command from the root of the repository to install all required dependencies for `zerokit`
```bash
make installdeps
```
## Building the library
First, navigate to the rln-wasm-utils directory:
```bash
cd rln-wasm-utils
```
Compile rln-wasm-utils for `wasm32-unknown-unknown`:
```bash
cargo make build
```
## Running tests
```bash
cargo make test
```
## License
This project is licensed under both MIT and Apache 2.0 licenses. See the LICENSE files for details.

View File

@@ -1,112 +0,0 @@
#![cfg(target_arch = "wasm32")]
use js_sys::Uint8Array;
use rln::public::{
extended_key_gen, hash, key_gen, poseidon_hash, seeded_extended_key_gen, seeded_key_gen,
};
use std::vec::Vec;
use wasm_bindgen::prelude::*;
#[allow(clippy::not_unsafe_ptr_arg_deref)]
#[wasm_bindgen(js_name = generateMembershipKey)]
pub fn wasm_key_gen(is_little_endian: bool) -> Result<Uint8Array, String> {
let mut output_data: Vec<u8> = Vec::new();
if let Err(err) = key_gen(&mut output_data, is_little_endian) {
std::mem::forget(output_data);
Err(format!(
"Msg: could not generate membership keys, Error: {:#?}",
err
))
} else {
let result = Uint8Array::from(&output_data[..]);
std::mem::forget(output_data);
Ok(result)
}
}
#[allow(clippy::not_unsafe_ptr_arg_deref)]
#[wasm_bindgen(js_name = generateExtendedMembershipKey)]
pub fn wasm_extended_key_gen(is_little_endian: bool) -> Result<Uint8Array, String> {
let mut output_data: Vec<u8> = Vec::new();
if let Err(err) = extended_key_gen(&mut output_data, is_little_endian) {
std::mem::forget(output_data);
Err(format!(
"Msg: could not generate membership keys, Error: {:#?}",
err
))
} else {
let result = Uint8Array::from(&output_data[..]);
std::mem::forget(output_data);
Ok(result)
}
}
#[allow(clippy::not_unsafe_ptr_arg_deref)]
#[wasm_bindgen(js_name = generateSeededMembershipKey)]
pub fn wasm_seeded_key_gen(seed: Uint8Array, is_little_endian: bool) -> Result<Uint8Array, String> {
let mut output_data: Vec<u8> = Vec::new();
let input_data = &seed.to_vec()[..];
if let Err(err) = seeded_key_gen(input_data, &mut output_data, is_little_endian) {
std::mem::forget(output_data);
Err(format!(
"Msg: could not generate membership key, Error: {:#?}",
err
))
} else {
let result = Uint8Array::from(&output_data[..]);
std::mem::forget(output_data);
Ok(result)
}
}
#[allow(clippy::not_unsafe_ptr_arg_deref)]
#[wasm_bindgen(js_name = generateSeededExtendedMembershipKey)]
pub fn wasm_seeded_extended_key_gen(
seed: Uint8Array,
is_little_endian: bool,
) -> Result<Uint8Array, String> {
let mut output_data: Vec<u8> = Vec::new();
let input_data = &seed.to_vec()[..];
if let Err(err) = seeded_extended_key_gen(input_data, &mut output_data, is_little_endian) {
std::mem::forget(output_data);
Err(format!(
"Msg: could not generate membership key, Error: {:#?}",
err
))
} else {
let result = Uint8Array::from(&output_data[..]);
std::mem::forget(output_data);
Ok(result)
}
}
#[wasm_bindgen(js_name = hash)]
pub fn wasm_hash(input: Uint8Array, is_little_endian: bool) -> Result<Uint8Array, String> {
let mut output_data: Vec<u8> = Vec::new();
let input_data = &input.to_vec()[..];
if let Err(err) = hash(input_data, &mut output_data, is_little_endian) {
std::mem::forget(output_data);
Err(format!("Msg: could not generate hash, Error: {:#?}", err))
} else {
let result = Uint8Array::from(&output_data[..]);
std::mem::forget(output_data);
Ok(result)
}
}
#[wasm_bindgen(js_name = poseidonHash)]
pub fn wasm_poseidon_hash(input: Uint8Array, is_little_endian: bool) -> Result<Uint8Array, String> {
let mut output_data: Vec<u8> = Vec::new();
let input_data = &input.to_vec()[..];
if let Err(err) = poseidon_hash(input_data, &mut output_data, is_little_endian) {
std::mem::forget(output_data);
Err(format!(
"Msg: could not generate poseidon hash, Error: {:#?}",
err
))
} else {
let result = Uint8Array::from(&output_data[..]);
std::mem::forget(output_data);
Ok(result)
}
}

View File

@@ -1,114 +0,0 @@
#![cfg(target_arch = "wasm32")]
#[cfg(test)]
mod test {
use ark_std::{UniformRand, rand::thread_rng};
use rand::Rng;
use rln::circuit::Fr;
use rln::hashers::{ROUND_PARAMS, hash_to_field_le, poseidon_hash};
use rln::protocol::{
deserialize_identity_pair_be, deserialize_identity_pair_le, deserialize_identity_tuple_be,
deserialize_identity_tuple_le,
};
use rln::utils::{bytes_le_to_fr, vec_fr_to_bytes_le};
use rln_wasm_utils::{
wasm_extended_key_gen, wasm_hash, wasm_key_gen, wasm_poseidon_hash,
wasm_seeded_extended_key_gen, wasm_seeded_key_gen,
};
use wasm_bindgen_test::*;
#[wasm_bindgen_test]
fn test_wasm_key_gen() {
let result_le = wasm_key_gen(true);
assert!(result_le.is_ok());
deserialize_identity_pair_le(result_le.unwrap().to_vec());
let result_be = wasm_key_gen(false);
assert!(result_be.is_ok());
deserialize_identity_pair_be(result_be.unwrap().to_vec());
}
#[wasm_bindgen_test]
fn test_wasm_extended_key_gen() {
let result_le = wasm_extended_key_gen(true);
assert!(result_le.is_ok());
deserialize_identity_tuple_le(result_le.unwrap().to_vec());
let result_be = wasm_extended_key_gen(false);
assert!(result_be.is_ok());
deserialize_identity_tuple_be(result_be.unwrap().to_vec());
}
#[wasm_bindgen_test]
fn test_wasm_seeded_key_gen() {
// Create a test seed
let seed_data = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let seed = js_sys::Uint8Array::from(&seed_data[..]);
let result_le = wasm_seeded_key_gen(seed.clone(), true);
assert!(result_le.is_ok());
let fr_le = deserialize_identity_pair_le(result_le.unwrap().to_vec());
let result_be = wasm_seeded_key_gen(seed, false);
assert!(result_be.is_ok());
let fr_be = deserialize_identity_pair_be(result_be.unwrap().to_vec());
assert_eq!(fr_le, fr_be);
}
#[wasm_bindgen_test]
fn test_wasm_seeded_extended_key_gen() {
// Create a test seed
let seed_data = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let seed = js_sys::Uint8Array::from(&seed_data[..]);
let result_le = wasm_seeded_extended_key_gen(seed.clone(), true);
assert!(result_le.is_ok());
let fr_le = deserialize_identity_tuple_le(result_le.unwrap().to_vec());
let result_be = wasm_seeded_extended_key_gen(seed, false);
assert!(result_be.is_ok());
let fr_be = deserialize_identity_tuple_be(result_be.unwrap().to_vec());
assert_eq!(fr_le, fr_be);
}
#[wasm_bindgen_test]
fn test_wasm_hash() {
// Create test input data
let signal: [u8; 32] = [0; 32];
let input = js_sys::Uint8Array::from(&signal[..]);
let result_le = wasm_hash(input.clone(), true);
assert!(result_le.is_ok());
let serialized_hash = result_le.unwrap().to_vec();
let (hash1, _) = bytes_le_to_fr(&serialized_hash);
let hash2 = hash_to_field_le(&signal);
assert_eq!(hash1, hash2);
}
#[wasm_bindgen_test]
fn test_wasm_poseidon_hash() {
let mut rng = thread_rng();
let number_of_inputs = rng.gen_range(1..ROUND_PARAMS.len());
let mut inputs = Vec::with_capacity(number_of_inputs);
for _ in 0..number_of_inputs {
inputs.push(Fr::rand(&mut rng));
}
let inputs_ser = vec_fr_to_bytes_le(&inputs);
let input = js_sys::Uint8Array::from(&inputs_ser[..]);
let expected_hash = poseidon_hash(inputs.as_ref());
let result_le = wasm_poseidon_hash(input.clone(), true);
assert!(result_le.is_ok());
let serialized_hash = result_le.unwrap().to_vec();
let (received_hash, _) = bytes_le_to_fr(&serialized_hash);
assert_eq!(received_hash, expected_hash);
}
}

5
rln-wasm/.gitignore vendored
View File

@@ -6,10 +6,11 @@ tmp/
# Generated by Cargo will have compiled files and executables
/target
Cargo.lock
# Generated by rln-wasm
pkg/
/pkg
/examples/node_modules
/examples/package-lock.json
# Generated by Nix
result

1792
rln-wasm/Cargo.lock generated Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -1,27 +1,30 @@
[package]
name = "rln-wasm"
version = "0.3.0"
version = "1.0.0"
edition = "2021"
license = "MIT or Apache2"
license = "MIT OR Apache-2.0"
[lib]
crate-type = ["cdylib", "rlib"]
[dependencies]
rln = { path = "../rln", version = "0.9.0", default-features = false, features = [
rln = { path = "../rln", version = "1.0.0", default-features = false, features = [
"stateless",
] }
rln-wasm-utils = { path = "../rln-wasm-utils", version = "0.1.0", default-features = false }
zerokit_utils = { path = "../utils", version = "0.7.0", default-features = false }
zerokit_utils = { path = "../utils", version = "1.0.0", default-features = false }
num-bigint = { version = "0.4.6", default-features = false }
js-sys = "0.3.77"
wasm-bindgen = "0.2.100"
js-sys = "0.3.83"
wasm-bindgen = "0.2.106"
serde-wasm-bindgen = "0.6.5"
serde = "1.0.228"
wasm-bindgen-rayon = { version = "1.3.0", features = [
"no-bundler",
], optional = true }
ark-relations = { version = "0.5.1", features = ["std"] }
ark-groth16 = { version = "0.5.0", default-features = false }
rand = "0.8.5"
# The `console_error_panic_xhook` crate provides better debugging of panics by
# The `console_error_panic_hook` crate provides better debugging of panics by
# logging them with `console.error`. This is great for development, but requires
# all the `std::fmt` and `std::panicking` infrastructure, so isn't great for
# code size when deploying.
@@ -31,17 +34,20 @@ console_error_panic_hook = { version = "0.1.7", optional = true }
getrandom = { version = "0.2.16", features = ["js"] }
[dev-dependencies]
serde_json = "1.0.141"
wasm-bindgen-test = "0.3.50"
wasm-bindgen-futures = "0.4.50"
serde_json = "1.0.145"
wasm-bindgen-test = "0.3.56"
wasm-bindgen-futures = "0.4.56"
ark-std = { version = "0.5.0", default-features = false }
[dev-dependencies.web-sys]
version = "0.3.77"
version = "0.3.83"
features = ["Window", "Navigator"]
[features]
default = ["console_error_panic_hook"]
parallel = ["rln/parallel", "wasm-bindgen-rayon"]
default = []
utils = []
panic_hook = ["console_error_panic_hook"]
parallel = ["rln/parallel", "wasm-bindgen-rayon", "ark-groth16/parallel"]
[package.metadata.docs.rs]
all-features = true

View File

@@ -1,19 +1,30 @@
[tasks.build]
clear = true
dependencies = ["pack_build", "pack_rename", "pack_resize"]
dependencies = ["pack_build", "pack_rename", "pack_add_keywords"]
[tasks.build_parallel]
clear = true
dependencies = ["pack_build_parallel", "pack_rename", "pack_resize"]
dependencies = [
"pack_build_parallel",
"pack_rename_parallel",
"pack_add_keywords",
]
[tasks.build_utils]
clear = true
dependencies = ["pack_build_utils", "pack_rename_utils", "pack_add_keywords"]
[tasks.pack_build]
command = "wasm-pack"
args = ["build", "--release", "--target", "web", "--scope", "waku"]
[tasks.pack_rename]
script = "sed -i.bak 's/rln-wasm/zerokit-rln-wasm/g' pkg/package.json && rm pkg/package.json.bak"
[tasks.pack_build_parallel]
command = "env"
args = [
"RUSTFLAGS=-C target-feature=+atomics,+bulk-memory,+mutable-globals",
"CARGO_TARGET_WASM32_UNKNOWN_UNKNOWN_RUSTFLAGS=-C target-feature=+atomics,+bulk-memory,+mutable-globals -C link-arg=--shared-memory -C link-arg=--max-memory=1073741824 -C link-arg=--import-memory -C link-arg=--export=__wasm_init_tls -C link-arg=--export=__tls_size -C link-arg=--export=__tls_align -C link-arg=--export=__tls_base",
"rustup",
"run",
"nightly",
@@ -29,22 +40,33 @@ args = [
"-Z",
"build-std=panic_abort,std",
]
[tasks.pack_rename]
script = "sed -i.bak 's/rln-wasm/zerokit-rln-wasm/g' pkg/package.json && rm pkg/package.json.bak"
[tasks.pack_resize]
command = "wasm-opt"
[tasks.pack_rename_parallel]
script = "sed -i.bak 's/rln-wasm/zerokit-rln-wasm-parallel/g' pkg/package.json && rm pkg/package.json.bak"
[tasks.pack_build_utils]
command = "wasm-pack"
args = [
"pkg/rln_wasm_bg.wasm",
"-Oz",
"--strip-debug",
"--strip-dwarf",
"--remove-unused-module-elements",
"--vacuum",
"-o",
"pkg/rln_wasm_bg.wasm",
"build",
"--release",
"--target",
"web",
"--scope",
"waku",
"--no-default-features",
"--features",
"utils",
]
[tasks.pack_rename_utils]
script = "sed -i.bak 's/rln-wasm/zerokit-rln-wasm-utils/g' pkg/package.json && rm pkg/package.json.bak"
[tasks.pack_add_keywords]
script = """
jq '. + {keywords: ["zerokit", "rln", "wasm"]}' pkg/package.json > pkg/package.json.tmp && \
mv pkg/package.json.tmp pkg/package.json
"""
[tasks.test]
command = "wasm-pack"
args = [
@@ -75,7 +97,7 @@ dependencies = ["build"]
[tasks.test_parallel]
command = "env"
args = [
"RUSTFLAGS=-C target-feature=+atomics,+bulk-memory,+mutable-globals",
"CARGO_TARGET_WASM32_UNKNOWN_UNKNOWN_RUSTFLAGS=-C target-feature=+atomics,+bulk-memory,+mutable-globals -C link-arg=--shared-memory -C link-arg=--max-memory=1073741824 -C link-arg=--import-memory -C link-arg=--export=__wasm_init_tls -C link-arg=--export=__tls_size -C link-arg=--export=__tls_align -C link-arg=--export=__tls_base",
"rustup",
"run",
"nightly",
@@ -95,5 +117,21 @@ args = [
]
dependencies = ["build_parallel"]
[tasks.test_utils]
command = "wasm-pack"
args = [
"test",
"--release",
"--node",
"--target",
"wasm32-unknown-unknown",
"--no-default-features",
"--features",
"utils",
"--",
"--nocapture",
]
dependencies = ["build_utils"]
[tasks.bench]
disabled = true

View File

@@ -5,7 +5,7 @@
[![License: Apache 2.0](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0)
The Zerokit RLN WASM Module provides WebAssembly bindings for working with
Rate-Limiting Nullifier [RLN](https://rfc.vac.dev/spec/32/) zkSNARK proofs and primitives.
Rate-Limiting Nullifier [RLN](https://rfc.vac.dev/vac/raw/rln-v2) zkSNARK proofs and primitives.
This module is used by [waku-org/js-rln](https://github.com/waku-org/js-rln/) to enable
RLN functionality in JavaScript/TypeScript applications.
@@ -14,119 +14,92 @@ RLN functionality in JavaScript/TypeScript applications.
> [!NOTE]
> This project requires the following tools:
>
> - `wasm-pack` - for compiling Rust to WebAssembly
> - `wasm-pack` (v0.13.1) - for compiling Rust to WebAssembly
> - `cargo-make` - for running build commands
> - `nvm` - to install and manage Node.js
>
> Ensure all dependencies are installed before proceeding.
> - `nvm` - to install and manage Node.js (v22.14.0+)
### Manually
#### Install `wasm-pack`
```bash
cargo install wasm-pack --version=0.13.1
```
#### Install `cargo-make`
```bash
cargo install cargo-make
```
#### Install `Node.js`
If you don't have `nvm` (Node Version Manager), install it by following
the [installation instructions](https://github.com/nvm-sh/nvm?tab=readme-ov-file#install--update-script).
After installing `nvm`, install and use Node.js `v22.14.0`:
```bash
nvm install 22.14.0
nvm use 22.14.0
nvm alias default 22.14.0
```
If you already have Node.js installed,
check your version with `node -v` command — the version must be strictly greater than 22.
### Or install everything
You can run the following command from the root of the repository to install all required dependencies for `zerokit`
### Quick Install
```bash
make installdeps
```
## Building the library
### Manual Installation
First, navigate to the rln-wasm directory:
```bash
# Install wasm-pack
cargo install wasm-pack --version=0.13.1
# Install cargo-make
cargo install cargo-make
# Install Node.js via nvm
nvm install 22.14.0
nvm use 22.14.0
nvm alias default 22.14.0
```
## Building the Library
Navigate to the rln-wasm directory:
```bash
cd rln-wasm
```
Compile zerokit for `wasm32-unknown-unknown`:
Build commands:
```bash
cargo make build
cargo make build # Default → @waku/zerokit-rln-wasm
cargo make build_parallel # Parallel → @waku/zerokit-rln-wasm-parallel (requires nightly Rust)
cargo make build_utils # Utils only → @waku/zerokit-rln-wasm-utils
```
## Running tests and benchmarks
All packages output to `pkg/` directory.
## Running Tests and Benchmarks
```bash
cargo make test
cargo make test # Standard tests
cargo make test_browser # Browser headless mode
cargo make test_utils # Utils-only tests
cargo make test_parallel # Parallel tests
```
If you want to run the tests in browser headless mode, you can use the following command:
## Examples
```bash
cargo make test_browser
```
See [Node example](./examples/index.js) and [README](./examples/Readme.md) for proof generation, verification, and slashing.
## Parallel computation
## Parallel Computation
The library supports parallel computation using the `wasm-bindgen-rayon` crate,
enabling multi-threaded execution in the browser.
Enables multi-threaded browser execution using `wasm-bindgen-rayon`.
> [!NOTE]
> Parallel support is not enabled by default due to WebAssembly and browser limitations. \
> Compiling this feature requires `nightly` Rust.
>
> - Parallel support is not enabled by default due to WebAssembly and browser limitations.
> - Requires `nightly` Rust: `rustup install nightly`
> - Browser-only (not compatible with Node.js)
> - Requires HTTP headers for `SharedArrayBuffer`:
> - `Cross-Origin-Opener-Policy: same-origin`
> - `Cross-Origin-Embedder-Policy: require-corp`
### Build Setup
### Usage
#### Install `nightly` Rust
Direct usage (modern browsers with WebAssembly threads support):
```bash
rustup install nightly
```js
import * as wasmPkg from '@waku/zerokit-rln-wasm-parallel';
await wasmPkg.default();
await wasmPkg.initThreadPool(navigator.hardwareConcurrency);
wasmPkg.nowCallAnyExportedFuncs();
```
### Build Commands
### Feature Detection for Older Browsers
To enable parallel computation for WebAssembly threads, you can use the following command:
If you're targeting [older browser versions that didn't support WebAssembly threads yet](https://webassembly.org/roadmap/), you'll want to use both builds - the parallel version for modern browsers and the default version as a fallback. Use feature detection to choose the appropriate build on the JavaScript side.
```bash
cargo make build_parallel
```
### WebAssembly Threading Support
Most modern browsers support WebAssembly threads,
but they require the following headers to enable `SharedArrayBuffer`, which is necessary for multithreading:
- Cross-Origin-Opener-Policy: same-origin
- Cross-Origin-Embedder-Policy: require-corp
Without these, the application will fall back to single-threaded mode.
## Feature detection
If you're targeting [older browser versions that didn't support WebAssembly threads yet](https://webassembly.org/roadmap/),
you'll likely want to create two builds - one with thread support and one without -
and use feature detection to choose the right one on the JavaScript side.
You can use [wasm-feature-detect](https://github.com/GoogleChromeLabs/wasm-feature-detect) library for this purpose.
For example, your code might look like this:
You can use the [wasm-feature-detect](https://github.com/GoogleChromeLabs/wasm-feature-detect) library for this purpose:
```js
import { threads } from 'wasm-feature-detect';
@@ -134,11 +107,11 @@ import { threads } from 'wasm-feature-detect';
let wasmPkg;
if (await threads()) {
wasmPkg = await import('./pkg-with-threads/index.js');
wasmPkg = await import('@waku/zerokit-rln-wasm-parallel');
await wasmPkg.default();
await wasmPkg.initThreadPool(navigator.hardwareConcurrency);
} else {
wasmPkg = await import('./pkg-without-threads/index.js');
wasmPkg = await import('@waku/zerokit-rln-wasm');
await wasmPkg.default();
}

View File

@@ -0,0 +1,22 @@
# RLN WASM Node Examples
This example demonstrates how to use the RLN WASM package in a Node.js environment.
## Build the @waku/zerokit-rln-wasm package at the root of rln-wasm module
```bash
cargo make build
```
## Move into this directory and install dependencies
```bash
cd examples
npm install
```
## Run
```bash
npm start
```

484
rln-wasm/examples/index.js Normal file
View File

@@ -0,0 +1,484 @@
import { readFileSync } from "fs";
import { fileURLToPath } from "url";
import { dirname, join } from "path";
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
function debugUint8Array(uint8Array) {
return Array.from(uint8Array, (byte) =>
byte.toString(16).padStart(2, "0")
).join(", ");
}
async function calculateWitness(circomPath, inputs, witnessCalculatorFile) {
const wasmFile = readFileSync(circomPath);
const wasmFileBuffer = wasmFile.buffer.slice(
wasmFile.byteOffset,
wasmFile.byteOffset + wasmFile.byteLength
);
const witnessCalculator = await witnessCalculatorFile(wasmFileBuffer);
const calculatedWitness = await witnessCalculator.calculateWitness(
inputs,
false
);
return calculatedWitness;
}
async function main() {
const rlnWasm = await import("../pkg/rln_wasm.js");
const wasmPath = join(__dirname, "../pkg/rln_wasm_bg.wasm");
const wasmBytes = readFileSync(wasmPath);
rlnWasm.initSync({ module: wasmBytes });
const zkeyPath = join(
__dirname,
"../../rln/resources/tree_depth_20/rln_final.arkzkey"
);
const circomPath = join(
__dirname,
"../../rln/resources/tree_depth_20/rln.wasm"
);
const witnessCalculatorPath = join(
__dirname,
"../resources/witness_calculator.js"
);
const { builder: witnessCalculatorFile } = await import(
witnessCalculatorPath
);
console.log("Creating RLN instance");
const zkeyData = readFileSync(zkeyPath);
let rlnInstance;
try {
rlnInstance = new rlnWasm.WasmRLN(new Uint8Array(zkeyData));
} catch (error) {
console.error("Initial RLN instance creation error:", error);
return;
}
console.log("RLN instance created successfully");
console.log("\nGenerating identity keys");
let identity;
try {
identity = rlnWasm.Identity.generate();
} catch (error) {
console.error("Key generation error:", error);
return;
}
const identitySecret = identity.getSecretHash();
const idCommitment = identity.getCommitment();
console.log("Identity generated");
console.log(" - identity_secret = " + identitySecret.debug());
console.log(" - id_commitment = " + idCommitment.debug());
console.log("\nCreating message limit");
const userMessageLimit = rlnWasm.WasmFr.fromUint(1);
console.log(" - user_message_limit = " + userMessageLimit.debug());
console.log("\nComputing rate commitment");
let rateCommitment;
try {
rateCommitment = rlnWasm.Hasher.poseidonHashPair(
idCommitment,
userMessageLimit
);
} catch (error) {
console.error("Rate commitment hash error:", error);
return;
}
console.log(" - rate_commitment = " + rateCommitment.debug());
console.log("\nWasmFr serialization: WasmFr <-> bytes");
const serRateCommitment = rateCommitment.toBytesLE();
console.log(
" - serialized rate_commitment = [" +
debugUint8Array(serRateCommitment) +
"]"
);
let deserRateCommitment;
try {
deserRateCommitment = rlnWasm.WasmFr.fromBytesLE(serRateCommitment);
} catch (error) {
console.error("Rate commitment deserialization error:", error);
return;
}
console.log(
" - deserialized rate_commitment = " + deserRateCommitment.debug()
);
console.log("\nIdentity serialization: Identity <-> bytes");
const serIdentity = identity.toBytesLE();
console.log(
" - serialized identity = [" + debugUint8Array(serIdentity) + "]"
);
let deserIdentity;
try {
deserIdentity = rlnWasm.Identity.fromBytesLE(serIdentity);
} catch (error) {
console.error("Identity deserialization error:", error);
return;
}
const deserIdentitySecret = deserIdentity.getSecretHash();
const deserIdCommitment = deserIdentity.getCommitment();
console.log(
" - deserialized identity = [" +
deserIdentitySecret.debug() +
", " +
deserIdCommitment.debug() +
"]"
);
console.log("\nBuilding Merkle path for stateless mode");
const treeDepth = 20;
const defaultLeaf = rlnWasm.WasmFr.zero();
const defaultHashes = [];
try {
defaultHashes[0] = rlnWasm.Hasher.poseidonHashPair(
defaultLeaf,
defaultLeaf
);
for (let i = 1; i < treeDepth - 1; i++) {
defaultHashes[i] = rlnWasm.Hasher.poseidonHashPair(
defaultHashes[i - 1],
defaultHashes[i - 1]
);
}
} catch (error) {
console.error("Poseidon hash error:", error);
return;
}
const pathElements = new rlnWasm.VecWasmFr();
pathElements.push(defaultLeaf);
for (let i = 1; i < treeDepth; i++) {
pathElements.push(defaultHashes[i - 1]);
}
const identityPathIndex = new Uint8Array(treeDepth);
console.log("\nVecWasmFr serialization: VecWasmFr <-> bytes");
const serPathElements = pathElements.toBytesLE();
console.log(
" - serialized path_elements = [" + debugUint8Array(serPathElements) + "]"
);
let deserPathElements;
try {
deserPathElements = rlnWasm.VecWasmFr.fromBytesLE(serPathElements);
} catch (error) {
console.error("Path elements deserialization error:", error);
return;
}
console.log(" - deserialized path_elements = ", deserPathElements.debug());
console.log("\nUint8Array serialization: Uint8Array <-> bytes");
const serPathIndex = rlnWasm.Uint8ArrayUtils.toBytesLE(identityPathIndex);
console.log(
" - serialized path_index = [" + debugUint8Array(serPathIndex) + "]"
);
let deserPathIndex;
try {
deserPathIndex = rlnWasm.Uint8ArrayUtils.fromBytesLE(serPathIndex);
} catch (error) {
console.error("Path index deserialization error:", error);
return;
}
console.log(" - deserialized path_index =", deserPathIndex);
console.log("\nComputing Merkle root for stateless mode");
console.log(" - computing root for index 0 with rate_commitment");
let computedRoot;
try {
computedRoot = rlnWasm.Hasher.poseidonHashPair(rateCommitment, defaultLeaf);
for (let i = 1; i < treeDepth; i++) {
computedRoot = rlnWasm.Hasher.poseidonHashPair(
computedRoot,
defaultHashes[i - 1]
);
}
} catch (error) {
console.error("Poseidon hash error:", error);
return;
}
console.log(" - computed_root = " + computedRoot.debug());
console.log("\nHashing signal");
const signal = new Uint8Array([
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0,
]);
let x;
try {
x = rlnWasm.Hasher.hashToFieldLE(signal);
} catch (error) {
console.error("Hash signal error:", error);
return;
}
console.log(" - x = " + x.debug());
console.log("\nHashing epoch");
const epochStr = "test-epoch";
let epoch;
try {
epoch = rlnWasm.Hasher.hashToFieldLE(new TextEncoder().encode(epochStr));
} catch (error) {
console.error("Hash epoch error:", error);
return;
}
console.log(" - epoch = " + epoch.debug());
console.log("\nHashing RLN identifier");
const rlnIdStr = "test-rln-identifier";
let rlnIdentifier;
try {
rlnIdentifier = rlnWasm.Hasher.hashToFieldLE(
new TextEncoder().encode(rlnIdStr)
);
} catch (error) {
console.error("Hash RLN identifier error:", error);
return;
}
console.log(" - rln_identifier = " + rlnIdentifier.debug());
console.log("\nComputing Poseidon hash for external nullifier");
let externalNullifier;
try {
externalNullifier = rlnWasm.Hasher.poseidonHashPair(epoch, rlnIdentifier);
} catch (error) {
console.error("External nullifier hash error:", error);
return;
}
console.log(" - external_nullifier = " + externalNullifier.debug());
console.log("\nCreating message_id");
const messageId = rlnWasm.WasmFr.fromUint(0);
console.log(" - message_id = " + messageId.debug());
console.log("\nCreating RLN Witness");
const witness = new rlnWasm.WasmRLNWitnessInput(
identitySecret,
userMessageLimit,
messageId,
pathElements,
identityPathIndex,
x,
externalNullifier
);
console.log("RLN Witness created successfully");
console.log(
"\nWasmRLNWitnessInput serialization: WasmRLNWitnessInput <-> bytes"
);
let serWitness;
try {
serWitness = witness.toBytesLE();
} catch (error) {
console.error("Witness serialization error:", error);
return;
}
console.log(
" - serialized witness = [" + debugUint8Array(serWitness) + " ]"
);
let deserWitness;
try {
deserWitness = rlnWasm.WasmRLNWitnessInput.fromBytesLE(serWitness);
} catch (error) {
console.error("Witness deserialization error:", error);
return;
}
console.log(" - witness deserialized successfully");
console.log("\nCalculating witness");
let witnessJson;
try {
witnessJson = witness.toBigIntJson();
} catch (error) {
console.error("Witness to BigInt JSON error:", error);
return;
}
const calculatedWitness = await calculateWitness(
circomPath,
witnessJson,
witnessCalculatorFile
);
console.log("Witness calculated successfully");
console.log("\nGenerating RLN Proof");
let rln_proof;
try {
rln_proof = rlnInstance.generateRLNProofWithWitness(
calculatedWitness,
witness
);
} catch (error) {
console.error("Proof generation error:", error);
return;
}
console.log("Proof generated successfully");
console.log("\nGetting proof values");
const proofValues = rln_proof.getValues();
console.log(" - y = " + proofValues.y.debug());
console.log(" - nullifier = " + proofValues.nullifier.debug());
console.log(" - root = " + proofValues.root.debug());
console.log(" - x = " + proofValues.x.debug());
console.log(
" - external_nullifier = " + proofValues.externalNullifier.debug()
);
console.log("\nRLNProof serialization: RLNProof <-> bytes");
let serProof;
try {
serProof = rln_proof.toBytesLE();
} catch (error) {
console.error("Proof serialization error:", error);
return;
}
console.log(" - serialized proof = [" + debugUint8Array(serProof) + " ]");
let deserProof;
try {
deserProof = rlnWasm.WasmRLNProof.fromBytesLE(serProof);
} catch (error) {
console.error("Proof deserialization error:", error);
return;
}
console.log(" - proof deserialized successfully");
console.log("\nRLNProofValues serialization: RLNProofValues <-> bytes");
const serProofValues = proofValues.toBytesLE();
console.log(
" - serialized proof_values = [" + debugUint8Array(serProofValues) + " ]"
);
let deserProofValues2;
try {
deserProofValues2 = rlnWasm.WasmRLNProofValues.fromBytesLE(serProofValues);
} catch (error) {
console.error("Proof values deserialization error:", error);
return;
}
console.log(" - proof_values deserialized successfully");
console.log(
" - deserialized external_nullifier = " +
deserProofValues2.externalNullifier.debug()
);
console.log("\nVerifying Proof");
const roots = new rlnWasm.VecWasmFr();
roots.push(computedRoot);
let isValid;
try {
isValid = rlnInstance.verifyWithRoots(rln_proof, roots, x);
} catch (error) {
console.error("Proof verification error:", error);
return;
}
if (isValid) {
console.log("Proof verified successfully");
} else {
console.log("Proof verification failed");
return;
}
console.log(
"\nSimulating double-signaling attack (same epoch, different message)"
);
console.log("\nHashing second signal");
const signal2 = new Uint8Array([
11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
]);
let x2;
try {
x2 = rlnWasm.Hasher.hashToFieldLE(signal2);
} catch (error) {
console.error("Hash second signal error:", error);
return;
}
console.log(" - x2 = " + x2.debug());
console.log("\nCreating second message with the same id");
const messageId2 = rlnWasm.WasmFr.fromUint(0);
console.log(" - message_id2 = " + messageId2.debug());
console.log("\nCreating second RLN Witness");
const witness2 = new rlnWasm.WasmRLNWitnessInput(
identitySecret,
userMessageLimit,
messageId2,
pathElements,
identityPathIndex,
x2,
externalNullifier
);
console.log("Second RLN Witness created successfully");
console.log("\nCalculating second witness");
let witnessJson2;
try {
witnessJson2 = witness2.toBigIntJson();
} catch (error) {
console.error("Second witness to BigInt JSON error:", error);
return;
}
const calculatedWitness2 = await calculateWitness(
circomPath,
witnessJson2,
witnessCalculatorFile
);
console.log("Second witness calculated successfully");
console.log("\nGenerating second RLN Proof");
let rln_proof2;
try {
rln_proof2 = rlnInstance.generateRLNProofWithWitness(
calculatedWitness2,
witness2
);
} catch (error) {
console.error("Second proof generation error:", error);
return;
}
console.log("Second proof generated successfully");
console.log("\nVerifying second proof");
let isValid2;
try {
isValid2 = rlnInstance.verifyWithRoots(rln_proof2, roots, x2);
} catch (error) {
console.error("Proof verification error:", error);
return;
}
if (isValid2) {
console.log("Second proof verified successfully");
console.log("\nRecovering identity secret");
const proofValues1 = rln_proof.getValues();
const proofValues2 = rln_proof2.getValues();
let recoveredSecret;
try {
recoveredSecret = rlnWasm.WasmRLNProofValues.recoverIdSecret(
proofValues1,
proofValues2
);
} catch (error) {
console.error("Identity recovery error:", error);
return;
}
console.log(" - recovered_secret = " + recoveredSecret.debug());
console.log(" - original_secret = " + identitySecret.debug());
console.log("Slashing successful: Identity is recovered!");
} else {
console.log("Second proof verification failed");
}
}
main().catch(console.error);

View File

@@ -0,0 +1,13 @@
{
"name": "rln-wasm-node-example",
"version": "1.0.0",
"description": "Node.js example for RLN WASM",
"type": "module",
"main": "index.js",
"scripts": {
"start": "node index.js"
},
"dependencies": {
"@waku/zerokit-rln-wasm": "file:../../pkg"
}
}

View File

@@ -1,212 +1,16 @@
#![cfg(target_arch = "wasm32")]
use js_sys::{BigInt as JsBigInt, Object, Uint8Array};
use num_bigint::BigInt;
use rln::public::RLN;
use std::vec::Vec;
use wasm_bindgen::prelude::*;
pub mod wasm_rln;
pub mod wasm_utils;
#[cfg(feature = "parallel")]
#[cfg(all(feature = "parallel", not(feature = "utils")))]
pub use wasm_bindgen_rayon::init_thread_pool;
#[cfg(not(feature = "utils"))]
pub use wasm_rln::{WasmRLN, WasmRLNProof, WasmRLNProofValues, WasmRLNWitnessInput};
pub use wasm_utils::{ExtendedIdentity, Hasher, Identity, VecWasmFr, WasmFr};
#[cfg(feature = "panic_hook")]
#[wasm_bindgen(js_name = initPanicHook)]
pub fn init_panic_hook() {
console_error_panic_hook::set_once();
}
#[wasm_bindgen(js_name = RLN)]
pub struct RLNWrapper {
// The purpose of this wrapper is to hold a RLN instance with the 'static lifetime
// because wasm_bindgen does not allow returning elements with lifetimes
instance: RLN,
}
// Macro to call methods with arbitrary amount of arguments,
// which have the last argument is output buffer pointer
// First argument to the macro is context,
// second is the actual method on `RLN`
// third is the aforementioned output buffer argument
// rest are all other arguments to the method
macro_rules! call_with_output_and_error_msg {
// this variant is needed for the case when
// there are zero other arguments
($instance:expr, $method:ident, $error_msg:expr) => {
{
let mut output_data: Vec<u8> = Vec::new();
let new_instance = $instance.process();
if let Err(err) = new_instance.instance.$method(&mut output_data) {
std::mem::forget(output_data);
Err(format!("Msg: {:#?}, Error: {:#?}", $error_msg, err))
} else {
let result = Uint8Array::from(&output_data[..]);
std::mem::forget(output_data);
Ok(result)
}
}
};
($instance:expr, $method:ident, $error_msg:expr, $( $arg:expr ),* ) => {
{
let mut output_data: Vec<u8> = Vec::new();
let new_instance = $instance.process();
if let Err(err) = new_instance.instance.$method($($arg.process()),*, &mut output_data) {
std::mem::forget(output_data);
Err(format!("Msg: {:#?}, Error: {:#?}", $error_msg, err))
} else {
let result = Uint8Array::from(&output_data[..]);
std::mem::forget(output_data);
Ok(result)
}
}
};
}
macro_rules! call {
($instance:expr, $method:ident $(, $arg:expr)*) => {
{
let new_instance: &mut RLNWrapper = $instance.process();
new_instance.instance.$method($($arg.process()),*)
}
}
}
macro_rules! call_bool_method_with_error_msg {
($instance:expr, $method:ident, $error_msg:expr $(, $arg:expr)*) => {
{
let new_instance: &RLNWrapper = $instance.process();
new_instance.instance.$method($($arg.process()),*).map_err(|err| format!("Msg: {:#?}, Error: {:#?}", $error_msg, err))
}
}
}
trait ProcessArg {
type ReturnType;
fn process(self) -> Self::ReturnType;
}
impl ProcessArg for usize {
type ReturnType = usize;
fn process(self) -> Self::ReturnType {
self
}
}
impl<T> ProcessArg for Vec<T> {
type ReturnType = Vec<T>;
fn process(self) -> Self::ReturnType {
self
}
}
impl ProcessArg for *const RLN {
type ReturnType = &'static RLN;
fn process(self) -> Self::ReturnType {
unsafe { &*self }
}
}
impl ProcessArg for *const RLNWrapper {
type ReturnType = &'static RLNWrapper;
fn process(self) -> Self::ReturnType {
unsafe { &*self }
}
}
impl ProcessArg for *mut RLNWrapper {
type ReturnType = &'static mut RLNWrapper;
fn process(self) -> Self::ReturnType {
unsafe { &mut *self }
}
}
impl<'a> ProcessArg for &'a [u8] {
type ReturnType = &'a [u8];
fn process(self) -> Self::ReturnType {
self
}
}
#[allow(clippy::not_unsafe_ptr_arg_deref)]
#[wasm_bindgen(js_name = newRLN)]
pub fn wasm_new(zkey: Uint8Array) -> Result<*mut RLNWrapper, String> {
let instance = RLN::new_with_params(zkey.to_vec()).map_err(|err| format!("{:#?}", err))?;
let wrapper = RLNWrapper { instance };
Ok(Box::into_raw(Box::new(wrapper)))
}
#[allow(clippy::not_unsafe_ptr_arg_deref)]
#[wasm_bindgen(js_name = rlnWitnessToJson)]
pub fn wasm_rln_witness_to_json(
ctx: *mut RLNWrapper,
serialized_witness: Uint8Array,
) -> Result<Object, String> {
let inputs = call!(
ctx,
get_rln_witness_bigint_json,
&serialized_witness.to_vec()[..]
)
.map_err(|err| err.to_string())?;
let js_value = serde_wasm_bindgen::to_value(&inputs).map_err(|err| err.to_string())?;
Object::from_entries(&js_value).map_err(|err| format!("{:#?}", err))
}
#[allow(clippy::not_unsafe_ptr_arg_deref)]
#[wasm_bindgen(js_name = generateRLNProofWithWitness)]
pub fn wasm_generate_rln_proof_with_witness(
ctx: *mut RLNWrapper,
calculated_witness: Vec<JsBigInt>,
serialized_witness: Uint8Array,
) -> Result<Uint8Array, String> {
let mut witness_vec: Vec<BigInt> = vec![];
for v in calculated_witness {
witness_vec.push(
v.to_string(10)
.map_err(|err| format!("{:#?}", err))?
.as_string()
.ok_or("not a string error")?
.parse::<BigInt>()
.map_err(|err| format!("{:#?}", err))?,
);
}
call_with_output_and_error_msg!(
ctx,
generate_rln_proof_with_witness,
"could not generate proof",
witness_vec,
serialized_witness.to_vec()
)
}
#[allow(clippy::not_unsafe_ptr_arg_deref)]
#[wasm_bindgen(js_name = recovedIDSecret)]
pub fn wasm_recover_id_secret(
ctx: *const RLNWrapper,
input_proof_data_1: Uint8Array,
input_proof_data_2: Uint8Array,
) -> Result<Uint8Array, String> {
call_with_output_and_error_msg!(
ctx,
recover_id_secret,
"could not recover id secret",
&input_proof_data_1.to_vec()[..],
&input_proof_data_2.to_vec()[..]
)
}
#[allow(clippy::not_unsafe_ptr_arg_deref)]
#[wasm_bindgen(js_name = verifyWithRoots)]
pub fn wasm_verify_with_roots(
ctx: *const RLNWrapper,
proof: Uint8Array,
roots: Uint8Array,
) -> Result<bool, String> {
call_bool_method_with_error_msg!(
ctx,
verify_with_roots,
"error while verifying proof with roots".to_string(),
&proof.to_vec()[..],
&roots.to_vec()[..]
)
}

253
rln-wasm/src/wasm_rln.rs Normal file
View File

@@ -0,0 +1,253 @@
#![cfg(target_arch = "wasm32")]
#![cfg(not(feature = "utils"))]
use js_sys::{BigInt as JsBigInt, Object, Uint8Array};
use num_bigint::BigInt;
use rln::prelude::*;
use serde::Serialize;
use wasm_bindgen::prelude::*;
use crate::wasm_utils::{VecWasmFr, WasmFr};
#[wasm_bindgen]
pub struct WasmRLN(RLN);
#[wasm_bindgen]
impl WasmRLN {
#[wasm_bindgen(constructor)]
pub fn new(zkey_data: &Uint8Array) -> Result<WasmRLN, String> {
let rln = RLN::new_with_params(zkey_data.to_vec()).map_err(|err| err.to_string())?;
Ok(WasmRLN(rln))
}
#[wasm_bindgen(js_name = generateRLNProofWithWitness)]
pub fn generate_rln_proof_with_witness(
&self,
calculated_witness: Vec<JsBigInt>,
witness: &WasmRLNWitnessInput,
) -> Result<WasmRLNProof, String> {
let calculated_witness_bigint: Vec<BigInt> = calculated_witness
.iter()
.map(|js_bigint| {
js_bigint
.to_string(10)
.ok()
.and_then(|js_str| js_str.as_string())
.ok_or_else(|| "Failed to convert JsBigInt to string".to_string())
.and_then(|str_val| {
str_val
.parse::<BigInt>()
.map_err(|err| format!("Failed to parse BigInt: {}", err))
})
})
.collect::<Result<Vec<_>, _>>()?;
let (proof, proof_values) = self
.0
.generate_rln_proof_with_witness(calculated_witness_bigint, &witness.0)
.map_err(|err| err.to_string())?;
let rln_proof = RLNProof {
proof_values,
proof,
};
Ok(WasmRLNProof(rln_proof))
}
#[wasm_bindgen(js_name = verifyWithRoots)]
pub fn verify_with_roots(
&self,
rln_proof: &WasmRLNProof,
roots: &VecWasmFr,
x: &WasmFr,
) -> Result<bool, String> {
let roots_fr: Vec<Fr> = (0..roots.length())
.filter_map(|i| roots.get(i))
.map(|root| *root)
.collect();
self.0
.verify_with_roots(&rln_proof.0.proof, &rln_proof.0.proof_values, x, &roots_fr)
.map_err(|err| err.to_string())
}
}
#[wasm_bindgen]
pub struct WasmRLNProof(RLNProof);
#[wasm_bindgen]
impl WasmRLNProof {
#[wasm_bindgen(js_name = getValues)]
pub fn get_values(&self) -> WasmRLNProofValues {
WasmRLNProofValues(self.0.proof_values)
}
#[wasm_bindgen(js_name = toBytesLE)]
pub fn to_bytes_le(&self) -> Result<Uint8Array, String> {
let bytes = rln_proof_to_bytes_le(&self.0).map_err(|err| err.to_string())?;
Ok(Uint8Array::from(&bytes[..]))
}
#[wasm_bindgen(js_name = toBytesBE)]
pub fn to_bytes_be(&self) -> Result<Uint8Array, String> {
let bytes = rln_proof_to_bytes_be(&self.0).map_err(|err| err.to_string())?;
Ok(Uint8Array::from(&bytes[..]))
}
#[wasm_bindgen(js_name = fromBytesLE)]
pub fn from_bytes_le(bytes: &Uint8Array) -> Result<WasmRLNProof, String> {
let bytes_vec = bytes.to_vec();
let (proof, _) = bytes_le_to_rln_proof(&bytes_vec).map_err(|err| err.to_string())?;
Ok(WasmRLNProof(proof))
}
#[wasm_bindgen(js_name = fromBytesBE)]
pub fn from_bytes_be(bytes: &Uint8Array) -> Result<WasmRLNProof, String> {
let bytes_vec = bytes.to_vec();
let (proof, _) = bytes_be_to_rln_proof(&bytes_vec).map_err(|err| err.to_string())?;
Ok(WasmRLNProof(proof))
}
}
#[wasm_bindgen]
pub struct WasmRLNProofValues(RLNProofValues);
#[wasm_bindgen]
impl WasmRLNProofValues {
#[wasm_bindgen(getter)]
pub fn y(&self) -> WasmFr {
WasmFr::from(self.0.y)
}
#[wasm_bindgen(getter)]
pub fn nullifier(&self) -> WasmFr {
WasmFr::from(self.0.nullifier)
}
#[wasm_bindgen(getter)]
pub fn root(&self) -> WasmFr {
WasmFr::from(self.0.root)
}
#[wasm_bindgen(getter)]
pub fn x(&self) -> WasmFr {
WasmFr::from(self.0.x)
}
#[wasm_bindgen(getter, js_name = externalNullifier)]
pub fn external_nullifier(&self) -> WasmFr {
WasmFr::from(self.0.external_nullifier)
}
#[wasm_bindgen(js_name = toBytesLE)]
pub fn to_bytes_le(&self) -> Uint8Array {
Uint8Array::from(&rln_proof_values_to_bytes_le(&self.0)[..])
}
#[wasm_bindgen(js_name = toBytesBE)]
pub fn to_bytes_be(&self) -> Uint8Array {
Uint8Array::from(&rln_proof_values_to_bytes_be(&self.0)[..])
}
#[wasm_bindgen(js_name = fromBytesLE)]
pub fn from_bytes_le(bytes: &Uint8Array) -> Result<WasmRLNProofValues, String> {
let bytes_vec = bytes.to_vec();
let (proof_values, _) =
bytes_le_to_rln_proof_values(&bytes_vec).map_err(|err| err.to_string())?;
Ok(WasmRLNProofValues(proof_values))
}
#[wasm_bindgen(js_name = fromBytesBE)]
pub fn from_bytes_be(bytes: &Uint8Array) -> Result<WasmRLNProofValues, String> {
let bytes_vec = bytes.to_vec();
let (proof_values, _) =
bytes_be_to_rln_proof_values(&bytes_vec).map_err(|err| err.to_string())?;
Ok(WasmRLNProofValues(proof_values))
}
#[wasm_bindgen(js_name = recoverIdSecret)]
pub fn recover_id_secret(
proof_values_1: &WasmRLNProofValues,
proof_values_2: &WasmRLNProofValues,
) -> Result<WasmFr, String> {
let recovered_identity_secret = recover_id_secret(&proof_values_1.0, &proof_values_2.0)
.map_err(|err| err.to_string())?;
Ok(WasmFr::from(*recovered_identity_secret))
}
}
#[wasm_bindgen]
pub struct WasmRLNWitnessInput(RLNWitnessInput);
#[wasm_bindgen]
impl WasmRLNWitnessInput {
#[wasm_bindgen(constructor)]
pub fn new(
identity_secret: &WasmFr,
user_message_limit: &WasmFr,
message_id: &WasmFr,
path_elements: &VecWasmFr,
identity_path_index: &Uint8Array,
x: &WasmFr,
external_nullifier: &WasmFr,
) -> Result<WasmRLNWitnessInput, String> {
let mut identity_secret_fr = identity_secret.inner();
let path_elements: Vec<Fr> = path_elements.inner();
let identity_path_index: Vec<u8> = identity_path_index.to_vec();
let witness = RLNWitnessInput::new(
IdSecret::from(&mut identity_secret_fr),
user_message_limit.inner(),
message_id.inner(),
path_elements,
identity_path_index,
x.inner(),
external_nullifier.inner(),
)
.map_err(|err| err.to_string())?;
Ok(WasmRLNWitnessInput(witness))
}
#[wasm_bindgen(js_name = toBigIntJson)]
pub fn to_bigint_json(&self) -> Result<Object, String> {
let bigint_json = rln_witness_to_bigint_json(&self.0).map_err(|err| err.to_string())?;
let serializer = serde_wasm_bindgen::Serializer::json_compatible();
let js_value = bigint_json
.serialize(&serializer)
.map_err(|err| err.to_string())?;
js_value
.dyn_into::<Object>()
.map_err(|err| format!("{:#?}", err))
}
#[wasm_bindgen(js_name = toBytesLE)]
pub fn to_bytes_le(&self) -> Result<Uint8Array, String> {
let bytes = rln_witness_to_bytes_le(&self.0).map_err(|err| err.to_string())?;
Ok(Uint8Array::from(&bytes[..]))
}
#[wasm_bindgen(js_name = toBytesBE)]
pub fn to_bytes_be(&self) -> Result<Uint8Array, String> {
let bytes = rln_witness_to_bytes_be(&self.0).map_err(|err| err.to_string())?;
Ok(Uint8Array::from(&bytes[..]))
}
#[wasm_bindgen(js_name = fromBytesLE)]
pub fn from_bytes_le(bytes: &Uint8Array) -> Result<WasmRLNWitnessInput, String> {
let bytes_vec = bytes.to_vec();
let (witness, _) = bytes_le_to_rln_witness(&bytes_vec).map_err(|err| err.to_string())?;
Ok(WasmRLNWitnessInput(witness))
}
#[wasm_bindgen(js_name = fromBytesBE)]
pub fn from_bytes_be(bytes: &Uint8Array) -> Result<WasmRLNWitnessInput, String> {
let bytes_vec = bytes.to_vec();
let (witness, _) = bytes_be_to_rln_witness(&bytes_vec).map_err(|err| err.to_string())?;
Ok(WasmRLNWitnessInput(witness))
}
}

420
rln-wasm/src/wasm_utils.rs Normal file
View File

@@ -0,0 +1,420 @@
#![cfg(target_arch = "wasm32")]
use std::ops::Deref;
use js_sys::Uint8Array;
use rln::prelude::*;
use wasm_bindgen::prelude::*;
// WasmFr
#[wasm_bindgen]
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub struct WasmFr(Fr);
impl From<Fr> for WasmFr {
fn from(fr: Fr) -> Self {
Self(fr)
}
}
impl Deref for WasmFr {
type Target = Fr;
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[wasm_bindgen]
impl WasmFr {
#[wasm_bindgen(js_name = zero)]
pub fn zero() -> Self {
Self(Fr::from(0u32))
}
#[wasm_bindgen(js_name = one)]
pub fn one() -> Self {
Self(Fr::from(1u32))
}
#[wasm_bindgen(js_name = fromUint)]
pub fn from_uint(value: u32) -> Self {
Self(Fr::from(value))
}
#[wasm_bindgen(js_name = fromBytesLE)]
pub fn from_bytes_le(bytes: &Uint8Array) -> Result<Self, String> {
let bytes_vec = bytes.to_vec();
let (fr, _) = bytes_le_to_fr(&bytes_vec).map_err(|err| err.to_string())?;
Ok(Self(fr))
}
#[wasm_bindgen(js_name = fromBytesBE)]
pub fn from_bytes_be(bytes: &Uint8Array) -> Result<Self, String> {
let bytes_vec = bytes.to_vec();
let (fr, _) = bytes_be_to_fr(&bytes_vec).map_err(|err| err.to_string())?;
Ok(Self(fr))
}
#[wasm_bindgen(js_name = toBytesLE)]
pub fn to_bytes_le(&self) -> Uint8Array {
let bytes = fr_to_bytes_le(&self.0);
Uint8Array::from(&bytes[..])
}
#[wasm_bindgen(js_name = toBytesBE)]
pub fn to_bytes_be(&self) -> Uint8Array {
let bytes = fr_to_bytes_be(&self.0);
Uint8Array::from(&bytes[..])
}
#[wasm_bindgen(js_name = debug)]
pub fn debug(&self) -> String {
format!("{:?}", self.0)
}
}
impl WasmFr {
pub fn inner(&self) -> Fr {
self.0
}
}
// VecWasmFr
#[wasm_bindgen]
#[derive(Debug, Clone, PartialEq, Default)]
pub struct VecWasmFr(Vec<Fr>);
#[wasm_bindgen]
impl VecWasmFr {
#[wasm_bindgen(constructor)]
pub fn new() -> Self {
Self(Vec::new())
}
#[wasm_bindgen(js_name = fromBytesLE)]
pub fn from_bytes_le(bytes: &Uint8Array) -> Result<VecWasmFr, String> {
let bytes_vec = bytes.to_vec();
bytes_le_to_vec_fr(&bytes_vec)
.map(|(vec_fr, _)| VecWasmFr(vec_fr))
.map_err(|err| err.to_string())
}
#[wasm_bindgen(js_name = fromBytesBE)]
pub fn from_bytes_be(bytes: &Uint8Array) -> Result<VecWasmFr, String> {
let bytes_vec = bytes.to_vec();
bytes_be_to_vec_fr(&bytes_vec)
.map(|(vec_fr, _)| VecWasmFr(vec_fr))
.map_err(|err| err.to_string())
}
#[wasm_bindgen(js_name = toBytesLE)]
pub fn to_bytes_le(&self) -> Uint8Array {
let bytes = vec_fr_to_bytes_le(&self.0);
Uint8Array::from(&bytes[..])
}
#[wasm_bindgen(js_name = toBytesBE)]
pub fn to_bytes_be(&self) -> Uint8Array {
let bytes = vec_fr_to_bytes_be(&self.0);
Uint8Array::from(&bytes[..])
}
#[wasm_bindgen(js_name = get)]
pub fn get(&self, index: usize) -> Option<WasmFr> {
self.0.get(index).map(|&fr| WasmFr(fr))
}
#[wasm_bindgen(js_name = length)]
pub fn length(&self) -> usize {
self.0.len()
}
#[wasm_bindgen(js_name = push)]
pub fn push(&mut self, element: &WasmFr) {
self.0.push(element.0);
}
#[wasm_bindgen(js_name = debug)]
pub fn debug(&self) -> String {
format!("{:?}", self.0)
}
}
impl VecWasmFr {
pub fn inner(&self) -> Vec<Fr> {
self.0.clone()
}
}
// Uint8Array
#[wasm_bindgen]
pub struct Uint8ArrayUtils;
#[wasm_bindgen]
impl Uint8ArrayUtils {
#[wasm_bindgen(js_name = toBytesLE)]
pub fn to_bytes_le(input: &Uint8Array) -> Uint8Array {
let input_vec = input.to_vec();
let bytes = vec_u8_to_bytes_le(&input_vec);
Uint8Array::from(&bytes[..])
}
#[wasm_bindgen(js_name = toBytesBE)]
pub fn to_bytes_be(input: &Uint8Array) -> Uint8Array {
let input_vec = input.to_vec();
let bytes = vec_u8_to_bytes_be(&input_vec);
Uint8Array::from(&bytes[..])
}
#[wasm_bindgen(js_name = fromBytesLE)]
pub fn from_bytes_le(bytes: &Uint8Array) -> Result<Uint8Array, String> {
let bytes_vec = bytes.to_vec();
bytes_le_to_vec_u8(&bytes_vec)
.map(|(vec_u8, _)| Uint8Array::from(&vec_u8[..]))
.map_err(|err| err.to_string())
}
#[wasm_bindgen(js_name = fromBytesBE)]
pub fn from_bytes_be(bytes: &Uint8Array) -> Result<Uint8Array, String> {
let bytes_vec = bytes.to_vec();
bytes_be_to_vec_u8(&bytes_vec)
.map(|(vec_u8, _)| Uint8Array::from(&vec_u8[..]))
.map_err(|err| err.to_string())
}
}
// Utility APIs
#[wasm_bindgen]
pub struct Hasher;
#[wasm_bindgen]
impl Hasher {
#[wasm_bindgen(js_name = hashToFieldLE)]
pub fn hash_to_field_le(input: &Uint8Array) -> Result<WasmFr, String> {
hash_to_field_le(&input.to_vec())
.map(WasmFr)
.map_err(|err| err.to_string())
}
#[wasm_bindgen(js_name = hashToFieldBE)]
pub fn hash_to_field_be(input: &Uint8Array) -> Result<WasmFr, String> {
hash_to_field_be(&input.to_vec())
.map(WasmFr)
.map_err(|err| err.to_string())
}
#[wasm_bindgen(js_name = poseidonHashPair)]
pub fn poseidon_hash_pair(a: &WasmFr, b: &WasmFr) -> Result<WasmFr, String> {
poseidon_hash(&[a.0, b.0])
.map(WasmFr)
.map_err(|err| err.to_string())
}
}
#[wasm_bindgen]
pub struct Identity {
identity_secret: Fr,
id_commitment: Fr,
}
#[wasm_bindgen]
impl Identity {
#[wasm_bindgen(js_name = generate)]
pub fn generate() -> Result<Identity, String> {
let (identity_secret, id_commitment) = keygen().map_err(|err| err.to_string())?;
Ok(Identity {
identity_secret: *identity_secret,
id_commitment,
})
}
#[wasm_bindgen(js_name = generateSeeded)]
pub fn generate_seeded(seed: &Uint8Array) -> Result<Identity, String> {
let seed_vec = seed.to_vec();
let (identity_secret, id_commitment) =
seeded_keygen(&seed_vec).map_err(|err| err.to_string())?;
Ok(Identity {
identity_secret,
id_commitment,
})
}
#[wasm_bindgen(js_name = getSecretHash)]
pub fn get_secret_hash(&self) -> WasmFr {
WasmFr(self.identity_secret)
}
#[wasm_bindgen(js_name = getCommitment)]
pub fn get_commitment(&self) -> WasmFr {
WasmFr(self.id_commitment)
}
#[wasm_bindgen(js_name = toArray)]
pub fn to_array(&self) -> VecWasmFr {
VecWasmFr(vec![self.identity_secret, self.id_commitment])
}
#[wasm_bindgen(js_name = toBytesLE)]
pub fn to_bytes_le(&self) -> Uint8Array {
let vec_fr = vec![self.identity_secret, self.id_commitment];
let bytes = vec_fr_to_bytes_le(&vec_fr);
Uint8Array::from(&bytes[..])
}
#[wasm_bindgen(js_name = toBytesBE)]
pub fn to_bytes_be(&self) -> Uint8Array {
let vec_fr = vec![self.identity_secret, self.id_commitment];
let bytes = vec_fr_to_bytes_be(&vec_fr);
Uint8Array::from(&bytes[..])
}
#[wasm_bindgen(js_name = fromBytesLE)]
pub fn from_bytes_le(bytes: &Uint8Array) -> Result<Identity, String> {
let bytes_vec = bytes.to_vec();
let (vec_fr, _) = bytes_le_to_vec_fr(&bytes_vec).map_err(|err| err.to_string())?;
if vec_fr.len() != 2 {
return Err(format!("Expected 2 elements, got {}", vec_fr.len()));
}
Ok(Identity {
identity_secret: vec_fr[0],
id_commitment: vec_fr[1],
})
}
#[wasm_bindgen(js_name = fromBytesBE)]
pub fn from_bytes_be(bytes: &Uint8Array) -> Result<Identity, String> {
let bytes_vec = bytes.to_vec();
let (vec_fr, _) = bytes_be_to_vec_fr(&bytes_vec).map_err(|err| err.to_string())?;
if vec_fr.len() != 2 {
return Err(format!("Expected 2 elements, got {}", vec_fr.len()));
}
Ok(Identity {
identity_secret: vec_fr[0],
id_commitment: vec_fr[1],
})
}
}
#[wasm_bindgen]
pub struct ExtendedIdentity {
identity_trapdoor: Fr,
identity_nullifier: Fr,
identity_secret: Fr,
id_commitment: Fr,
}
#[wasm_bindgen]
impl ExtendedIdentity {
#[wasm_bindgen(js_name = generate)]
pub fn generate() -> Result<ExtendedIdentity, String> {
let (identity_trapdoor, identity_nullifier, identity_secret, id_commitment) =
extended_keygen().map_err(|err| err.to_string())?;
Ok(ExtendedIdentity {
identity_trapdoor,
identity_nullifier,
identity_secret,
id_commitment,
})
}
#[wasm_bindgen(js_name = generateSeeded)]
pub fn generate_seeded(seed: &Uint8Array) -> Result<ExtendedIdentity, String> {
let seed_vec = seed.to_vec();
let (identity_trapdoor, identity_nullifier, identity_secret, id_commitment) =
extended_seeded_keygen(&seed_vec).map_err(|err| err.to_string())?;
Ok(ExtendedIdentity {
identity_trapdoor,
identity_nullifier,
identity_secret,
id_commitment,
})
}
#[wasm_bindgen(js_name = getTrapdoor)]
pub fn get_trapdoor(&self) -> WasmFr {
WasmFr(self.identity_trapdoor)
}
#[wasm_bindgen(js_name = getNullifier)]
pub fn get_nullifier(&self) -> WasmFr {
WasmFr(self.identity_nullifier)
}
#[wasm_bindgen(js_name = getSecretHash)]
pub fn get_secret_hash(&self) -> WasmFr {
WasmFr(self.identity_secret)
}
#[wasm_bindgen(js_name = getCommitment)]
pub fn get_commitment(&self) -> WasmFr {
WasmFr(self.id_commitment)
}
#[wasm_bindgen(js_name = toArray)]
pub fn to_array(&self) -> VecWasmFr {
VecWasmFr(vec![
self.identity_trapdoor,
self.identity_nullifier,
self.identity_secret,
self.id_commitment,
])
}
#[wasm_bindgen(js_name = toBytesLE)]
pub fn to_bytes_le(&self) -> Uint8Array {
let vec_fr = vec![
self.identity_trapdoor,
self.identity_nullifier,
self.identity_secret,
self.id_commitment,
];
let bytes = vec_fr_to_bytes_le(&vec_fr);
Uint8Array::from(&bytes[..])
}
#[wasm_bindgen(js_name = toBytesBE)]
pub fn to_bytes_be(&self) -> Uint8Array {
let vec_fr = vec![
self.identity_trapdoor,
self.identity_nullifier,
self.identity_secret,
self.id_commitment,
];
let bytes = vec_fr_to_bytes_be(&vec_fr);
Uint8Array::from(&bytes[..])
}
#[wasm_bindgen(js_name = fromBytesLE)]
pub fn from_bytes_le(bytes: &Uint8Array) -> Result<ExtendedIdentity, String> {
let bytes_vec = bytes.to_vec();
let (vec_fr, _) = bytes_le_to_vec_fr(&bytes_vec).map_err(|err| err.to_string())?;
if vec_fr.len() != 4 {
return Err(format!("Expected 4 elements, got {}", vec_fr.len()));
}
Ok(ExtendedIdentity {
identity_trapdoor: vec_fr[0],
identity_nullifier: vec_fr[1],
identity_secret: vec_fr[2],
id_commitment: vec_fr[3],
})
}
#[wasm_bindgen(js_name = fromBytesBE)]
pub fn from_bytes_be(bytes: &Uint8Array) -> Result<ExtendedIdentity, String> {
let bytes_vec = bytes.to_vec();
let (vec_fr, _) = bytes_be_to_vec_fr(&bytes_vec).map_err(|err| err.to_string())?;
if vec_fr.len() != 4 {
return Err(format!("Expected 4 elements, got {}", vec_fr.len()));
}
Ok(ExtendedIdentity {
identity_trapdoor: vec_fr[0],
identity_nullifier: vec_fr[1],
identity_secret: vec_fr[2],
id_commitment: vec_fr[3],
})
}
}

View File

@@ -1,23 +1,18 @@
#![cfg(target_arch = "wasm32")]
#![cfg(not(feature = "utils"))]
#[cfg(test)]
mod tests {
mod test {
use js_sys::{BigInt as JsBigInt, Date, Object, Uint8Array};
use rln::circuit::{Fr, TEST_TREE_DEPTH};
use rln::hashers::{hash_to_field_le, poseidon_hash, PoseidonHash};
use rln::protocol::{prepare_verify_input, rln_witness_from_values, serialize_witness};
use rln::utils::{bytes_le_to_fr, fr_to_bytes_le, IdSecret};
use rln::prelude::*;
use rln_wasm::{
wasm_generate_rln_proof_with_witness, wasm_new, wasm_rln_witness_to_json,
wasm_verify_with_roots,
Hasher, Identity, VecWasmFr, WasmFr, WasmRLN, WasmRLNProof, WasmRLNWitnessInput,
};
use rln_wasm_utils::wasm_key_gen;
use wasm_bindgen::{prelude::wasm_bindgen, JsValue};
use wasm_bindgen_test::{console_log, wasm_bindgen_test, wasm_bindgen_test_configure};
use zerokit_utils::{
use zerokit_utils::merkle_tree::{
OptimalMerkleProof, OptimalMerkleTree, ZerokitMerkleProof, ZerokitMerkleTree,
};
#[cfg(feature = "parallel")]
use {rln_wasm::init_thread_pool, wasm_bindgen_futures::JsFuture, web_sys::window};
@@ -85,154 +80,137 @@ mod tests {
pub async fn rln_wasm_benchmark() {
// Check if thread pool is supported
#[cfg(feature = "parallel")]
if !isThreadpoolSupported().expect("Failed to check thread pool support") {
if !isThreadpoolSupported().unwrap() {
panic!("Thread pool is NOT supported");
} else {
// Initialize thread pool
let cpu_count = window()
.expect("Failed to get window")
.navigator()
.hardware_concurrency() as usize;
JsFuture::from(init_thread_pool(cpu_count))
.await
.expect("Failed to initialize thread pool");
let cpu_count = window().unwrap().navigator().hardware_concurrency() as usize;
JsFuture::from(init_thread_pool(cpu_count)).await.unwrap();
}
// Initialize witness calculator
initWitnessCalculator(WITNESS_CALCULATOR_JS)
.expect("Failed to initialize witness calculator");
initWitnessCalculator(WITNESS_CALCULATOR_JS).unwrap();
let mut results = String::from("\nbenchmarks:\n");
let iterations = 10;
let zkey = readFile(&ARKZKEY_BYTES).expect("Failed to read zkey file");
let zkey = readFile(ARKZKEY_BYTES).unwrap();
// Benchmark wasm_new
let start_wasm_new = Date::now();
// Benchmark RLN instance creation
let start_rln_new = Date::now();
for _ in 0..iterations {
let _ = wasm_new(zkey.clone()).expect("Failed to create RLN instance");
let _ = WasmRLN::new(&zkey).unwrap();
}
let wasm_new_result = Date::now() - start_wasm_new;
let rln_new_result = Date::now() - start_rln_new;
// Create RLN instance for other benchmarks
let rln_instance = wasm_new(zkey).expect("Failed to create RLN instance");
let rln_instance = WasmRLN::new(&zkey).unwrap();
let mut tree: OptimalMerkleTree<PoseidonHash> =
OptimalMerkleTree::default(TEST_TREE_DEPTH).expect("Failed to create tree");
OptimalMerkleTree::default(DEFAULT_TREE_DEPTH).unwrap();
// Benchmark wasm_key_gen
let start_wasm_key_gen = Date::now();
// Benchmark generate identity
let start_identity_gen = Date::now();
for _ in 0..iterations {
let _ = wasm_key_gen(true).expect("Failed to generate keys");
let _ = Identity::generate().unwrap();
}
let wasm_key_gen_result = Date::now() - start_wasm_key_gen;
let identity_gen_result = Date::now() - start_identity_gen;
// Generate identity pair for other benchmarks
let mem_keys = wasm_key_gen(true).expect("Failed to generate keys");
let id_key = mem_keys.subarray(0, 32);
let (identity_secret_hash, _) = IdSecret::from_bytes_le(&id_key.to_vec());
let (id_commitment, _) = bytes_le_to_fr(&mem_keys.subarray(32, 64).to_vec());
// Generate identity for other benchmarks
let identity_pair = Identity::generate().unwrap();
let identity_secret = identity_pair.get_secret_hash();
let id_commitment = identity_pair.get_commitment();
let epoch = hash_to_field_le(b"test-epoch");
let rln_identifier = hash_to_field_le(b"test-rln-identifier");
let external_nullifier = poseidon_hash(&[epoch, rln_identifier]);
let epoch = Hasher::hash_to_field_le(&Uint8Array::from(b"test-epoch" as &[u8])).unwrap();
let rln_identifier =
Hasher::hash_to_field_le(&Uint8Array::from(b"test-rln-identifier" as &[u8])).unwrap();
let external_nullifier = Hasher::poseidon_hash_pair(&epoch, &rln_identifier).unwrap();
let identity_index = tree.leaves_set();
let user_message_limit = Fr::from(100);
let user_message_limit = WasmFr::from_uint(100);
let rate_commitment = poseidon_hash(&[id_commitment, user_message_limit]);
tree.update_next(rate_commitment)
.expect("Failed to update tree");
let rate_commitment =
Hasher::poseidon_hash_pair(&id_commitment, &user_message_limit).unwrap();
tree.update_next(*rate_commitment).unwrap();
let message_id = Fr::from(0);
let message_id = WasmFr::from_uint(0);
let signal: [u8; 32] = [0; 32];
let x = hash_to_field_le(&signal);
let x = Hasher::hash_to_field_le(&Uint8Array::from(&signal[..])).unwrap();
let merkle_proof: OptimalMerkleProof<PoseidonHash> = tree
.proof(identity_index)
.expect("Failed to generate merkle proof");
let merkle_proof: OptimalMerkleProof<PoseidonHash> = tree.proof(identity_index).unwrap();
let rln_witness = rln_witness_from_values(
identity_secret_hash,
merkle_proof.get_path_elements(),
merkle_proof.get_path_index(),
x,
external_nullifier,
user_message_limit,
message_id,
let mut path_elements = VecWasmFr::new();
for path_element in merkle_proof.get_path_elements() {
path_elements.push(&WasmFr::from(path_element));
}
let path_index = Uint8Array::from(&merkle_proof.get_path_index()[..]);
let witness = WasmRLNWitnessInput::new(
&identity_secret,
&user_message_limit,
&message_id,
&path_elements,
&path_index,
&x,
&external_nullifier,
)
.expect("Failed to create RLN witness");
.unwrap();
let serialized_witness =
serialize_witness(&rln_witness).expect("Failed to serialize witness");
let witness_buffer = Uint8Array::from(&serialized_witness[..]);
let bigint_json = witness.to_bigint_json().unwrap();
let json_inputs = wasm_rln_witness_to_json(rln_instance, witness_buffer.clone())
.expect("Failed to convert witness to JSON");
// Benchmark calculateWitness
// Benchmark witness calculation
let start_calculate_witness = Date::now();
for _ in 0..iterations {
let _ = calculateWitness(&CIRCOM_BYTES, json_inputs.clone())
let _ = calculateWitness(CIRCOM_BYTES, bigint_json.clone())
.await
.expect("Failed to calculate witness");
.unwrap();
}
let calculate_witness_result = Date::now() - start_calculate_witness;
// Calculate witness for other benchmarks
let calculated_witness_json = calculateWitness(&CIRCOM_BYTES, json_inputs)
let calculated_witness_str = calculateWitness(CIRCOM_BYTES, bigint_json.clone())
.await
.expect("Failed to calculate witness")
.unwrap()
.as_string()
.expect("Failed to convert calculated witness to string");
.unwrap();
let calculated_witness_vec_str: Vec<String> =
serde_json::from_str(&calculated_witness_json).expect("Failed to parse JSON");
serde_json::from_str(&calculated_witness_str).unwrap();
let calculated_witness: Vec<JsBigInt> = calculated_witness_vec_str
.iter()
.map(|x| JsBigInt::new(&x.into()).expect("Failed to create JsBigInt"))
.map(|x| JsBigInt::new(&x.into()).unwrap())
.collect();
// Benchmark wasm_generate_rln_proof_with_witness
let start_wasm_generate_rln_proof_with_witness = Date::now();
// Benchmark proof generation with witness
let start_generate_rln_proof_with_witness = Date::now();
for _ in 0..iterations {
let _ = wasm_generate_rln_proof_with_witness(
rln_instance,
calculated_witness.clone(),
witness_buffer.clone(),
)
.expect("Failed to generate proof");
let _ = rln_instance
.generate_rln_proof_with_witness(calculated_witness.clone(), &witness)
.unwrap();
}
let wasm_generate_rln_proof_with_witness_result =
Date::now() - start_wasm_generate_rln_proof_with_witness;
let generate_rln_proof_with_witness_result =
Date::now() - start_generate_rln_proof_with_witness;
// Generate a proof for other benchmarks
let proof =
wasm_generate_rln_proof_with_witness(rln_instance, calculated_witness, witness_buffer)
.expect("Failed to generate proof");
// Generate proof with witness for other benchmarks
let proof: WasmRLNProof = rln_instance
.generate_rln_proof_with_witness(calculated_witness, &witness)
.unwrap();
let proof_data = proof.to_vec();
let verify_input = prepare_verify_input(proof_data, &signal);
let input_buffer = Uint8Array::from(&verify_input[..]);
let root = WasmFr::from(tree.root());
let mut roots = VecWasmFr::new();
roots.push(&root);
let root = tree.root();
let roots_serialized = fr_to_bytes_le(&root);
let roots_buffer = Uint8Array::from(&roots_serialized[..]);
// Benchmark wasm_verify_with_roots
let start_wasm_verify_with_roots = Date::now();
// Benchmark proof verification with the root
let start_verify_with_roots = Date::now();
for _ in 0..iterations {
let _ =
wasm_verify_with_roots(rln_instance, input_buffer.clone(), roots_buffer.clone())
.expect("Failed to verify proof");
let _ = rln_instance.verify_with_roots(&proof, &roots, &x).unwrap();
}
let wasm_verify_with_roots_result = Date::now() - start_wasm_verify_with_roots;
let verify_with_roots_result = Date::now() - start_verify_with_roots;
// Verify the proof with the root
let is_proof_valid = wasm_verify_with_roots(rln_instance, input_buffer, roots_buffer)
.expect("Failed to verify proof");
// Verify proof with the root for other benchmarks
let is_proof_valid = rln_instance.verify_with_roots(&proof, &roots, &x).unwrap();
assert!(is_proof_valid, "verification failed");
// Format and display results
// Format and display the benchmark results
let format_duration = |duration_ms: f64| -> String {
let avg_ms = duration_ms / (iterations as f64);
if avg_ms >= 1000.0 {
@@ -242,22 +220,25 @@ mod tests {
}
};
results.push_str(&format!("wasm_new: {}\n", format_duration(wasm_new_result)));
results.push_str(&format!(
"wasm_key_gen: {}\n",
format_duration(wasm_key_gen_result)
"RLN instance creation: {}\n",
format_duration(rln_new_result)
));
results.push_str(&format!(
"calculateWitness: {}\n",
"Identity generation: {}\n",
format_duration(identity_gen_result)
));
results.push_str(&format!(
"Witness calculation: {}\n",
format_duration(calculate_witness_result)
));
results.push_str(&format!(
"wasm_generate_rln_proof_with_witness: {}\n",
format_duration(wasm_generate_rln_proof_with_witness_result)
"Proof generation with witness: {}\n",
format_duration(generate_rln_proof_with_witness_result)
));
results.push_str(&format!(
"wasm_verify_with_roots: {}\n",
format_duration(wasm_verify_with_roots_result)
"Proof verification with roots: {}\n",
format_duration(verify_with_roots_result)
));
// Log the results

View File

@@ -1,26 +1,19 @@
#![cfg(not(feature = "parallel"))]
#![cfg(target_arch = "wasm32")]
#![cfg(not(feature = "utils"))]
#[cfg(test)]
mod tests {
mod test {
use js_sys::{BigInt as JsBigInt, Date, Object, Uint8Array};
use rln::circuit::{Fr, TEST_TREE_DEPTH};
use rln::hashers::{hash_to_field_le, poseidon_hash, PoseidonHash};
use rln::protocol::{prepare_verify_input, rln_witness_from_values, serialize_witness};
use rln::utils::{bytes_le_to_fr, fr_to_bytes_le, IdSecret};
use rln::prelude::*;
use rln_wasm::{
wasm_generate_rln_proof_with_witness, wasm_new, wasm_rln_witness_to_json,
wasm_verify_with_roots,
Hasher, Identity, VecWasmFr, WasmFr, WasmRLN, WasmRLNProof, WasmRLNWitnessInput,
};
use rln_wasm_utils::wasm_key_gen;
use wasm_bindgen::{prelude::wasm_bindgen, JsValue};
use wasm_bindgen_test::{console_log, wasm_bindgen_test};
use zerokit_utils::{
use zerokit_utils::merkle_tree::{
OptimalMerkleProof, OptimalMerkleTree, ZerokitMerkleProof, ZerokitMerkleTree,
};
const WITNESS_CALCULATOR_JS: &str = include_str!("../resources/witness_calculator.js");
#[wasm_bindgen(inline_js = r#"
const fs = require("fs");
@@ -47,7 +40,7 @@ mod tests {
calculateWitness: async function (circom_path, inputs) {
const wasmFile = fs.readFileSync(circom_path);
const wasmFileBuffer = wasmFile.slice(
const wasmFileBuffer = wasmFile.buffer.slice(
wasmFile.byteOffset,
wasmFile.byteOffset + wasmFile.byteLength
);
@@ -73,6 +66,8 @@ mod tests {
async fn calculateWitness(circom_path: &str, input: Object) -> Result<JsValue, JsValue>;
}
const WITNESS_CALCULATOR_JS: &str = include_str!("../resources/witness_calculator.js");
const ARKZKEY_PATH: &str = "../rln/resources/tree_depth_20/rln_final.arkzkey";
const CIRCOM_PATH: &str = "../rln/resources/tree_depth_20/rln.wasm";
@@ -80,140 +75,128 @@ mod tests {
#[wasm_bindgen_test]
pub async fn rln_wasm_benchmark() {
// Initialize witness calculator
initWitnessCalculator(WITNESS_CALCULATOR_JS)
.expect("Failed to initialize witness calculator");
initWitnessCalculator(WITNESS_CALCULATOR_JS).unwrap();
let mut results = String::from("\nbenchmarks:\n");
let iterations = 10;
let zkey = readFile(&ARKZKEY_PATH).expect("Failed to read zkey file");
let zkey = readFile(ARKZKEY_PATH).unwrap();
// Benchmark wasm_new
let start_wasm_new = Date::now();
// Benchmark RLN instance creation
let start_rln_new = Date::now();
for _ in 0..iterations {
let _ = wasm_new(zkey.clone()).expect("Failed to create RLN instance");
let _ = WasmRLN::new(&zkey).unwrap();
}
let wasm_new_result = Date::now() - start_wasm_new;
let rln_new_result = Date::now() - start_rln_new;
// Create RLN instance for other benchmarks
let rln_instance = wasm_new(zkey).expect("Failed to create RLN instance");
let rln_instance = WasmRLN::new(&zkey).unwrap();
let mut tree: OptimalMerkleTree<PoseidonHash> =
OptimalMerkleTree::default(TEST_TREE_DEPTH).expect("Failed to create tree");
OptimalMerkleTree::default(DEFAULT_TREE_DEPTH).unwrap();
// Benchmark wasm_key_gen
let start_wasm_key_gen = Date::now();
// Benchmark generate identity
let start_identity_gen = Date::now();
for _ in 0..iterations {
let _ = wasm_key_gen(true).expect("Failed to generate keys");
let _ = Identity::generate().unwrap();
}
let wasm_key_gen_result = Date::now() - start_wasm_key_gen;
let identity_gen_result = Date::now() - start_identity_gen;
// Generate identity pair for other benchmarks
let mem_keys = wasm_key_gen(true).expect("Failed to generate keys");
let id_key = mem_keys.subarray(0, 32);
let (identity_secret_hash, _) = IdSecret::from_bytes_le(&id_key.to_vec());
let (id_commitment, _) = bytes_le_to_fr(&mem_keys.subarray(32, 64).to_vec());
// Generate identity for other benchmarks
let identity_pair = Identity::generate().unwrap();
let identity_secret = identity_pair.get_secret_hash();
let id_commitment = identity_pair.get_commitment();
let epoch = hash_to_field_le(b"test-epoch");
let rln_identifier = hash_to_field_le(b"test-rln-identifier");
let external_nullifier = poseidon_hash(&[epoch, rln_identifier]);
let epoch = Hasher::hash_to_field_le(&Uint8Array::from(b"test-epoch" as &[u8])).unwrap();
let rln_identifier =
Hasher::hash_to_field_le(&Uint8Array::from(b"test-rln-identifier" as &[u8])).unwrap();
let external_nullifier = Hasher::poseidon_hash_pair(&epoch, &rln_identifier).unwrap();
let identity_index = tree.leaves_set();
let user_message_limit = Fr::from(100);
let user_message_limit = WasmFr::from_uint(100);
let rate_commitment = poseidon_hash(&[id_commitment, user_message_limit]);
tree.update_next(rate_commitment)
.expect("Failed to update tree");
let rate_commitment =
Hasher::poseidon_hash_pair(&id_commitment, &user_message_limit).unwrap();
tree.update_next(*rate_commitment).unwrap();
let message_id = Fr::from(0);
let message_id = WasmFr::from_uint(0);
let signal: [u8; 32] = [0; 32];
let x = hash_to_field_le(&signal);
let x = Hasher::hash_to_field_le(&Uint8Array::from(&signal[..])).unwrap();
let merkle_proof: OptimalMerkleProof<PoseidonHash> = tree
.proof(identity_index)
.expect("Failed to generate merkle proof");
let merkle_proof: OptimalMerkleProof<PoseidonHash> = tree.proof(identity_index).unwrap();
let rln_witness = rln_witness_from_values(
identity_secret_hash,
merkle_proof.get_path_elements(),
merkle_proof.get_path_index(),
x,
external_nullifier,
user_message_limit,
message_id,
let mut path_elements = VecWasmFr::new();
for path_element in merkle_proof.get_path_elements() {
path_elements.push(&WasmFr::from(path_element));
}
let path_index = Uint8Array::from(&merkle_proof.get_path_index()[..]);
let witness = WasmRLNWitnessInput::new(
&identity_secret,
&user_message_limit,
&message_id,
&path_elements,
&path_index,
&x,
&external_nullifier,
)
.expect("Failed to create RLN witness");
.unwrap();
let serialized_witness =
serialize_witness(&rln_witness).expect("Failed to serialize witness");
let witness_buffer = Uint8Array::from(&serialized_witness[..]);
let bigint_json = witness.to_bigint_json().unwrap();
let json_inputs = wasm_rln_witness_to_json(rln_instance, witness_buffer.clone())
.expect("Failed to convert witness to JSON");
// Benchmark calculateWitness
// Benchmark witness calculation
let start_calculate_witness = Date::now();
for _ in 0..iterations {
let _ = calculateWitness(&CIRCOM_PATH, json_inputs.clone())
let _ = calculateWitness(CIRCOM_PATH, bigint_json.clone())
.await
.expect("Failed to calculate witness");
.unwrap();
}
let calculate_witness_result = Date::now() - start_calculate_witness;
// Calculate witness for other benchmarks
let calculated_witness_json = calculateWitness(&CIRCOM_PATH, json_inputs)
let calculated_witness_str = calculateWitness(CIRCOM_PATH, bigint_json.clone())
.await
.expect("Failed to calculate witness")
.unwrap()
.as_string()
.expect("Failed to convert calculated witness to string");
.unwrap();
let calculated_witness_vec_str: Vec<String> =
serde_json::from_str(&calculated_witness_json).expect("Failed to parse JSON");
serde_json::from_str(&calculated_witness_str).unwrap();
let calculated_witness: Vec<JsBigInt> = calculated_witness_vec_str
.iter()
.map(|x| JsBigInt::new(&x.into()).expect("Failed to create JsBigInt"))
.map(|x| JsBigInt::new(&x.into()).unwrap())
.collect();
// Benchmark wasm_generate_rln_proof_with_witness
let start_wasm_generate_rln_proof_with_witness = Date::now();
// Benchmark proof generation with witness
let start_generate_rln_proof_with_witness = Date::now();
for _ in 0..iterations {
let _ = wasm_generate_rln_proof_with_witness(
rln_instance,
calculated_witness.clone(),
witness_buffer.clone(),
)
.expect("Failed to generate proof");
let _ = rln_instance
.generate_rln_proof_with_witness(calculated_witness.clone(), &witness)
.unwrap();
}
let wasm_generate_rln_proof_with_witness_result =
Date::now() - start_wasm_generate_rln_proof_with_witness;
let generate_rln_proof_with_witness_result =
Date::now() - start_generate_rln_proof_with_witness;
// Generate a proof for other benchmarks
let proof =
wasm_generate_rln_proof_with_witness(rln_instance, calculated_witness, witness_buffer)
.expect("Failed to generate proof");
// Generate proof with witness for other benchmarks
let proof: WasmRLNProof = rln_instance
.generate_rln_proof_with_witness(calculated_witness, &witness)
.unwrap();
let proof_data = proof.to_vec();
let verify_input = prepare_verify_input(proof_data, &signal);
let input_buffer = Uint8Array::from(&verify_input[..]);
let root = WasmFr::from(tree.root());
let mut roots = VecWasmFr::new();
roots.push(&root);
let root = tree.root();
let roots_serialized = fr_to_bytes_le(&root);
let roots_buffer = Uint8Array::from(&roots_serialized[..]);
// Benchmark wasm_verify_with_roots
let start_wasm_verify_with_roots = Date::now();
// Benchmark proof verification with the root
let start_verify_with_roots = Date::now();
for _ in 0..iterations {
let _ =
wasm_verify_with_roots(rln_instance, input_buffer.clone(), roots_buffer.clone())
.expect("Failed to verify proof");
let _ = rln_instance.verify_with_roots(&proof, &roots, &x).unwrap();
}
let wasm_verify_with_roots_result = Date::now() - start_wasm_verify_with_roots;
let verify_with_roots_result = Date::now() - start_verify_with_roots;
// Verify the proof with the root
let is_proof_valid = wasm_verify_with_roots(rln_instance, input_buffer, roots_buffer)
.expect("Failed to verify proof");
// Verify proof with the root for other benchmarks
let is_proof_valid = rln_instance.verify_with_roots(&proof, &roots, &x).unwrap();
assert!(is_proof_valid, "verification failed");
// Format and display results
// Format and display the benchmark results
let format_duration = |duration_ms: f64| -> String {
let avg_ms = duration_ms / (iterations as f64);
if avg_ms >= 1000.0 {
@@ -223,22 +206,25 @@ mod tests {
}
};
results.push_str(&format!("wasm_new: {}\n", format_duration(wasm_new_result)));
results.push_str(&format!(
"wasm_key_gen: {}\n",
format_duration(wasm_key_gen_result)
"RLN instance creation: {}\n",
format_duration(rln_new_result)
));
results.push_str(&format!(
"calculate_witness: {}\n",
"Identity generation: {}\n",
format_duration(identity_gen_result)
));
results.push_str(&format!(
"Witness calculation: {}\n",
format_duration(calculate_witness_result)
));
results.push_str(&format!(
"wasm_generate_rln_proof_with_witness: {}\n",
format_duration(wasm_generate_rln_proof_with_witness_result)
"Proof generation with witness: {}\n",
format_duration(generate_rln_proof_with_witness_result)
));
results.push_str(&format!(
"wasm_verify_with_roots: {}\n",
format_duration(wasm_verify_with_roots_result)
"Proof verification with roots: {}\n",
format_duration(verify_with_roots_result)
));
// Log the results

222
rln-wasm/tests/utils.rs Normal file
View File

@@ -0,0 +1,222 @@
#![cfg(target_arch = "wasm32")]
#[cfg(test)]
mod test {
use std::assert_eq;
use ark_std::rand::thread_rng;
use js_sys::Uint8Array;
use rand::Rng;
use rln::prelude::*;
use rln_wasm::{ExtendedIdentity, Hasher, Identity, VecWasmFr, WasmFr};
use wasm_bindgen_test::wasm_bindgen_test;
#[wasm_bindgen_test]
fn test_keygen_wasm() {
let identity = Identity::generate().unwrap();
let identity_secret = *identity.get_secret_hash();
let id_commitment = *identity.get_commitment();
assert_ne!(identity_secret, Fr::from(0u8));
assert_ne!(id_commitment, Fr::from(0u8));
let arr = identity.to_array();
assert_eq!(arr.length(), 2);
assert_eq!(*arr.get(0).unwrap(), identity_secret);
assert_eq!(*arr.get(1).unwrap(), id_commitment);
}
#[wasm_bindgen_test]
fn test_extended_keygen_wasm() {
let identity = ExtendedIdentity::generate().unwrap();
let identity_trapdoor = *identity.get_trapdoor();
let identity_nullifier = *identity.get_nullifier();
let identity_secret = *identity.get_secret_hash();
let id_commitment = *identity.get_commitment();
assert_ne!(identity_trapdoor, Fr::from(0u8));
assert_ne!(identity_nullifier, Fr::from(0u8));
assert_ne!(identity_secret, Fr::from(0u8));
assert_ne!(id_commitment, Fr::from(0u8));
let arr = identity.to_array();
assert_eq!(arr.length(), 4);
assert_eq!(*arr.get(0).unwrap(), identity_trapdoor);
assert_eq!(*arr.get(1).unwrap(), identity_nullifier);
assert_eq!(*arr.get(2).unwrap(), identity_secret);
assert_eq!(*arr.get(3).unwrap(), id_commitment);
}
#[wasm_bindgen_test]
fn test_seeded_keygen_wasm() {
let seed_bytes: Vec<u8> = vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
let seed = Uint8Array::from(&seed_bytes[..]);
let identity = Identity::generate_seeded(&seed).unwrap();
let identity_secret = *identity.get_secret_hash();
let id_commitment = *identity.get_commitment();
let expected_identity_secret_seed_bytes = str_to_fr(
"0x766ce6c7e7a01bdf5b3f257616f603918c30946fa23480f2859c597817e6716",
16,
)
.unwrap();
let expected_id_commitment_seed_bytes = str_to_fr(
"0xbf16d2b5c0d6f9d9d561e05bfca16a81b4b873bb063508fae360d8c74cef51f",
16,
)
.unwrap();
assert_eq!(identity_secret, expected_identity_secret_seed_bytes);
assert_eq!(id_commitment, expected_id_commitment_seed_bytes);
}
#[wasm_bindgen_test]
fn test_seeded_extended_keygen_wasm() {
let seed_bytes: Vec<u8> = vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
let seed = Uint8Array::from(&seed_bytes[..]);
let identity = ExtendedIdentity::generate_seeded(&seed).unwrap();
let identity_trapdoor = *identity.get_trapdoor();
let identity_nullifier = *identity.get_nullifier();
let identity_secret = *identity.get_secret_hash();
let id_commitment = *identity.get_commitment();
let expected_identity_trapdoor_seed_bytes = str_to_fr(
"0x766ce6c7e7a01bdf5b3f257616f603918c30946fa23480f2859c597817e6716",
16,
)
.unwrap();
let expected_identity_nullifier_seed_bytes = str_to_fr(
"0x1f18714c7bc83b5bca9e89d404cf6f2f585bc4c0f7ed8b53742b7e2b298f50b4",
16,
)
.unwrap();
let expected_identity_secret_seed_bytes = str_to_fr(
"0x2aca62aaa7abaf3686fff2caf00f55ab9462dc12db5b5d4bcf3994e671f8e521",
16,
)
.unwrap();
let expected_id_commitment_seed_bytes = str_to_fr(
"0x68b66aa0a8320d2e56842581553285393188714c48f9b17acd198b4f1734c5c",
16,
)
.unwrap();
assert_eq!(identity_trapdoor, expected_identity_trapdoor_seed_bytes);
assert_eq!(identity_nullifier, expected_identity_nullifier_seed_bytes);
assert_eq!(identity_secret, expected_identity_secret_seed_bytes);
assert_eq!(id_commitment, expected_id_commitment_seed_bytes);
}
#[wasm_bindgen_test]
fn test_wasmfr() {
let wasmfr_zero = WasmFr::zero();
let fr_zero = Fr::from(0u8);
assert_eq!(*wasmfr_zero, fr_zero);
let wasmfr_one = WasmFr::one();
let fr_one = Fr::from(1u8);
assert_eq!(*wasmfr_one, fr_one);
let wasmfr_int = WasmFr::from_uint(42);
let fr_int = Fr::from(42u8);
assert_eq!(*wasmfr_int, fr_int);
let wasmfr_debug_str = wasmfr_int.debug();
assert_eq!(wasmfr_debug_str.to_string(), "42");
let identity = Identity::generate().unwrap();
let mut id_secret_fr = *identity.get_secret_hash();
let id_secret_hash = IdSecret::from(&mut id_secret_fr);
let id_commitment = *identity.get_commitment();
let wasmfr_id_secret_hash = *identity.get_secret_hash();
assert_eq!(wasmfr_id_secret_hash, *id_secret_hash);
let wasmfr_id_commitment = *identity.get_commitment();
assert_eq!(wasmfr_id_commitment, id_commitment);
}
#[wasm_bindgen_test]
fn test_vec_wasmfr() {
let vec_fr = vec![Fr::from(1u8), Fr::from(2u8), Fr::from(3u8), Fr::from(4u8)];
let mut vec_wasmfr = VecWasmFr::new();
for fr in &vec_fr {
vec_wasmfr.push(&WasmFr::from(*fr));
}
let bytes_le = vec_wasmfr.to_bytes_le();
let expected_le = rln::utils::vec_fr_to_bytes_le(&vec_fr);
assert_eq!(bytes_le.to_vec(), expected_le);
let bytes_be = vec_wasmfr.to_bytes_be();
let expected_be = rln::utils::vec_fr_to_bytes_be(&vec_fr);
assert_eq!(bytes_be.to_vec(), expected_be);
let vec_wasmfr_from_le = match VecWasmFr::from_bytes_le(&bytes_le) {
Ok(v) => v,
Err(err) => panic!("VecWasmFr::from_bytes_le call failed: {}", err),
};
assert_eq!(vec_wasmfr_from_le.length(), vec_wasmfr.length());
for i in 0..vec_wasmfr.length() {
assert_eq!(
*vec_wasmfr_from_le.get(i).unwrap(),
*vec_wasmfr.get(i).unwrap()
);
}
let vec_wasmfr_from_be = match VecWasmFr::from_bytes_be(&bytes_be) {
Ok(v) => v,
Err(err) => panic!("VecWasmFr::from_bytes_be call failed: {}", err),
};
for i in 0..vec_wasmfr.length() {
assert_eq!(
*vec_wasmfr_from_be.get(i).unwrap(),
*vec_wasmfr.get(i).unwrap()
);
}
}
#[wasm_bindgen_test]
fn test_hash_to_field_wasm() {
let mut rng = thread_rng();
let signal_gen: [u8; 32] = rng.gen();
let signal = Uint8Array::from(&signal_gen[..]);
let wasmfr_le_1 = Hasher::hash_to_field_le(&signal).unwrap();
let fr_le_2 = hash_to_field_le(&signal_gen).unwrap();
assert_eq!(*wasmfr_le_1, fr_le_2);
let wasmfr_be_1 = Hasher::hash_to_field_be(&signal).unwrap();
let fr_be_2 = hash_to_field_be(&signal_gen).unwrap();
assert_eq!(*wasmfr_be_1, fr_be_2);
assert_eq!(*wasmfr_le_1, *wasmfr_be_1);
assert_eq!(fr_le_2, fr_be_2);
let hash_wasmfr_le_1 = wasmfr_le_1.to_bytes_le();
let hash_fr_le_2 = fr_to_bytes_le(&fr_le_2);
assert_eq!(hash_wasmfr_le_1.to_vec(), hash_fr_le_2);
let hash_wasmfr_be_1 = wasmfr_be_1.to_bytes_be();
let hash_fr_be_2 = fr_to_bytes_be(&fr_be_2);
assert_eq!(hash_wasmfr_be_1.to_vec(), hash_fr_be_2);
assert_ne!(hash_wasmfr_le_1.to_vec(), hash_wasmfr_be_1.to_vec());
assert_ne!(hash_fr_le_2, hash_fr_be_2);
}
#[wasm_bindgen_test]
fn test_poseidon_hash_pair_wasm() {
let input_1 = Fr::from(42u8);
let input_2 = Fr::from(99u8);
let expected_hash = poseidon_hash(&[input_1, input_2]).unwrap();
let wasmfr_1 = WasmFr::from_uint(42);
let wasmfr_2 = WasmFr::from_uint(99);
let received_hash = Hasher::poseidon_hash_pair(&wasmfr_1, &wasmfr_2).unwrap();
assert_eq!(*received_hash, expected_hash);
}
}

View File

@@ -1,6 +1,6 @@
[package]
name = "rln"
version = "0.9.0"
version = "1.0.0"
edition = "2021"
license = "MIT OR Apache-2.0"
description = "APIs to manage, compute and verify zkSNARK proofs and RLN primitives"
@@ -12,7 +12,7 @@ repository = "https://github.com/vacp2p/zerokit"
crate-type = ["rlib", "staticlib", "cdylib"]
bench = false
# This flag disable cargo doctests, i.e. testing example code-snippets in documentation
# This flag disables cargo doctests, i.e. testing example code-snippets in documentation
doctest = false
[dependencies]
@@ -26,51 +26,59 @@ ark-poly = { version = "0.5.0", default-features = false }
ark-groth16 = { version = "0.5.0", default-features = false }
ark-serialize = { version = "0.5.0", default-features = false }
# error handling
thiserror = "2.0.12"
# Error Handling
thiserror = "2.0.17"
# utilities
rayon = { version = "1.10.0", optional = true }
# Utilities
rayon = { version = "1.11.0", optional = true }
byteorder = "1.5.0"
cfg-if = "1.0"
cfg-if = "1.0.4"
num-bigint = { version = "0.4.6", default-features = false, features = ["std"] }
num-traits = "0.2.19"
once_cell = "1.21.3"
lazy_static = "1.5.0"
rand = "0.8.5"
rand_chacha = "0.3.1"
ruint = { version = "1.15.0", features = ["rand", "serde", "ark-ff-04"] }
ruint = { version = "1.17.0", default-features = false, features = [
"rand",
"serde",
"ark-ff-05",
] }
tiny-keccak = { version = "2.0.2", features = ["keccak"] }
zeroize = "1.8"
tempfile = "3.21.0"
utils = { package = "zerokit_utils", version = "0.7.0", path = "../utils", default-features = false }
zeroize = "1.8.2"
tempfile = "3.23.0"
zerokit_utils = { version = "1.0.0", path = "../utils", default-features = false }
# serialization
# FFI
safer-ffi.version = "0.1"
# Serialization
prost = "0.14.1"
serde_json = "1.0.141"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0.145"
serde = { version = "1.0.228", features = ["derive"] }
document-features = { version = "0.2.11", optional = true }
# Documentation
document-features = { version = "0.2.12", optional = true }
[dev-dependencies]
criterion = { version = "0.7.0", features = ["html_reports"] }
criterion = { version = "0.8.0", features = ["html_reports"] }
[features]
default = ["parallel", "pmtree-ft"]
stateless = []
parallel = [
"rayon",
"utils/parallel",
"ark-ff/parallel",
"ark-ec/parallel",
"ark-std/parallel",
"ark-poly/parallel",
"ark-groth16/parallel",
"ark-serialize/parallel",
"zerokit_utils/parallel",
]
fullmerkletree = [] # Pre-allocated tree, fastest access
optimalmerkletree = [] # Sparse storage, memory efficient
pmtree-ft = ["utils/pmtree-ft"] # Persistent storage, disk-based
pmtree-ft = ["zerokit_utils/pmtree-ft"] # Persistent storage, disk-based
headers = ["safer-ffi/headers"] # Generate C header file with safer-ffi
[[bench]]
name = "pmtree_benchmark"
@@ -83,3 +91,7 @@ harness = false
[package.metadata.docs.rs]
all-features = true
[[bin]]
name = "generate-headers"
required-features = ["headers"] # Do not build unless generating headers.

View File

@@ -8,7 +8,15 @@ args = ["test", "--release", "--", "--nocapture"]
[tasks.test_stateless]
command = "cargo"
args = ["test", "--release", "--no-default-features", "--features", "stateless"]
args = [
"test",
"--release",
"--no-default-features",
"--features",
"stateless",
"--",
"--nocapture",
]
[tasks.bench]
command = "cargo"

View File

@@ -5,7 +5,7 @@
[![License: Apache 2.0](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0)
The Zerokit RLN Module provides a Rust implementation for working with
Rate-Limiting Nullifier [RLN](https://rfc.vac.dev/spec/32/) zkSNARK proofs and primitives.
Rate-Limiting Nullifier [RLN](https://rfc.vac.dev/vac/raw/rln-v2) zkSNARK proofs and primitives.
This module allows you to:
- Generate and verify RLN proofs
@@ -24,7 +24,7 @@ We start by adding zerokit RLN to our `Cargo.toml`
```toml
[dependencies]
rln = { git = "https://github.com/vacp2p/zerokit" }
rln = "1.0.0"
```
## Basic Usage Example
@@ -36,93 +36,70 @@ The RLN object constructor requires the following files:
Additionally, `rln.wasm` is used for testing in the rln-wasm module.
In the following we will use [cursors](https://doc.rust-lang.org/std/io/struct.Cursor.html)
as readers/writers for interfacing with RLN public APIs.
```rust
use std::io::Cursor;
use rln::{
circuit::Fr,
hashers::{hash_to_field, poseidon_hash},
protocol::{keygen, prepare_prove_input, prepare_verify_input},
public::RLN,
utils::fr_to_bytes_le,
};
use serde_json::json;
use rln::prelude::{keygen, poseidon_hash, hash_to_field_le, RLN, RLNWitnessInput, Fr, IdSecret};
fn main() {
// 1. Initialize RLN with parameters:
// - the tree depth;
// - the tree config, if it is not defined, the default value will be set
let tree_depth = 20;
let input = Cursor::new(json!({}).to_string());
let mut rln = RLN::new(tree_depth, input).unwrap();
let mut rln = RLN::new(tree_depth, "").unwrap();
// 2. Generate an identity keypair
let (identity_secret_hash, id_commitment) = keygen();
let (identity_secret, id_commitment) = keygen();
// 3. Add a rate commitment to the Merkle tree
let id_index = 10;
let leaf_index = 10;
let user_message_limit = Fr::from(10);
let rate_commitment = poseidon_hash(&[id_commitment, user_message_limit]);
let mut buffer = Cursor::new(fr_to_bytes_le(&rate_commitment));
rln.set_leaf(id_index, &mut buffer).unwrap();
rln.set_leaf(leaf_index, rate_commitment).unwrap();
// 4. Set up external nullifier (epoch + app identifier)
// 4. Get the Merkle proof for the added commitment
let (path_elements, identity_path_index) = rln.get_merkle_proof(leaf_index).unwrap();
// 5. Set up external nullifier (epoch + app identifier)
// We generate epoch from a date seed and we ensure is
// mapped to a field element by hashing-to-field its content
let epoch = hash_to_field(b"Today at noon, this year");
// We generate rln_identifier from a date seed and we ensure is
// mapped to a field element by hashing-to-field its content
let rln_identifier = hash_to_field(b"test-rln-identifier");
let epoch = hash_to_field_le(b"Today at noon, this year");
// We generate rln_identifier from an application identifier and
// we ensure is mapped to a field element by hashing-to-field its content
let rln_identifier = hash_to_field_le(b"test-rln-identifier");
// We generate a external nullifier
let external_nullifier = poseidon_hash(&[epoch, rln_identifier]);
// We choose a message_id satisfy 0 <= message_id < user_message_limit
let message_id = Fr::from(1);
// 5. Generate and verify a proof for a message
// 6. Define the message signal
let signal = b"RLN is awesome";
// 6. Prepare input for generate_rln_proof API
// input_data is [ identity_secret<32> | id_index<8> | external_nullifier<32>
// | user_message_limit<32> | message_id<32> | signal_len<8> | signal<var> ]
let prove_input = prepare_prove_input(
identity_secret_hash,
id_index,
// 7. Compute x from the signal
let x = hash_to_field_le(signal);
// 8. Create witness input for RLN proof generation
let witness = RLNWitnessInput::new(
identity_secret,
user_message_limit,
message_id,
path_elements,
identity_path_index,
x,
external_nullifier,
signal,
);
)
.unwrap();
// 7. Generate a RLN proof
// We generate a RLN proof for proof_input
let mut input_buffer = Cursor::new(prove_input);
let mut output_buffer = Cursor::new(Vec::<u8>::new());
rln.generate_rln_proof(&mut input_buffer, &mut output_buffer)
.unwrap();
// 9. Generate a RLN proof
// We generate proof and proof values from the witness
let (proof, proof_values) = rln.generate_rln_proof(&witness).unwrap();
// We get the public outputs returned by the circuit evaluation
// The byte vector `proof_data` is serialized as
// `[ zk-proof | tree_root | external_nullifier | share_x | share_y | nullifier ]`.
let proof_data = output_buffer.into_inner();
// 8. Verify a RLN proof
// Input buffer is serialized as `[proof_data | signal_len | signal ]`,
// where `proof_data` is (computed as) the output obtained by `generate_rln_proof`.
let verify_data = prepare_verify_input(proof_data, signal);
// We verify the zk-proof against the provided proof values
let mut input_buffer = Cursor::new(verify_data);
let verified = rln.verify_rln_proof(&mut input_buffer).unwrap();
// We ensure the proof is valid
// 10. Verify the RLN proof
// We verify the proof using the proof and proof values and the hashed signal x
let verified = rln.verify_rln_proof(&proof, &proof_values, &x).unwrap();
assert!(verified);
}
```
### Comments for the code above for point 4
### Comments for the code above for point 5
The `external nullifier` includes two parameters.
@@ -171,8 +148,8 @@ cargo make test_stateless
## Advanced: Custom Circuit Compilation
The `rln` (<https://github.com/rate-limiting-nullifier/circom-rln>) repository,
which contains the RLN circuit implementation is using for pre-compiled RLN circuit for zerokit RLN.
The `circom-rln` (<https://github.com/rate-limiting-nullifier/circom-rln>) repository,
which contains the RLN circuit implementation used for pre-compiled RLN circuit for zerokit RLN.
If you want to compile your own RLN circuit, you can follow the instructions below.
### 1. Compile ZK Circuits for getting the zkey file
@@ -205,15 +182,15 @@ Where:
> for instructions on how to run an appropriate Powers of Tau ceremony and Phase 2 in order to compile the desired circuit. \
> Additionally, while `M` sets an upper bound on the number of messages per epoch (`2^M`),
> you can configure lower message limit for your use case, as long as it satisfies `user_message_limit ≤ 2^M`. \
> Currently, the `rln` module comes with a [pre-compiled](https://github.com/vacp2p/zerokit/tree/master/rln/resources)
> Currently, the `rln` module comes with a [pre-compiled](https://github.com/vacp2p/zerokit/tree/master/rln/resources/tree_depth_20)
> RLN circuit with a Merkle tree of depth `20` and a bit size of `16`,
> allowing up to `2^20` registered members and a `2^16` message limit per epoch.
#### Install circom compiler
You can follow the instructions below or refer to the
[installing Circom](https://docs.circom.io/getting-started/installation/#installing-circom) guide for more details,
but make sure to use the specific version `v2.1.0`.
[installing Circom](https://docs.circom.io/getting-started/installation/#installing-circom) guide for more details.
Make sure to use the specific version `v2.1.0`.
```sh
# Clone the circom repository
@@ -268,7 +245,7 @@ cargo build
cargo run --package circom_witnesscalc --bin build-circuit ../circom-rln/circuits/rln.circom <path_to_graph.bin>
```
The `rln` module comes with [pre-compiled](https://github.com/vacp2p/zerokit/tree/master/rln/resources)
The `rln` module comes with [pre-compiled](https://github.com/vacp2p/zerokit/tree/master/rln/resources/tree_depth_20)
execution graph files for the RLN circuit.
### 3. Generate Arkzkey Representation for zkey file
@@ -291,7 +268,7 @@ cargo run --bin arkzkey-util <path_to_rln_final.zkey>
This will generate the `rln_final.arkzkey` file, which is used by the `rln` module.
Currently, the `rln` module comes with
[pre-compiled](https://github.com/vacp2p/zerokit/tree/master/rln/resources) arkzkey keys for the RLN circuit.
[pre-compiled](https://github.com/vacp2p/zerokit/tree/master/rln/resources/tree_depth_20) arkzkey keys for the RLN circuit.
> [!NOTE]
> You can use this [convert_zkey.sh](./convert_zkey.sh) script
@@ -304,17 +281,26 @@ chmod +x ./convert_zkey.sh
./convert_zkey.sh <path_to_rln_final.zkey>
```
## Get involved
## FFI Interface
Zerokit RLN public and FFI APIs allow interaction with many more features than what briefly showcased above.
RLN provides C-compatible bindings for integration with C, C++, Nim, and other languages through [safer_ffi](https://getditto.github.io/safer_ffi/).
We invite you to check our API documentation by running
The FFI layer is organized into several modules:
```rust
cargo doc --no-deps
```
- [`ffi_rln.rs`](./src/ffi/ffi_rln.rs) Implements core RLN functionality, including initialization functions, proof generation, and proof verification.
- [`ffi_tree.rs`](./src/ffi/ffi_tree.rs) Provides all tree-related operations and helper functions for Merkle tree management.
- [`ffi_utils.rs`](./src/ffi/ffi_utils.rs) Contains all utility functions and structure definitions used across the FFI layer.
and look at unit tests to have an hint on how to interface and use them.
### Examples
Working examples demonstrating proof generation, proof verification and slashing in C and Nim:
- [C example](./ffi_c_examples/main.c) and [README](./ffi_c_examples/Readme.md)
- [Nim example](./ffi_nim_examples/main.nim) and [README](./ffi_nim_examples/Readme.md)
### Memory Management
- All **heap-allocated** objects returned from Rust FFI **must** be freed using their corresponding FFI `_free` functions.
## Detailed Protocol Flow
@@ -326,9 +312,20 @@ and look at unit tests to have an hint on how to interface and use them.
- Ensures rate-limiting constraints are satisfied
- Generates a nullifier to prevent double-usage
5. **Proof Verification**: Verify the proof without revealing the prover's identity
6. **Slashing Mechanism**: Detect and penalize double-usage attempts
## Getting Involved
Zerokit RLN public and FFI APIs allow interaction with many more features than what briefly showcased above.
We invite you to check our API documentation by running
```bash
cargo doc --no-deps
```
and look at unit tests to have an hint on how to interface and use them.
- Check the [unit tests](https://github.com/vacp2p/zerokit/tree/master/rln/tests) for more usage examples
- [RFC specification](https://rfc.vac.dev/spec/32/) for the Rate-Limiting Nullifier protocol
- [RFC specification](https://rfc.vac.dev/vac/raw/rln-v2) for the Rate-Limiting Nullifier protocol
- [GitHub repository](https://github.com/vacp2p/zerokit) for the latest updates

View File

@@ -1,6 +1,6 @@
use criterion::{criterion_group, criterion_main, Criterion};
use rln::{circuit::Fr, pm_tree_adapter::PmTree};
use utils::ZerokitMerkleTree;
use rln::prelude::*;
use zerokit_utils::merkle_tree::ZerokitMerkleTree;
pub fn pmtree_benchmark(c: &mut Criterion) {
let mut tree = PmTree::default(2).unwrap();
@@ -13,7 +13,7 @@ pub fn pmtree_benchmark(c: &mut Criterion) {
})
});
c.bench_function("Pmtree:delete", |b| {
c.bench_function("Pmtree::delete", |b| {
b.iter(|| {
tree.delete(0).unwrap();
})

View File

@@ -1,9 +1,6 @@
use criterion::{criterion_group, criterion_main, BenchmarkId, Criterion};
use rln::{
circuit::{Fr, TEST_TREE_DEPTH},
hashers::PoseidonHash,
};
use utils::{FullMerkleTree, OptimalMerkleTree, ZerokitMerkleTree};
use rln::prelude::*;
use zerokit_utils::merkle_tree::{FullMerkleTree, OptimalMerkleTree, ZerokitMerkleTree};
pub fn get_leaves(n: u32) -> Vec<Fr> {
(0..n).map(Fr::from).collect()
@@ -12,7 +9,7 @@ pub fn get_leaves(n: u32) -> Vec<Fr> {
pub fn optimal_merkle_tree_poseidon_benchmark(c: &mut Criterion) {
c.bench_function("OptimalMerkleTree::<Poseidon>::full_depth_gen", |b| {
b.iter(|| {
OptimalMerkleTree::<PoseidonHash>::default(TEST_TREE_DEPTH).unwrap();
OptimalMerkleTree::<PoseidonHash>::default(DEFAULT_TREE_DEPTH).unwrap();
})
});
@@ -20,7 +17,7 @@ pub fn optimal_merkle_tree_poseidon_benchmark(c: &mut Criterion) {
for &n in [1u32, 10, 100].iter() {
let leaves = get_leaves(n);
let mut tree = OptimalMerkleTree::<PoseidonHash>::default(TEST_TREE_DEPTH).unwrap();
let mut tree = OptimalMerkleTree::<PoseidonHash>::default(DEFAULT_TREE_DEPTH).unwrap();
group.bench_function(
BenchmarkId::new("OptimalMerkleTree::<Poseidon>::set", n),
|b| {
@@ -43,7 +40,7 @@ pub fn optimal_merkle_tree_poseidon_benchmark(c: &mut Criterion) {
pub fn full_merkle_tree_poseidon_benchmark(c: &mut Criterion) {
c.bench_function("FullMerkleTree::<Poseidon>::full_depth_gen", |b| {
b.iter(|| {
FullMerkleTree::<PoseidonHash>::default(TEST_TREE_DEPTH).unwrap();
FullMerkleTree::<PoseidonHash>::default(DEFAULT_TREE_DEPTH).unwrap();
})
});
@@ -51,7 +48,7 @@ pub fn full_merkle_tree_poseidon_benchmark(c: &mut Criterion) {
for &n in [1u32, 10, 100].iter() {
let leaves = get_leaves(n);
let mut tree = FullMerkleTree::<PoseidonHash>::default(TEST_TREE_DEPTH).unwrap();
let mut tree = FullMerkleTree::<PoseidonHash>::default(DEFAULT_TREE_DEPTH).unwrap();
group.bench_function(
BenchmarkId::new("FullMerkleTree::<Poseidon>::set", n),
|b| {

View File

@@ -1,7 +1,7 @@
#!/bin/bash
# Convert zkey to arkzkey using /tmp directory
# Usage: ./convert.sh <path_to_zkey_file>
# Usage: ./convert_zkey.sh <path_to_zkey_file>
set -e
@@ -50,4 +50,7 @@ ARKZKEY_FILE="${ZKEY_ABSOLUTE_PATH%.zkey}.arkzkey"
if [ ! -f "$ARKZKEY_FILE" ]; then
echo "Could not find generated .arkzkey file at $ARKZKEY_FILE"
exit 1
fi
fi
echo "Conversion successful!"
echo "Output file: $ARKZKEY_FILE"

View File

@@ -0,0 +1,47 @@
# RLN FFI C example
This example demonstrates how to use the RLN C FFI in both stateless and non-stateless modes.
## Non-stateless mode
### Compile lib non-stateless
```bash
cargo build -p rln
cargo run --features headers --bin generate-headers
mv -v rln.h rln/ffi_c_examples/
```
### Compile and run example non-stateless
```bash
cd rln/ffi_c_examples/
gcc -Wall main.c -o main -lrln -L../../target/debug
./main
```
## Stateless mode
### Compile lib stateless
```bash
cargo build -p rln --no-default-features --features stateless
cargo run --no-default-features --features stateless,headers --bin generate-headers
mv -v rln.h rln/ffi_c_examples/
```
### Compile example stateless
```bash
cd rln/ffi_c_examples/
gcc -Wall -DSTATELESS main.c -o main -lrln -L../../target/debug
./main
```
## Note
### Find C lib used by Rust
```bash
cargo +nightly rustc --release -p rln -- -Z unstable-options --print native-static-libs
```

668
rln/ffi_c_examples/main.c Normal file
View File

@@ -0,0 +1,668 @@
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "rln.h"
int main(int argc, char const *const argv[])
{
printf("Creating RLN instance\n");
#ifdef STATELESS
CResult_FFI_RLN_ptr_Vec_uint8_t ffi_rln_new_result = ffi_rln_new();
#else
const char *config_path = "../resources/tree_depth_20/config.json";
CResult_FFI_RLN_ptr_Vec_uint8_t ffi_rln_new_result = ffi_rln_new(20, config_path);
#endif
if (!ffi_rln_new_result.ok)
{
fprintf(stderr, "Initial RLN instance creation error: %s\n", ffi_rln_new_result.err.ptr);
ffi_c_string_free(ffi_rln_new_result.err);
return EXIT_FAILURE;
}
FFI_RLN_t *rln = ffi_rln_new_result.ok;
printf("RLN instance created successfully\n");
printf("\nGenerating identity keys\n");
CResult_Vec_CFr_Vec_uint8_t keys_result = ffi_key_gen();
if (keys_result.err.ptr)
{
fprintf(stderr, "Key generation error: %s\n", keys_result.err.ptr);
ffi_c_string_free(keys_result.err);
return EXIT_FAILURE;
}
Vec_CFr_t keys = keys_result.ok;
const CFr_t *identity_secret = ffi_vec_cfr_get(&keys, 0);
const CFr_t *id_commitment = ffi_vec_cfr_get(&keys, 1);
printf("Identity generated\n");
Vec_uint8_t debug = ffi_cfr_debug(identity_secret);
printf(" - identity_secret = %s\n", debug.ptr);
ffi_c_string_free(debug);
debug = ffi_cfr_debug(id_commitment);
printf(" - id_commitment = %s\n", debug.ptr);
ffi_c_string_free(debug);
printf("\nCreating message limit\n");
CFr_t *user_message_limit = ffi_uint_to_cfr(1);
debug = ffi_cfr_debug(user_message_limit);
printf(" - user_message_limit = %s\n", debug.ptr);
ffi_c_string_free(debug);
printf("\nComputing rate commitment\n");
CResult_CFr_ptr_Vec_uint8_t rate_commitment_result = ffi_poseidon_hash_pair(id_commitment, user_message_limit);
if (!rate_commitment_result.ok)
{
fprintf(stderr, "Rate commitment hash error: %s\n", rate_commitment_result.err.ptr);
ffi_c_string_free(rate_commitment_result.err);
return EXIT_FAILURE;
}
CFr_t *rate_commitment = rate_commitment_result.ok;
debug = ffi_cfr_debug(rate_commitment);
printf(" - rate_commitment = %s\n", debug.ptr);
ffi_c_string_free(debug);
printf("\nCFr serialization: CFr <-> bytes\n");
Vec_uint8_t ser_rate_commitment = ffi_cfr_to_bytes_le(rate_commitment);
debug = ffi_vec_u8_debug(&ser_rate_commitment);
printf(" - serialized rate_commitment = %s\n", debug.ptr);
ffi_c_string_free(debug);
CResult_CFr_ptr_Vec_uint8_t deser_rate_commitment_result = ffi_bytes_le_to_cfr(&ser_rate_commitment);
if (!deser_rate_commitment_result.ok)
{
fprintf(stderr, "Rate commitment deserialization error: %s\n", deser_rate_commitment_result.err.ptr);
ffi_c_string_free(deser_rate_commitment_result.err);
return EXIT_FAILURE;
}
CFr_t *deser_rate_commitment = deser_rate_commitment_result.ok;
debug = ffi_cfr_debug(deser_rate_commitment);
printf(" - deserialized rate_commitment = %s\n", debug.ptr);
ffi_c_string_free(debug);
ffi_vec_u8_free(ser_rate_commitment);
ffi_cfr_free(deser_rate_commitment);
printf("\nVec<CFr> serialization: Vec<CFr> <-> bytes\n");
Vec_uint8_t ser_keys = ffi_vec_cfr_to_bytes_le(&keys);
debug = ffi_vec_u8_debug(&ser_keys);
printf(" - serialized keys = %s\n", debug.ptr);
ffi_c_string_free(debug);
CResult_Vec_CFr_Vec_uint8_t deser_keys_result = ffi_bytes_le_to_vec_cfr(&ser_keys);
if (deser_keys_result.err.ptr)
{
fprintf(stderr, "Keys deserialization error: %s\n", deser_keys_result.err.ptr);
ffi_c_string_free(deser_keys_result.err);
return EXIT_FAILURE;
}
debug = ffi_vec_cfr_debug(&deser_keys_result.ok);
printf(" - deserialized keys = %s\n", debug.ptr);
ffi_c_string_free(debug);
Vec_CFr_t deser_keys = deser_keys_result.ok;
ffi_vec_cfr_free(deser_keys);
ffi_vec_u8_free(ser_keys);
#ifdef STATELESS
#define TREE_DEPTH 20
#define CFR_SIZE 32
printf("\nBuilding Merkle path for stateless mode\n");
CFr_t *default_leaf = ffi_cfr_zero();
CFr_t *default_hashes[TREE_DEPTH - 1];
CResult_CFr_ptr_Vec_uint8_t hash_result = ffi_poseidon_hash_pair(default_leaf, default_leaf);
if (!hash_result.ok)
{
fprintf(stderr, "Poseidon hash error: %s\n", hash_result.err.ptr);
ffi_c_string_free(hash_result.err);
return EXIT_FAILURE;
}
default_hashes[0] = hash_result.ok;
for (size_t i = 1; i < TREE_DEPTH - 1; i++)
{
hash_result = ffi_poseidon_hash_pair(default_hashes[i - 1], default_hashes[i - 1]);
if (!hash_result.ok)
{
fprintf(stderr, "Poseidon hash error: %s\n", hash_result.err.ptr);
ffi_c_string_free(hash_result.err);
return EXIT_FAILURE;
}
default_hashes[i] = hash_result.ok;
}
Vec_CFr_t path_elements = ffi_vec_cfr_new(TREE_DEPTH);
ffi_vec_cfr_push(&path_elements, default_leaf);
for (size_t i = 0; i < TREE_DEPTH - 1; i++)
{
ffi_vec_cfr_push(&path_elements, default_hashes[i]);
}
printf("\nVec<CFr> serialization: Vec<CFr> <-> bytes\n");
Vec_uint8_t ser_path_elements = ffi_vec_cfr_to_bytes_le(&path_elements);
debug = ffi_vec_u8_debug(&ser_path_elements);
printf(" - serialized path_elements = %s\n", debug.ptr);
ffi_c_string_free(debug);
CResult_Vec_CFr_Vec_uint8_t deser_path_elements_result = ffi_bytes_le_to_vec_cfr(&ser_path_elements);
if (deser_path_elements_result.err.ptr)
{
fprintf(stderr, "Path elements deserialization error: %s\n", deser_path_elements_result.err.ptr);
ffi_c_string_free(deser_path_elements_result.err);
return EXIT_FAILURE;
}
debug = ffi_vec_cfr_debug(&deser_path_elements_result.ok);
printf(" - deserialized path_elements = %s\n", debug.ptr);
ffi_c_string_free(debug);
Vec_CFr_t deser_path_elements = deser_path_elements_result.ok;
ffi_vec_cfr_free(deser_path_elements);
ffi_vec_u8_free(ser_path_elements);
uint8_t path_index_arr[TREE_DEPTH] = {0};
Vec_uint8_t identity_path_index = {
.ptr = path_index_arr,
.len = TREE_DEPTH,
.cap = TREE_DEPTH};
printf("\nVec<uint8> serialization: Vec<uint8> <-> bytes\n");
Vec_uint8_t ser_path_index = ffi_vec_u8_to_bytes_le(&identity_path_index);
debug = ffi_vec_u8_debug(&ser_path_index);
printf(" - serialized path_index = %s\n", debug.ptr);
ffi_c_string_free(debug);
CResult_Vec_uint8_Vec_uint8_t deser_path_index_result = ffi_bytes_le_to_vec_u8(&ser_path_index);
if (deser_path_index_result.err.ptr)
{
fprintf(stderr, "Path index deserialization error: %s\n", deser_path_index_result.err.ptr);
ffi_c_string_free(deser_path_index_result.err);
return EXIT_FAILURE;
}
debug = ffi_vec_u8_debug(&deser_path_index_result.ok);
printf(" - deserialized path_index = %s\n", debug.ptr);
ffi_c_string_free(debug);
Vec_uint8_t deser_path_index = deser_path_index_result.ok;
ffi_vec_u8_free(deser_path_index);
ffi_vec_u8_free(ser_path_index);
printf("\nComputing Merkle root for stateless mode\n");
printf(" - computing root for index 0 with rate_commitment\n");
CResult_CFr_ptr_Vec_uint8_t root_result = ffi_poseidon_hash_pair(rate_commitment, default_leaf);
if (!root_result.ok)
{
fprintf(stderr, "Poseidon hash error: %s\n", root_result.err.ptr);
ffi_c_string_free(root_result.err);
return EXIT_FAILURE;
}
CFr_t *computed_root = root_result.ok;
for (size_t i = 1; i < TREE_DEPTH; i++)
{
root_result = ffi_poseidon_hash_pair(computed_root, default_hashes[i - 1]);
if (!root_result.ok)
{
fprintf(stderr, "Poseidon hash error: %s\n", root_result.err.ptr);
ffi_c_string_free(root_result.err);
return EXIT_FAILURE;
}
CFr_t *next_root = root_result.ok;
ffi_cfr_free(computed_root);
computed_root = next_root;
}
debug = ffi_cfr_debug(computed_root);
printf(" - computed_root = %s\n", debug.ptr);
ffi_c_string_free(debug);
#else
printf("\nAdding rate_commitment to tree\n");
CBoolResult_t set_err = ffi_set_next_leaf(&rln, rate_commitment);
if (!set_err.ok)
{
fprintf(stderr, "Set next leaf error: %s\n", set_err.err.ptr);
ffi_c_string_free(set_err.err);
return EXIT_FAILURE;
}
size_t leaf_index = ffi_leaves_set(&rln) - 1;
printf(" - added to tree at index %zu\n", leaf_index);
printf("\nGetting Merkle proof\n");
CResult_FFI_MerkleProof_ptr_Vec_uint8_t proof_result = ffi_get_merkle_proof(&rln, leaf_index);
if (!proof_result.ok)
{
fprintf(stderr, "Get proof error: %s\n", proof_result.err.ptr);
ffi_c_string_free(proof_result.err);
return EXIT_FAILURE;
}
FFI_MerkleProof_t *merkle_proof = proof_result.ok;
printf(" - proof obtained (depth: %zu)\n", merkle_proof->path_elements.len);
#endif
printf("\nHashing signal\n");
uint8_t signal[32] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
Vec_uint8_t signal_vec = {signal, 32, 32};
CResult_CFr_ptr_Vec_uint8_t x_result = ffi_hash_to_field_le(&signal_vec);
if (!x_result.ok)
{
fprintf(stderr, "Hash signal error: %s\n", x_result.err.ptr);
ffi_c_string_free(x_result.err);
return EXIT_FAILURE;
}
CFr_t *x = x_result.ok;
debug = ffi_cfr_debug(x);
printf(" - x = %s\n", debug.ptr);
ffi_c_string_free(debug);
printf("\nHashing epoch\n");
const char *epoch_str = "test-epoch";
Vec_uint8_t epoch_vec = {(uint8_t *)epoch_str, strlen(epoch_str), strlen(epoch_str)};
CResult_CFr_ptr_Vec_uint8_t epoch_result = ffi_hash_to_field_le(&epoch_vec);
if (!epoch_result.ok)
{
fprintf(stderr, "Hash epoch error: %s\n", epoch_result.err.ptr);
ffi_c_string_free(epoch_result.err);
return EXIT_FAILURE;
}
CFr_t *epoch = epoch_result.ok;
debug = ffi_cfr_debug(epoch);
printf(" - epoch = %s\n", debug.ptr);
ffi_c_string_free(debug);
printf("\nHashing RLN identifier\n");
const char *rln_id_str = "test-rln-identifier";
Vec_uint8_t rln_id_vec = {(uint8_t *)rln_id_str, strlen(rln_id_str), strlen(rln_id_str)};
CResult_CFr_ptr_Vec_uint8_t rln_identifier_result = ffi_hash_to_field_le(&rln_id_vec);
if (!rln_identifier_result.ok)
{
fprintf(stderr, "Hash RLN identifier error: %s\n", rln_identifier_result.err.ptr);
ffi_c_string_free(rln_identifier_result.err);
return EXIT_FAILURE;
}
CFr_t *rln_identifier = rln_identifier_result.ok;
debug = ffi_cfr_debug(rln_identifier);
printf(" - rln_identifier = %s\n", debug.ptr);
ffi_c_string_free(debug);
printf("\nComputing Poseidon hash for external nullifier\n");
CResult_CFr_ptr_Vec_uint8_t external_nullifier_result = ffi_poseidon_hash_pair(epoch, rln_identifier);
if (!external_nullifier_result.ok)
{
fprintf(stderr, "External nullifier hash error: %s\n", external_nullifier_result.err.ptr);
ffi_c_string_free(external_nullifier_result.err);
return EXIT_FAILURE;
}
CFr_t *external_nullifier = external_nullifier_result.ok;
debug = ffi_cfr_debug(external_nullifier);
printf(" - external_nullifier = %s\n", debug.ptr);
ffi_c_string_free(debug);
printf("\nCreating message_id\n");
CFr_t *message_id = ffi_uint_to_cfr(0);
debug = ffi_cfr_debug(message_id);
printf(" - message_id = %s\n", debug.ptr);
ffi_c_string_free(debug);
printf("\nCreating RLN Witness\n");
#ifdef STATELESS
CResult_FFI_RLNWitnessInput_ptr_Vec_uint8_t witness_result = ffi_rln_witness_input_new(
identity_secret,
user_message_limit,
message_id,
&path_elements,
&identity_path_index,
x,
external_nullifier);
if (!witness_result.ok)
{
fprintf(stderr, "RLN Witness creation error: %s\n", witness_result.err.ptr);
ffi_c_string_free(witness_result.err);
return EXIT_FAILURE;
}
FFI_RLNWitnessInput_t *witness = witness_result.ok;
printf("RLN Witness created successfully\n");
#else
CResult_FFI_RLNWitnessInput_ptr_Vec_uint8_t witness_result = ffi_rln_witness_input_new(
identity_secret,
user_message_limit,
message_id,
&merkle_proof->path_elements,
&merkle_proof->path_index,
x,
external_nullifier);
if (!witness_result.ok)
{
fprintf(stderr, "RLN Witness creation error: %s\n", witness_result.err.ptr);
ffi_c_string_free(witness_result.err);
return EXIT_FAILURE;
}
FFI_RLNWitnessInput_t *witness = witness_result.ok;
printf("RLN Witness created successfully\n");
#endif
printf("\nRLNWitnessInput serialization: RLNWitnessInput <-> bytes\n");
CResult_Vec_uint8_Vec_uint8_t ser_witness_result = ffi_rln_witness_to_bytes_le(&witness);
if (ser_witness_result.err.ptr)
{
fprintf(stderr, "Witness serialization error: %s\n", ser_witness_result.err.ptr);
ffi_c_string_free(ser_witness_result.err);
return EXIT_FAILURE;
}
Vec_uint8_t ser_witness = ser_witness_result.ok;
debug = ffi_vec_u8_debug(&ser_witness);
printf(" - serialized witness = %s\n", debug.ptr);
ffi_c_string_free(debug);
CResult_FFI_RLNWitnessInput_ptr_Vec_uint8_t deser_witness_result = ffi_bytes_le_to_rln_witness(&ser_witness);
if (!deser_witness_result.ok)
{
fprintf(stderr, "Witness deserialization error: %s\n", deser_witness_result.err.ptr);
ffi_c_string_free(deser_witness_result.err);
return EXIT_FAILURE;
}
FFI_RLNWitnessInput_t *deser_witness = deser_witness_result.ok;
printf(" - witness deserialized successfully\n");
ffi_rln_witness_input_free(deser_witness);
ffi_vec_u8_free(ser_witness);
printf("\nGenerating RLN Proof\n");
CResult_FFI_RLNProof_ptr_Vec_uint8_t proof_gen_result = ffi_generate_rln_proof(
&rln,
&witness);
if (!proof_gen_result.ok)
{
fprintf(stderr, "Proof generation error: %s\n", proof_gen_result.err.ptr);
ffi_c_string_free(proof_gen_result.err);
return EXIT_FAILURE;
}
FFI_RLNProof_t *rln_proof = proof_gen_result.ok;
printf("Proof generated successfully\n");
printf("\nGetting proof values\n");
FFI_RLNProofValues_t *proof_values = ffi_rln_proof_get_values(&rln_proof);
CFr_t *y = ffi_rln_proof_values_get_y(&proof_values);
debug = ffi_cfr_debug(y);
printf(" - y = %s\n", debug.ptr);
ffi_c_string_free(debug);
ffi_cfr_free(y);
CFr_t *nullifier = ffi_rln_proof_values_get_nullifier(&proof_values);
debug = ffi_cfr_debug(nullifier);
printf(" - nullifier = %s\n", debug.ptr);
ffi_c_string_free(debug);
ffi_cfr_free(nullifier);
CFr_t *root = ffi_rln_proof_values_get_root(&proof_values);
debug = ffi_cfr_debug(root);
printf(" - root = %s\n", debug.ptr);
ffi_c_string_free(debug);
ffi_cfr_free(root);
CFr_t *x_val = ffi_rln_proof_values_get_x(&proof_values);
debug = ffi_cfr_debug(x_val);
printf(" - x = %s\n", debug.ptr);
ffi_c_string_free(debug);
ffi_cfr_free(x_val);
CFr_t *ext_nullifier = ffi_rln_proof_values_get_external_nullifier(&proof_values);
debug = ffi_cfr_debug(ext_nullifier);
printf(" - external_nullifier = %s\n", debug.ptr);
ffi_c_string_free(debug);
ffi_cfr_free(ext_nullifier);
printf("\nRLNProof serialization: RLNProof <-> bytes\n");
CResult_Vec_uint8_Vec_uint8_t ser_proof_result = ffi_rln_proof_to_bytes_le(&rln_proof);
if (ser_proof_result.err.ptr)
{
fprintf(stderr, "Proof serialization error: %s\n", ser_proof_result.err.ptr);
ffi_c_string_free(ser_proof_result.err);
return EXIT_FAILURE;
}
Vec_uint8_t ser_proof = ser_proof_result.ok;
debug = ffi_vec_u8_debug(&ser_proof);
printf(" - serialized proof = %s\n", debug.ptr);
ffi_c_string_free(debug);
CResult_FFI_RLNProof_ptr_Vec_uint8_t deser_proof_result = ffi_bytes_le_to_rln_proof(&ser_proof);
if (!deser_proof_result.ok)
{
fprintf(stderr, "Proof deserialization error: %s\n", deser_proof_result.err.ptr);
ffi_c_string_free(deser_proof_result.err);
return EXIT_FAILURE;
}
FFI_RLNProof_t *deser_proof = deser_proof_result.ok;
printf(" - proof deserialized successfully\n");
printf("\nRLNProofValues serialization: RLNProofValues <-> bytes\n");
Vec_uint8_t ser_proof_values = ffi_rln_proof_values_to_bytes_le(&proof_values);
debug = ffi_vec_u8_debug(&ser_proof_values);
printf(" - serialized proof_values = %s\n", debug.ptr);
ffi_c_string_free(debug);
CResult_FFI_RLNProofValues_ptr_Vec_uint8_t deser_proof_values_result = ffi_bytes_le_to_rln_proof_values(&ser_proof_values);
if (!deser_proof_values_result.ok)
{
fprintf(stderr, "Proof values deserialization error: %s\n", deser_proof_values_result.err.ptr);
ffi_c_string_free(deser_proof_values_result.err);
return EXIT_FAILURE;
}
FFI_RLNProofValues_t *deser_proof_values = deser_proof_values_result.ok;
printf(" - proof_values deserialized successfully\n");
CFr_t *deser_external_nullifier = ffi_rln_proof_values_get_external_nullifier(&deser_proof_values);
debug = ffi_cfr_debug(deser_external_nullifier);
printf(" - deserialized external_nullifier = %s\n", debug.ptr);
ffi_c_string_free(debug);
ffi_cfr_free(deser_external_nullifier);
ffi_rln_proof_values_free(deser_proof_values);
ffi_vec_u8_free(ser_proof_values);
ffi_rln_proof_free(deser_proof);
ffi_vec_u8_free(ser_proof);
printf("\nVerifying Proof\n");
#ifdef STATELESS
Vec_CFr_t roots = ffi_vec_cfr_from_cfr(computed_root);
CBoolResult_t verify_err = ffi_verify_with_roots(&rln, &rln_proof, &roots, x);
#else
CBoolResult_t verify_err = ffi_verify_rln_proof(&rln, &rln_proof, x);
#endif
if (!verify_err.ok)
{
fprintf(stderr, "Proof verification error: %s\n", verify_err.err.ptr);
ffi_c_string_free(verify_err.err);
return EXIT_FAILURE;
}
printf("Proof verified successfully\n");
ffi_rln_proof_free(rln_proof);
printf("\nSimulating double-signaling attack (same epoch, different message)\n");
printf("\nHashing second signal\n");
uint8_t signal2[32] = {11, 12, 13, 14, 15, 16, 17, 18, 19, 20};
Vec_uint8_t signal2_vec = {signal2, 32, 32};
CResult_CFr_ptr_Vec_uint8_t x2_result = ffi_hash_to_field_le(&signal2_vec);
if (!x2_result.ok)
{
fprintf(stderr, "Hash second signal error: %s\n", x2_result.err.ptr);
ffi_c_string_free(x2_result.err);
return EXIT_FAILURE;
}
CFr_t *x2 = x2_result.ok;
debug = ffi_cfr_debug(x2);
printf(" - x2 = %s\n", debug.ptr);
ffi_c_string_free(debug);
printf("\nCreating second message with the same id\n");
CFr_t *message_id2 = ffi_uint_to_cfr(0);
debug = ffi_cfr_debug(message_id2);
printf(" - message_id2 = %s\n", debug.ptr);
ffi_c_string_free(debug);
printf("\nCreating second RLN Witness\n");
#ifdef STATELESS
CResult_FFI_RLNWitnessInput_ptr_Vec_uint8_t witness_result2 = ffi_rln_witness_input_new(
identity_secret,
user_message_limit,
message_id2,
&path_elements,
&identity_path_index,
x2,
external_nullifier);
if (!witness_result2.ok)
{
fprintf(stderr, "Second RLN Witness creation error: %s\n", witness_result2.err.ptr);
ffi_c_string_free(witness_result2.err);
return EXIT_FAILURE;
}
FFI_RLNWitnessInput_t *witness2 = witness_result2.ok;
printf("Second RLN Witness created successfully\n");
#else
CResult_FFI_RLNWitnessInput_ptr_Vec_uint8_t witness_result2 = ffi_rln_witness_input_new(
identity_secret,
user_message_limit,
message_id2,
&merkle_proof->path_elements,
&merkle_proof->path_index,
x2,
external_nullifier);
if (!witness_result2.ok)
{
fprintf(stderr, "Second RLN Witness creation error: %s\n", witness_result2.err.ptr);
ffi_c_string_free(witness_result2.err);
return EXIT_FAILURE;
}
FFI_RLNWitnessInput_t *witness2 = witness_result2.ok;
printf("Second RLN Witness created successfully\n");
#endif
printf("\nGenerating second RLN Proof\n");
CResult_FFI_RLNProof_ptr_Vec_uint8_t proof_gen_result2 = ffi_generate_rln_proof(
&rln,
&witness2);
if (!proof_gen_result2.ok)
{
fprintf(stderr, "Second proof generation error: %s\n", proof_gen_result2.err.ptr);
ffi_c_string_free(proof_gen_result2.err);
return EXIT_FAILURE;
}
FFI_RLNProof_t *rln_proof2 = proof_gen_result2.ok;
printf("Second proof generated successfully\n");
FFI_RLNProofValues_t *proof_values2 = ffi_rln_proof_get_values(&rln_proof2);
printf("\nVerifying second proof\n");
#ifdef STATELESS
CBoolResult_t verify_err2 = ffi_verify_with_roots(&rln, &rln_proof2, &roots, x2);
#else
CBoolResult_t verify_err2 = ffi_verify_rln_proof(&rln, &rln_proof2, x2);
#endif
if (!verify_err2.ok)
{
fprintf(stderr, "Proof verification error: %s\n", verify_err2.err.ptr);
ffi_c_string_free(verify_err2.err);
return EXIT_FAILURE;
}
printf("Second proof verified successfully\n");
ffi_rln_proof_free(rln_proof2);
printf("\nRecovering identity secret\n");
CResult_CFr_ptr_Vec_uint8_t recover_result = ffi_recover_id_secret(&proof_values, &proof_values2);
if (!recover_result.ok)
{
fprintf(stderr, "Identity recovery error: %s\n", recover_result.err.ptr);
ffi_c_string_free(recover_result.err);
return EXIT_FAILURE;
}
CFr_t *recovered_secret = recover_result.ok;
debug = ffi_cfr_debug(recovered_secret);
printf(" - recovered_secret = %s\n", debug.ptr);
ffi_c_string_free(debug);
debug = ffi_cfr_debug(identity_secret);
printf(" - original_secret = %s\n", debug.ptr);
ffi_c_string_free(debug);
printf("Slashing successful: Identity is recovered!\n");
ffi_cfr_free(recovered_secret);
ffi_rln_proof_values_free(proof_values2);
ffi_rln_proof_values_free(proof_values);
ffi_cfr_free(x2);
ffi_cfr_free(message_id2);
#ifdef STATELESS
ffi_rln_witness_input_free(witness2);
ffi_rln_witness_input_free(witness);
ffi_vec_cfr_free(roots);
ffi_vec_cfr_free(path_elements);
for (size_t i = 0; i < TREE_DEPTH - 1; i++)
{
ffi_cfr_free(default_hashes[i]);
}
ffi_cfr_free(default_leaf);
ffi_cfr_free(computed_root);
#else
ffi_rln_witness_input_free(witness2);
ffi_rln_witness_input_free(witness);
ffi_merkle_proof_free(merkle_proof);
#endif
ffi_cfr_free(rate_commitment);
ffi_cfr_free(x);
ffi_cfr_free(epoch);
ffi_cfr_free(rln_identifier);
ffi_cfr_free(external_nullifier);
ffi_cfr_free(user_message_limit);
ffi_cfr_free(message_id);
ffi_vec_cfr_free(keys);
ffi_rln_free(rln);
return EXIT_SUCCESS;
}

View File

@@ -0,0 +1,124 @@
# RLN FFI Nim example
This example demonstrates how to use the RLN C FFI from Nim in both stateless and non-stateless modes. It covers:
- Creating an RLN handle (stateless or with Merkle tree backend)
- Generating identity keys and commitments
- Building a witness (mock Merkle path in stateless mode, real Merkle proof in non-stateless mode)
- Generating and verifying a proof
- Serializing/deserializing FFI objects (CFr, Vec\<CFr>, RLNWitnessInput, RLNProof, RLNProofValues)
- Simulating a double-signaling attack and recovering the identity secret
## Build the RLN library
From the repository root:
```bash
# Stateless build (no tree APIs)
cargo build -p rln --release --no-default-features --features stateless
# Non-stateless build (with tree APIs)
cargo build -p rln --release
```
This produces the shared library in `target/release`:
- macOS: `librln.dylib`
- Linux: `librln.so`
- Windows: `rln.dll`
## Build the Nim example (two modes)
From this directory:
```bash
# Stateless mode (no tree APIs, uses mock Merkle path)
nim c -d:release -d:ffiStateless main.nim
# Non-stateless mode (uses exported tree APIs to insert leaf and fetch proof)
nim c -d:release main.nim
```
Notes:
- The example links dynamically. If your OS linker cannot find the library at runtime,
set an rpath or environment variable as shown below.
- The example auto-picks a platform-specific default library name.
You can override it with `-d:RLN_LIB:"/absolute/path/to/lib"` if needed.
## Run the example
Ensure the dynamic loader can find the RLN library, then run the binary.
macOS:
```bash
DYLD_LIBRARY_PATH=../../target/release ./main
```
Linux:
```bash
LD_LIBRARY_PATH=../../target/release ./main
```
Windows (PowerShell):
```powershell
$env:PATH = "$PWD\..\..\target\release;$env:PATH"
./main.exe
```
You should see detailed output showing each step, for example:
```text
Creating RLN instance
RLN instance created successfully
Generating identity keys
Identity generated
- identity_secret = ...
- id_commitment = ...
Creating message limit
- user_message_limit = ...
Computing rate commitment
- rate_commitment = ...
CFr serialization: CFr <-> bytes
- serialized rate_commitment = ...
- deserialized rate_commitment = ...
Vec<CFr> serialization: Vec<CFr> <-> bytes
- serialized keys = ...
- deserialized keys = ...
... (Merkle path, hashing, witness, proof, verification, and slashing steps) ...
Proof verified successfully
Slashing successful: Identity is recovered!
```
## What the example does
### Stateless mode
1. Creates an RLN handle via the stateless constructor.
2. Generates identity keys, sets a `user_message_limit` and `message_id`.
3. Hashes a signal, epoch, and RLN identifier to field elements.
4. Computes `rateCommitment = Poseidon(id_commitment, user_message_limit)`.
5. Builds a mock Merkle path for an empty depth-20 tree at index 0 (no exported tree APIs):
- Path siblings: level 0 sibling is `0`, then each level uses precomputed default hashes `H(0,0)`, `H(H(0,0),H(0,0))`, ...
- Path indices: all zeros (left at every level)
- Root: folds the path upwards with `rateCommitment` at index 0
6. Builds the witness, generates the proof, and verifies it with `ffi_verify_with_roots`, passing a one-element roots vector containing the computed root.
7. Simulates a double-signaling attack and recovers the identity secret from two proofs.
### Non-stateless mode
1. Creates an RLN handle with a Merkle tree backend and configuration.
2. Generates identity keys and computes `rateCommitment = Poseidon(id_commitment, user_message_limit)`.
3. Inserts the leaf with `ffi_set_next_leaf` and fetches a real Merkle path for index 0 via `ffi_get_merkle_proof`.
4. Builds the witness from the exported proof, generates the proof, and verifies with `ffi_verify_rln_proof` using the current tree root.
5. Simulates a double-signaling attack and recovers the identity secret from two proofs.

View File

@@ -0,0 +1,940 @@
# Embed rpaths to find Cargo's built library relative to the executable
when defined(macosx):
{.passL: "-Wl,-rpath,@executable_path/../../target/release".}
when defined(linux):
{.passL: "-Wl,-rpath,'$ORIGIN/../../target/release'".}
# Portable dynlib name with override capability (-d:RLN_LIB:"...")
when defined(macosx):
const RLN_LIB* {.strdefine.} = "librln.dylib"
elif defined(linux):
const RLN_LIB* {.strdefine.} = "librln.so"
elif defined(windows):
const RLN_LIB* {.strdefine.} = "rln.dll"
else:
const RLN_LIB* {.strdefine.} = "rln"
# FFI objects
type
CSize* = csize_t
CFr* = object
FFI_RLN* = object
FFI_RLNProof* = object
FFI_RLNWitnessInput* = object
Vec_CFr* = object
dataPtr*: ptr CFr
len*: CSize
cap*: CSize
Vec_uint8* = object
dataPtr*: ptr uint8
len*: CSize
cap*: CSize
SliceRefU8* = object
dataPtr*: ptr uint8
len*: CSize
FFI_MerkleProof* = object
path_elements*: Vec_CFr
path_index*: Vec_uint8
CResultRLNPtrVecU8* = object
ok*: ptr FFI_RLN
err*: Vec_uint8
CResultProofPtrVecU8* = object
ok*: ptr FFI_RLNProof
err*: Vec_uint8
CResultWitnessInputPtrVecU8* = object
ok*: ptr FFI_RLNWitnessInput
err*: Vec_uint8
FFI_RLNProofValues* = object
CResultCFrPtrVecU8* = object
ok*: ptr CFr
err*: Vec_uint8
CResultRLNProofValuesPtrVecU8* = object
ok*: ptr FFI_RLNProofValues
err*: Vec_uint8
CResultMerkleProofPtrVecU8* = object
ok*: ptr FFI_MerkleProof
err*: Vec_uint8
CResultVecCFrVecU8* = object
ok*: Vec_CFr
err*: Vec_uint8
CResultVecU8VecU8* = object
ok*: Vec_uint8
err*: Vec_uint8
CResultBigIntJsonVecU8* = object
ok*: Vec_uint8
err*: Vec_uint8
CBoolResult* = object
ok*: bool
err*: Vec_uint8
# CFr functions
proc ffi_cfr_zero*(): ptr CFr {.importc: "ffi_cfr_zero", cdecl,
dynlib: RLN_LIB.}
proc ffi_cfr_one*(): ptr CFr {.importc: "ffi_cfr_one", cdecl, dynlib: RLN_LIB.}
proc ffi_cfr_free*(x: ptr CFr) {.importc: "ffi_cfr_free", cdecl,
dynlib: RLN_LIB.}
proc ffi_uint_to_cfr*(value: uint32): ptr CFr {.importc: "ffi_uint_to_cfr",
cdecl, dynlib: RLN_LIB.}
proc ffi_cfr_debug*(cfr: ptr CFr): Vec_uint8 {.importc: "ffi_cfr_debug", cdecl,
dynlib: RLN_LIB.}
proc ffi_cfr_to_bytes_le*(cfr: ptr CFr): Vec_uint8 {.importc: "ffi_cfr_to_bytes_le",
cdecl, dynlib: RLN_LIB.}
proc ffi_cfr_to_bytes_be*(cfr: ptr CFr): Vec_uint8 {.importc: "ffi_cfr_to_bytes_be",
cdecl, dynlib: RLN_LIB.}
proc ffi_bytes_le_to_cfr*(bytes: ptr Vec_uint8): CResultCFrPtrVecU8 {.importc: "ffi_bytes_le_to_cfr",
cdecl, dynlib: RLN_LIB.}
proc ffi_bytes_be_to_cfr*(bytes: ptr Vec_uint8): CResultCFrPtrVecU8 {.importc: "ffi_bytes_be_to_cfr",
cdecl, dynlib: RLN_LIB.}
# Vec<CFr> functions
proc ffi_vec_cfr_new*(capacity: CSize): Vec_CFr {.importc: "ffi_vec_cfr_new",
cdecl, dynlib: RLN_LIB.}
proc ffi_vec_cfr_from_cfr*(cfr: ptr CFr): Vec_CFr {.importc: "ffi_vec_cfr_from_cfr",
cdecl, dynlib: RLN_LIB.}
proc ffi_vec_cfr_push*(v: ptr Vec_CFr, cfr: ptr CFr) {.importc: "ffi_vec_cfr_push",
cdecl, dynlib: RLN_LIB.}
proc ffi_vec_cfr_len*(v: ptr Vec_CFr): CSize {.importc: "ffi_vec_cfr_len",
cdecl, dynlib: RLN_LIB.}
proc ffi_vec_cfr_get*(v: ptr Vec_CFr, i: CSize): ptr CFr {.importc: "ffi_vec_cfr_get",
cdecl, dynlib: RLN_LIB.}
proc ffi_vec_cfr_to_bytes_le*(v: ptr Vec_CFr): Vec_uint8 {.importc: "ffi_vec_cfr_to_bytes_le",
cdecl, dynlib: RLN_LIB.}
proc ffi_vec_cfr_to_bytes_be*(v: ptr Vec_CFr): Vec_uint8 {.importc: "ffi_vec_cfr_to_bytes_be",
cdecl, dynlib: RLN_LIB.}
proc ffi_bytes_le_to_vec_cfr*(bytes: ptr Vec_uint8): CResultVecCFrVecU8 {.importc: "ffi_bytes_le_to_vec_cfr",
cdecl, dynlib: RLN_LIB.}
proc ffi_bytes_be_to_vec_cfr*(bytes: ptr Vec_uint8): CResultVecCFrVecU8 {.importc: "ffi_bytes_be_to_vec_cfr",
cdecl, dynlib: RLN_LIB.}
proc ffi_vec_cfr_debug*(v: ptr Vec_CFr): Vec_uint8 {.importc: "ffi_vec_cfr_debug",
cdecl, dynlib: RLN_LIB.}
proc ffi_vec_cfr_free*(v: Vec_CFr) {.importc: "ffi_vec_cfr_free", cdecl,
dynlib: RLN_LIB.}
# Vec<u8> functions
proc ffi_vec_u8_to_bytes_le*(v: ptr Vec_uint8): Vec_uint8 {.importc: "ffi_vec_u8_to_bytes_le",
cdecl, dynlib: RLN_LIB.}
proc ffi_vec_u8_to_bytes_be*(v: ptr Vec_uint8): Vec_uint8 {.importc: "ffi_vec_u8_to_bytes_be",
cdecl, dynlib: RLN_LIB.}
proc ffi_bytes_le_to_vec_u8*(bytes: ptr Vec_uint8): CResultVecU8VecU8 {.importc: "ffi_bytes_le_to_vec_u8",
cdecl, dynlib: RLN_LIB.}
proc ffi_bytes_be_to_vec_u8*(bytes: ptr Vec_uint8): CResultVecU8VecU8 {.importc: "ffi_bytes_be_to_vec_u8",
cdecl, dynlib: RLN_LIB.}
proc ffi_vec_u8_debug*(v: ptr Vec_uint8): Vec_uint8 {.importc: "ffi_vec_u8_debug",
cdecl, dynlib: RLN_LIB.}
proc ffi_vec_u8_free*(v: Vec_uint8) {.importc: "ffi_vec_u8_free", cdecl,
dynlib: RLN_LIB.}
# Hashing functions
proc ffi_hash_to_field_le*(input: ptr Vec_uint8): CResultCFrPtrVecU8 {.importc: "ffi_hash_to_field_le",
cdecl, dynlib: RLN_LIB.}
proc ffi_hash_to_field_be*(input: ptr Vec_uint8): CResultCFrPtrVecU8 {.importc: "ffi_hash_to_field_be",
cdecl, dynlib: RLN_LIB.}
proc ffi_poseidon_hash_pair*(a: ptr CFr,
b: ptr CFr): CResultCFrPtrVecU8 {.importc: "ffi_poseidon_hash_pair", cdecl,
dynlib: RLN_LIB.}
# Keygen function
proc ffi_key_gen*(): CResultVecCFrVecU8 {.importc: "ffi_key_gen", cdecl,
dynlib: RLN_LIB.}
proc ffi_seeded_key_gen*(seed: ptr Vec_uint8): CResultVecCFrVecU8 {.importc: "ffi_seeded_key_gen",
cdecl, dynlib: RLN_LIB.}
proc ffi_extended_key_gen*(): CResultVecCFrVecU8 {.importc: "ffi_extended_key_gen",
cdecl, dynlib: RLN_LIB.}
proc ffi_seeded_extended_key_gen*(seed: ptr Vec_uint8): CResultVecCFrVecU8 {.importc: "ffi_seeded_extended_key_gen",
cdecl, dynlib: RLN_LIB.}
# RLN instance functions
when defined(ffiStateless):
proc ffi_rln_new*(): CResultRLNPtrVecU8 {.importc: "ffi_rln_new", cdecl,
dynlib: RLN_LIB.}
proc ffi_rln_new_with_params*(zkey_data: ptr Vec_uint8,
graph_data: ptr Vec_uint8): CResultRLNPtrVecU8 {.importc: "ffi_rln_new_with_params",
cdecl, dynlib: RLN_LIB.}
else:
proc ffi_rln_new*(treeDepth: CSize, config: cstring): CResultRLNPtrVecU8 {.importc: "ffi_rln_new",
cdecl, dynlib: RLN_LIB.}
proc ffi_rln_new_with_params*(treeDepth: CSize, zkey_data: ptr Vec_uint8,
graph_data: ptr Vec_uint8, config: cstring): CResultRLNPtrVecU8 {.importc: "ffi_rln_new_with_params",
cdecl, dynlib: RLN_LIB.}
proc ffi_rln_free*(rln: ptr FFI_RLN) {.importc: "ffi_rln_free", cdecl,
dynlib: RLN_LIB.}
# Witness input functions
proc ffi_rln_witness_input_new*(
identity_secret: ptr CFr,
user_message_limit: ptr CFr,
message_id: ptr CFr,
path_elements: ptr Vec_CFr,
identity_path_index: ptr Vec_uint8,
x: ptr CFr,
external_nullifier: ptr CFr
): CResultWitnessInputPtrVecU8 {.importc: "ffi_rln_witness_input_new", cdecl,
dynlib: RLN_LIB.}
proc ffi_rln_witness_to_bytes_le*(witness: ptr ptr FFI_RLNWitnessInput): CResultVecU8VecU8 {.importc: "ffi_rln_witness_to_bytes_le",
cdecl, dynlib: RLN_LIB.}
proc ffi_rln_witness_to_bytes_be*(witness: ptr ptr FFI_RLNWitnessInput): CResultVecU8VecU8 {.importc: "ffi_rln_witness_to_bytes_be",
cdecl, dynlib: RLN_LIB.}
proc ffi_bytes_le_to_rln_witness*(bytes: ptr Vec_uint8): CResultWitnessInputPtrVecU8 {.importc: "ffi_bytes_le_to_rln_witness",
cdecl, dynlib: RLN_LIB.}
proc ffi_bytes_be_to_rln_witness*(bytes: ptr Vec_uint8): CResultWitnessInputPtrVecU8 {.importc: "ffi_bytes_be_to_rln_witness",
cdecl, dynlib: RLN_LIB.}
proc ffi_rln_witness_to_bigint_json*(witness: ptr ptr FFI_RLNWitnessInput): CResultBigIntJsonVecU8 {.importc: "ffi_rln_witness_to_bigint_json",
cdecl, dynlib: RLN_LIB.}
proc ffi_rln_witness_input_free*(witness: ptr FFI_RLNWitnessInput) {.importc: "ffi_rln_witness_input_free",
cdecl, dynlib: RLN_LIB.}
# Proof generation/verification functions
proc ffi_generate_rln_proof*(
rln: ptr ptr FFI_RLN,
witness: ptr ptr FFI_RLNWitnessInput
): CResultProofPtrVecU8 {.importc: "ffi_generate_rln_proof", cdecl,
dynlib: RLN_LIB.}
proc ffi_generate_rln_proof_with_witness*(
rln: ptr ptr FFI_RLN,
calculated_witness: ptr Vec_uint8,
witness: ptr ptr FFI_RLNWitnessInput
): CResultProofPtrVecU8 {.importc: "ffi_generate_rln_proof_with_witness",
cdecl, dynlib: RLN_LIB.}
when not defined(ffiStateless):
proc ffi_verify_rln_proof*(
rln: ptr ptr FFI_RLN,
proof: ptr ptr FFI_RLNProof,
x: ptr CFr
): CBoolResult {.importc: "ffi_verify_rln_proof", cdecl,
dynlib: RLN_LIB.}
proc ffi_verify_with_roots*(
rln: ptr ptr FFI_RLN,
proof: ptr ptr FFI_RLNProof,
roots: ptr Vec_CFr,
x: ptr CFr
): CBoolResult {.importc: "ffi_verify_with_roots", cdecl,
dynlib: RLN_LIB.}
proc ffi_rln_proof_free*(p: ptr FFI_RLNProof) {.importc: "ffi_rln_proof_free",
cdecl, dynlib: RLN_LIB.}
# Merkle tree operations (non-stateless mode)
when not defined(ffiStateless):
proc ffi_set_tree*(rln: ptr ptr FFI_RLN,
tree_depth: CSize): CBoolResult {.importc: "ffi_set_tree",
cdecl, dynlib: RLN_LIB.}
proc ffi_delete_leaf*(rln: ptr ptr FFI_RLN,
index: CSize): CBoolResult {.importc: "ffi_delete_leaf",
cdecl, dynlib: RLN_LIB.}
proc ffi_set_leaf*(rln: ptr ptr FFI_RLN, index: CSize,
leaf: ptr CFr): CBoolResult {.importc: "ffi_set_leaf",
cdecl, dynlib: RLN_LIB.}
proc ffi_get_leaf*(rln: ptr ptr FFI_RLN,
index: CSize): CResultCFrPtrVecU8 {.importc: "ffi_get_leaf",
cdecl, dynlib: RLN_LIB.}
proc ffi_set_next_leaf*(rln: ptr ptr FFI_RLN,
leaf: ptr CFr): CBoolResult {.importc: "ffi_set_next_leaf",
cdecl, dynlib: RLN_LIB.}
proc ffi_set_leaves_from*(rln: ptr ptr FFI_RLN, index: CSize,
leaves: ptr Vec_CFr): CBoolResult {.importc: "ffi_set_leaves_from",
cdecl, dynlib: RLN_LIB.}
proc ffi_init_tree_with_leaves*(rln: ptr ptr FFI_RLN,
leaves: ptr Vec_CFr): CBoolResult {.importc: "ffi_init_tree_with_leaves",
cdecl, dynlib: RLN_LIB.}
proc ffi_atomic_operation*(rln: ptr ptr FFI_RLN, index: CSize,
leaves: ptr Vec_CFr,
indices: ptr Vec_uint8): CBoolResult {.importc: "ffi_atomic_operation",
cdecl, dynlib: RLN_LIB.}
proc ffi_seq_atomic_operation*(rln: ptr ptr FFI_RLN, leaves: ptr Vec_CFr,
indices: ptr Vec_uint8): CBoolResult {.importc: "ffi_seq_atomic_operation",
cdecl, dynlib: RLN_LIB.}
proc ffi_get_root*(rln: ptr ptr FFI_RLN): ptr CFr {.importc: "ffi_get_root",
cdecl, dynlib: RLN_LIB.}
proc ffi_leaves_set*(rln: ptr ptr FFI_RLN): CSize {.importc: "ffi_leaves_set",
cdecl, dynlib: RLN_LIB.}
proc ffi_get_merkle_proof*(rln: ptr ptr FFI_RLN,
index: CSize): CResultMerkleProofPtrVecU8 {.importc: "ffi_get_merkle_proof",
cdecl, dynlib: RLN_LIB.}
proc ffi_set_metadata*(rln: ptr ptr FFI_RLN,
metadata: ptr Vec_uint8): CBoolResult {.importc: "ffi_set_metadata",
cdecl, dynlib: RLN_LIB.}
proc ffi_get_metadata*(rln: ptr ptr FFI_RLN): CResultVecU8VecU8 {.importc: "ffi_get_metadata",
cdecl, dynlib: RLN_LIB.}
proc ffi_flush*(rln: ptr ptr FFI_RLN): CBoolResult {.importc: "ffi_flush",
cdecl, dynlib: RLN_LIB.}
proc ffi_merkle_proof_free*(p: ptr FFI_MerkleProof) {.importc: "ffi_merkle_proof_free",
cdecl, dynlib: RLN_LIB.}
# Identity secret recovery
proc ffi_recover_id_secret*(proof_values_1: ptr ptr FFI_RLNProofValues,
proof_values_2: ptr ptr FFI_RLNProofValues): CResultCFrPtrVecU8 {.importc: "ffi_recover_id_secret",
cdecl, dynlib: RLN_LIB.}
# RLNProof serialization
proc ffi_rln_proof_to_bytes_le*(proof: ptr ptr FFI_RLNProof): CResultVecU8VecU8 {.importc: "ffi_rln_proof_to_bytes_le",
cdecl, dynlib: RLN_LIB.}
proc ffi_rln_proof_to_bytes_be*(proof: ptr ptr FFI_RLNProof): CResultVecU8VecU8 {.importc: "ffi_rln_proof_to_bytes_be",
cdecl, dynlib: RLN_LIB.}
proc ffi_bytes_le_to_rln_proof*(bytes: ptr Vec_uint8): CResultProofPtrVecU8 {.importc: "ffi_bytes_le_to_rln_proof",
cdecl, dynlib: RLN_LIB.}
proc ffi_bytes_be_to_rln_proof*(bytes: ptr Vec_uint8): CResultProofPtrVecU8 {.importc: "ffi_bytes_be_to_rln_proof",
cdecl, dynlib: RLN_LIB.}
# RLNProofValues functions
proc ffi_rln_proof_get_values*(proof: ptr ptr FFI_RLNProof): ptr FFI_RLNProofValues {.importc: "ffi_rln_proof_get_values",
cdecl, dynlib: RLN_LIB.}
proc ffi_rln_proof_values_get_y*(pv: ptr ptr FFI_RLNProofValues): ptr CFr {.importc: "ffi_rln_proof_values_get_y",
cdecl, dynlib: RLN_LIB.}
proc ffi_rln_proof_values_get_nullifier*(pv: ptr ptr FFI_RLNProofValues): ptr CFr {.importc: "ffi_rln_proof_values_get_nullifier",
cdecl, dynlib: RLN_LIB.}
proc ffi_rln_proof_values_get_root*(pv: ptr ptr FFI_RLNProofValues): ptr CFr {.importc: "ffi_rln_proof_values_get_root",
cdecl, dynlib: RLN_LIB.}
proc ffi_rln_proof_values_get_x*(pv: ptr ptr FFI_RLNProofValues): ptr CFr {.importc: "ffi_rln_proof_values_get_x",
cdecl, dynlib: RLN_LIB.}
proc ffi_rln_proof_values_get_external_nullifier*(pv: ptr ptr FFI_RLNProofValues): ptr CFr {.importc: "ffi_rln_proof_values_get_external_nullifier",
cdecl, dynlib: RLN_LIB.}
proc ffi_rln_proof_values_to_bytes_le*(pv: ptr ptr FFI_RLNProofValues): Vec_uint8 {.importc: "ffi_rln_proof_values_to_bytes_le",
cdecl, dynlib: RLN_LIB.}
proc ffi_rln_proof_values_to_bytes_be*(pv: ptr ptr FFI_RLNProofValues): Vec_uint8 {.importc: "ffi_rln_proof_values_to_bytes_be",
cdecl, dynlib: RLN_LIB.}
proc ffi_bytes_le_to_rln_proof_values*(bytes: ptr Vec_uint8): CResultRLNProofValuesPtrVecU8 {.importc: "ffi_bytes_le_to_rln_proof_values",
cdecl, dynlib: RLN_LIB.}
proc ffi_bytes_be_to_rln_proof_values*(bytes: ptr Vec_uint8): CResultRLNProofValuesPtrVecU8 {.importc: "ffi_bytes_be_to_rln_proof_values",
cdecl, dynlib: RLN_LIB.}
proc ffi_rln_proof_values_free*(pv: ptr FFI_RLNProofValues) {.importc: "ffi_rln_proof_values_free",
cdecl, dynlib: RLN_LIB.}
# Helpers functions
proc asVecU8*(buf: var seq[uint8]): Vec_uint8 =
result.dataPtr = if buf.len == 0: nil else: addr buf[0]
result.len = CSize(buf.len)
result.cap = CSize(buf.len)
proc asString*(v: Vec_uint8): string =
if v.dataPtr.isNil or v.len == 0: return ""
result = newString(v.len.int)
copyMem(addr result[0], v.dataPtr, v.len.int)
proc ffi_c_string_free*(s: Vec_uint8) {.importc: "ffi_c_string_free", cdecl,
dynlib: RLN_LIB.}
when isMainModule:
echo "Creating RLN instance"
var rlnRes: CResultRLNPtrVecU8
when defined(ffiStateless):
rlnRes = ffi_rln_new()
else:
let config_path = """../resources/tree_depth_20/config.json""".cstring
rlnRes = ffi_rln_new(CSize(20), config_path)
if rlnRes.ok.isNil:
stderr.writeLine "Initial RLN instance creation error: ", asString(rlnRes.err)
ffi_c_string_free(rlnRes.err)
quit 1
var rln = rlnRes.ok
echo "RLN instance created successfully"
echo "\nGenerating identity keys"
var keysResult = ffi_key_gen()
if keysResult.err.dataPtr != nil:
let errMsg = asString(keysResult.err)
ffi_c_string_free(keysResult.err)
echo "Key generation error: ", errMsg
quit 1
var keys = keysResult.ok
let identitySecret = ffi_vec_cfr_get(addr keys, CSize(0))
let idCommitment = ffi_vec_cfr_get(addr keys, CSize(1))
echo "Identity generated"
block:
let debug = ffi_cfr_debug(identitySecret)
echo " - identity_secret = ", asString(debug)
ffi_c_string_free(debug)
block:
let debug = ffi_cfr_debug(idCommitment)
echo " - id_commitment = ", asString(debug)
ffi_c_string_free(debug)
echo "\nCreating message limit"
let userMessageLimit = ffi_uint_to_cfr(1'u32)
block:
let debug = ffi_cfr_debug(userMessageLimit)
echo " - user_message_limit = ", asString(debug)
ffi_c_string_free(debug)
echo "\nComputing rate commitment"
let rateCommitmentResult = ffi_poseidon_hash_pair(idCommitment, userMessageLimit)
if rateCommitmentResult.ok.isNil:
let errMsg = asString(rateCommitmentResult.err)
ffi_c_string_free(rateCommitmentResult.err)
echo "Rate commitment hash error: ", errMsg
quit 1
let rateCommitment = rateCommitmentResult.ok
block:
let debug = ffi_cfr_debug(rateCommitment)
echo " - rate_commitment = ", asString(debug)
ffi_c_string_free(debug)
echo "\nCFr serialization: CFr <-> bytes"
var serRateCommitment = ffi_cfr_to_bytes_be(rateCommitment)
block:
let debug = ffi_vec_u8_debug(addr serRateCommitment)
echo " - serialized rate_commitment = ", asString(debug)
ffi_c_string_free(debug)
let deserRateCommitmentResult = ffi_bytes_be_to_cfr(addr serRateCommitment)
if deserRateCommitmentResult.ok.isNil:
stderr.writeLine "Rate commitment deserialization error: ", asString(
deserRateCommitmentResult.err)
ffi_c_string_free(deserRateCommitmentResult.err)
quit 1
let deserRateCommitment = deserRateCommitmentResult.ok
block:
let debug = ffi_cfr_debug(deserRateCommitment)
echo " - deserialized rate_commitment = ", asString(debug)
ffi_c_string_free(debug)
ffi_vec_u8_free(serRateCommitment)
ffi_cfr_free(deserRateCommitment)
echo "\nVec<CFr> serialization: Vec<CFr> <-> bytes"
var serKeys = ffi_vec_cfr_to_bytes_be(addr keys)
block:
let debug = ffi_vec_u8_debug(addr serKeys)
echo " - serialized keys = ", asString(debug)
ffi_c_string_free(debug)
let deserKeysResult = ffi_bytes_be_to_vec_cfr(addr serKeys)
if deserKeysResult.err.dataPtr != nil:
stderr.writeLine "Keys deserialization error: ", asString(
deserKeysResult.err)
ffi_c_string_free(deserKeysResult.err)
quit 1
block:
var okKeys = deserKeysResult.ok
let debug = ffi_vec_cfr_debug(addr okKeys)
echo " - deserialized keys = ", asString(debug)
ffi_c_string_free(debug)
ffi_vec_cfr_free(deserKeysResult.ok)
ffi_vec_u8_free(serKeys)
when defined(ffiStateless):
const treeDepth = 20
const CFR_SIZE = 32
echo "\nBuilding Merkle path for stateless mode"
let defaultLeaf = ffi_cfr_zero()
var defaultHashes: array[treeDepth-1, ptr CFr]
block:
let hashResult = ffi_poseidon_hash_pair(defaultLeaf, defaultLeaf)
if hashResult.ok.isNil:
let errMsg = asString(hashResult.err)
ffi_c_string_free(hashResult.err)
echo "Poseidon hash error: ", errMsg
quit 1
defaultHashes[0] = hashResult.ok
for i in 1..treeDepth-2:
let hashResult = ffi_poseidon_hash_pair(defaultHashes[i-1], defaultHashes[i-1])
if hashResult.ok.isNil:
let errMsg = asString(hashResult.err)
ffi_c_string_free(hashResult.err)
echo "Poseidon hash error: ", errMsg
quit 1
defaultHashes[i] = hashResult.ok
var pathElements = ffi_vec_cfr_new(CSize(treeDepth))
ffi_vec_cfr_push(addr pathElements, defaultLeaf)
for i in 0..treeDepth-2:
ffi_vec_cfr_push(addr pathElements, defaultHashes[i])
echo "\nVec<CFr> serialization: Vec<CFr> <-> bytes"
var serPathElements = ffi_vec_cfr_to_bytes_be(addr pathElements)
block:
let debug = ffi_vec_u8_debug(addr serPathElements)
echo " - serialized path_elements = ", asString(debug)
ffi_c_string_free(debug)
let deserPathElements = ffi_bytes_be_to_vec_cfr(addr serPathElements)
if deserPathElements.err.dataPtr != nil:
stderr.writeLine "Path elements deserialization error: ", asString(
deserPathElements.err)
ffi_c_string_free(deserPathElements.err)
quit 1
block:
var okPathElems = deserPathElements.ok
let debug = ffi_vec_cfr_debug(addr okPathElems)
echo " - deserialized path_elements = ", asString(debug)
ffi_c_string_free(debug)
ffi_vec_cfr_free(deserPathElements.ok)
ffi_vec_u8_free(serPathElements)
var pathIndexSeq = newSeq[uint8](treeDepth)
var identityPathIndex = asVecU8(pathIndexSeq)
echo "\nVec<uint8> serialization: Vec<uint8> <-> bytes"
var serPathIndex = ffi_vec_u8_to_bytes_be(addr identityPathIndex)
block:
let debug = ffi_vec_u8_debug(addr serPathIndex)
echo " - serialized path_index = ", asString(debug)
ffi_c_string_free(debug)
let deserPathIndex = ffi_bytes_be_to_vec_u8(addr serPathIndex)
if deserPathIndex.err.dataPtr != nil:
stderr.writeLine "Path index deserialization error: ", asString(
deserPathIndex.err)
ffi_c_string_free(deserPathIndex.err)
quit 1
block:
var okPathIdx = deserPathIndex.ok
let debug = ffi_vec_u8_debug(addr okPathIdx)
echo " - deserialized path_index = ", asString(debug)
ffi_c_string_free(debug)
ffi_vec_u8_free(deserPathIndex.ok)
ffi_vec_u8_free(serPathIndex)
echo "\nComputing Merkle root for stateless mode"
echo " - computing root for index 0 with rate_commitment"
let rootResult = ffi_poseidon_hash_pair(rateCommitment, defaultLeaf)
if rootResult.ok.isNil:
let errMsg = asString(rootResult.err)
ffi_c_string_free(rootResult.err)
echo "Poseidon hash error: ", errMsg
quit 1
var computedRoot = rootResult.ok
for i in 1..treeDepth-1:
let nextResult = ffi_poseidon_hash_pair(computedRoot, defaultHashes[i-1])
if nextResult.ok.isNil:
let errMsg = asString(nextResult.err)
ffi_c_string_free(nextResult.err)
echo "Poseidon hash error: ", errMsg
quit 1
let next = nextResult.ok
ffi_cfr_free(computedRoot)
computedRoot = next
block:
let debug = ffi_cfr_debug(computedRoot)
echo " - computed_root = ", asString(debug)
ffi_c_string_free(debug)
else:
echo "\nAdding rate_commitment to tree"
var rcPtr = rateCommitment
let setErr = ffi_set_next_leaf(addr rln, rcPtr)
if not setErr.ok:
stderr.writeLine "Set next leaf error: ", asString(setErr.err)
ffi_c_string_free(setErr.err)
quit 1
let leafIndex = ffi_leaves_set(addr rln) - 1
echo " - added to tree at index ", leafIndex
echo "\nGetting Merkle proof"
let proofResult = ffi_get_merkle_proof(addr rln, leafIndex)
if proofResult.ok.isNil:
stderr.writeLine "Get proof error: ", asString(proofResult.err)
ffi_c_string_free(proofResult.err)
quit 1
let merkleProof = proofResult.ok
echo " - proof obtained (depth: ", merkleProof.path_elements.len, ")"
echo "\nHashing signal"
var signal: array[32, uint8] = [1'u8, 2, 3, 4, 5, 6, 7, 8, 9, 10, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
var signalVec = Vec_uint8(dataPtr: cast[ptr uint8](addr signal[0]),
len: CSize(signal.len), cap: CSize(signal.len))
let xResult = ffi_hash_to_field_be(addr signalVec)
if xResult.ok.isNil:
stderr.writeLine "Hash signal error: ", asString(xResult.err)
ffi_c_string_free(xResult.err)
quit 1
let x = xResult.ok
block:
let debug = ffi_cfr_debug(x)
echo " - x = ", asString(debug)
ffi_c_string_free(debug)
echo "\nHashing epoch"
let epochStr = "test-epoch"
var epochBytes = newSeq[uint8](epochStr.len)
for i in 0..<epochStr.len: epochBytes[i] = uint8(epochStr[i])
var epochVec = asVecU8(epochBytes)
let epochResult = ffi_hash_to_field_be(addr epochVec)
if epochResult.ok.isNil:
stderr.writeLine "Hash epoch error: ", asString(epochResult.err)
ffi_c_string_free(epochResult.err)
quit 1
let epoch = epochResult.ok
block:
let debug = ffi_cfr_debug(epoch)
echo " - epoch = ", asString(debug)
ffi_c_string_free(debug)
echo "\nHashing RLN identifier"
let rlnIdStr = "test-rln-identifier"
var rlnIdBytes = newSeq[uint8](rlnIdStr.len)
for i in 0..<rlnIdStr.len: rlnIdBytes[i] = uint8(rlnIdStr[i])
var rlnIdVec = asVecU8(rlnIdBytes)
let rlnIdentifierResult = ffi_hash_to_field_be(addr rlnIdVec)
if rlnIdentifierResult.ok.isNil:
stderr.writeLine "Hash RLN identifier error: ", asString(
rlnIdentifierResult.err)
ffi_c_string_free(rlnIdentifierResult.err)
quit 1
let rlnIdentifier = rlnIdentifierResult.ok
block:
let debug = ffi_cfr_debug(rlnIdentifier)
echo " - rln_identifier = ", asString(debug)
ffi_c_string_free(debug)
echo "\nComputing Poseidon hash for external nullifier"
let externalNullifierResult = ffi_poseidon_hash_pair(epoch, rlnIdentifier)
if externalNullifierResult.ok.isNil:
let errMsg = asString(externalNullifierResult.err)
ffi_c_string_free(externalNullifierResult.err)
echo "External nullifier hash error: ", errMsg
quit 1
let externalNullifier = externalNullifierResult.ok
block:
let debug = ffi_cfr_debug(externalNullifier)
echo " - external_nullifier = ", asString(debug)
ffi_c_string_free(debug)
echo "\nCreating message_id"
let messageId = ffi_uint_to_cfr(0'u32)
block:
let debug = ffi_cfr_debug(messageId)
echo " - message_id = ", asString(debug)
ffi_c_string_free(debug)
echo "\nCreating RLN Witness"
when defined(ffiStateless):
var witnessRes = ffi_rln_witness_input_new(identitySecret,
userMessageLimit, messageId, addr pathElements, addr identityPathIndex,
x, externalNullifier)
if witnessRes.ok.isNil:
stderr.writeLine "RLN Witness creation error: ", asString(witnessRes.err)
ffi_c_string_free(witnessRes.err)
quit 1
var witness = witnessRes.ok
echo "RLN Witness created successfully"
else:
var witnessRes = ffi_rln_witness_input_new(identitySecret,
userMessageLimit, messageId, addr merkleProof.path_elements,
addr merkleProof.path_index, x, externalNullifier)
if witnessRes.ok.isNil:
stderr.writeLine "RLN Witness creation error: ", asString(witnessRes.err)
ffi_c_string_free(witnessRes.err)
quit 1
var witness = witnessRes.ok
echo "RLN Witness created successfully"
echo "\nRLNWitnessInput serialization: RLNWitnessInput <-> bytes"
let serWitnessResult = ffi_rln_witness_to_bytes_be(addr witness)
if serWitnessResult.err.dataPtr != nil:
stderr.writeLine "Witness serialization error: ", asString(
serWitnessResult.err)
ffi_c_string_free(serWitnessResult.err)
quit 1
var serWitness = serWitnessResult.ok
block:
let debug = ffi_vec_u8_debug(addr serWitness)
echo " - serialized witness = ", asString(debug)
ffi_c_string_free(debug)
let deserWitnessResult = ffi_bytes_be_to_rln_witness(addr serWitness)
if deserWitnessResult.ok.isNil:
stderr.writeLine "Witness deserialization error: ", asString(
deserWitnessResult.err)
ffi_c_string_free(deserWitnessResult.err)
quit 1
echo " - witness deserialized successfully"
ffi_rln_witness_input_free(deserWitnessResult.ok)
ffi_vec_u8_free(serWitness)
echo "\nGenerating RLN Proof"
var proofRes = ffi_generate_rln_proof(addr rln, addr witness)
if proofRes.ok.isNil:
stderr.writeLine "Proof generation error: ", asString(proofRes.err)
ffi_c_string_free(proofRes.err)
quit 1
var proof = proofRes.ok
echo "Proof generated successfully"
echo "\nGetting proof values"
var proofValues = ffi_rln_proof_get_values(addr proof)
block:
let y = ffi_rln_proof_values_get_y(addr proofValues)
let debug = ffi_cfr_debug(y)
echo " - y = ", asString(debug)
ffi_c_string_free(debug)
ffi_cfr_free(y)
block:
let nullifier = ffi_rln_proof_values_get_nullifier(addr proofValues)
let debug = ffi_cfr_debug(nullifier)
echo " - nullifier = ", asString(debug)
ffi_c_string_free(debug)
ffi_cfr_free(nullifier)
block:
let root = ffi_rln_proof_values_get_root(addr proofValues)
let debug = ffi_cfr_debug(root)
echo " - root = ", asString(debug)
ffi_c_string_free(debug)
ffi_cfr_free(root)
block:
let xVal = ffi_rln_proof_values_get_x(addr proofValues)
let debug = ffi_cfr_debug(xVal)
echo " - x = ", asString(debug)
ffi_c_string_free(debug)
ffi_cfr_free(xVal)
block:
let extNullifier = ffi_rln_proof_values_get_external_nullifier(
addr proofValues)
let debug = ffi_cfr_debug(extNullifier)
echo " - external_nullifier = ", asString(debug)
ffi_c_string_free(debug)
ffi_cfr_free(extNullifier)
echo "\nRLNProof serialization: RLNProof <-> bytes"
let serProofResult = ffi_rln_proof_to_bytes_be(addr proof)
if serProofResult.err.dataPtr != nil:
stderr.writeLine "Proof serialization error: ", asString(serProofResult.err)
ffi_c_string_free(serProofResult.err)
quit 1
var serProof = serProofResult.ok
block:
let debug = ffi_vec_u8_debug(addr serProof)
echo " - serialized proof = ", asString(debug)
ffi_c_string_free(debug)
let deserProofResult = ffi_bytes_be_to_rln_proof(addr serProof)
if deserProofResult.ok.isNil:
stderr.writeLine "Proof deserialization error: ", asString(
deserProofResult.err)
ffi_c_string_free(deserProofResult.err)
quit 1
var deserProof = deserProofResult.ok
echo " - proof deserialized successfully"
echo "\nRLNProofValues serialization: RLNProofValues <-> bytes"
var serProofValues = ffi_rln_proof_values_to_bytes_be(addr proofValues)
block:
let debug = ffi_vec_u8_debug(addr serProofValues)
echo " - serialized proof_values = ", asString(debug)
ffi_c_string_free(debug)
let deserProofValuesResult = ffi_bytes_be_to_rln_proof_values(
addr serProofValues)
if deserProofValuesResult.ok.isNil:
stderr.writeLine "Proof values deserialization error: ", asString(
deserProofValuesResult.err)
ffi_c_string_free(deserProofValuesResult.err)
quit 1
var deserProofValues = deserProofValuesResult.ok
echo " - proof_values deserialized successfully"
block:
let deserExternalNullifier = ffi_rln_proof_values_get_external_nullifier(
addr deserProofValues)
let debug = ffi_cfr_debug(deserExternalNullifier)
echo " - deserialized external_nullifier = ", asString(debug)
ffi_c_string_free(debug)
ffi_cfr_free(deserExternalNullifier)
ffi_rln_proof_values_free(deserProofValues)
ffi_vec_u8_free(serProofValues)
ffi_rln_proof_free(deserProof)
ffi_vec_u8_free(serProof)
echo "\nVerifying Proof"
when defined(ffiStateless):
var roots = ffi_vec_cfr_from_cfr(computedRoot)
let verifyErr = ffi_verify_with_roots(addr rln, addr proof, addr roots, x)
else:
let verifyErr = ffi_verify_rln_proof(addr rln, addr proof, x)
if not verifyErr.ok:
stderr.writeLine "Proof verification error: ", asString(verifyErr.err)
ffi_c_string_free(verifyErr.err)
quit 1
echo "Proof verified successfully"
ffi_rln_proof_free(proof)
echo "\nSimulating double-signaling attack (same epoch, different message)"
echo "\nHashing second signal"
var signal2: array[32, uint8] = [11'u8, 12, 13, 14, 15, 16, 17, 18, 19, 20, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
var signal2Vec = Vec_uint8(dataPtr: cast[ptr uint8](addr signal2[0]),
len: CSize(signal2.len), cap: CSize(signal2.len))
let x2Result = ffi_hash_to_field_be(addr signal2Vec)
if x2Result.ok.isNil:
stderr.writeLine "Hash second signal error: ", asString(x2Result.err)
ffi_c_string_free(x2Result.err)
quit 1
let x2 = x2Result.ok
block:
let debug = ffi_cfr_debug(x2)
echo " - x2 = ", asString(debug)
ffi_c_string_free(debug)
echo "\nCreating second message with the same id"
let messageId2 = ffi_uint_to_cfr(0'u32)
block:
let debug = ffi_cfr_debug(messageId2)
echo " - message_id2 = ", asString(debug)
ffi_c_string_free(debug)
echo "\nCreating second RLN Witness"
when defined(ffiStateless):
var witnessRes2 = ffi_rln_witness_input_new(identitySecret,
userMessageLimit, messageId2, addr pathElements, addr identityPathIndex,
x2, externalNullifier)
if witnessRes2.ok.isNil:
stderr.writeLine "Second RLN Witness creation error: ", asString(
witnessRes2.err)
ffi_c_string_free(witnessRes2.err)
quit 1
var witness2 = witnessRes2.ok
echo "Second RLN Witness created successfully"
else:
var witnessRes2 = ffi_rln_witness_input_new(identitySecret,
userMessageLimit, messageId2, addr merkleProof.path_elements,
addr merkleProof.path_index, x2, externalNullifier)
if witnessRes2.ok.isNil:
stderr.writeLine "Second RLN Witness creation error: ", asString(
witnessRes2.err)
ffi_c_string_free(witnessRes2.err)
quit 1
var witness2 = witnessRes2.ok
echo "Second RLN Witness created successfully"
echo "\nGenerating second RLN Proof"
var proofRes2 = ffi_generate_rln_proof(addr rln, addr witness2)
if proofRes2.ok.isNil:
stderr.writeLine "Second proof generation error: ", asString(proofRes2.err)
ffi_c_string_free(proofRes2.err)
quit 1
var proof2 = proofRes2.ok
echo "Second proof generated successfully"
var proofValues2 = ffi_rln_proof_get_values(addr proof2)
echo "\nVerifying second proof"
when defined(ffiStateless):
let verifyErr2 = ffi_verify_with_roots(addr rln, addr proof2, addr roots, x2)
else:
let verifyErr2 = ffi_verify_rln_proof(addr rln, addr proof2, x2)
if not verifyErr2.ok:
stderr.writeLine "Proof verification error: ", asString(
verifyErr2.err)
ffi_c_string_free(verifyErr2.err)
quit 1
echo "Second proof verified successfully"
echo "\nRecovering identity secret"
let recoverRes = ffi_recover_id_secret(addr proofValues, addr proofValues2)
if recoverRes.ok.isNil:
stderr.writeLine "Identity recovery error: ", asString(recoverRes.err)
ffi_c_string_free(recoverRes.err)
quit 1
let recoveredSecret = recoverRes.ok
block:
let debug = ffi_cfr_debug(recoveredSecret)
echo " - recovered_secret = ", asString(debug)
ffi_c_string_free(debug)
block:
let debug = ffi_cfr_debug(identitySecret)
echo " - original_secret = ", asString(debug)
ffi_c_string_free(debug)
echo "Slashing successful: Identity is recovered!"
ffi_cfr_free(recoveredSecret)
ffi_rln_proof_values_free(proofValues2)
ffi_rln_proof_values_free(proofValues)
ffi_rln_proof_free(proof2)
ffi_cfr_free(x2)
ffi_cfr_free(messageId2)
when defined(ffiStateless):
ffi_rln_witness_input_free(witness2)
ffi_rln_witness_input_free(witness)
ffi_vec_cfr_free(roots)
ffi_vec_cfr_free(pathElements)
for i in 0..treeDepth-2:
ffi_cfr_free(defaultHashes[i])
ffi_cfr_free(defaultLeaf)
ffi_cfr_free(computedRoot)
else:
ffi_rln_witness_input_free(witness2)
ffi_rln_witness_input_free(witness)
ffi_merkle_proof_free(merkleProof)
ffi_cfr_free(rateCommitment)
ffi_cfr_free(x)
ffi_cfr_free(epoch)
ffi_cfr_free(rlnIdentifier)
ffi_cfr_free(externalNullifier)
ffi_cfr_free(userMessageLimit)
ffi_cfr_free(messageId)
ffi_vec_cfr_free(keys)
ffi_rln_free(rln)

View File

@@ -1,5 +1,5 @@
{
"path": "database",
"path": "./database",
"temporary": false,
"cache_capacity": 1073741824,
"flush_every_ms": 500,

View File

@@ -0,0 +1,5 @@
use rln::ffi;
fn main() -> std::io::Result<()> {
ffi::generate_headers()
}

View File

@@ -1,7 +1,25 @@
/// Errors that can occur during zkey reading operations
#[derive(Debug, thiserror::Error)]
pub enum ZKeyReadError {
#[error("No proving key found!")]
#[error("Empty zkey bytes provided")]
EmptyBytes,
#[error("{0}")]
SerializationError(#[from] ark_serialize::SerializationError),
}
/// Errors that can occur during witness calculation
#[derive(Debug, thiserror::Error)]
pub enum WitnessCalcError {
#[error("Failed to deserialize witness calculation graph: {0}")]
GraphDeserialization(#[from] std::io::Error),
#[error("Failed to evaluate witness calculation graph: {0}")]
GraphEvaluation(String),
#[error("Invalid input length for '{name}': expected {expected}, got {actual}")]
InvalidInputLength {
name: String,
expected: usize,
actual: usize,
},
#[error("Missing required input: {0}")]
MissingInput(String),
}

View File

@@ -1,26 +1,27 @@
// This file is based on the code by iden3. Its preimage can be found here:
// This crate is based on the code by iden3. Its preimage can be found here:
// https://github.com/iden3/circom-witnesscalc/blob/5cb365b6e4d9052ecc69d4567fcf5bc061c20e94/src/lib.rs
pub mod graph;
pub mod proto;
pub mod storage;
mod graph;
mod proto;
mod storage;
use ruint::aliases::U256;
use std::collections::HashMap;
use graph::Node;
use ruint::aliases::U256;
use storage::deserialize_witnesscalc_graph;
use zeroize::zeroize_flat_type;
use crate::circuit::iden3calc::graph::fr_to_u256;
use crate::circuit::Fr;
use self::graph::fr_to_u256;
use super::{error::WitnessCalcError, Fr};
use crate::utils::FrOrSecret;
use graph::Node;
pub type InputSignalsInfo = HashMap<String, (usize, usize)>;
pub(crate) type InputSignalsInfo = HashMap<String, (usize, usize)>;
pub fn calc_witness<I: IntoIterator<Item = (String, Vec<FrOrSecret>)>>(
pub(crate) fn calc_witness<I: IntoIterator<Item = (String, Vec<FrOrSecret>)>>(
inputs: I,
graph_data: &[u8],
) -> Vec<Fr> {
) -> Result<Vec<Fr>, WitnessCalcError> {
let mut inputs: HashMap<String, Vec<U256>> = inputs
.into_iter()
.map(|(key, value)| {
@@ -38,19 +39,28 @@ pub fn calc_witness<I: IntoIterator<Item = (String, Vec<FrOrSecret>)>>(
.collect();
let (nodes, signals, input_mapping): (Vec<Node>, Vec<usize>, InputSignalsInfo) =
deserialize_witnesscalc_graph(std::io::Cursor::new(graph_data)).unwrap();
deserialize_witnesscalc_graph(std::io::Cursor::new(graph_data))?;
let mut inputs_buffer = get_inputs_buffer(get_inputs_size(&nodes));
populate_inputs(&inputs, &input_mapping, &mut inputs_buffer);
populate_inputs(&inputs, &input_mapping, &mut inputs_buffer)?;
if let Some(v) = inputs.get_mut("identitySecret") {
// ~== v[0] = U256::ZERO;
unsafe { zeroize_flat_type(v) };
// DO NOT USE: unsafe { zeroize_flat_type(v) } only clears the Vec pointer, not the data—can cause memory leaks
for val in v.iter_mut() {
unsafe { zeroize_flat_type(val) };
}
}
let res = graph::evaluate(&nodes, inputs_buffer.as_slice(), &signals);
inputs_buffer.iter_mut().for_each(|i| {
unsafe { zeroize_flat_type(i) };
});
res
let res = graph::evaluate(&nodes, inputs_buffer.as_slice(), &signals)
.map_err(WitnessCalcError::GraphEvaluation)?;
for val in inputs_buffer.iter_mut() {
unsafe { zeroize_flat_type(val) };
}
Ok(res)
}
fn get_inputs_size(nodes: &[Node]) -> usize {
@@ -73,17 +83,26 @@ fn populate_inputs(
input_list: &HashMap<String, Vec<U256>>,
inputs_info: &InputSignalsInfo,
input_buffer: &mut [U256],
) {
) -> Result<(), WitnessCalcError> {
for (key, value) in input_list {
let (offset, len) = inputs_info[key];
if len != value.len() {
panic!("Invalid input length for {key}");
let (offset, len) = inputs_info
.get(key)
.ok_or_else(|| WitnessCalcError::MissingInput(key.clone()))?;
if *len != value.len() {
return Err(WitnessCalcError::InvalidInputLength {
name: key.clone(),
expected: *len,
actual: value.len(),
});
}
for (i, v) in value.iter().enumerate() {
input_buffer[offset + i] = *v;
}
}
Ok(())
}
/// Allocates inputs vec with position 0 set to 1

View File

@@ -1,22 +1,17 @@
// This file is based on the code by iden3. Its preimage can be found here:
// This crate is based on the code by iden3. Its preimage can be found here:
// https://github.com/iden3/circom-witnesscalc/blob/5cb365b6e4d9052ecc69d4567fcf5bc061c20e94/src/graph.rs
use std::cmp::Ordering;
use ark_ff::{BigInt, BigInteger, One, PrimeField, Zero};
use ark_serialize::{CanonicalDeserialize, CanonicalSerialize, Compress, Validate};
use rand::Rng;
use ruint::{aliases::U256, uint};
use serde::{Deserialize, Serialize};
use std::{
cmp::Ordering,
collections::HashMap,
error::Error,
ops::{Deref, Shl, Shr},
};
use crate::circuit::iden3calc::proto;
use super::proto;
use crate::circuit::Fr;
pub const M: U256 =
const M: U256 =
uint!(21888242871839275222246405745257275088548364400416034343698204186575808495617_U256);
fn ark_se<S, A: CanonicalSerialize>(a: &A, s: S) -> Result<S::Ok, S::Error>
@@ -39,17 +34,18 @@ where
}
#[inline(always)]
pub fn fr_to_u256(x: &Fr) -> U256 {
pub(crate) fn fr_to_u256(x: &Fr) -> U256 {
U256::from_limbs(x.into_bigint().0)
}
#[inline(always)]
pub fn u256_to_fr(x: &U256) -> Fr {
Fr::from_bigint(BigInt::new(x.into_limbs())).expect("Failed to convert U256 to Fr")
pub(crate) fn u256_to_fr(x: &U256) -> Result<Fr, String> {
Fr::from_bigint(BigInt::new(x.into_limbs()))
.ok_or_else(|| "Failed to convert U256 to Fr".to_string())
}
#[derive(Hash, PartialEq, Eq, Debug, Clone, Copy, Serialize, Deserialize)]
pub enum Operation {
pub(crate) enum Operation {
Mul,
Div,
Add,
@@ -73,113 +69,76 @@ pub enum Operation {
}
impl Operation {
// TODO: rewrite to &U256 type
pub fn eval(&self, a: U256, b: U256) -> U256 {
fn eval_fr(&self, a: Fr, b: Fr) -> Result<Fr, String> {
use Operation::*;
match self {
Mul => a.mul_mod(b, M),
Div => {
if b == U256::ZERO {
// as we are simulating a circuit execution with signals
// values all equal to 0, just return 0 here in case of
// division by zero
U256::ZERO
} else {
a.mul_mod(b.inv_mod(M).unwrap(), M)
}
}
Add => a.add_mod(b, M),
Sub => a.add_mod(M - b, M),
Pow => a.pow_mod(b, M),
Mod => a.div_rem(b).1,
Eq => U256::from(a == b),
Neq => U256::from(a != b),
Lt => u_lt(&a, &b),
Gt => u_gt(&a, &b),
Leq => u_lte(&a, &b),
Geq => u_gte(&a, &b),
Land => U256::from(a != U256::ZERO && b != U256::ZERO),
Lor => U256::from(a != U256::ZERO || b != U256::ZERO),
Shl => compute_shl_uint(a, b),
Shr => compute_shr_uint(a, b),
// TODO test with conner case when it is possible to get the number
// bigger then modulus
Bor => a.bitor(b),
Band => a.bitand(b),
// TODO test with conner case when it is possible to get the number
// bigger then modulus
Bxor => a.bitxor(b),
Idiv => a / b,
}
}
pub fn eval_fr(&self, a: Fr, b: Fr) -> Fr {
use Operation::*;
match self {
Mul => a * b,
Mul => Ok(a * b),
// We always should return something on the circuit execution.
// So in case of division by 0 we would return 0. And the proof
// should be invalid in the end.
Div => {
if b.is_zero() {
Fr::zero()
Ok(Fr::zero())
} else {
a / b
Ok(a / b)
}
}
Add => a + b,
Sub => a - b,
Add => Ok(a + b),
Sub => Ok(a - b),
// Modular exponentiation to prevent overflow and keep result in field
Pow => {
let a_u256 = fr_to_u256(&a);
let b_u256 = fr_to_u256(&b);
let result = a_u256.pow_mod(b_u256, M);
u256_to_fr(&result)
}
// Integer division (not field division)
Idiv => {
if b.is_zero() {
Fr::zero()
Ok(Fr::zero())
} else {
let a_u256 = fr_to_u256(&a);
let b_u256 = fr_to_u256(&b);
u256_to_fr(&(a_u256 / b_u256))
}
}
// Integer modulo (not field arithmetic)
Mod => {
if b.is_zero() {
Fr::zero()
Ok(Fr::zero())
} else {
let a_u256 = fr_to_u256(&a);
let b_u256 = fr_to_u256(&b);
u256_to_fr(&(a_u256 % b_u256))
}
}
Eq => match a.cmp(&b) {
Eq => Ok(match a.cmp(&b) {
Ordering::Equal => Fr::one(),
_ => Fr::zero(),
},
Neq => match a.cmp(&b) {
}),
Neq => Ok(match a.cmp(&b) {
Ordering::Equal => Fr::zero(),
_ => Fr::one(),
},
}),
Lt => u256_to_fr(&u_lt(&fr_to_u256(&a), &fr_to_u256(&b))),
Gt => u256_to_fr(&u_gt(&fr_to_u256(&a), &fr_to_u256(&b))),
Leq => u256_to_fr(&u_lte(&fr_to_u256(&a), &fr_to_u256(&b))),
Geq => u256_to_fr(&u_gte(&fr_to_u256(&a), &fr_to_u256(&b))),
Land => {
if a.is_zero() || b.is_zero() {
Fr::zero()
} else {
Fr::one()
}
}
Lor => {
if a.is_zero() && b.is_zero() {
Fr::zero()
} else {
Fr::one()
}
}
Land => Ok(if a.is_zero() || b.is_zero() {
Fr::zero()
} else {
Fr::one()
}),
Lor => Ok(if a.is_zero() && b.is_zero() {
Fr::zero()
} else {
Fr::one()
}),
Shl => shl(a, b),
Shr => shr(a, b),
Bor => bit_or(a, b),
Band => bit_and(a, b),
Bxor => bit_xor(a, b),
// TODO implement other operators
_ => unimplemented!("operator {:?} not implemented for Montgomery", self),
}
}
}
@@ -212,37 +171,27 @@ impl From<&Operation> for proto::DuoOp {
}
#[derive(Hash, PartialEq, Eq, Debug, Clone, Copy, Serialize, Deserialize)]
pub enum UnoOperation {
pub(crate) enum UnoOperation {
Neg,
Id, // identity - just return self
}
impl UnoOperation {
pub fn eval(&self, a: U256) -> U256 {
match self {
UnoOperation::Neg => {
if a == U256::ZERO {
U256::ZERO
} else {
M - a
}
}
UnoOperation::Id => a,
}
}
pub fn eval_fr(&self, a: Fr) -> Fr {
fn eval_fr(&self, a: Fr) -> Result<Fr, String> {
match self {
UnoOperation::Neg => {
if a.is_zero() {
Fr::zero()
Ok(Fr::zero())
} else {
let mut x = Fr::MODULUS;
x.sub_with_borrow(&a.into_bigint());
Fr::from_bigint(x).unwrap()
Fr::from_bigint(x).ok_or_else(|| "Failed to compute negation".to_string())
}
}
_ => unimplemented!("uno operator {:?} not implemented for Montgomery", self),
_ => Err(format!(
"uno operator {:?} not implemented for Montgomery",
self
)),
}
}
}
@@ -257,30 +206,18 @@ impl From<&UnoOperation> for proto::UnoOp {
}
#[derive(Hash, PartialEq, Eq, Debug, Clone, Copy, Serialize, Deserialize)]
pub enum TresOperation {
pub(crate) enum TresOperation {
TernCond,
}
impl TresOperation {
pub fn eval(&self, a: U256, b: U256, c: U256) -> U256 {
match self {
TresOperation::TernCond => {
if a == U256::ZERO {
c
} else {
b
}
}
}
}
pub fn eval_fr(&self, a: Fr, b: Fr, c: Fr) -> Fr {
fn eval_fr(&self, a: Fr, b: Fr, c: Fr) -> Result<Fr, String> {
match self {
TresOperation::TernCond => {
if a.is_zero() {
c
Ok(c)
} else {
b
Ok(b)
}
}
}
@@ -296,7 +233,7 @@ impl From<&TresOperation> for proto::TresOp {
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum Node {
pub(crate) enum Node {
Input(usize),
Constant(U256),
#[serde(serialize_with = "ark_se", deserialize_with = "ark_de")]
@@ -306,133 +243,21 @@ pub enum Node {
TresOp(TresOperation, usize, usize, usize),
}
// TODO remove pub from Vec<Node>
#[derive(Default)]
pub struct Nodes(pub Vec<Node>);
impl Nodes {
pub fn new() -> Self {
Nodes(Vec::new())
}
pub fn to_const(&self, idx: NodeIdx) -> Result<U256, NodeConstErr> {
let me = self.0.get(idx.0).ok_or(NodeConstErr::EmptyNode(idx))?;
match me {
Node::Constant(v) => Ok(*v),
Node::UnoOp(op, a) => Ok(op.eval(self.to_const(NodeIdx(*a))?)),
Node::Op(op, a, b) => {
Ok(op.eval(self.to_const(NodeIdx(*a))?, self.to_const(NodeIdx(*b))?))
}
Node::TresOp(op, a, b, c) => Ok(op.eval(
self.to_const(NodeIdx(*a))?,
self.to_const(NodeIdx(*b))?,
self.to_const(NodeIdx(*c))?,
)),
Node::Input(_) => Err(NodeConstErr::InputSignal),
Node::MontConstant(_) => {
panic!("MontConstant should not be used here")
}
}
}
pub fn push(&mut self, n: Node) -> NodeIdx {
self.0.push(n);
NodeIdx(self.0.len() - 1)
}
pub fn get(&self, idx: NodeIdx) -> Option<&Node> {
self.0.get(idx.0)
}
}
impl Deref for Nodes {
type Target = Vec<Node>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[derive(Debug, Copy, Clone)]
pub struct NodeIdx(pub usize);
impl From<usize> for NodeIdx {
fn from(v: usize) -> Self {
NodeIdx(v)
}
}
#[derive(Debug)]
pub enum NodeConstErr {
EmptyNode(NodeIdx),
InputSignal,
}
impl std::fmt::Display for NodeConstErr {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
NodeConstErr::EmptyNode(idx) => {
write!(f, "empty node at index {}", idx.0)
}
NodeConstErr::InputSignal => {
write!(f, "input signal is not a constant")
}
}
}
}
impl Error for NodeConstErr {}
fn compute_shl_uint(a: U256, b: U256) -> U256 {
debug_assert!(b.lt(&U256::from(256)));
let ls_limb = b.as_limbs()[0];
a.shl(ls_limb as usize)
}
fn compute_shr_uint(a: U256, b: U256) -> U256 {
debug_assert!(b.lt(&U256::from(256)));
let ls_limb = b.as_limbs()[0];
a.shr(ls_limb as usize)
}
/// All references must be backwards.
fn assert_valid(nodes: &[Node]) {
for (i, &node) in nodes.iter().enumerate() {
if let Node::Op(_, a, b) = node {
assert!(a < i);
assert!(b < i);
} else if let Node::UnoOp(_, a) = node {
assert!(a < i);
} else if let Node::TresOp(_, a, b, c) = node {
assert!(a < i);
assert!(b < i);
assert!(c < i);
}
}
}
pub fn optimize(nodes: &mut Vec<Node>, outputs: &mut [usize]) {
tree_shake(nodes, outputs);
propagate(nodes);
value_numbering(nodes, outputs);
constants(nodes);
tree_shake(nodes, outputs);
montgomery_form(nodes);
}
pub fn evaluate(nodes: &[Node], inputs: &[U256], outputs: &[usize]) -> Vec<Fr> {
// assert_valid(nodes);
pub(crate) fn evaluate(
nodes: &[Node],
inputs: &[U256],
outputs: &[usize],
) -> Result<Vec<Fr>, String> {
// Evaluate the graph.
let mut values = Vec::with_capacity(nodes.len());
for &node in nodes.iter() {
let value = match node {
Node::Constant(c) => u256_to_fr(&c),
Node::Constant(c) => u256_to_fr(&c)?,
Node::MontConstant(c) => c,
Node::Input(i) => u256_to_fr(&inputs[i]),
Node::Op(op, a, b) => op.eval_fr(values[a], values[b]),
Node::UnoOp(op, a) => op.eval_fr(values[a]),
Node::TresOp(op, a, b, c) => op.eval_fr(values[a], values[b], values[c]),
Node::Input(i) => u256_to_fr(&inputs[i])?,
Node::Op(op, a, b) => op.eval_fr(values[a], values[b])?,
Node::UnoOp(op, a) => op.eval_fr(values[a])?,
Node::TresOp(op, a, b, c) => op.eval_fr(values[a], values[b], values[c])?,
};
values.push(value);
}
@@ -443,246 +268,31 @@ pub fn evaluate(nodes: &[Node], inputs: &[U256], outputs: &[usize]) -> Vec<Fr> {
out[i] = values[outputs[i]];
}
out
Ok(out)
}
/// Constant propagation
pub fn propagate(nodes: &mut [Node]) {
assert_valid(nodes);
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));
} else if a == b {
// Not constant but equal
use Operation::*;
if let Some(c) = match op {
Eq | Leq | Geq => Some(true),
Neq | Lt | Gt => Some(false),
_ => None,
} {
nodes[i] = Node::Constant(U256::from(c));
}
}
} else if let Node::UnoOp(op, a) = nodes[i] {
if let Node::Constant(va) = nodes[a] {
nodes[i] = Node::Constant(op.eval(va));
}
} 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));
}
}
}
}
/// Remove unused nodes
pub fn tree_shake(nodes: &mut Vec<Node>, outputs: &mut [usize]) {
assert_valid(nodes);
// Mark all nodes that are used.
let mut used = vec![false; nodes.len()];
for &i in outputs.iter() {
used[i] = true;
}
// Work backwards from end as all references are backwards.
for i in (0..nodes.len()).rev() {
if used[i] {
if let Node::Op(_, a, b) = nodes[i] {
used[a] = true;
used[b] = true;
}
if let Node::UnoOp(_, a) = nodes[i] {
used[a] = true;
}
if let Node::TresOp(_, a, b, c) = nodes[i] {
used[a] = true;
used[b] = true;
used[c] = true;
}
}
}
// Remove unused nodes
let n = nodes.len();
let mut retain = used.iter();
nodes.retain(|_| *retain.next().unwrap());
// Renumber references.
let mut renumber = vec![None; n];
let mut index = 0;
for (i, &used) in used.iter().enumerate() {
if used {
renumber[i] = Some(index);
index += 1;
}
}
assert_eq!(index, nodes.len());
for (&used, renumber) in used.iter().zip(renumber.iter()) {
assert_eq!(used, renumber.is_some());
}
// Renumber references.
for node in nodes.iter_mut() {
if let Node::Op(_, a, b) = node {
*a = renumber[*a].unwrap();
*b = renumber[*b].unwrap();
}
if let Node::UnoOp(_, a) = node {
*a = renumber[*a].unwrap();
}
if let Node::TresOp(_, a, b, c) = node {
*a = renumber[*a].unwrap();
*b = renumber[*b].unwrap();
*c = renumber[*c].unwrap();
}
}
for output in outputs.iter_mut() {
*output = renumber[*output].unwrap();
}
}
/// Randomly evaluate the graph
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();
let mut prfs = HashMap::new();
let mut prfs_uno = HashMap::new();
let mut prfs_tres = HashMap::new();
for node in nodes.iter() {
use Operation::*;
let value = match node {
// Constants evaluate to themselves
Node::Constant(c) => *c,
Node::MontConstant(_) => unimplemented!("should not be used"),
// Algebraic Ops are evaluated directly
// Since the field is large, by Swartz-Zippel if
// two values are the same then they are likely algebraically equal.
Node::Op(op @ (Add | Sub | Mul), a, b) => op.eval(values[*a], values[*b]),
// Input and non-algebraic ops are random functions
// TODO: https://github.com/recmo/uint/issues/95 and use .gen_range(..M)
Node::Input(i) => *inputs.entry(*i).or_insert_with(|| rng.gen::<U256>() % M),
Node::Op(op, a, b) => *prfs
.entry((*op, values[*a], values[*b]))
.or_insert_with(|| rng.gen::<U256>() % M),
Node::UnoOp(op, a) => *prfs_uno
.entry((*op, values[*a]))
.or_insert_with(|| rng.gen::<U256>() % M),
Node::TresOp(op, a, b, c) => *prfs_tres
.entry((*op, values[*a], values[*b], values[*c]))
.or_insert_with(|| rng.gen::<U256>() % M),
};
values.push(value);
}
values
}
/// Value numbering
pub fn value_numbering(nodes: &mut [Node], outputs: &mut [usize]) {
assert_valid(nodes);
// Evaluate the graph in random field elements.
let values = random_eval(nodes);
// Find all nodes with the same value.
let mut value_map = HashMap::new();
for (i, &value) in values.iter().enumerate() {
value_map.entry(value).or_insert_with(Vec::new).push(i);
}
// For nodes that are the same, pick the first index.
let renumber: Vec<_> = values.into_iter().map(|v| value_map[&v][0]).collect();
// Renumber references.
for node in nodes.iter_mut() {
if let Node::Op(_, a, b) = node {
*a = renumber[*a];
*b = renumber[*b];
}
if let Node::UnoOp(_, a) = node {
*a = renumber[*a];
}
if let Node::TresOp(_, a, b, c) = node {
*a = renumber[*a];
*b = renumber[*b];
*c = renumber[*c];
}
}
for output in outputs.iter_mut() {
*output = renumber[*output];
}
}
/// Probabilistic constant determination
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.
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]);
}
}
}
/// Convert to Montgomery form
pub fn montgomery_form(nodes: &mut [Node]) {
for node in nodes.iter_mut() {
use Node::*;
use Operation::*;
match node {
Constant(c) => *node = MontConstant(u256_to_fr(c)),
MontConstant(..) => (),
Input(..) => (),
Op(
Mul | Div | Add | Sub | Idiv | Mod | Eq | Neq | Lt | Gt | Leq | Geq | Land | Lor
| Shl | Shr | Bor | Band | Bxor,
..,
) => (),
Op(op @ Pow, ..) => unimplemented!("Operators Montgomery form: {:?}", op),
UnoOp(UnoOperation::Neg, ..) => (),
UnoOp(op, ..) => unimplemented!("Uno Operators Montgomery form: {:?}", op),
TresOp(TresOperation::TernCond, ..) => (),
}
}
}
fn shl(a: Fr, b: Fr) -> Fr {
fn shl(a: Fr, b: Fr) -> Result<Fr, String> {
if b.is_zero() {
return a;
return Ok(a);
}
if b.cmp(&Fr::from(Fr::MODULUS_BIT_SIZE)).is_ge() {
return Fr::zero();
return Ok(Fr::zero());
}
let n = b.into_bigint().0[0] as u32;
let a = a.into_bigint();
Fr::from_bigint(a << n).unwrap()
Fr::from_bigint(a << n).ok_or_else(|| "Failed to compute left shift".to_string())
}
fn shr(a: Fr, b: Fr) -> Fr {
fn shr(a: Fr, b: Fr) -> Result<Fr, String> {
if b.is_zero() {
return a;
return Ok(a);
}
match b.cmp(&Fr::from(254u64)) {
Ordering::Equal => return Fr::zero(),
Ordering::Greater => return Fr::zero(),
Ordering::Equal => return Ok(Fr::zero()),
Ordering::Greater => return Ok(Fr::zero()),
_ => (),
};
@@ -698,7 +308,7 @@ fn shr(a: Fr, b: Fr) -> Fr {
}
if n == 0 {
return Fr::from_bigint(result).unwrap();
return Fr::from_bigint(result).ok_or_else(|| "Failed to compute right shift".to_string());
}
let mask: u64 = (1 << n) - 1;
@@ -709,10 +319,10 @@ fn shr(a: Fr, b: Fr) -> Fr {
c[i] = (c[i] >> n) | (carrier << (64 - n));
carrier = new_carrier;
}
Fr::from_bigint(result).unwrap()
Fr::from_bigint(result).ok_or_else(|| "Failed to compute right shift".to_string())
}
fn bit_and(a: Fr, b: Fr) -> Fr {
fn bit_and(a: Fr, b: Fr) -> Result<Fr, String> {
let a = a.into_bigint();
let b = b.into_bigint();
let c: [u64; 4] = [
@@ -726,10 +336,10 @@ fn bit_and(a: Fr, b: Fr) -> Fr {
d.sub_with_borrow(&Fr::MODULUS);
}
Fr::from_bigint(d).unwrap()
Fr::from_bigint(d).ok_or_else(|| "Failed to compute bitwise AND".to_string())
}
fn bit_or(a: Fr, b: Fr) -> Fr {
fn bit_or(a: Fr, b: Fr) -> Result<Fr, String> {
let a = a.into_bigint();
let b = b.into_bigint();
let c: [u64; 4] = [
@@ -743,10 +353,10 @@ fn bit_or(a: Fr, b: Fr) -> Fr {
d.sub_with_borrow(&Fr::MODULUS);
}
Fr::from_bigint(d).unwrap()
Fr::from_bigint(d).ok_or_else(|| "Failed to compute bitwise OR".to_string())
}
fn bit_xor(a: Fr, b: Fr) -> Fr {
fn bit_xor(a: Fr, b: Fr) -> Result<Fr, String> {
let a = a.into_bigint();
let b = b.into_bigint();
let c: [u64; 4] = [
@@ -760,7 +370,7 @@ fn bit_xor(a: Fr, b: Fr) -> Fr {
d.sub_with_borrow(&Fr::MODULUS);
}
Fr::from_bigint(d).unwrap()
Fr::from_bigint(d).ok_or_else(|| "Failed to compute bitwise XOR".to_string())
}
// M / 2
@@ -816,24 +426,27 @@ fn u_lt(a: &U256, b: &U256) -> U256 {
}
#[cfg(test)]
mod tests {
use super::*;
mod test {
use std::{ops::Div, str::FromStr};
use ruint::uint;
use std::ops::Div;
use std::str::FromStr;
use super::*;
#[test]
fn test_ok() {
let a = Fr::from(4u64);
let b = Fr::from(2u64);
let c = shl(a, b);
let c = shl(a, b).unwrap();
assert_eq!(c.cmp(&Fr::from(16u64)), Ordering::Equal)
}
#[test]
fn test_div() {
assert_eq!(
Operation::Div.eval_fr(Fr::from(2u64), Fr::from(3u64)),
Operation::Div
.eval_fr(Fr::from(2u64), Fr::from(3u64))
.unwrap(),
Fr::from_str(
"7296080957279758407415468581752425029516121466805344781232734728858602831873"
)
@@ -841,12 +454,16 @@ mod tests {
);
assert_eq!(
Operation::Div.eval_fr(Fr::from(6u64), Fr::from(2u64)),
Operation::Div
.eval_fr(Fr::from(6u64), Fr::from(2u64))
.unwrap(),
Fr::from_str("3").unwrap()
);
assert_eq!(
Operation::Div.eval_fr(Fr::from(7u64), Fr::from(2u64)),
Operation::Div
.eval_fr(Fr::from(7u64), Fr::from(2u64))
.unwrap(),
Fr::from_str(
"10944121435919637611123202872628637544274182200208017171849102093287904247812"
)
@@ -857,17 +474,23 @@ mod tests {
#[test]
fn test_idiv() {
assert_eq!(
Operation::Idiv.eval_fr(Fr::from(2u64), Fr::from(3u64)),
Operation::Idiv
.eval_fr(Fr::from(2u64), Fr::from(3u64))
.unwrap(),
Fr::from_str("0").unwrap()
);
assert_eq!(
Operation::Idiv.eval_fr(Fr::from(6u64), Fr::from(2u64)),
Operation::Idiv
.eval_fr(Fr::from(6u64), Fr::from(2u64))
.unwrap(),
Fr::from_str("3").unwrap()
);
assert_eq!(
Operation::Idiv.eval_fr(Fr::from(7u64), Fr::from(2u64)),
Operation::Idiv
.eval_fr(Fr::from(7u64), Fr::from(2u64))
.unwrap(),
Fr::from_str("3").unwrap()
);
}
@@ -875,12 +498,16 @@ mod tests {
#[test]
fn test_fr_mod() {
assert_eq!(
Operation::Mod.eval_fr(Fr::from(7u64), Fr::from(2u64)),
Operation::Mod
.eval_fr(Fr::from(7u64), Fr::from(2u64))
.unwrap(),
Fr::from_str("1").unwrap()
);
assert_eq!(
Operation::Mod.eval_fr(Fr::from(7u64), Fr::from(9u64)),
Operation::Mod
.eval_fr(Fr::from(7u64), Fr::from(9u64))
.unwrap(),
Fr::from_str("7").unwrap()
);
}

View File

@@ -1,33 +1,33 @@
// This file has been generated by prost-build during compilation of the code by iden3
// This crate has been generated by prost-build during compilation of the code by iden3
// and modified manually. The *.proto file used to generate this on can be found here:
// https://github.com/iden3/circom-witnesscalc/blob/5cb365b6e4d9052ecc69d4567fcf5bc061c20e94/protos/messages.proto
use std::collections::HashMap;
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct BigUInt {
#[derive(Clone, PartialEq, prost::Message)]
pub(crate) struct BigUInt {
#[prost(bytes = "vec", tag = "1")]
pub value_le: Vec<u8>,
}
#[derive(Clone, Copy, PartialEq, ::prost::Message)]
pub struct InputNode {
#[derive(Clone, Copy, PartialEq, prost::Message)]
pub(crate) struct InputNode {
#[prost(uint32, tag = "1")]
pub idx: u32,
}
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct ConstantNode {
#[derive(Clone, PartialEq, prost::Message)]
pub(crate) struct ConstantNode {
#[prost(message, optional, tag = "1")]
pub value: Option<BigUInt>,
}
#[derive(Clone, Copy, PartialEq, ::prost::Message)]
pub struct UnoOpNode {
#[derive(Clone, Copy, PartialEq, prost::Message)]
pub(crate) struct UnoOpNode {
#[prost(enumeration = "UnoOp", tag = "1")]
pub op: i32,
#[prost(uint32, tag = "2")]
pub a_idx: u32,
}
#[derive(Clone, Copy, PartialEq, ::prost::Message)]
pub struct DuoOpNode {
#[derive(Clone, Copy, PartialEq, prost::Message)]
pub(crate) struct DuoOpNode {
#[prost(enumeration = "DuoOp", tag = "1")]
pub op: i32,
#[prost(uint32, tag = "2")]
@@ -35,8 +35,8 @@ pub struct DuoOpNode {
#[prost(uint32, tag = "3")]
pub b_idx: u32,
}
#[derive(Clone, Copy, PartialEq, ::prost::Message)]
pub struct TresOpNode {
#[derive(Clone, Copy, PartialEq, prost::Message)]
pub(crate) struct TresOpNode {
#[prost(enumeration = "TresOp", tag = "1")]
pub op: i32,
#[prost(uint32, tag = "2")]
@@ -46,15 +46,15 @@ pub struct TresOpNode {
#[prost(uint32, tag = "4")]
pub c_idx: u32,
}
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct Node {
#[derive(Clone, PartialEq, prost::Message)]
pub(crate) struct Node {
#[prost(oneof = "node::Node", tags = "1, 2, 3, 4, 5")]
pub node: Option<node::Node>,
}
/// Nested message and enum types in `Node`.
pub mod node {
#[derive(Clone, PartialEq, ::prost::Oneof)]
pub enum Node {
pub(crate) mod node {
#[derive(Clone, PartialEq, prost::Oneof)]
pub(crate) enum Node {
#[prost(message, tag = "1")]
Input(super::InputNode),
#[prost(message, tag = "2")]
@@ -67,22 +67,22 @@ pub mod node {
TresOp(super::TresOpNode),
}
}
#[derive(Clone, Copy, PartialEq, ::prost::Message)]
pub struct SignalDescription {
#[derive(Clone, Copy, PartialEq, prost::Message)]
pub(crate) struct SignalDescription {
#[prost(uint32, tag = "1")]
pub offset: u32,
#[prost(uint32, tag = "2")]
pub len: u32,
}
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct GraphMetadata {
#[derive(Clone, PartialEq, prost::Message)]
pub(crate) struct GraphMetadata {
#[prost(uint32, repeated, tag = "1")]
pub witness_signals: Vec<u32>,
#[prost(map = "string, message", tag = "2")]
pub inputs: HashMap<String, SignalDescription>,
}
#[derive(Clone, Copy, Debug, PartialEq, ::prost::Enumeration)]
pub enum DuoOp {
#[derive(Clone, Copy, Debug, PartialEq, prost::Enumeration)]
pub(crate) enum DuoOp {
Mul = 0,
Div = 1,
Add = 2,
@@ -105,13 +105,13 @@ pub enum DuoOp {
Bxor = 19,
}
#[derive(Clone, Copy, Debug, PartialEq, ::prost::Enumeration)]
pub enum UnoOp {
#[derive(Clone, Copy, Debug, PartialEq, prost::Enumeration)]
pub(crate) enum UnoOp {
Neg = 0,
Id = 1,
}
#[derive(Clone, Copy, Debug, PartialEq, ::prost::Enumeration)]
pub enum TresOp {
#[derive(Clone, Copy, Debug, PartialEq, prost::Enumeration)]
pub(crate) enum TresOp {
TernCond = 0,
}

View File

@@ -1,57 +1,86 @@
// This file is based on the code by iden3. Its preimage can be found here:
// This crate is based on the code by iden3. Its preimage can be found here:
// https://github.com/iden3/circom-witnesscalc/blob/5cb365b6e4d9052ecc69d4567fcf5bc061c20e94/src/storage.rs
use ark_bn254::Fr;
use std::io::{Read, Write};
use ark_ff::PrimeField;
use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
use prost::Message;
use std::io::{Read, Write};
use crate::circuit::iden3calc::{
graph,
graph::{Operation, TresOperation, UnoOperation},
use super::{
graph::{self, Operation, TresOperation, UnoOperation},
proto, InputSignalsInfo,
};
use crate::circuit::Fr;
// format of the wtns.graph file:
// + magic line: wtns.graph.001
// + 4 bytes unsigned LE 32-bit integer: number of nodes
// + series of protobuf serialized nodes. Each node prefixed by varint length
// + protobuf serialized GraphMetadata
// + 8 bytes unsigned LE 64-bit integer: offset of GraphMetadata message
/// Format of the wtns.graph file:
/// + magic line: wtns.graph.001
/// + 4 bytes unsigned LE 32-bit integer: number of nodes
/// + series of protobuf serialized nodes. Each node prefixed by varint length
/// + protobuf serialized GraphMetadata
/// + 8 bytes unsigned LE 64-bit integer: offset of GraphMetadata message
const WITNESSCALC_GRAPH_MAGIC: &[u8] = b"wtns.graph.001";
const MAX_VARINT_LENGTH: usize = 10;
impl From<proto::Node> for graph::Node {
fn from(value: proto::Node) -> Self {
match value.node.unwrap() {
proto::node::Node::Input(input_node) => graph::Node::Input(input_node.idx as usize),
impl TryFrom<proto::Node> for graph::Node {
type Error = std::io::Error;
fn try_from(value: proto::Node) -> Result<Self, Self::Error> {
let node = value.node.ok_or_else(|| {
std::io::Error::new(
std::io::ErrorKind::InvalidData,
"Proto::Node must have a node field",
)
})?;
match node {
proto::node::Node::Input(input_node) => Ok(graph::Node::Input(input_node.idx as usize)),
proto::node::Node::Constant(constant_node) => {
let i = constant_node.value.unwrap();
graph::Node::MontConstant(Fr::from_le_bytes_mod_order(i.value_le.as_slice()))
let i = constant_node.value.ok_or_else(|| {
std::io::Error::new(
std::io::ErrorKind::InvalidData,
"Constant node must have a value",
)
})?;
Ok(graph::Node::MontConstant(Fr::from_le_bytes_mod_order(
i.value_le.as_slice(),
)))
}
proto::node::Node::UnoOp(uno_op_node) => {
let op = proto::UnoOp::try_from(uno_op_node.op).unwrap();
graph::Node::UnoOp(op.into(), uno_op_node.a_idx as usize)
let op = proto::UnoOp::try_from(uno_op_node.op).map_err(|_| {
std::io::Error::new(
std::io::ErrorKind::InvalidData,
"UnoOp must be valid enum value",
)
})?;
Ok(graph::Node::UnoOp(op.into(), uno_op_node.a_idx as usize))
}
proto::node::Node::DuoOp(duo_op_node) => {
let op = proto::DuoOp::try_from(duo_op_node.op).unwrap();
graph::Node::Op(
let op = proto::DuoOp::try_from(duo_op_node.op).map_err(|_| {
std::io::Error::new(
std::io::ErrorKind::InvalidData,
"DuoOp must be valid enum value",
)
})?;
Ok(graph::Node::Op(
op.into(),
duo_op_node.a_idx as usize,
duo_op_node.b_idx as usize,
)
))
}
proto::node::Node::TresOp(tres_op_node) => {
let op = proto::TresOp::try_from(tres_op_node.op).unwrap();
graph::Node::TresOp(
let op = proto::TresOp::try_from(tres_op_node.op).map_err(|_| {
std::io::Error::new(
std::io::ErrorKind::InvalidData,
"TresOp must be valid enum value",
)
})?;
Ok(graph::Node::TresOp(
op.into(),
tres_op_node.a_idx as usize,
tres_op_node.b_idx as usize,
tres_op_node.c_idx as usize,
)
))
}
}
}
@@ -137,14 +166,15 @@ impl From<proto::TresOp> for graph::TresOperation {
}
}
pub fn serialize_witnesscalc_graph<T: Write>(
#[allow(dead_code)]
pub(crate) fn serialize_witnesscalc_graph<T: Write>(
mut w: T,
nodes: &Vec<graph::Node>,
witness_signals: &[usize],
input_signals: &InputSignalsInfo,
) -> std::io::Result<()> {
let mut ptr = 0usize;
w.write_all(WITNESSCALC_GRAPH_MAGIC).unwrap();
w.write_all(WITNESSCALC_GRAPH_MAGIC)?;
ptr += WITNESSCALC_GRAPH_MAGIC.len();
w.write_u64::<LittleEndian>(nodes.len() as u64)?;
@@ -232,7 +262,7 @@ fn read_message<R: Read, M: Message + std::default::Default>(
Ok(msg)
}
pub fn deserialize_witnesscalc_graph(
pub(crate) fn deserialize_witnesscalc_graph(
r: impl Read,
) -> std::io::Result<(Vec<graph::Node>, Vec<usize>, InputSignalsInfo)> {
let mut br = WriteBackReader::new(r);
@@ -251,8 +281,7 @@ pub fn deserialize_witnesscalc_graph(
let mut nodes = Vec::with_capacity(nodes_num as usize);
for _ in 0..nodes_num {
let n: proto::Node = read_message(&mut br)?;
let n2: graph::Node = n.into();
nodes.push(n2);
nodes.push(n.try_into()?);
}
let md: proto::GraphMetadata = read_message(&mut br)?;
@@ -331,13 +360,15 @@ impl<R: Read> Write for WriteBackReader<R> {
}
#[cfg(test)]
mod tests {
use super::*;
use byteorder::ByteOrder;
mod test {
use core::str::FromStr;
use graph::{Operation, TresOperation, UnoOperation};
use std::collections::HashMap;
use byteorder::ByteOrder;
use graph::{Operation, TresOperation, UnoOperation};
use super::*;
#[test]
fn test_read_message() {
let mut buf = Vec::new();

View File

@@ -1,51 +1,80 @@
// This crate provides interfaces for the zero-knowledge circuit and keys
pub mod error;
pub mod iden3calc;
pub mod qap;
pub(crate) mod error;
pub(crate) mod iden3calc;
pub(crate) mod qap;
#[cfg(not(target_arch = "wasm32"))]
use std::sync::LazyLock;
use ::lazy_static::lazy_static;
use ark_bn254::{
Bn254, Fq as ArkFq, Fq2 as ArkFq2, Fr as ArkFr, G1Affine as ArkG1Affine,
G1Projective as ArkG1Projective, G2Affine as ArkG2Affine, G2Projective as ArkG2Projective,
};
use ark_groth16::ProvingKey;
use ark_ff::Field;
use ark_groth16::{
Proof as ArkProof, ProvingKey as ArkProvingKey, VerifyingKey as ArkVerifyingKey,
};
use ark_relations::r1cs::ConstraintMatrices;
use ark_serialize::{CanonicalDeserialize, CanonicalSerialize};
use crate::circuit::error::ZKeyReadError;
use crate::circuit::iden3calc::calc_witness;
use {ark_ff::Field, ark_serialize::CanonicalDeserialize, ark_serialize::CanonicalSerialize};
use crate::utils::FrOrSecret;
pub const ARKZKEY_BYTES: &[u8] = include_bytes!("../../resources/tree_depth_20/rln_final.arkzkey");
use self::error::ZKeyReadError;
#[cfg(not(target_arch = "wasm32"))]
const GRAPH_BYTES: &[u8] = include_bytes!("../../resources/tree_depth_20/graph.bin");
lazy_static! {
static ref ARKZKEY: (ProvingKey<Curve>, ConstraintMatrices<Fr>) =
read_arkzkey_from_bytes_uncompressed(ARKZKEY_BYTES).expect("Failed to read arkzkey");
}
#[cfg(not(target_arch = "wasm32"))]
const ARKZKEY_BYTES: &[u8] = include_bytes!("../../resources/tree_depth_20/rln_final.arkzkey");
pub const TEST_TREE_DEPTH: usize = 20;
#[cfg(not(target_arch = "wasm32"))]
static ARKZKEY: LazyLock<Zkey> = LazyLock::new(|| {
read_arkzkey_from_bytes_uncompressed(ARKZKEY_BYTES).expect("Default zkey must be valid")
});
pub const DEFAULT_TREE_DEPTH: usize = 20;
pub const COMPRESS_PROOF_SIZE: usize = 128;
// The following types define the pairing friendly elliptic curve, the underlying finite fields and groups default to this module
// Note that proofs are serialized assuming Fr to be 4x8 = 32 bytes in size. Hence, changing to a curve with different encoding will make proof verification to fail
/// BN254 pairing-friendly elliptic curve.
pub type Curve = Bn254;
/// Scalar field Fr of the BN254 curve.
pub type Fr = ArkFr;
/// Base field Fq of the BN254 curve.
pub type Fq = ArkFq;
/// Quadratic extension field element for the BN254 curve.
pub type Fq2 = ArkFq2;
/// Affine representation of a G1 group element on the BN254 curve.
pub type G1Affine = ArkG1Affine;
/// Projective representation of a G1 group element on the BN254 curve.
pub type G1Projective = ArkG1Projective;
/// Affine representation of a G2 group element on the BN254 curve.
pub type G2Affine = ArkG2Affine;
/// Projective representation of a G2 group element on the BN254 curve.
pub type G2Projective = ArkG2Projective;
// Loads the proving key using a bytes vector
pub fn zkey_from_raw(
zkey_data: &[u8],
) -> Result<(ProvingKey<Curve>, ConstraintMatrices<Fr>), ZKeyReadError> {
/// Groth16 proof for the BN254 curve.
pub type Proof = ArkProof<Curve>;
/// Proving key for the Groth16 proof system.
pub type ProvingKey = ArkProvingKey<Curve>;
/// Combining the proving key and constraint matrices.
pub type Zkey = (ArkProvingKey<Curve>, ConstraintMatrices<Fr>);
/// Verifying key for the Groth16 proof system.
pub type VerifyingKey = ArkVerifyingKey<Curve>;
/// Loads the zkey from raw bytes
pub fn zkey_from_raw(zkey_data: &[u8]) -> Result<Zkey, ZKeyReadError> {
if zkey_data.is_empty() {
return Err(ZKeyReadError::EmptyBytes);
}
@@ -55,53 +84,43 @@ pub fn zkey_from_raw(
Ok(proving_key_and_matrices)
}
// Loads the proving key
// Loads default zkey from folder
#[cfg(not(target_arch = "wasm32"))]
pub fn zkey_from_folder() -> &'static (ProvingKey<Curve>, ConstraintMatrices<Fr>) {
pub fn zkey_from_folder() -> &'static Zkey {
&ARKZKEY
}
pub fn calculate_rln_witness<I: IntoIterator<Item = (String, Vec<FrOrSecret>)>>(
inputs: I,
graph_data: &[u8],
) -> Vec<Fr> {
calc_witness(inputs, graph_data)
}
// Loads default graph from folder
#[cfg(not(target_arch = "wasm32"))]
pub fn graph_from_folder() -> &'static [u8] {
GRAPH_BYTES
}
////////////////////////////////////////////////////////
// Functions and structs from [arkz-key](https://github.com/zkmopro/ark-zkey/blob/main/src/lib.rs#L106)
// without print and allow to choose between compressed and uncompressed arkzkey
////////////////////////////////////////////////////////
// The following functions and structs are based on code from ark-zkey:
// https://github.com/zkmopro/ark-zkey/blob/main/src/lib.rs#L106
#[derive(CanonicalSerialize, CanonicalDeserialize, Clone, Debug, PartialEq)]
pub struct SerializableProvingKey(pub ProvingKey<Bn254>);
struct SerializableProvingKey(ArkProvingKey<Curve>);
#[derive(CanonicalSerialize, CanonicalDeserialize, Clone, Debug, PartialEq)]
pub struct SerializableConstraintMatrices<F: Field> {
pub num_instance_variables: usize,
pub num_witness_variables: usize,
pub num_constraints: usize,
pub a_num_non_zero: usize,
pub b_num_non_zero: usize,
pub c_num_non_zero: usize,
pub a: SerializableMatrix<F>,
pub b: SerializableMatrix<F>,
pub c: SerializableMatrix<F>,
struct SerializableConstraintMatrices<F: Field> {
num_instance_variables: usize,
num_witness_variables: usize,
num_constraints: usize,
a_num_non_zero: usize,
b_num_non_zero: usize,
c_num_non_zero: usize,
a: SerializableMatrix<F>,
b: SerializableMatrix<F>,
c: SerializableMatrix<F>,
}
#[derive(CanonicalSerialize, CanonicalDeserialize, Clone, Debug, PartialEq)]
pub struct SerializableMatrix<F: Field> {
struct SerializableMatrix<F: Field> {
pub data: Vec<Vec<(F, usize)>>,
}
pub fn read_arkzkey_from_bytes_uncompressed(
arkzkey_data: &[u8],
) -> Result<(ProvingKey<Curve>, ConstraintMatrices<Fr>), ZKeyReadError> {
fn read_arkzkey_from_bytes_uncompressed(arkzkey_data: &[u8]) -> Result<Zkey, ZKeyReadError> {
if arkzkey_data.is_empty() {
return Err(ZKeyReadError::EmptyBytes);
}
@@ -114,9 +133,8 @@ pub fn read_arkzkey_from_bytes_uncompressed(
let serialized_constraint_matrices =
SerializableConstraintMatrices::deserialize_uncompressed_unchecked(&mut cursor)?;
// Get on right form for API
let proving_key: ProvingKey<Bn254> = serialized_proving_key.0;
let constraint_matrices: ConstraintMatrices<ark_bn254::Fr> = ConstraintMatrices {
let proving_key: ProvingKey = serialized_proving_key.0;
let constraint_matrices: ConstraintMatrices<Fr> = ConstraintMatrices {
num_instance_variables: serialized_constraint_matrices.num_instance_variables,
num_witness_variables: serialized_constraint_matrices.num_witness_variables,
num_constraints: serialized_constraint_matrices.num_constraints,
@@ -127,6 +145,7 @@ pub fn read_arkzkey_from_bytes_uncompressed(
b: serialized_constraint_matrices.b.data,
c: serialized_constraint_matrices.c.data,
};
let zkey = (proving_key, constraint_matrices);
Ok((proving_key, constraint_matrices))
Ok(zkey)
}

View File

@@ -1,4 +1,4 @@
// This file is based on the code by arkworks. Its preimage can be found here:
// This crate is based on the code by arkworks. Its preimage can be found here:
// https://github.com/arkworks-rs/circom-compat/blob/3c95ed98e23a408b4d99a53e483a9bba39685a4e/src/circom/qap.rs
use ark_ff::PrimeField;
@@ -6,7 +6,6 @@ use ark_groth16::r1cs_to_qap::{evaluate_constraint, LibsnarkReduction, R1CSToQAP
use ark_poly::EvaluationDomain;
use ark_relations::r1cs::{ConstraintMatrices, ConstraintSystemRef, SynthesisError};
use ark_std::{cfg_into_iter, cfg_iter, cfg_iter_mut, vec};
#[cfg(feature = "parallel")]
use rayon::iter::{
IndexedParallelIterator, IntoParallelIterator, IntoParallelRefIterator,
@@ -18,7 +17,7 @@ use rayon::iter::{
/// coefficients domain. snarkjs instead precomputes the Lagrange form of the powers of tau bases
/// in a domain twice as large and the witness map is computed as the odd coefficients of (AB-C)
/// in that domain. This serves as HZ when computing the C proof element.
pub struct CircomReduction;
pub(crate) struct CircomReduction;
impl R1CSToQAP for CircomReduction {
#[allow(clippy::type_complexity)]

View File

@@ -1,79 +1,83 @@
use crate::circuit::error::ZKeyReadError;
use ark_bn254::Fr;
use ark_relations::r1cs::SynthesisError;
use ark_serialize::SerializationError;
use num_bigint::{BigInt, ParseBigIntError};
use std::array::TryFromSliceError;
use std::num::TryFromIntError;
use std::string::FromUtf8Error;
use thiserror::Error;
use utils::error::{FromConfigError, ZerokitMerkleTreeError};
use std::{array::TryFromSliceError, num::TryFromIntError};
use ark_relations::r1cs::SynthesisError;
use num_bigint::{BigInt, ParseBigIntError};
use thiserror::Error;
use zerokit_utils::error::{FromConfigError, HashError, ZerokitMerkleTreeError};
use crate::circuit::{
error::{WitnessCalcError, ZKeyReadError},
Fr,
};
/// Errors that can occur during RLN utility operations (conversions, parsing, etc.)
#[derive(Debug, thiserror::Error)]
pub enum ConversionError {
pub enum UtilsError {
#[error("Expected radix 10 or 16")]
WrongRadix,
#[error("{0}")]
#[error("Failed to parse big integer: {0}")]
ParseBigInt(#[from] ParseBigIntError),
#[error("{0}")]
#[error("Failed to convert to usize: {0}")]
ToUsize(#[from] TryFromIntError),
#[error("{0}")]
#[error("Failed to convert from slice: {0}")]
FromSlice(#[from] TryFromSliceError),
#[error("Input data too short: expected at least {expected} bytes, got {actual} bytes")]
InsufficientData { expected: usize, actual: usize },
}
#[derive(Error, Debug)]
pub enum ProofError {
#[error("{0}")]
ProtocolError(#[from] ProtocolError),
#[error("Error producing proof: {0}")]
SynthesisError(#[from] SynthesisError),
}
/// Errors that can occur during RLN protocol operations (proof generation, verification, etc.)
#[derive(Debug, thiserror::Error)]
pub enum ProtocolError {
#[error("{0}")]
Conversion(#[from] ConversionError),
#[error("Error producing proof: {0}")]
Synthesis(#[from] SynthesisError),
#[error("RLN utility error: {0}")]
Utils(#[from] UtilsError),
#[error("Error calculating witness: {0}")]
WitnessCalc(#[from] WitnessCalcError),
#[error("Expected to read {0} bytes but read only {1} bytes")]
InvalidReadLen(usize, usize),
#[error("Cannot convert bigint {0:?} to biguint")]
BigUintConversion(BigInt),
#[error("{0}")]
JsonError(#[from] serde_json::Error),
#[error("Message id ({0}) is not within user_message_limit ({1})")]
InvalidMessageId(Fr, Fr),
}
#[derive(Debug, thiserror::Error)]
pub enum ComputeIdSecretError {
/// Usually it means that the same signal is used to recover the user secret hash
#[error("Merkle proof length mismatch: expected {0}, got {1}")]
InvalidMerkleProofLength(usize, usize),
#[error("External nullifiers mismatch: {0} != {1}")]
ExternalNullifierMismatch(Fr, Fr),
#[error("Cannot recover secret: division by zero")]
DivisionByZero,
#[error("Merkle tree operation error: {0}")]
MerkleTree(#[from] ZerokitMerkleTreeError),
#[error("Hash computation error: {0}")]
Hash(#[from] HashError),
#[error("Proof serialization error: {0}")]
SerializationError(#[from] ark_serialize::SerializationError),
}
/// Errors that can occur during proof verification
#[derive(Error, Debug)]
pub enum VerifyError {
#[error("Invalid proof provided")]
InvalidProof,
#[error("Expected one of the provided roots")]
InvalidRoot,
#[error("Signal value does not match")]
InvalidSignal,
}
/// Top-level RLN error type encompassing all RLN operations
#[derive(Debug, thiserror::Error)]
pub enum RLNError {
#[error("I/O error: {0}")]
IO(#[from] std::io::Error),
#[error("Utf8 error: {0}")]
Utf8(#[from] FromUtf8Error),
#[error("Serde json error: {0}")]
JSON(#[from] serde_json::Error),
#[error("Config error: {0}")]
#[error("Configuration error: {0}")]
Config(#[from] FromConfigError),
#[error("Serialization error: {0}")]
Serialization(#[from] SerializationError),
#[error("Merkle tree error: {0}")]
MerkleTree(#[from] ZerokitMerkleTreeError),
#[error("Hash error: {0}")]
Hash(#[from] HashError),
#[error("ZKey error: {0}")]
ZKey(#[from] ZKeyReadError),
#[error("Conversion error: {0}")]
Conversion(#[from] ConversionError),
#[error("Protocol error: {0}")]
Protocol(#[from] ProtocolError),
#[error("Proof error: {0}")]
Proof(#[from] ProofError),
#[error("Unable to extract secret")]
RecoverSecret(#[from] ComputeIdSecretError),
#[error("Verification error: {0}")]
Verify(#[from] VerifyError),
}

View File

@@ -1,615 +0,0 @@
// This crate implements the public Foreign Function Interface (FFI) for the RLN module
use std::slice;
use crate::public::{
extended_key_gen as public_extended_key_gen, hash as public_hash, key_gen as public_key_gen,
poseidon_hash as public_poseidon_hash,
seeded_extended_key_gen as public_seeded_extended_key_gen,
seeded_key_gen as public_seeded_key_gen, RLN,
};
// Macro to call methods with arbitrary amount of arguments,
// First argument to the macro is context,
// second is the actual method on `RLN`
// rest are all other arguments to the method
#[cfg(not(feature = "stateless"))]
macro_rules! call {
($instance:expr, $method:ident $(, $arg:expr)*) => {
{
let new_instance: &mut RLN = $instance.process();
match new_instance.$method($($arg.process()),*) {
Ok(()) => {
true
}
Err(err) => {
eprintln!("execution error: {err}");
false
}
}
}
}
}
// Macro to call methods with arbitrary amount of arguments,
// which have the last argument is output buffer pointer
// First argument to the macro is context,
// second is the actual method on `RLN`
// third is the aforementioned output buffer argument
// rest are all other arguments to the method
macro_rules! call_with_output_arg {
// this variant is needed for the case when
// there are zero other arguments
($instance:expr, $method:ident, $output_arg:expr) => {
{
let mut output_data: Vec<u8> = Vec::new();
let new_instance = $instance.process();
match new_instance.$method(&mut output_data) {
Ok(()) => {
unsafe { *$output_arg = Buffer::from(&output_data[..]) };
std::mem::forget(output_data);
true
}
Err(err) => {
std::mem::forget(output_data);
eprintln!("execution error: {err}");
false
}
}
}
};
($instance:expr, $method:ident, $output_arg:expr, $( $arg:expr ),* ) => {
{
let mut output_data: Vec<u8> = Vec::new();
let new_instance = $instance.process();
match new_instance.$method($($arg.process()),*, &mut output_data) {
Ok(()) => {
unsafe { *$output_arg = Buffer::from(&output_data[..]) };
std::mem::forget(output_data);
true
}
Err(err) => {
std::mem::forget(output_data);
eprintln!("execution error: {err}");
false
}
}
}
};
}
// Macro to call methods with arbitrary amount of arguments,
// which are not implemented in a ctx RLN object
// First argument is the method to call
// Second argument is the output buffer argument
// The remaining arguments are all other inputs to the method
macro_rules! no_ctx_call_with_output_arg {
($method:ident, $output_arg:expr, $input_arg:expr, $endianness_arg:expr) => {{
let mut output_data: Vec<u8> = Vec::new();
match $method(
$input_arg.process(),
&mut output_data,
$endianness_arg.process(),
) {
Ok(()) => {
unsafe { *$output_arg = Buffer::from(&output_data[..]) };
std::mem::forget(output_data);
true
}
Err(err) => {
std::mem::forget(output_data);
eprintln!("execution error: {err}");
false
}
}
}};
}
// Macro to call methods with arbitrary amount of arguments,
// which are not implemented in a ctx RLN object
// First argument is the method to call
// Second argument is the output buffer argument
// The remaining arguments are all other inputs to the method
macro_rules! no_ctx_call_with_output_arg_and_endianness {
($method:ident, $output_arg:expr, $endianness_arg:expr) => {{
let mut output_data: Vec<u8> = Vec::new();
match $method(&mut output_data, $endianness_arg.process()) {
Ok(()) => {
unsafe { *$output_arg = Buffer::from(&output_data[..]) };
std::mem::forget(output_data);
true
}
Err(err) => {
std::mem::forget(output_data);
eprintln!("execution error: {err}");
false
}
}
}};
}
// Macro to call methods with arbitrary amount of arguments,
// which have the last argument as bool
// First argument to the macro is context,
// second is the actual method on `RLN`
// third is the aforementioned bool argument
// rest are all other arguments to the method
macro_rules! call_with_bool_arg {
($instance:expr, $method:ident, $bool_arg:expr, $( $arg:expr ),* ) => {
{
let new_instance = $instance.process();
if match new_instance.$method($($arg.process()),*,) {
Ok(result) => result,
Err(err) => {
eprintln!("execution error: {err}");
return false
},
} {
unsafe { *$bool_arg = true };
} else {
unsafe { *$bool_arg = false };
};
true
}
}
}
trait ProcessArg {
type ReturnType;
fn process(self) -> Self::ReturnType;
}
impl ProcessArg for usize {
type ReturnType = usize;
fn process(self) -> Self::ReturnType {
self
}
}
impl ProcessArg for *const Buffer {
type ReturnType = &'static [u8];
fn process(self) -> Self::ReturnType {
<&[u8]>::from(unsafe { &*self })
}
}
impl ProcessArg for *const RLN {
type ReturnType = &'static RLN;
fn process(self) -> Self::ReturnType {
unsafe { &*self }
}
}
impl ProcessArg for *mut RLN {
type ReturnType = &'static mut RLN;
fn process(self) -> Self::ReturnType {
unsafe { &mut *self }
}
}
impl ProcessArg for bool {
type ReturnType = bool;
fn process(self) -> Self::ReturnType {
self
}
}
///// Buffer struct is taken from
///// <https://github.com/celo-org/celo-threshold-bls-rs/blob/master/crates/threshold-bls-ffi/src/ffi.rs>
/////
///// Also heavily inspired by <https://github.com/kilic/rln/blob/master/src/ffi.rs>
#[repr(C)]
#[derive(Clone, Debug, PartialEq)]
pub struct Buffer {
pub ptr: *const u8,
pub len: usize,
}
impl From<&[u8]> for Buffer {
fn from(src: &[u8]) -> Self {
Self {
ptr: src.as_ptr(),
len: src.len(),
}
}
}
impl<'a> From<&Buffer> for &'a [u8] {
fn from(src: &Buffer) -> &'a [u8] {
unsafe { slice::from_raw_parts(src.ptr, src.len) }
}
}
// TODO: check if there are security implications by using this clippy
// #[allow(clippy::not_unsafe_ptr_arg_deref)]
////////////////////////////////////////////////////////
// RLN APIs
////////////////////////////////////////////////////////
#[allow(clippy::not_unsafe_ptr_arg_deref)]
#[cfg(not(feature = "stateless"))]
#[no_mangle]
pub extern "C" fn new(tree_depth: usize, input_buffer: *const Buffer, ctx: *mut *mut RLN) -> bool {
match RLN::new(tree_depth, input_buffer.process()) {
Ok(rln) => {
unsafe { *ctx = Box::into_raw(Box::new(rln)) };
true
}
Err(err) => {
eprintln!("could not instantiate rln: {err}");
false
}
}
}
#[allow(clippy::not_unsafe_ptr_arg_deref)]
#[cfg(feature = "stateless")]
#[no_mangle]
pub extern "C" fn new(ctx: *mut *mut RLN) -> bool {
match RLN::new() {
Ok(rln) => {
unsafe { *ctx = Box::into_raw(Box::new(rln)) };
true
}
Err(err) => {
eprintln!("could not instantiate rln: {err}");
false
}
}
}
#[allow(clippy::not_unsafe_ptr_arg_deref)]
#[cfg(not(feature = "stateless"))]
#[no_mangle]
pub extern "C" fn new_with_params(
tree_depth: usize,
zkey_buffer: *const Buffer,
graph_data: *const Buffer,
tree_config: *const Buffer,
ctx: *mut *mut RLN,
) -> bool {
match RLN::new_with_params(
tree_depth,
zkey_buffer.process().to_vec(),
graph_data.process().to_vec(),
tree_config.process(),
) {
Ok(rln) => {
unsafe { *ctx = Box::into_raw(Box::new(rln)) };
true
}
Err(err) => {
eprintln!("could not instantiate rln: {err}");
false
}
}
}
#[allow(clippy::not_unsafe_ptr_arg_deref)]
#[cfg(feature = "stateless")]
#[no_mangle]
pub extern "C" fn new_with_params(
zkey_buffer: *const Buffer,
graph_buffer: *const Buffer,
ctx: *mut *mut RLN,
) -> bool {
match RLN::new_with_params(
zkey_buffer.process().to_vec(),
graph_buffer.process().to_vec(),
) {
Ok(rln) => {
unsafe { *ctx = Box::into_raw(Box::new(rln)) };
true
}
Err(err) => {
eprintln!("could not instantiate rln: {err}");
false
}
}
}
////////////////////////////////////////////////////////
// Merkle tree APIs
////////////////////////////////////////////////////////
#[allow(clippy::not_unsafe_ptr_arg_deref)]
#[no_mangle]
#[cfg(not(feature = "stateless"))]
pub extern "C" fn set_tree(ctx: *mut RLN, tree_depth: usize) -> bool {
call!(ctx, set_tree, tree_depth)
}
#[allow(clippy::not_unsafe_ptr_arg_deref)]
#[no_mangle]
#[cfg(not(feature = "stateless"))]
pub extern "C" fn delete_leaf(ctx: *mut RLN, index: usize) -> bool {
call!(ctx, delete_leaf, index)
}
#[allow(clippy::not_unsafe_ptr_arg_deref)]
#[no_mangle]
#[cfg(not(feature = "stateless"))]
pub extern "C" fn set_leaf(ctx: *mut RLN, index: usize, input_buffer: *const Buffer) -> bool {
call!(ctx, set_leaf, index, input_buffer)
}
#[allow(clippy::not_unsafe_ptr_arg_deref)]
#[no_mangle]
#[cfg(not(feature = "stateless"))]
pub extern "C" fn get_leaf(ctx: *mut RLN, index: usize, output_buffer: *mut Buffer) -> bool {
call_with_output_arg!(ctx, get_leaf, output_buffer, index)
}
#[allow(clippy::not_unsafe_ptr_arg_deref)]
#[no_mangle]
#[cfg(not(feature = "stateless"))]
pub extern "C" fn leaves_set(ctx: *mut RLN) -> usize {
ctx.process().leaves_set()
}
#[allow(clippy::not_unsafe_ptr_arg_deref)]
#[no_mangle]
#[cfg(not(feature = "stateless"))]
pub extern "C" fn set_next_leaf(ctx: *mut RLN, input_buffer: *const Buffer) -> bool {
call!(ctx, set_next_leaf, input_buffer)
}
#[allow(clippy::not_unsafe_ptr_arg_deref)]
#[no_mangle]
#[cfg(not(feature = "stateless"))]
pub extern "C" fn set_leaves_from(
ctx: *mut RLN,
index: usize,
input_buffer: *const Buffer,
) -> bool {
call!(ctx, set_leaves_from, index, input_buffer)
}
#[allow(clippy::not_unsafe_ptr_arg_deref)]
#[no_mangle]
#[cfg(not(feature = "stateless"))]
pub extern "C" fn init_tree_with_leaves(ctx: *mut RLN, input_buffer: *const Buffer) -> bool {
call!(ctx, init_tree_with_leaves, input_buffer)
}
#[allow(clippy::not_unsafe_ptr_arg_deref)]
#[no_mangle]
#[cfg(not(feature = "stateless"))]
pub extern "C" fn atomic_operation(
ctx: *mut RLN,
index: usize,
leaves_buffer: *const Buffer,
indices_buffer: *const Buffer,
) -> bool {
call!(ctx, atomic_operation, index, leaves_buffer, indices_buffer)
}
#[allow(clippy::not_unsafe_ptr_arg_deref)]
#[no_mangle]
#[cfg(not(feature = "stateless"))]
pub extern "C" fn seq_atomic_operation(
ctx: *mut RLN,
leaves_buffer: *const Buffer,
indices_buffer: *const Buffer,
) -> bool {
call!(
ctx,
atomic_operation,
ctx.process().leaves_set(),
leaves_buffer,
indices_buffer
)
}
#[allow(clippy::not_unsafe_ptr_arg_deref)]
#[no_mangle]
#[cfg(not(feature = "stateless"))]
pub extern "C" fn get_root(ctx: *const RLN, output_buffer: *mut Buffer) -> bool {
call_with_output_arg!(ctx, get_root, output_buffer)
}
#[allow(clippy::not_unsafe_ptr_arg_deref)]
#[no_mangle]
#[cfg(not(feature = "stateless"))]
pub extern "C" fn get_proof(ctx: *const RLN, index: usize, output_buffer: *mut Buffer) -> bool {
call_with_output_arg!(ctx, get_proof, output_buffer, index)
}
////////////////////////////////////////////////////////
// zkSNARKs APIs
////////////////////////////////////////////////////////
#[allow(clippy::not_unsafe_ptr_arg_deref)]
#[no_mangle]
pub extern "C" fn prove(
ctx: *mut RLN,
input_buffer: *const Buffer,
output_buffer: *mut Buffer,
) -> bool {
call_with_output_arg!(ctx, prove, output_buffer, input_buffer)
}
#[allow(clippy::not_unsafe_ptr_arg_deref)]
#[no_mangle]
pub extern "C" fn verify(
ctx: *const RLN,
proof_buffer: *const Buffer,
proof_is_valid_ptr: *mut bool,
) -> bool {
call_with_bool_arg!(ctx, verify, proof_is_valid_ptr, proof_buffer)
}
#[allow(clippy::not_unsafe_ptr_arg_deref)]
#[no_mangle]
#[cfg(not(feature = "stateless"))]
pub extern "C" fn generate_rln_proof(
ctx: *mut RLN,
input_buffer: *const Buffer,
output_buffer: *mut Buffer,
) -> bool {
call_with_output_arg!(ctx, generate_rln_proof, output_buffer, input_buffer)
}
#[allow(clippy::not_unsafe_ptr_arg_deref)]
#[no_mangle]
pub extern "C" fn generate_rln_proof_with_witness(
ctx: *mut RLN,
input_buffer: *const Buffer,
output_buffer: *mut Buffer,
) -> bool {
call_with_output_arg!(
ctx,
generate_rln_proof_with_witness,
output_buffer,
input_buffer
)
}
#[allow(clippy::not_unsafe_ptr_arg_deref)]
#[no_mangle]
#[cfg(not(feature = "stateless"))]
pub extern "C" fn verify_rln_proof(
ctx: *const RLN,
proof_buffer: *const Buffer,
proof_is_valid_ptr: *mut bool,
) -> bool {
call_with_bool_arg!(ctx, verify_rln_proof, proof_is_valid_ptr, proof_buffer)
}
#[allow(clippy::not_unsafe_ptr_arg_deref)]
#[no_mangle]
pub extern "C" fn verify_with_roots(
ctx: *const RLN,
proof_buffer: *const Buffer,
roots_buffer: *const Buffer,
proof_is_valid_ptr: *mut bool,
) -> bool {
call_with_bool_arg!(
ctx,
verify_with_roots,
proof_is_valid_ptr,
proof_buffer,
roots_buffer
)
}
////////////////////////////////////////////////////////
// Utils
////////////////////////////////////////////////////////
#[allow(clippy::not_unsafe_ptr_arg_deref)]
#[no_mangle]
pub extern "C" fn recover_id_secret(
ctx: *const RLN,
input_proof_buffer_1: *const Buffer,
input_proof_buffer_2: *const Buffer,
output_buffer: *mut Buffer,
) -> bool {
call_with_output_arg!(
ctx,
recover_id_secret,
output_buffer,
input_proof_buffer_1,
input_proof_buffer_2
)
}
////////////////////////////////////////////////////////
// Persistent metadata APIs
////////////////////////////////////////////////////////
#[allow(clippy::not_unsafe_ptr_arg_deref)]
#[no_mangle]
#[cfg(not(feature = "stateless"))]
pub extern "C" fn set_metadata(ctx: *mut RLN, input_buffer: *const Buffer) -> bool {
call!(ctx, set_metadata, input_buffer)
}
#[allow(clippy::not_unsafe_ptr_arg_deref)]
#[no_mangle]
#[cfg(not(feature = "stateless"))]
pub extern "C" fn get_metadata(ctx: *const RLN, output_buffer: *mut Buffer) -> bool {
call_with_output_arg!(ctx, get_metadata, output_buffer)
}
#[allow(clippy::not_unsafe_ptr_arg_deref)]
#[no_mangle]
#[cfg(not(feature = "stateless"))]
pub extern "C" fn flush(ctx: *mut RLN) -> bool {
call!(ctx, flush)
}
////////////////////////////////////////////////////////
// Utils APIs
////////////////////////////////////////////////////////
#[allow(clippy::not_unsafe_ptr_arg_deref)]
#[no_mangle]
pub extern "C" fn hash(
input_buffer: *const Buffer,
output_buffer: *mut Buffer,
is_little_endian: bool,
) -> bool {
no_ctx_call_with_output_arg!(public_hash, output_buffer, input_buffer, is_little_endian)
}
#[allow(clippy::not_unsafe_ptr_arg_deref)]
#[no_mangle]
pub extern "C" fn poseidon_hash(
input_buffer: *const Buffer,
output_buffer: *mut Buffer,
is_little_endian: bool,
) -> bool {
no_ctx_call_with_output_arg!(
public_poseidon_hash,
output_buffer,
input_buffer,
is_little_endian
)
}
#[allow(clippy::not_unsafe_ptr_arg_deref)]
#[no_mangle]
pub extern "C" fn key_gen(output_buffer: *mut Buffer, is_little_endian: bool) -> bool {
no_ctx_call_with_output_arg_and_endianness!(public_key_gen, output_buffer, is_little_endian)
}
#[allow(clippy::not_unsafe_ptr_arg_deref)]
#[no_mangle]
pub extern "C" fn seeded_key_gen(
input_buffer: *const Buffer,
output_buffer: *mut Buffer,
is_little_endian: bool,
) -> bool {
no_ctx_call_with_output_arg!(
public_seeded_key_gen,
output_buffer,
input_buffer,
is_little_endian
)
}
#[allow(clippy::not_unsafe_ptr_arg_deref)]
#[no_mangle]
pub extern "C" fn extended_key_gen(output_buffer: *mut Buffer, is_little_endian: bool) -> bool {
no_ctx_call_with_output_arg_and_endianness!(
public_extended_key_gen,
output_buffer,
is_little_endian
)
}
#[allow(clippy::not_unsafe_ptr_arg_deref)]
#[no_mangle]
pub extern "C" fn seeded_extended_key_gen(
input_buffer: *const Buffer,
output_buffer: *mut Buffer,
is_little_endian: bool,
) -> bool {
no_ctx_call_with_output_arg!(
public_seeded_extended_key_gen,
output_buffer,
input_buffer,
is_little_endian
)
}

566
rln/src/ffi/ffi_rln.rs Normal file
View File

@@ -0,0 +1,566 @@
#![allow(non_camel_case_types)]
use num_bigint::BigInt;
use safer_ffi::{boxed::Box_, derive_ReprC, ffi_export, prelude::repr_c};
#[cfg(not(feature = "stateless"))]
use {safer_ffi::prelude::char_p, std::fs::File, std::io::Read};
use super::ffi_utils::{CBoolResult, CFr, CResult};
use crate::prelude::*;
#[cfg(not(feature = "stateless"))]
const MAX_CONFIG_SIZE: u64 = 1024 * 1024; // 1MB
// FFI_RLN
#[derive_ReprC]
#[repr(opaque)]
pub struct FFI_RLN(pub(crate) RLN);
// RLN initialization APIs
#[cfg(not(feature = "stateless"))]
#[ffi_export]
pub fn ffi_rln_new(
tree_depth: usize,
config_path: char_p::Ref<'_>,
) -> CResult<repr_c::Box<FFI_RLN>, repr_c::String> {
let config_str = File::open(config_path.to_str())
.and_then(|mut file| {
let metadata = file.metadata()?;
if metadata.len() > MAX_CONFIG_SIZE {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidData,
format!(
"Config file too large: {} bytes (max {} bytes)",
metadata.len(),
MAX_CONFIG_SIZE
),
));
}
let mut s = String::new();
file.read_to_string(&mut s)?;
Ok(s)
})
.unwrap_or_default();
match RLN::new(tree_depth, config_str.as_str()) {
Ok(rln) => CResult {
ok: Some(Box_::new(FFI_RLN(rln))),
err: None,
},
Err(err) => CResult {
ok: None,
err: Some(err.to_string().into()),
},
}
}
#[cfg(feature = "stateless")]
#[ffi_export]
pub fn ffi_rln_new() -> CResult<repr_c::Box<FFI_RLN>, repr_c::String> {
match RLN::new() {
Ok(rln) => CResult {
ok: Some(Box_::new(FFI_RLN(rln))),
err: None,
},
Err(err) => CResult {
ok: None,
err: Some(err.to_string().into()),
},
}
}
#[cfg(not(feature = "stateless"))]
#[ffi_export]
pub fn ffi_rln_new_with_params(
tree_depth: usize,
zkey_data: &repr_c::Vec<u8>,
graph_data: &repr_c::Vec<u8>,
config_path: char_p::Ref<'_>,
) -> CResult<repr_c::Box<FFI_RLN>, repr_c::String> {
let config_str = File::open(config_path.to_str())
.and_then(|mut file| {
let metadata = file.metadata()?;
if metadata.len() > MAX_CONFIG_SIZE {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidData,
format!(
"Config file too large: {} bytes (max {} bytes)",
metadata.len(),
MAX_CONFIG_SIZE
),
));
}
let mut s = String::new();
file.read_to_string(&mut s)?;
Ok(s)
})
.unwrap_or_default();
match RLN::new_with_params(
tree_depth,
zkey_data.to_vec(),
graph_data.to_vec(),
config_str.as_str(),
) {
Ok(rln) => CResult {
ok: Some(Box_::new(FFI_RLN(rln))),
err: None,
},
Err(err) => CResult {
ok: None,
err: Some(err.to_string().into()),
},
}
}
#[cfg(feature = "stateless")]
#[ffi_export]
pub fn ffi_rln_new_with_params(
zkey_data: &repr_c::Vec<u8>,
graph_data: &repr_c::Vec<u8>,
) -> CResult<repr_c::Box<FFI_RLN>, repr_c::String> {
match RLN::new_with_params(zkey_data.to_vec(), graph_data.to_vec()) {
Ok(rln) => CResult {
ok: Some(Box_::new(FFI_RLN(rln))),
err: None,
},
Err(err) => CResult {
ok: None,
err: Some(err.to_string().into()),
},
}
}
#[ffi_export]
pub fn ffi_rln_free(rln: repr_c::Box<FFI_RLN>) {
drop(rln);
}
// RLNProof
#[derive_ReprC]
#[repr(opaque)]
pub struct FFI_RLNProof(pub(crate) RLNProof);
#[ffi_export]
pub fn ffi_rln_proof_get_values(
rln_proof: &repr_c::Box<FFI_RLNProof>,
) -> repr_c::Box<FFI_RLNProofValues> {
Box_::new(FFI_RLNProofValues(rln_proof.0.proof_values))
}
#[ffi_export]
pub fn ffi_rln_proof_to_bytes_le(
rln_proof: &repr_c::Box<FFI_RLNProof>,
) -> CResult<repr_c::Vec<u8>, repr_c::String> {
match rln_proof_to_bytes_le(&rln_proof.0) {
Ok(bytes) => CResult {
ok: Some(bytes.into()),
err: None,
},
Err(err) => CResult {
ok: None,
err: Some(err.to_string().into()),
},
}
}
#[ffi_export]
pub fn ffi_rln_proof_to_bytes_be(
rln_proof: &repr_c::Box<FFI_RLNProof>,
) -> CResult<repr_c::Vec<u8>, repr_c::String> {
match rln_proof_to_bytes_be(&rln_proof.0) {
Ok(bytes) => CResult {
ok: Some(bytes.into()),
err: None,
},
Err(err) => CResult {
ok: None,
err: Some(err.to_string().into()),
},
}
}
#[ffi_export]
pub fn ffi_bytes_le_to_rln_proof(
bytes: &repr_c::Vec<u8>,
) -> CResult<repr_c::Box<FFI_RLNProof>, repr_c::String> {
match bytes_le_to_rln_proof(bytes) {
Ok((rln_proof, _)) => CResult {
ok: Some(Box_::new(FFI_RLNProof(rln_proof))),
err: None,
},
Err(err) => CResult {
ok: None,
err: Some(err.to_string().into()),
},
}
}
#[ffi_export]
pub fn ffi_bytes_be_to_rln_proof(
bytes: &repr_c::Vec<u8>,
) -> CResult<repr_c::Box<FFI_RLNProof>, repr_c::String> {
match bytes_be_to_rln_proof(bytes) {
Ok((rln_proof, _)) => CResult {
ok: Some(Box_::new(FFI_RLNProof(rln_proof))),
err: None,
},
Err(err) => CResult {
ok: None,
err: Some(err.to_string().into()),
},
}
}
#[ffi_export]
pub fn ffi_rln_proof_free(rln_proof: repr_c::Box<FFI_RLNProof>) {
drop(rln_proof);
}
// RLNWitnessInput
#[derive_ReprC]
#[repr(opaque)]
pub struct FFI_RLNWitnessInput(pub(crate) RLNWitnessInput);
#[ffi_export]
pub fn ffi_rln_witness_input_new(
identity_secret: &CFr,
user_message_limit: &CFr,
message_id: &CFr,
path_elements: &repr_c::Vec<CFr>,
identity_path_index: &repr_c::Vec<u8>,
x: &CFr,
external_nullifier: &CFr,
) -> CResult<repr_c::Box<FFI_RLNWitnessInput>, repr_c::String> {
let mut identity_secret_fr = identity_secret.0;
let path_elements: Vec<Fr> = path_elements.iter().map(|cfr| cfr.0).collect();
let identity_path_index: Vec<u8> = identity_path_index.iter().copied().collect();
match RLNWitnessInput::new(
IdSecret::from(&mut identity_secret_fr),
user_message_limit.0,
message_id.0,
path_elements,
identity_path_index,
x.0,
external_nullifier.0,
) {
Ok(witness) => CResult {
ok: Some(Box_::new(FFI_RLNWitnessInput(witness))),
err: None,
},
Err(err) => CResult {
ok: None,
err: Some(err.to_string().into()),
},
}
}
#[ffi_export]
pub fn ffi_rln_witness_to_bytes_le(
witness: &repr_c::Box<FFI_RLNWitnessInput>,
) -> CResult<repr_c::Vec<u8>, repr_c::String> {
match rln_witness_to_bytes_le(&witness.0) {
Ok(bytes) => CResult {
ok: Some(bytes.into()),
err: None,
},
Err(err) => CResult {
ok: None,
err: Some(err.to_string().into()),
},
}
}
#[ffi_export]
pub fn ffi_rln_witness_to_bytes_be(
witness: &repr_c::Box<FFI_RLNWitnessInput>,
) -> CResult<repr_c::Vec<u8>, repr_c::String> {
match rln_witness_to_bytes_be(&witness.0) {
Ok(bytes) => CResult {
ok: Some(bytes.into()),
err: None,
},
Err(err) => CResult {
ok: None,
err: Some(err.to_string().into()),
},
}
}
#[ffi_export]
pub fn ffi_bytes_le_to_rln_witness(
bytes: &repr_c::Vec<u8>,
) -> CResult<repr_c::Box<FFI_RLNWitnessInput>, repr_c::String> {
match bytes_le_to_rln_witness(bytes) {
Ok((witness, _)) => CResult {
ok: Some(Box_::new(FFI_RLNWitnessInput(witness))),
err: None,
},
Err(err) => CResult {
ok: None,
err: Some(err.to_string().into()),
},
}
}
#[ffi_export]
pub fn ffi_bytes_be_to_rln_witness(
bytes: &repr_c::Vec<u8>,
) -> CResult<repr_c::Box<FFI_RLNWitnessInput>, repr_c::String> {
match bytes_be_to_rln_witness(bytes) {
Ok((witness, _)) => CResult {
ok: Some(Box_::new(FFI_RLNWitnessInput(witness))),
err: None,
},
Err(err) => CResult {
ok: None,
err: Some(err.to_string().into()),
},
}
}
#[ffi_export]
pub fn ffi_rln_witness_to_bigint_json(
witness: &repr_c::Box<FFI_RLNWitnessInput>,
) -> CResult<repr_c::String, repr_c::String> {
match rln_witness_to_bigint_json(&witness.0) {
Ok(json) => CResult {
ok: Some(json.to_string().into()),
err: None,
},
Err(err) => CResult {
ok: None,
err: Some(err.to_string().into()),
},
}
}
#[ffi_export]
pub fn ffi_rln_witness_input_free(witness: repr_c::Box<FFI_RLNWitnessInput>) {
drop(witness);
}
// RLNProofValues
#[derive_ReprC]
#[repr(opaque)]
pub struct FFI_RLNProofValues(pub(crate) RLNProofValues);
#[ffi_export]
pub fn ffi_rln_proof_values_get_y(pv: &repr_c::Box<FFI_RLNProofValues>) -> repr_c::Box<CFr> {
CFr::from(pv.0.y).into()
}
#[ffi_export]
pub fn ffi_rln_proof_values_get_nullifier(
pv: &repr_c::Box<FFI_RLNProofValues>,
) -> repr_c::Box<CFr> {
CFr::from(pv.0.nullifier).into()
}
#[ffi_export]
pub fn ffi_rln_proof_values_get_root(pv: &repr_c::Box<FFI_RLNProofValues>) -> repr_c::Box<CFr> {
CFr::from(pv.0.root).into()
}
#[ffi_export]
pub fn ffi_rln_proof_values_get_x(pv: &repr_c::Box<FFI_RLNProofValues>) -> repr_c::Box<CFr> {
CFr::from(pv.0.x).into()
}
#[ffi_export]
pub fn ffi_rln_proof_values_get_external_nullifier(
pv: &repr_c::Box<FFI_RLNProofValues>,
) -> repr_c::Box<CFr> {
CFr::from(pv.0.external_nullifier).into()
}
#[ffi_export]
pub fn ffi_rln_proof_values_to_bytes_le(pv: &repr_c::Box<FFI_RLNProofValues>) -> repr_c::Vec<u8> {
rln_proof_values_to_bytes_le(&pv.0).into()
}
#[ffi_export]
pub fn ffi_rln_proof_values_to_bytes_be(pv: &repr_c::Box<FFI_RLNProofValues>) -> repr_c::Vec<u8> {
rln_proof_values_to_bytes_be(&pv.0).into()
}
#[ffi_export]
pub fn ffi_bytes_le_to_rln_proof_values(
bytes: &repr_c::Vec<u8>,
) -> CResult<repr_c::Box<FFI_RLNProofValues>, repr_c::String> {
match bytes_le_to_rln_proof_values(bytes) {
Ok((pv, _)) => CResult {
ok: Some(Box_::new(FFI_RLNProofValues(pv))),
err: None,
},
Err(err) => CResult {
ok: None,
err: Some(format!("{:?}", err).into()),
},
}
}
#[ffi_export]
pub fn ffi_bytes_be_to_rln_proof_values(
bytes: &repr_c::Vec<u8>,
) -> CResult<repr_c::Box<FFI_RLNProofValues>, repr_c::String> {
match bytes_be_to_rln_proof_values(bytes) {
Ok((pv, _)) => CResult {
ok: Some(Box_::new(FFI_RLNProofValues(pv))),
err: None,
},
Err(err) => CResult {
ok: None,
err: Some(format!("{:?}", err).into()),
},
}
}
#[ffi_export]
pub fn ffi_rln_proof_values_free(proof_values: repr_c::Box<FFI_RLNProofValues>) {
drop(proof_values);
}
// Proof generation APIs
#[ffi_export]
pub fn ffi_generate_rln_proof(
rln: &repr_c::Box<FFI_RLN>,
witness: &repr_c::Box<FFI_RLNWitnessInput>,
) -> CResult<repr_c::Box<FFI_RLNProof>, repr_c::String> {
match rln.0.generate_rln_proof(&witness.0) {
Ok((proof, proof_values)) => {
let rln_proof = RLNProof {
proof_values,
proof,
};
CResult {
ok: Some(Box_::new(FFI_RLNProof(rln_proof))),
err: None,
}
}
Err(err) => CResult {
ok: None,
err: Some(err.to_string().into()),
},
}
}
#[ffi_export]
pub fn ffi_generate_rln_proof_with_witness(
rln: &repr_c::Box<FFI_RLN>,
calculated_witness: &repr_c::Vec<repr_c::String>,
witness: &repr_c::Box<FFI_RLNWitnessInput>,
) -> CResult<repr_c::Box<FFI_RLNProof>, repr_c::String> {
let calculated_witness_bigint: Result<Vec<BigInt>, _> = calculated_witness
.iter()
.map(|s| {
let s_str = unsafe { std::str::from_utf8_unchecked(s.as_bytes()) };
s_str.parse::<BigInt>()
})
.collect();
let calculated_witness_bigint = match calculated_witness_bigint {
Ok(w) => w,
Err(err) => {
return CResult {
ok: None,
err: Some(format!("Failed to parse witness: {}", err).into()),
}
}
};
match rln
.0
.generate_rln_proof_with_witness(calculated_witness_bigint, &witness.0)
{
Ok((proof, proof_values)) => {
let rln_proof = RLNProof {
proof_values,
proof,
};
CResult {
ok: Some(Box_::new(FFI_RLNProof(rln_proof))),
err: None,
}
}
Err(err) => CResult {
ok: None,
err: Some(err.to_string().into()),
},
}
}
// Proof verification APIs
#[cfg(not(feature = "stateless"))]
#[ffi_export]
pub fn ffi_verify_rln_proof(
rln: &repr_c::Box<FFI_RLN>,
rln_proof: &repr_c::Box<FFI_RLNProof>,
x: &CFr,
) -> CBoolResult {
match rln
.0
.verify_rln_proof(&rln_proof.0.proof, &rln_proof.0.proof_values, &x.0)
{
Ok(verified) => CBoolResult {
ok: verified,
err: None,
},
Err(err) => CBoolResult {
ok: false,
err: Some(err.to_string().into()),
},
}
}
#[ffi_export]
pub fn ffi_verify_with_roots(
rln: &repr_c::Box<FFI_RLN>,
rln_proof: &repr_c::Box<FFI_RLNProof>,
roots: &repr_c::Vec<CFr>,
x: &CFr,
) -> CBoolResult {
let roots_fr: Vec<Fr> = roots.iter().map(|cfr| cfr.0).collect();
match rln.0.verify_with_roots(
&rln_proof.0.proof,
&rln_proof.0.proof_values,
&x.0,
&roots_fr,
) {
Ok(verified) => CBoolResult {
ok: verified,
err: None,
},
Err(err) => CBoolResult {
ok: false,
err: Some(err.to_string().into()),
},
}
}
// Identity secret recovery API
#[ffi_export]
pub fn ffi_recover_id_secret(
proof_values_1: &repr_c::Box<FFI_RLNProofValues>,
proof_values_2: &repr_c::Box<FFI_RLNProofValues>,
) -> CResult<repr_c::Box<CFr>, repr_c::String> {
match recover_id_secret(&proof_values_1.0, &proof_values_2.0) {
Ok(secret) => CResult {
ok: Some(Box_::new(CFr::from(*secret))),
err: None,
},
Err(err) => CResult {
ok: None,
err: Some(err.to_string().into()),
},
}
}

269
rln/src/ffi/ffi_tree.rs Normal file
View File

@@ -0,0 +1,269 @@
#![allow(non_camel_case_types)]
#![cfg(not(feature = "stateless"))]
use safer_ffi::{boxed::Box_, derive_ReprC, ffi_export, prelude::repr_c};
use super::{
ffi_rln::FFI_RLN,
ffi_utils::{CBoolResult, CFr, CResult},
};
// MerkleProof
#[derive_ReprC]
#[repr(C)]
pub struct FFI_MerkleProof {
pub path_elements: repr_c::Vec<CFr>,
pub path_index: repr_c::Vec<u8>,
}
#[ffi_export]
pub fn ffi_merkle_proof_free(merkle_proof: repr_c::Box<FFI_MerkleProof>) {
drop(merkle_proof);
}
// Merkle tree management APIs
#[ffi_export]
pub fn ffi_set_tree(rln: &mut repr_c::Box<FFI_RLN>, tree_depth: usize) -> CBoolResult {
match rln.0.set_tree(tree_depth) {
Ok(_) => CBoolResult {
ok: true,
err: None,
},
Err(err) => CBoolResult {
ok: false,
err: Some(err.to_string().into()),
},
}
}
// Merkle tree leaf operations
#[ffi_export]
pub fn ffi_delete_leaf(rln: &mut repr_c::Box<FFI_RLN>, index: usize) -> CBoolResult {
match rln.0.delete_leaf(index) {
Ok(_) => CBoolResult {
ok: true,
err: None,
},
Err(err) => CBoolResult {
ok: false,
err: Some(err.to_string().into()),
},
}
}
#[ffi_export]
pub fn ffi_set_leaf(rln: &mut repr_c::Box<FFI_RLN>, index: usize, leaf: &CFr) -> CBoolResult {
match rln.0.set_leaf(index, leaf.0) {
Ok(_) => CBoolResult {
ok: true,
err: None,
},
Err(err) => CBoolResult {
ok: false,
err: Some(err.to_string().into()),
},
}
}
#[ffi_export]
pub fn ffi_get_leaf(
rln: &repr_c::Box<FFI_RLN>,
index: usize,
) -> CResult<repr_c::Box<CFr>, repr_c::String> {
match rln.0.get_leaf(index) {
Ok(leaf) => CResult {
ok: Some(CFr::from(leaf).into()),
err: None,
},
Err(err) => CResult {
ok: None,
err: Some(err.to_string().into()),
},
}
}
#[ffi_export]
pub fn ffi_leaves_set(rln: &repr_c::Box<FFI_RLN>) -> usize {
rln.0.leaves_set()
}
#[ffi_export]
pub fn ffi_set_next_leaf(rln: &mut repr_c::Box<FFI_RLN>, leaf: &CFr) -> CBoolResult {
match rln.0.set_next_leaf(leaf.0) {
Ok(_) => CBoolResult {
ok: true,
err: None,
},
Err(err) => CBoolResult {
ok: false,
err: Some(err.to_string().into()),
},
}
}
#[ffi_export]
pub fn ffi_set_leaves_from(
rln: &mut repr_c::Box<FFI_RLN>,
index: usize,
leaves: &repr_c::Vec<CFr>,
) -> CBoolResult {
let leaves_vec: Vec<_> = leaves.iter().map(|cfr| cfr.0).collect();
match rln.0.set_leaves_from(index, leaves_vec) {
Ok(_) => CBoolResult {
ok: true,
err: None,
},
Err(err) => CBoolResult {
ok: false,
err: Some(err.to_string().into()),
},
}
}
#[ffi_export]
pub fn ffi_init_tree_with_leaves(
rln: &mut repr_c::Box<FFI_RLN>,
leaves: &repr_c::Vec<CFr>,
) -> CBoolResult {
let leaves_vec: Vec<_> = leaves.iter().map(|cfr| cfr.0).collect();
match rln.0.init_tree_with_leaves(leaves_vec) {
Ok(_) => CBoolResult {
ok: true,
err: None,
},
Err(err) => CBoolResult {
ok: false,
err: Some(err.to_string().into()),
},
}
}
// Atomic operations
#[ffi_export]
pub fn ffi_atomic_operation(
rln: &mut repr_c::Box<FFI_RLN>,
index: usize,
leaves: &repr_c::Vec<CFr>,
indices: &repr_c::Vec<usize>,
) -> CBoolResult {
let leaves_vec: Vec<_> = leaves.iter().map(|cfr| cfr.0).collect();
let indices_vec: Vec<_> = indices.iter().copied().collect();
match rln.0.atomic_operation(index, leaves_vec, indices_vec) {
Ok(_) => CBoolResult {
ok: true,
err: None,
},
Err(err) => CBoolResult {
ok: false,
err: Some(err.to_string().into()),
},
}
}
#[ffi_export]
pub fn ffi_seq_atomic_operation(
rln: &mut repr_c::Box<FFI_RLN>,
leaves: &repr_c::Vec<CFr>,
indices: &repr_c::Vec<u8>,
) -> CBoolResult {
let index = rln.0.leaves_set();
let leaves_vec: Vec<_> = leaves.iter().map(|cfr| cfr.0).collect();
let indices_vec: Vec<_> = indices.iter().map(|x| *x as usize).collect();
match rln.0.atomic_operation(index, leaves_vec, indices_vec) {
Ok(_) => CBoolResult {
ok: true,
err: None,
},
Err(err) => CBoolResult {
ok: false,
err: Some(err.to_string().into()),
},
}
}
// Root and proof operations
#[ffi_export]
pub fn ffi_get_root(rln: &repr_c::Box<FFI_RLN>) -> repr_c::Box<CFr> {
CFr::from(rln.0.get_root()).into()
}
#[ffi_export]
pub fn ffi_get_merkle_proof(
rln: &repr_c::Box<FFI_RLN>,
index: usize,
) -> CResult<repr_c::Box<FFI_MerkleProof>, repr_c::String> {
match rln.0.get_merkle_proof(index) {
Ok((path_elements, path_index)) => {
let path_elements: repr_c::Vec<CFr> = path_elements
.iter()
.map(|fr| CFr::from(*fr))
.collect::<Vec<_>>()
.into();
let path_index: repr_c::Vec<u8> = path_index.into();
let merkle_proof = FFI_MerkleProof {
path_elements,
path_index,
};
CResult {
ok: Some(Box_::new(merkle_proof)),
err: None,
}
}
Err(err) => CResult {
ok: None,
err: Some(err.to_string().into()),
},
}
}
// Persistent metadata APIs
#[ffi_export]
pub fn ffi_set_metadata(rln: &mut repr_c::Box<FFI_RLN>, metadata: &repr_c::Vec<u8>) -> CBoolResult {
match rln.0.set_metadata(metadata) {
Ok(_) => CBoolResult {
ok: true,
err: None,
},
Err(err) => CBoolResult {
ok: false,
err: Some(err.to_string().into()),
},
}
}
#[ffi_export]
pub fn ffi_get_metadata(rln: &repr_c::Box<FFI_RLN>) -> CResult<repr_c::Vec<u8>, repr_c::String> {
match rln.0.get_metadata() {
Ok(metadata) => CResult {
ok: Some(metadata.into()),
err: None,
},
Err(err) => CResult {
ok: None,
err: Some(err.to_string().into()),
},
}
}
#[ffi_export]
pub fn ffi_flush(rln: &mut repr_c::Box<FFI_RLN>) -> CBoolResult {
match rln.0.flush() {
Ok(_) => CBoolResult {
ok: true,
err: None,
},
Err(err) => CBoolResult {
ok: false,
err: Some(err.to_string().into()),
},
}
}

407
rln/src/ffi/ffi_utils.rs Normal file
View File

@@ -0,0 +1,407 @@
#![allow(non_camel_case_types)]
use std::ops::Deref;
use safer_ffi::{
boxed::Box_,
derive_ReprC, ffi_export,
prelude::{repr_c, ReprC},
};
use crate::prelude::*;
// CResult
#[derive_ReprC]
#[repr(C)]
pub struct CResult<T: ReprC, Err: ReprC> {
pub ok: Option<T>,
pub err: Option<Err>,
}
// CBoolResult
#[derive_ReprC]
#[repr(C)]
pub struct CBoolResult {
pub ok: bool,
pub err: Option<repr_c::String>,
}
// CFr
#[derive_ReprC]
#[repr(opaque)]
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct CFr(pub(crate) Fr);
impl Deref for CFr {
type Target = Fr;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<Fr> for CFr {
fn from(fr: Fr) -> Self {
Self(fr)
}
}
impl From<CFr> for repr_c::Box<CFr> {
fn from(cfr: CFr) -> Self {
Box_::new(cfr)
}
}
impl From<&CFr> for repr_c::Box<CFr> {
fn from(cfr: &CFr) -> Self {
CFr(cfr.0).into()
}
}
impl PartialEq<Fr> for CFr {
fn eq(&self, other: &Fr) -> bool {
self.0 == *other
}
}
#[ffi_export]
pub fn ffi_cfr_zero() -> repr_c::Box<CFr> {
CFr::from(Fr::from(0)).into()
}
#[ffi_export]
pub fn ffi_cfr_one() -> repr_c::Box<CFr> {
CFr::from(Fr::from(1)).into()
}
#[ffi_export]
pub fn ffi_cfr_to_bytes_le(cfr: &CFr) -> repr_c::Vec<u8> {
fr_to_bytes_le(&cfr.0).into()
}
#[ffi_export]
pub fn ffi_cfr_to_bytes_be(cfr: &CFr) -> repr_c::Vec<u8> {
fr_to_bytes_be(&cfr.0).into()
}
#[ffi_export]
pub fn ffi_bytes_le_to_cfr(bytes: &repr_c::Vec<u8>) -> CResult<repr_c::Box<CFr>, repr_c::String> {
match bytes_le_to_fr(bytes) {
Ok((cfr, _)) => CResult {
ok: Some(CFr(cfr).into()),
err: None,
},
Err(err) => CResult {
ok: None,
err: Some(format!("{:?}", err).into()),
},
}
}
#[ffi_export]
pub fn ffi_bytes_be_to_cfr(bytes: &repr_c::Vec<u8>) -> CResult<repr_c::Box<CFr>, repr_c::String> {
match bytes_be_to_fr(bytes) {
Ok((cfr, _)) => CResult {
ok: Some(CFr(cfr).into()),
err: None,
},
Err(err) => CResult {
ok: None,
err: Some(format!("{:?}", err).into()),
},
}
}
#[ffi_export]
pub fn ffi_uint_to_cfr(value: u32) -> repr_c::Box<CFr> {
CFr::from(Fr::from(value)).into()
}
#[ffi_export]
pub fn ffi_cfr_debug(cfr: Option<&CFr>) -> repr_c::String {
match cfr {
Some(cfr) => format!("{:?}", cfr.0).into(),
None => "None".into(),
}
}
#[ffi_export]
pub fn ffi_cfr_free(cfr: repr_c::Box<CFr>) {
drop(cfr);
}
// Vec<CFr>
#[ffi_export]
pub fn ffi_vec_cfr_new(capacity: usize) -> repr_c::Vec<CFr> {
Vec::with_capacity(capacity).into()
}
#[ffi_export]
pub fn ffi_vec_cfr_from_cfr(cfr: &CFr) -> repr_c::Vec<CFr> {
vec![*cfr].into()
}
#[ffi_export]
pub fn ffi_vec_cfr_push(v: &mut safer_ffi::Vec<CFr>, cfr: &CFr) {
let mut new: Vec<CFr> = std::mem::replace(v, Vec::new().into()).into();
if new.len() == new.capacity() {
new.reserve_exact(1);
}
new.push(*cfr);
*v = new.into();
}
#[ffi_export]
pub fn ffi_vec_cfr_len(v: &repr_c::Vec<CFr>) -> usize {
v.len()
}
#[ffi_export]
pub fn ffi_vec_cfr_get(v: &repr_c::Vec<CFr>, i: usize) -> Option<&CFr> {
v.get(i)
}
#[ffi_export]
pub fn ffi_vec_cfr_to_bytes_le(vec: &repr_c::Vec<CFr>) -> repr_c::Vec<u8> {
let vec_fr: Vec<Fr> = vec.iter().map(|cfr| cfr.0).collect();
vec_fr_to_bytes_le(&vec_fr).into()
}
#[ffi_export]
pub fn ffi_vec_cfr_to_bytes_be(vec: &repr_c::Vec<CFr>) -> repr_c::Vec<u8> {
let vec_fr: Vec<Fr> = vec.iter().map(|cfr| cfr.0).collect();
vec_fr_to_bytes_be(&vec_fr).into()
}
#[ffi_export]
pub fn ffi_bytes_le_to_vec_cfr(
bytes: &repr_c::Vec<u8>,
) -> CResult<repr_c::Vec<CFr>, repr_c::String> {
match bytes_le_to_vec_fr(bytes) {
Ok((vec_fr, _)) => {
let vec_cfr: Vec<CFr> = vec_fr.into_iter().map(CFr).collect();
CResult {
ok: Some(vec_cfr.into()),
err: None,
}
}
Err(err) => CResult {
ok: None,
err: Some(err.to_string().into()),
},
}
}
#[ffi_export]
pub fn ffi_bytes_be_to_vec_cfr(
bytes: &repr_c::Vec<u8>,
) -> CResult<repr_c::Vec<CFr>, repr_c::String> {
match bytes_be_to_vec_fr(bytes) {
Ok((vec_fr, _)) => {
let vec_cfr: Vec<CFr> = vec_fr.into_iter().map(CFr).collect();
CResult {
ok: Some(vec_cfr.into()),
err: None,
}
}
Err(err) => CResult {
ok: None,
err: Some(err.to_string().into()),
},
}
}
#[ffi_export]
pub fn ffi_vec_cfr_debug(v: Option<&repr_c::Vec<CFr>>) -> repr_c::String {
match v {
Some(v) => {
let vec_fr: Vec<Fr> = v.iter().map(|cfr| cfr.0).collect();
format!("{:?}", vec_fr).into()
}
None => "None".into(),
}
}
#[ffi_export]
pub fn ffi_vec_cfr_free(v: repr_c::Vec<CFr>) {
drop(v);
}
// Vec<u8>
#[ffi_export]
pub fn ffi_vec_u8_to_bytes_le(vec: &repr_c::Vec<u8>) -> repr_c::Vec<u8> {
vec_u8_to_bytes_le(vec).into()
}
#[ffi_export]
pub fn ffi_vec_u8_to_bytes_be(vec: &repr_c::Vec<u8>) -> repr_c::Vec<u8> {
vec_u8_to_bytes_be(vec).into()
}
#[ffi_export]
pub fn ffi_bytes_le_to_vec_u8(bytes: &repr_c::Vec<u8>) -> CResult<repr_c::Vec<u8>, repr_c::String> {
match bytes_le_to_vec_u8(bytes) {
Ok((vec, _)) => CResult {
ok: Some(vec.into()),
err: None,
},
Err(err) => CResult {
ok: None,
err: Some(err.to_string().into()),
},
}
}
#[ffi_export]
pub fn ffi_bytes_be_to_vec_u8(bytes: &repr_c::Vec<u8>) -> CResult<repr_c::Vec<u8>, repr_c::String> {
match bytes_be_to_vec_u8(bytes) {
Ok((vec, _)) => CResult {
ok: Some(vec.into()),
err: None,
},
Err(err) => CResult {
ok: None,
err: Some(err.to_string().into()),
},
}
}
#[ffi_export]
pub fn ffi_vec_u8_debug(v: Option<&repr_c::Vec<u8>>) -> repr_c::String {
match v {
Some(v) => format!("{:x?}", v.deref()).into(),
None => "None".into(),
}
}
#[ffi_export]
pub fn ffi_vec_u8_free(v: repr_c::Vec<u8>) {
drop(v);
}
// Utility APIs
#[ffi_export]
pub fn ffi_hash_to_field_le(input: &repr_c::Vec<u8>) -> CResult<repr_c::Box<CFr>, repr_c::String> {
match hash_to_field_le(input) {
Ok(hash_result) => CResult {
ok: Some(CFr::from(hash_result).into()),
err: None,
},
Err(err) => CResult {
ok: None,
err: Some(format!("{:?}", err).into()),
},
}
}
#[ffi_export]
pub fn ffi_hash_to_field_be(input: &repr_c::Vec<u8>) -> CResult<repr_c::Box<CFr>, repr_c::String> {
match hash_to_field_be(input) {
Ok(hash_result) => CResult {
ok: Some(CFr::from(hash_result).into()),
err: None,
},
Err(err) => CResult {
ok: None,
err: Some(format!("{:?}", err).into()),
},
}
}
#[ffi_export]
pub fn ffi_poseidon_hash_pair(a: &CFr, b: &CFr) -> CResult<repr_c::Box<CFr>, repr_c::String> {
match poseidon_hash(&[a.0, b.0]) {
Ok(hash_result) => CResult {
ok: Some(CFr::from(hash_result).into()),
err: None,
},
Err(err) => CResult {
ok: None,
err: Some(format!("{:?}", err).into()),
},
}
}
#[ffi_export]
pub fn ffi_key_gen() -> CResult<repr_c::Vec<CFr>, repr_c::String> {
match keygen() {
Ok((identity_secret, id_commitment)) => CResult {
ok: Some(vec![CFr(*identity_secret), CFr(id_commitment)].into()),
err: None,
},
Err(err) => CResult {
ok: None,
err: Some(format!("{:?}", err).into()),
},
}
}
#[ffi_export]
pub fn ffi_seeded_key_gen(seed: &repr_c::Vec<u8>) -> CResult<repr_c::Vec<CFr>, repr_c::String> {
match seeded_keygen(seed) {
Ok((identity_secret, id_commitment)) => CResult {
ok: Some(vec![CFr(identity_secret), CFr(id_commitment)].into()),
err: None,
},
Err(err) => CResult {
ok: None,
err: Some(format!("{:?}", err).into()),
},
}
}
#[ffi_export]
pub fn ffi_extended_key_gen() -> CResult<repr_c::Vec<CFr>, repr_c::String> {
match extended_keygen() {
Ok((identity_trapdoor, identity_nullifier, identity_secret, id_commitment)) => CResult {
ok: Some(
vec![
CFr(identity_trapdoor),
CFr(identity_nullifier),
CFr(identity_secret),
CFr(id_commitment),
]
.into(),
),
err: None,
},
Err(err) => CResult {
ok: None,
err: Some(format!("{:?}", err).into()),
},
}
}
#[ffi_export]
pub fn ffi_seeded_extended_key_gen(
seed: &repr_c::Vec<u8>,
) -> CResult<repr_c::Vec<CFr>, repr_c::String> {
match extended_seeded_keygen(seed) {
Ok((identity_trapdoor, identity_nullifier, identity_secret, id_commitment)) => CResult {
ok: Some(
vec![
CFr(identity_trapdoor),
CFr(identity_nullifier),
CFr(identity_secret),
CFr(id_commitment),
]
.into(),
),
err: None,
},
Err(err) => CResult {
ok: None,
err: Some(format!("{:?}", err).into()),
},
}
}
#[ffi_export]
pub fn ffi_c_string_free(s: repr_c::String) {
drop(s);
}

10
rln/src/ffi/mod.rs Normal file
View File

@@ -0,0 +1,10 @@
#![cfg(not(target_arch = "wasm32"))]
pub mod ffi_rln;
pub mod ffi_tree;
pub mod ffi_utils;
#[cfg(feature = "headers")]
pub fn generate_headers() -> std::io::Result<()> {
safer_ffi::headers::builder().to_file("rln.h")?.generate()
}

View File

@@ -1,16 +1,19 @@
/// This crate instantiates the Poseidon hash algorithm.
use crate::{
circuit::Fr,
utils::{bytes_be_to_fr, bytes_le_to_fr},
};
// This crate instantiates the Poseidon hash algorithm.
use once_cell::sync::Lazy;
use tiny_keccak::{Hasher, Keccak};
use utils::poseidon::Poseidon;
use zerokit_utils::{error::HashError, poseidon::Poseidon};
use crate::{
circuit::Fr,
error::UtilsError,
utils::{bytes_be_to_fr, bytes_le_to_fr},
};
/// These indexed constants hardcode the supported round parameters tuples (t, RF, RN, SKIP_MATRICES) for the Bn254 scalar field.
/// SKIP_MATRICES is the index of the randomly generated secure MDS matrix.
/// TODO: generate these parameters
pub const ROUND_PARAMS: [(usize, usize, usize, usize); 8] = [
const ROUND_PARAMS: [(usize, usize, usize, usize); 8] = [
(2, 8, 56, 0),
(3, 8, 57, 0),
(4, 8, 56, 0),
@@ -24,10 +27,9 @@ pub const ROUND_PARAMS: [(usize, usize, usize, usize); 8] = [
/// Poseidon Hash wrapper over above implementation.
static POSEIDON: Lazy<Poseidon<Fr>> = Lazy::new(|| Poseidon::<Fr>::from(&ROUND_PARAMS));
pub fn poseidon_hash(input: &[Fr]) -> Fr {
POSEIDON
.hash(input)
.expect("hash with fixed input size can't fail")
pub fn poseidon_hash(input: &[Fr]) -> Result<Fr, HashError> {
let hash = POSEIDON.hash(input)?;
Ok(hash)
}
/// The zerokit RLN Merkle tree Hasher.
@@ -35,20 +37,21 @@ pub fn poseidon_hash(input: &[Fr]) -> Fr {
pub struct PoseidonHash;
/// The default Hasher trait used by Merkle tree implementation in utils.
impl utils::merkle_tree::Hasher for PoseidonHash {
impl zerokit_utils::merkle_tree::Hasher for PoseidonHash {
type Fr = Fr;
type Error = HashError;
fn default_leaf() -> Self::Fr {
Self::Fr::from(0)
}
fn hash(inputs: &[Self::Fr]) -> Self::Fr {
fn hash(inputs: &[Self::Fr]) -> Result<Self::Fr, Self::Error> {
poseidon_hash(inputs)
}
}
/// Hashes arbitrary signal to the underlying prime field.
pub fn hash_to_field_le(signal: &[u8]) -> Fr {
pub fn hash_to_field_le(signal: &[u8]) -> Result<Fr, UtilsError> {
// We hash the input signal using Keccak256
let mut hash = [0; 32];
let mut hasher = Keccak::v256();
@@ -56,12 +59,13 @@ pub fn hash_to_field_le(signal: &[u8]) -> Fr {
hasher.finalize(&mut hash);
// We export the hash as a field element
let (el, _) = bytes_le_to_fr(hash.as_ref());
el
let (el, _) = bytes_le_to_fr(hash.as_ref())?;
Ok(el)
}
/// Hashes arbitrary signal to the underlying prime field.
pub fn hash_to_field_be(signal: &[u8]) -> Fr {
pub fn hash_to_field_be(signal: &[u8]) -> Result<Fr, UtilsError> {
// We hash the input signal using Keccak256
let mut hash = [0; 32];
let mut hasher = Keccak::v256();
@@ -72,6 +76,7 @@ pub fn hash_to_field_be(signal: &[u8]) -> Fr {
hash.reverse();
// We export the hash as a field element
let (el, _) = bytes_be_to_fr(hash.as_ref());
el
let (el, _) = bytes_be_to_fr(hash.as_ref())?;
Ok(el)
}

View File

@@ -1,16 +1,12 @@
pub mod circuit;
pub mod error;
#[cfg(not(target_arch = "wasm32"))]
pub mod ffi;
pub mod hashers;
#[cfg(feature = "pmtree-ft")]
pub mod pm_tree_adapter;
#[cfg(not(feature = "stateless"))]
pub mod poseidon_tree;
pub mod prelude;
pub mod protocol;
pub mod public;
#[cfg(test)]
pub mod public_api_tests;
pub mod utils;
// Ensure that only one Merkle tree feature is enabled at a time

View File

@@ -1,16 +1,24 @@
use serde_json::Value;
use std::fmt::Debug;
use std::path::PathBuf;
use std::str::FromStr;
use tempfile::Builder;
#![cfg(feature = "pmtree-ft")]
use crate::circuit::Fr;
use crate::hashers::{poseidon_hash, PoseidonHash};
use crate::utils::{bytes_le_to_fr, fr_to_bytes_le};
use utils::error::{FromConfigError, ZerokitMerkleTreeError};
use utils::pmtree::tree::Key;
use utils::pmtree::{Database, Hasher, PmtreeErrorKind};
use utils::{pmtree, Config, Mode, SledDB, ZerokitMerkleProof, ZerokitMerkleTree};
use std::{fmt::Debug, path::PathBuf, str::FromStr};
use serde_json::Value;
use tempfile::Builder;
use zerokit_utils::{
error::{FromConfigError, ZerokitMerkleTreeError},
merkle_tree::{ZerokitMerkleProof, ZerokitMerkleTree},
pm_tree::{
pmtree,
pmtree::{tree::Key, Database, Hasher, PmtreeErrorKind},
Config, Mode, SledDB,
},
};
use crate::{
circuit::Fr,
hashers::{poseidon_hash, PoseidonHash},
utils::{bytes_le_to_fr, fr_to_bytes_le},
};
const METADATA_KEY: [u8; 8] = *b"metadata";
@@ -38,7 +46,8 @@ impl Hasher for PoseidonHash {
}
fn deserialize(value: pmtree::Value) -> Self::Fr {
let (fr, _) = bytes_le_to_fr(&value);
// TODO: allow to handle error properly in pmtree Hasher trait
let (fr, _) = bytes_le_to_fr(&value).expect("Fr deserialization must be valid");
fr
}
@@ -47,17 +56,17 @@ impl Hasher for PoseidonHash {
}
fn hash(inputs: &[Self::Fr]) -> Self::Fr {
poseidon_hash(inputs)
// TODO: allow to handle error properly in pmtree Hasher trait
poseidon_hash(inputs).expect("Poseidon hash must be valid")
}
}
fn default_tmp_path() -> PathBuf {
Builder::new()
fn default_tmp_path() -> Result<PathBuf, std::io::Error> {
Ok(Builder::new()
.prefix("pmtree-")
.tempfile()
.expect("Failed to create temp file")
.tempfile()?
.into_temp_path()
.to_path_buf()
.to_path_buf())
}
const DEFAULT_TEMPORARY: bool = true;
@@ -75,8 +84,14 @@ pub struct PmtreeConfigBuilder {
use_compression: bool,
}
impl Default for PmtreeConfigBuilder {
fn default() -> Self {
Self::new()
}
}
impl PmtreeConfigBuilder {
fn new() -> Self {
pub fn new() -> Self {
PmtreeConfigBuilder {
path: None,
temporary: DEFAULT_TEMPORARY,
@@ -119,7 +134,7 @@ impl PmtreeConfigBuilder {
pub fn build(self) -> Result<PmtreeConfig, FromConfigError> {
let path = match (self.temporary, self.path) {
(true, None) => default_tmp_path(),
(true, None) => default_tmp_path()?,
(false, None) => return Err(FromConfigError::MissingPath),
(true, Some(path)) if path.exists() => return Err(FromConfigError::PathExists),
(_, Some(path)) => path,
@@ -169,9 +184,10 @@ impl FromStr for PmtreeConfig {
}
}
let default_tmp_path = default_tmp_path()?;
let config = Config::new()
.temporary(temporary.unwrap_or(DEFAULT_TEMPORARY))
.path(path.unwrap_or(default_tmp_path()))
.path(path.unwrap_or(default_tmp_path))
.cache_capacity(cache_capacity.unwrap_or(DEFAULT_CACHE_CAPACITY))
.flush_every_ms(flush_every_ms)
.mode(mode)
@@ -184,9 +200,10 @@ impl Default for PmtreeConfig {
fn default() -> Self {
Self::builder()
.build()
.expect("Default configuration should never fail")
.expect("Default PmtreeConfig must be valid")
}
}
impl Debug for PmtreeConfig {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.0.fmt(f)
@@ -288,11 +305,10 @@ impl ZerokitMerkleTree for PmTree {
} else if n == self.depth() {
self.get(index)
} else {
let node = self
.tree
.get_elem(Key::new(n, index >> (self.depth() - n)))
.unwrap();
Ok(node)
match self.tree.get_elem(Key::new(n, index >> (self.depth() - n))) {
Ok(value) => Ok(value),
Err(_) => Err(ZerokitMerkleTreeError::InvalidSubTreeIndex),
}
}
}
@@ -358,12 +374,12 @@ impl ZerokitMerkleTree for PmTree {
fn verify(
&self,
leaf: &FrOf<Self::Hasher>,
witness: &Self::Proof,
merkle_proof: &Self::Proof,
) -> Result<bool, ZerokitMerkleTreeError> {
if self.tree.verify(leaf, &witness.proof) {
if self.tree.verify(leaf, &merkle_proof.proof) {
Ok(true)
} else {
Err(ZerokitMerkleTreeError::InvalidWitness)
Err(ZerokitMerkleTreeError::InvalidMerkleProof)
}
}
@@ -383,11 +399,8 @@ impl ZerokitMerkleTree for PmTree {
// if empty, try searching the db
let data = self.tree.db.get(METADATA_KEY)?;
if data.is_none() {
// send empty Metadata
return Ok(Vec::new());
}
Ok(data.unwrap())
// Return empty metadata if not found, otherwise return the data
Ok(data.unwrap_or_default())
}
fn close_db_connection(&mut self) -> Result<(), ZerokitMerkleTreeError> {
@@ -403,8 +416,13 @@ type FrOfPmTreeHasher = FrOf<PmTreeHasher>;
impl PmTree {
fn remove_indices(&mut self, indices: &[usize]) -> Result<(), PmtreeErrorKind> {
if indices.is_empty() {
return Err(PmtreeErrorKind::TreeError(
pmtree::TreeErrorKind::InvalidKey,
));
}
let start = indices[0];
let end = indices.last().unwrap() + 1;
let end = indices[indices.len() - 1] + 1;
let new_leaves = (start..end).map(|_| PmTreeHasher::default_leaf());
@@ -422,7 +440,12 @@ impl PmTree {
leaves: Vec<FrOfPmTreeHasher>,
indices: &[usize],
) -> Result<(), PmtreeErrorKind> {
let min_index = *indices.first().unwrap();
if indices.is_empty() {
return Err(PmtreeErrorKind::TreeError(
pmtree::TreeErrorKind::InvalidKey,
));
}
let min_index = indices[0];
let max_index = start + leaves.len();
let mut set_values = vec![PmTreeHasher::default_leaf(); max_index - min_index];
@@ -470,13 +493,17 @@ impl ZerokitMerkleProof for PmTreeProof {
fn get_path_index(&self) -> Vec<Self::Index> {
self.proof.get_path_index()
}
fn compute_root_from(&self, leaf: &FrOf<Self::Hasher>) -> FrOf<Self::Hasher> {
self.proof.compute_root_from(leaf)
fn compute_root_from(
&self,
leaf: &FrOf<Self::Hasher>,
) -> Result<FrOf<Self::Hasher>, ZerokitMerkleTreeError> {
Ok(self.proof.compute_root_from(leaf))
}
}
#[cfg(test)]
mod tests {
mod test {
use super::*;
#[test]
@@ -491,15 +518,15 @@ mod tests {
"use_compression": false
}"#;
let _: PmtreeConfig = json.parse().expect("Failed to parse JSON config");
let _: PmtreeConfig = json.parse().unwrap();
let _ = PmtreeConfig::builder()
.path(default_tmp_path())
.path(default_tmp_path().unwrap())
.temporary(DEFAULT_TEMPORARY)
.cache_capacity(DEFAULT_CACHE_CAPACITY)
.mode(DEFAULT_MODE)
.use_compression(DEFAULT_USE_COMPRESSION)
.build()
.expect("Failed to build config");
.unwrap();
}
}

View File

@@ -10,13 +10,13 @@ use cfg_if::cfg_if;
cfg_if! {
if #[cfg(feature = "fullmerkletree")] {
use utils::{FullMerkleTree, FullMerkleProof};
use zerokit_utils::merkle_tree::{FullMerkleTree, FullMerkleProof};
use crate::hashers::PoseidonHash;
pub type PoseidonTree = FullMerkleTree<PoseidonHash>;
pub type MerkleProof = FullMerkleProof<PoseidonHash>;
} else if #[cfg(feature = "optimalmerkletree")] {
use utils::{OptimalMerkleTree, OptimalMerkleProof};
use zerokit_utils::merkle_tree::{OptimalMerkleTree, OptimalMerkleProof};
use crate::hashers::PoseidonHash;
pub type PoseidonTree = OptimalMerkleTree<PoseidonHash>;

37
rln/src/prelude.rs Normal file
View File

@@ -0,0 +1,37 @@
// This module re-exports the most commonly used types and functions from the RLN library
#[cfg(not(target_arch = "wasm32"))]
pub use crate::circuit::{graph_from_folder, zkey_from_folder};
#[cfg(feature = "pmtree-ft")]
pub use crate::pm_tree_adapter::{FrOf, PmTree, PmTreeProof, PmtreeConfig, PmtreeConfigBuilder};
#[cfg(not(feature = "stateless"))]
pub use crate::poseidon_tree::{MerkleProof, PoseidonTree};
#[cfg(not(feature = "stateless"))]
pub use crate::protocol::compute_tree_root;
#[cfg(not(target_arch = "wasm32"))]
pub use crate::protocol::{generate_zk_proof, verify_zk_proof};
pub use crate::{
circuit::{
zkey_from_raw, Curve, Fq, Fq2, Fr, G1Affine, G1Projective, G2Affine, G2Projective, Proof,
VerifyingKey, Zkey, COMPRESS_PROOF_SIZE, DEFAULT_TREE_DEPTH,
},
error::{ProtocolError, RLNError, UtilsError, VerifyError},
hashers::{hash_to_field_be, hash_to_field_le, poseidon_hash, PoseidonHash},
protocol::{
bytes_be_to_rln_proof, bytes_be_to_rln_proof_values, bytes_be_to_rln_witness,
bytes_le_to_rln_proof, bytes_le_to_rln_proof_values, bytes_le_to_rln_witness,
extended_keygen, extended_seeded_keygen, generate_zk_proof_with_witness, keygen,
proof_values_from_witness, recover_id_secret, rln_proof_to_bytes_be, rln_proof_to_bytes_le,
rln_proof_values_to_bytes_be, rln_proof_values_to_bytes_le, rln_witness_to_bigint_json,
rln_witness_to_bytes_be, rln_witness_to_bytes_le, seeded_keygen, RLNProof, RLNProofValues,
RLNWitnessInput,
},
public::RLN,
utils::{
bytes_be_to_fr, bytes_be_to_vec_fr, bytes_be_to_vec_u8, bytes_be_to_vec_usize,
bytes_le_to_fr, bytes_le_to_vec_fr, bytes_le_to_vec_u8, bytes_le_to_vec_usize,
fr_to_bytes_be, fr_to_bytes_le, normalize_usize_be, normalize_usize_le, str_to_fr,
to_bigint, vec_fr_to_bytes_be, vec_fr_to_bytes_le, vec_u8_to_bytes_be, vec_u8_to_bytes_le,
IdSecret, FR_BYTE_SIZE,
},
};

View File

@@ -1,878 +0,0 @@
// This crate collects all the underlying primitives used to implement RLN
#[cfg(not(feature = "stateless"))]
use {
crate::error::ConversionError,
crate::poseidon_tree::PoseidonTree,
utils::{ZerokitMerkleProof, ZerokitMerkleTree},
};
use crate::circuit::{calculate_rln_witness, qap::CircomReduction, Curve};
use crate::error::{ComputeIdSecretError, ProofError, ProtocolError};
use crate::hashers::{hash_to_field_le, poseidon_hash};
use crate::public::RLN_IDENTIFIER;
use crate::utils::{
bytes_be_to_fr, bytes_le_to_fr, bytes_le_to_vec_fr, bytes_le_to_vec_u8, fr_byte_size,
fr_to_bytes_le, normalize_usize_le, to_bigint, vec_fr_to_bytes_le, vec_u8_to_bytes_le,
FrOrSecret, IdSecret,
};
use ark_bn254::{Fr, FrConfig};
use ark_ff::{AdditiveGroup, Fp, MontBackend};
use ark_groth16::{prepare_verifying_key, Groth16, Proof as ArkProof, ProvingKey, VerifyingKey};
use ark_relations::r1cs::ConstraintMatrices;
use ark_serialize::{CanonicalDeserialize, CanonicalSerialize};
use ark_std::{rand::thread_rng, UniformRand};
use num_bigint::BigInt;
use rand::{Rng, SeedableRng};
use rand_chacha::ChaCha20Rng;
use serde::{Deserialize, Serialize};
#[cfg(test)]
use std::time::Instant;
use tiny_keccak::{Hasher as _, Keccak};
use zeroize::Zeroize;
///////////////////////////////////////////////////////
// RLN Witness data structure and utility functions
///////////////////////////////////////////////////////
#[derive(Debug, PartialEq, Serialize, Deserialize)]
pub struct RLNWitnessInput {
#[serde(serialize_with = "ark_se", deserialize_with = "ark_de")]
identity_secret: IdSecret,
#[serde(serialize_with = "ark_se", deserialize_with = "ark_de")]
user_message_limit: Fr,
#[serde(serialize_with = "ark_se", deserialize_with = "ark_de")]
message_id: Fr,
#[serde(serialize_with = "ark_se", deserialize_with = "ark_de")]
path_elements: Vec<Fr>,
identity_path_index: Vec<u8>,
#[serde(serialize_with = "ark_se", deserialize_with = "ark_de")]
x: Fr,
#[serde(serialize_with = "ark_se", deserialize_with = "ark_de")]
external_nullifier: Fr,
}
#[derive(Debug, PartialEq)]
pub struct RLNProofValues {
// Public outputs:
pub y: Fr,
pub nullifier: Fr,
pub root: Fr,
// Public Inputs:
pub x: Fr,
pub external_nullifier: Fr,
}
pub fn serialize_field_element(element: Fr) -> Vec<u8> {
fr_to_bytes_le(&element)
}
pub fn deserialize_field_element(serialized: Vec<u8>) -> Fr {
let (element, _) = bytes_le_to_fr(&serialized);
element
}
pub fn deserialize_identity_pair_le(serialized: Vec<u8>) -> (Fr, Fr) {
let (identity_secret_hash, read) = bytes_le_to_fr(&serialized);
let (id_commitment, _) = bytes_le_to_fr(&serialized[read..]);
(identity_secret_hash, id_commitment)
}
pub fn deserialize_identity_pair_be(serialized: Vec<u8>) -> (Fr, Fr) {
let (identity_secret_hash, read) = bytes_be_to_fr(&serialized);
let (id_commitment, _) = bytes_be_to_fr(&serialized[read..]);
(identity_secret_hash, id_commitment)
}
pub fn deserialize_identity_tuple_le(serialized: Vec<u8>) -> (Fr, Fr, Fr, Fr) {
let mut all_read = 0;
let (identity_trapdoor, read) = bytes_le_to_fr(&serialized[all_read..]);
all_read += read;
let (identity_nullifier, read) = bytes_le_to_fr(&serialized[all_read..]);
all_read += read;
let (identity_secret_hash, read) = bytes_le_to_fr(&serialized[all_read..]);
all_read += read;
let (identity_commitment, _) = bytes_le_to_fr(&serialized[all_read..]);
(
identity_trapdoor,
identity_nullifier,
identity_secret_hash,
identity_commitment,
)
}
pub fn deserialize_identity_tuple_be(serialized: Vec<u8>) -> (Fr, Fr, Fr, Fr) {
let mut all_read = 0;
let (identity_trapdoor, read) = bytes_be_to_fr(&serialized[all_read..]);
all_read += read;
let (identity_nullifier, read) = bytes_be_to_fr(&serialized[all_read..]);
all_read += read;
let (identity_secret_hash, read) = bytes_be_to_fr(&serialized[all_read..]);
all_read += read;
let (identity_commitment, _) = bytes_be_to_fr(&serialized[all_read..]);
(
identity_trapdoor,
identity_nullifier,
identity_secret_hash,
identity_commitment,
)
}
/// Serializes witness
///
/// # Errors
///
/// Returns an error if `rln_witness.message_id` is not within `rln_witness.user_message_limit`.
/// input data is [ identity_secret<32> | user_message_limit<32> | message_id<32> | path_elements<32> | identity_path_index<8> | x<32> | external_nullifier<32> ]
pub fn serialize_witness(rln_witness: &RLNWitnessInput) -> Result<Vec<u8>, ProtocolError> {
// Check if message_id is within user_message_limit
message_id_range_check(&rln_witness.message_id, &rln_witness.user_message_limit)?;
// Calculate capacity for Vec:
// - 5 fixed field elements: identity_secret, user_message_limit, message_id, x, external_nullifier
// - variable number of path elements
// - identity_path_index (variable size)
let mut serialized: Vec<u8> = Vec::with_capacity(
fr_byte_size() * (5 + rln_witness.path_elements.len())
+ rln_witness.identity_path_index.len(),
);
serialized.extend_from_slice(&rln_witness.identity_secret.to_bytes_le());
serialized.extend_from_slice(&fr_to_bytes_le(&rln_witness.user_message_limit));
serialized.extend_from_slice(&fr_to_bytes_le(&rln_witness.message_id));
serialized.extend_from_slice(&vec_fr_to_bytes_le(&rln_witness.path_elements));
serialized.extend_from_slice(&vec_u8_to_bytes_le(&rln_witness.identity_path_index));
serialized.extend_from_slice(&fr_to_bytes_le(&rln_witness.x));
serialized.extend_from_slice(&fr_to_bytes_le(&rln_witness.external_nullifier));
Ok(serialized)
}
/// Deserializes witness
///
/// # Errors
///
/// Returns an error if `message_id` is not within `user_message_limit`.
pub fn deserialize_witness(serialized: &[u8]) -> Result<(RLNWitnessInput, usize), ProtocolError> {
let mut all_read: usize = 0;
let (identity_secret, read) = IdSecret::from_bytes_le(&serialized[all_read..]);
all_read += read;
let (user_message_limit, read) = bytes_le_to_fr(&serialized[all_read..]);
all_read += read;
let (message_id, read) = bytes_le_to_fr(&serialized[all_read..]);
all_read += read;
message_id_range_check(&message_id, &user_message_limit)?;
let (path_elements, read) = bytes_le_to_vec_fr(&serialized[all_read..])?;
all_read += read;
let (identity_path_index, read) = bytes_le_to_vec_u8(&serialized[all_read..])?;
all_read += read;
let (x, read) = bytes_le_to_fr(&serialized[all_read..]);
all_read += read;
let (external_nullifier, read) = bytes_le_to_fr(&serialized[all_read..]);
all_read += read;
if serialized.len() != all_read {
return Err(ProtocolError::InvalidReadLen(serialized.len(), all_read));
}
Ok((
RLNWitnessInput {
identity_secret,
path_elements,
identity_path_index,
x,
external_nullifier,
user_message_limit,
message_id,
},
all_read,
))
}
// This function deserializes input for kilic's rln generate_proof public API
// https://github.com/kilic/rln/blob/7ac74183f8b69b399e3bc96c1ae8ab61c026dc43/src/public.rs#L148
// input_data is [ identity_secret<32> | id_index<8> | user_message_limit<32> | message_id<32> | external_nullifier<32> | signal_len<8> | signal<var> ]
// return value is a rln witness populated according to this information
#[cfg(not(feature = "stateless"))]
pub fn proof_inputs_to_rln_witness(
tree: &mut PoseidonTree,
serialized: &[u8],
) -> Result<(RLNWitnessInput, usize), ProtocolError> {
let mut all_read: usize = 0;
let (identity_secret, read) = IdSecret::from_bytes_le(&serialized[all_read..]);
all_read += read;
let id_index = usize::try_from(u64::from_le_bytes(
serialized[all_read..all_read + 8]
.try_into()
.map_err(ConversionError::FromSlice)?,
))
.map_err(ConversionError::ToUsize)?;
all_read += 8;
let (user_message_limit, read) = bytes_le_to_fr(&serialized[all_read..]);
all_read += read;
let (message_id, read) = bytes_le_to_fr(&serialized[all_read..]);
all_read += read;
let (external_nullifier, read) = bytes_le_to_fr(&serialized[all_read..]);
all_read += read;
let signal_len = usize::try_from(u64::from_le_bytes(
serialized[all_read..all_read + 8]
.try_into()
.map_err(ConversionError::FromSlice)?,
))
.map_err(ConversionError::ToUsize)?;
all_read += 8;
let signal: Vec<u8> = serialized[all_read..all_read + signal_len].to_vec();
let merkle_proof = tree.proof(id_index).expect("proof should exist");
let path_elements = merkle_proof.get_path_elements();
let identity_path_index = merkle_proof.get_path_index();
let x = hash_to_field_le(&signal);
Ok((
RLNWitnessInput {
identity_secret,
path_elements,
identity_path_index,
user_message_limit,
message_id,
x,
external_nullifier,
},
all_read,
))
}
/// Creates [`RLNWitnessInput`] from it's fields.
///
/// # Errors
///
/// Returns an error if `message_id` is not within `user_message_limit`.
pub fn rln_witness_from_values(
identity_secret: IdSecret,
path_elements: Vec<Fp<MontBackend<FrConfig, 4>, 4>>,
identity_path_index: Vec<u8>,
x: Fr,
external_nullifier: Fr,
user_message_limit: Fr,
message_id: Fr,
) -> Result<RLNWitnessInput, ProtocolError> {
message_id_range_check(&message_id, &user_message_limit)?;
Ok(RLNWitnessInput {
identity_secret,
path_elements,
identity_path_index,
x,
external_nullifier,
user_message_limit,
message_id,
})
}
pub fn random_rln_witness(tree_depth: usize) -> RLNWitnessInput {
let mut rng = thread_rng();
let identity_secret = IdSecret::rand(&mut rng);
let x = hash_to_field_le(&rng.gen::<[u8; 32]>());
let epoch = hash_to_field_le(&rng.gen::<[u8; 32]>());
let rln_identifier = hash_to_field_le(RLN_IDENTIFIER);
let mut path_elements: Vec<Fr> = Vec::new();
let mut identity_path_index: Vec<u8> = Vec::new();
for _ in 0..tree_depth {
path_elements.push(hash_to_field_le(&rng.gen::<[u8; 32]>()));
identity_path_index.push(rng.gen_range(0..2) as u8);
}
let user_message_limit = Fr::from(100);
let message_id = Fr::from(1);
RLNWitnessInput {
identity_secret,
path_elements,
identity_path_index,
x,
external_nullifier: poseidon_hash(&[epoch, rln_identifier]),
user_message_limit,
message_id,
}
}
pub fn proof_values_from_witness(
rln_witness: &RLNWitnessInput,
) -> Result<RLNProofValues, ProtocolError> {
message_id_range_check(&rln_witness.message_id, &rln_witness.user_message_limit)?;
// y share
let a_0 = &rln_witness.identity_secret;
let mut to_hash = [
*(a_0.clone()),
rln_witness.external_nullifier,
rln_witness.message_id,
];
let a_1 = poseidon_hash(&to_hash);
let y = *(a_0.clone()) + rln_witness.x * a_1;
// Nullifier
let nullifier = poseidon_hash(&[a_1]);
to_hash[0].zeroize();
// Merkle tree root computations
let root = compute_tree_root(
&rln_witness.identity_secret,
&rln_witness.user_message_limit,
&rln_witness.path_elements,
&rln_witness.identity_path_index,
);
Ok(RLNProofValues {
y,
nullifier,
root,
x: rln_witness.x,
external_nullifier: rln_witness.external_nullifier,
})
}
/// input_data is [ root<32> | external_nullifier<32> | x<32> | y<32> | nullifier<32> ]
pub fn serialize_proof_values(rln_proof_values: &RLNProofValues) -> Vec<u8> {
// Calculate capacity for Vec:
// 5 field elements: root, external_nullifier, x, y, nullifier
let mut serialized = Vec::with_capacity(fr_byte_size() * 5);
serialized.extend_from_slice(&fr_to_bytes_le(&rln_proof_values.root));
serialized.extend_from_slice(&fr_to_bytes_le(&rln_proof_values.external_nullifier));
serialized.extend_from_slice(&fr_to_bytes_le(&rln_proof_values.x));
serialized.extend_from_slice(&fr_to_bytes_le(&rln_proof_values.y));
serialized.extend_from_slice(&fr_to_bytes_le(&rln_proof_values.nullifier));
serialized
}
// Note: don't forget to skip the 128 bytes ZK proof, if serialized contains it.
// This proc deserialzies only proof _values_, i.e. circuit outputs, not the zk proof.
pub fn deserialize_proof_values(serialized: &[u8]) -> (RLNProofValues, usize) {
let mut all_read: usize = 0;
let (root, read) = bytes_le_to_fr(&serialized[all_read..]);
all_read += read;
let (external_nullifier, read) = bytes_le_to_fr(&serialized[all_read..]);
all_read += read;
let (x, read) = bytes_le_to_fr(&serialized[all_read..]);
all_read += read;
let (y, read) = bytes_le_to_fr(&serialized[all_read..]);
all_read += read;
let (nullifier, read) = bytes_le_to_fr(&serialized[all_read..]);
all_read += read;
(
RLNProofValues {
y,
nullifier,
root,
x,
external_nullifier,
},
all_read,
)
}
// input_data is [ identity_secret<32> | id_index<8> | user_message_limit<32> | message_id<32> | external_nullifier<32> | signal_len<8> | signal<var> ]
pub fn prepare_prove_input(
identity_secret: IdSecret,
id_index: usize,
user_message_limit: Fr,
message_id: Fr,
external_nullifier: Fr,
signal: &[u8],
) -> Vec<u8> {
// Calculate capacity for Vec:
// - 4 field elements: identity_secret, user_message_limit, message_id, external_nullifier
// - 16 bytes for two normalized usize values (id_index<8> + signal_len<8>)
// - variable length signal data
let mut serialized = Vec::with_capacity(fr_byte_size() * 4 + 16 + signal.len()); // length of 4 fr elements + 16 bytes (id_index + len) + signal length
serialized.extend_from_slice(&identity_secret.to_bytes_le());
serialized.extend_from_slice(&normalize_usize_le(id_index));
serialized.extend_from_slice(&fr_to_bytes_le(&user_message_limit));
serialized.extend_from_slice(&fr_to_bytes_le(&message_id));
serialized.extend_from_slice(&fr_to_bytes_le(&external_nullifier));
serialized.extend_from_slice(&normalize_usize_le(signal.len()));
serialized.extend_from_slice(signal);
serialized
}
// input_data is [ proof<128> | root<32> | external_nullifier<32> | x<32> | y<32> | nullifier<32> | signal_len<8> | signal<var> ]
pub fn prepare_verify_input(proof_data: Vec<u8>, signal: &[u8]) -> Vec<u8> {
// Calculate capacity for Vec:
// - proof_data contains the proof and proof values (proof<128> + root<32> + external_nullifier<32> + x<32> + y<32> + nullifier<32>)
// - 8 bytes for normalized signal length value (signal_len<8>)
// - variable length signal data
let mut serialized = Vec::with_capacity(proof_data.len() + 8 + signal.len());
serialized.extend(proof_data);
serialized.extend_from_slice(&normalize_usize_le(signal.len()));
serialized.extend_from_slice(signal);
serialized
}
///////////////////////////////////////////////////////
// Merkle tree utility functions
///////////////////////////////////////////////////////
pub fn compute_tree_root(
identity_secret: &IdSecret,
user_message_limit: &Fr,
path_elements: &[Fr],
identity_path_index: &[u8],
) -> Fr {
let mut to_hash = [*identity_secret.clone()];
let id_commitment = poseidon_hash(&to_hash);
to_hash[0].zeroize();
let mut root = poseidon_hash(&[id_commitment, *user_message_limit]);
for i in 0..identity_path_index.len() {
if identity_path_index[i] == 0 {
root = poseidon_hash(&[root, path_elements[i]]);
} else {
root = poseidon_hash(&[path_elements[i], root]);
}
}
root
}
///////////////////////////////////////////////////////
// Protocol utility functions
///////////////////////////////////////////////////////
// Generates a tuple (identity_secret_hash, id_commitment) where
// identity_secret_hash is random and id_commitment = PoseidonHash(identity_secret_hash)
// RNG is instantiated using thread_rng()
pub fn keygen() -> (IdSecret, Fr) {
let mut rng = thread_rng();
let identity_secret_hash = IdSecret::rand(&mut rng);
let mut to_hash = [*identity_secret_hash.clone()];
let id_commitment = poseidon_hash(&to_hash);
to_hash[0].zeroize();
(identity_secret_hash, id_commitment)
}
// Generates a tuple (identity_trapdoor, identity_nullifier, identity_secret_hash, id_commitment) where
// identity_trapdoor and identity_nullifier are random,
// identity_secret_hash = PoseidonHash(identity_trapdoor, identity_nullifier),
// id_commitment = PoseidonHash(identity_secret_hash),
// RNG is instantiated using thread_rng()
// Generated credentials are compatible with Semaphore credentials
pub fn extended_keygen() -> (Fr, Fr, Fr, Fr) {
let mut rng = thread_rng();
let identity_trapdoor = Fr::rand(&mut rng);
let identity_nullifier = Fr::rand(&mut rng);
let identity_secret_hash = poseidon_hash(&[identity_trapdoor, identity_nullifier]);
let id_commitment = poseidon_hash(&[identity_secret_hash]);
(
identity_trapdoor,
identity_nullifier,
identity_secret_hash,
id_commitment,
)
}
// Generates a tuple (identity_secret_hash, id_commitment) where
// identity_secret_hash is random and id_commitment = PoseidonHash(identity_secret_hash)
// RNG is instantiated using 20 rounds of ChaCha seeded with the hash of the input
pub fn seeded_keygen(signal: &[u8]) -> (Fr, Fr) {
// ChaCha20 requires a seed of exactly 32 bytes.
// We first hash the input seed signal to a 32 bytes array and pass this as seed to ChaCha20
let mut seed = [0; 32];
let mut hasher = Keccak::v256();
hasher.update(signal);
hasher.finalize(&mut seed);
let mut rng = ChaCha20Rng::from_seed(seed);
let identity_secret_hash = Fr::rand(&mut rng);
let id_commitment = poseidon_hash(&[identity_secret_hash]);
(identity_secret_hash, id_commitment)
}
// Generates a tuple (identity_trapdoor, identity_nullifier, identity_secret_hash, id_commitment) where
// identity_trapdoor and identity_nullifier are random,
// identity_secret_hash = PoseidonHash(identity_trapdoor, identity_nullifier),
// id_commitment = PoseidonHash(identity_secret_hash),
// RNG is instantiated using 20 rounds of ChaCha seeded with the hash of the input
// Generated credentials are compatible with Semaphore credentials
pub fn extended_seeded_keygen(signal: &[u8]) -> (Fr, Fr, Fr, Fr) {
// ChaCha20 requires a seed of exactly 32 bytes.
// We first hash the input seed signal to a 32 bytes array and pass this as seed to ChaCha20
let mut seed = [0; 32];
let mut hasher = Keccak::v256();
hasher.update(signal);
hasher.finalize(&mut seed);
let mut rng = ChaCha20Rng::from_seed(seed);
let identity_trapdoor = Fr::rand(&mut rng);
let identity_nullifier = Fr::rand(&mut rng);
let identity_secret_hash = poseidon_hash(&[identity_trapdoor, identity_nullifier]);
let id_commitment = poseidon_hash(&[identity_secret_hash]);
(
identity_trapdoor,
identity_nullifier,
identity_secret_hash,
id_commitment,
)
}
pub fn compute_id_secret(
share1: (Fr, Fr),
share2: (Fr, Fr),
) -> Result<IdSecret, ComputeIdSecretError> {
// Assuming a0 is the identity secret and a1 = poseidonHash([a0, external_nullifier]),
// a (x,y) share satisfies the following relation
// y = a_0 + x * a_1
let (x1, y1) = share1;
let (x2, y2) = share2;
// If the two input shares were computed for the same external_nullifier and identity secret, we can recover the latter
// y1 = a_0 + x1 * a_1
// y2 = a_0 + x2 * a_1
if (x1 - x2) != Fr::ZERO {
let a_1 = (y1 - y2) / (x1 - x2);
let mut a_0 = y1 - x1 * a_1;
// If shares come from the same polynomial, a0 is correctly recovered and a1 = poseidonHash([a0, external_nullifier])
let id_secret = IdSecret::from(&mut a_0);
Ok(id_secret)
} else {
Err(ComputeIdSecretError::DivisionByZero)
}
}
///////////////////////////////////////////////////////
// zkSNARK utility functions
///////////////////////////////////////////////////////
fn calculate_witness_element<E: ark_ec::pairing::Pairing>(
witness: Vec<BigInt>,
) -> Result<Vec<E::ScalarField>, ProtocolError> {
use ark_ff::PrimeField;
let modulus = <E::ScalarField as PrimeField>::MODULUS;
// convert it to field elements
use num_traits::Signed;
let mut witness_vec = vec![];
for w in witness.into_iter() {
let w = if w.sign() == num_bigint::Sign::Minus {
// Need to negate the witness element if negative
modulus.into()
- w.abs()
.to_biguint()
.ok_or(ProtocolError::BigUintConversion(w))?
} else {
w.to_biguint().ok_or(ProtocolError::BigUintConversion(w))?
};
witness_vec.push(E::ScalarField::from(w))
}
Ok(witness_vec)
}
pub fn generate_proof_with_witness(
witness: Vec<BigInt>,
proving_key: &(ProvingKey<Curve>, ConstraintMatrices<Fr>),
) -> Result<ArkProof<Curve>, ProofError> {
// If in debug mode, we measure and later print time take to compute witness
#[cfg(test)]
let now = Instant::now();
let full_assignment = calculate_witness_element::<Curve>(witness)?;
#[cfg(test)]
println!("witness generation took: {:.2?}", now.elapsed());
// Random Values
let mut rng = thread_rng();
let r = Fr::rand(&mut rng);
let s = Fr::rand(&mut rng);
// If in debug mode, we measure and later print time take to compute proof
#[cfg(test)]
let now = Instant::now();
let proof = Groth16::<_, CircomReduction>::create_proof_with_reduction_and_matrices(
&proving_key.0,
r,
s,
&proving_key.1,
proving_key.1.num_instance_variables,
proving_key.1.num_constraints,
full_assignment.as_slice(),
)?;
#[cfg(test)]
println!("proof generation took: {:.2?}", now.elapsed());
Ok(proof)
}
/// Formats inputs for witness calculation
///
/// # Errors
///
/// Returns an error if `rln_witness.message_id` is not within `rln_witness.user_message_limit`.
pub fn inputs_for_witness_calculation(
rln_witness: &RLNWitnessInput,
) -> Result<[(&str, Vec<FrOrSecret>); 7], ProtocolError> {
message_id_range_check(&rln_witness.message_id, &rln_witness.user_message_limit)?;
let mut identity_path_index = Vec::with_capacity(rln_witness.identity_path_index.len());
rln_witness
.identity_path_index
.iter()
.for_each(|v| identity_path_index.push(Fr::from(*v)));
Ok([
(
"identitySecret",
vec![rln_witness.identity_secret.clone().into()],
),
(
"userMessageLimit",
vec![rln_witness.user_message_limit.into()],
),
("messageId", vec![rln_witness.message_id.into()]),
(
"pathElements",
rln_witness
.path_elements
.iter()
.cloned()
.map(Into::into)
.collect(),
),
(
"identityPathIndex",
identity_path_index.into_iter().map(Into::into).collect(),
),
("x", vec![rln_witness.x.into()]),
(
"externalNullifier",
vec![rln_witness.external_nullifier.into()],
),
])
}
/// Generates a RLN proof
///
/// # Errors
///
/// Returns a [`ProofError`] if proving fails.
pub fn generate_proof(
proving_key: &(ProvingKey<Curve>, ConstraintMatrices<Fr>),
rln_witness: &RLNWitnessInput,
graph_data: &[u8],
) -> Result<ArkProof<Curve>, ProofError> {
let inputs = inputs_for_witness_calculation(rln_witness)?
.into_iter()
.map(|(name, values)| (name.to_string(), values));
// If in debug mode, we measure and later print time take to compute witness
#[cfg(test)]
let now = Instant::now();
let full_assignment = calculate_rln_witness(inputs, graph_data);
#[cfg(test)]
println!("witness generation took: {:.2?}", now.elapsed());
// Random Values
let mut rng = thread_rng();
let r = Fr::rand(&mut rng);
let s = Fr::rand(&mut rng);
// If in debug mode, we measure and later print time take to compute proof
#[cfg(test)]
let now = Instant::now();
let proof = Groth16::<_, CircomReduction>::create_proof_with_reduction_and_matrices(
&proving_key.0,
r,
s,
&proving_key.1,
proving_key.1.num_instance_variables,
proving_key.1.num_constraints,
full_assignment.as_slice(),
)?;
#[cfg(test)]
println!("proof generation took: {:.2?}", now.elapsed());
Ok(proof)
}
/// Verifies a given RLN proof
///
/// # Errors
///
/// Returns a [`ProofError`] if verifying fails. Verification failure does not
/// necessarily mean the proof is incorrect.
pub fn verify_proof(
verifying_key: &VerifyingKey<Curve>,
proof: &ArkProof<Curve>,
proof_values: &RLNProofValues,
) -> Result<bool, ProofError> {
// We re-arrange proof-values according to the circuit specification
let inputs = vec![
proof_values.y,
proof_values.root,
proof_values.nullifier,
proof_values.x,
proof_values.external_nullifier,
];
// Check that the proof is valid
let pvk = prepare_verifying_key(verifying_key);
//let pr: ArkProof<Curve> = (*proof).into();
// If in debug mode, we measure and later print time take to verify proof
#[cfg(test)]
let now = Instant::now();
let verified = Groth16::<_, CircomReduction>::verify_proof(&pvk, proof, &inputs)?;
#[cfg(test)]
println!("verify took: {:.2?}", now.elapsed());
Ok(verified)
}
// auxiliary function for serialisation Fr to json using ark serilize
fn ark_se<S, A: CanonicalSerialize>(a: &A, s: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
let mut bytes = vec![];
a.serialize_compressed(&mut bytes)
.map_err(serde::ser::Error::custom)?;
s.serialize_bytes(&bytes)
}
// auxiliary function for deserialisation Fr to json using ark serilize
fn ark_de<'de, D, A: CanonicalDeserialize>(data: D) -> Result<A, D::Error>
where
D: serde::de::Deserializer<'de>,
{
let s: Vec<u8> = serde::de::Deserialize::deserialize(data)?;
let a = A::deserialize_compressed_unchecked(s.as_slice());
a.map_err(serde::de::Error::custom)
}
/// Converts a JSON value into [`RLNWitnessInput`] object.
///
/// # Errors
///
/// Returns an error if `rln_witness.message_id` is not within `rln_witness.user_message_limit`.
pub fn rln_witness_from_json(
input_json: serde_json::Value,
) -> Result<RLNWitnessInput, ProtocolError> {
let rln_witness: RLNWitnessInput = serde_json::from_value(input_json).unwrap();
message_id_range_check(&rln_witness.message_id, &rln_witness.user_message_limit)?;
Ok(rln_witness)
}
/// Converts a [`RLNWitnessInput`] object to the corresponding JSON serialization.
///
/// # Errors
///
/// Returns an error if `message_id` is not within `user_message_limit`.
pub fn rln_witness_to_json(
rln_witness: &RLNWitnessInput,
) -> Result<serde_json::Value, ProtocolError> {
message_id_range_check(&rln_witness.message_id, &rln_witness.user_message_limit)?;
let rln_witness_json = serde_json::to_value(rln_witness)?;
Ok(rln_witness_json)
}
/// Converts a [`RLNWitnessInput`] object to the corresponding JSON serialization.
/// Before serialisation the data should be translated into big int for further calculation in the witness calculator.
///
/// # Errors
///
/// Returns an error if `message_id` is not within `user_message_limit`.
pub fn rln_witness_to_bigint_json(
rln_witness: &RLNWitnessInput,
) -> Result<serde_json::Value, ProtocolError> {
message_id_range_check(&rln_witness.message_id, &rln_witness.user_message_limit)?;
let mut path_elements = Vec::new();
for v in rln_witness.path_elements.iter() {
path_elements.push(to_bigint(v).to_str_radix(10));
}
let mut identity_path_index = Vec::new();
rln_witness
.identity_path_index
.iter()
.for_each(|v| identity_path_index.push(BigInt::from(*v).to_str_radix(10)));
let inputs = serde_json::json!({
"identitySecret": to_bigint(&rln_witness.identity_secret).to_str_radix(10),
"userMessageLimit": to_bigint(&rln_witness.user_message_limit).to_str_radix(10),
"messageId": to_bigint(&rln_witness.message_id).to_str_radix(10),
"pathElements": path_elements,
"identityPathIndex": identity_path_index,
"x": to_bigint(&rln_witness.x).to_str_radix(10),
"externalNullifier": to_bigint(&rln_witness.external_nullifier).to_str_radix(10),
});
Ok(inputs)
}
pub fn message_id_range_check(
message_id: &Fr,
user_message_limit: &Fr,
) -> Result<(), ProtocolError> {
if message_id > user_message_limit {
return Err(ProtocolError::InvalidMessageId(
*message_id,
*user_message_limit,
));
}
Ok(())
}

View File

@@ -0,0 +1,80 @@
use ark_std::{rand::thread_rng, UniformRand};
use rand::SeedableRng;
use rand_chacha::ChaCha20Rng;
use tiny_keccak::{Hasher as _, Keccak};
use zerokit_utils::error::ZerokitMerkleTreeError;
use crate::{circuit::Fr, hashers::poseidon_hash, utils::IdSecret};
/// Generates a random RLN identity using a cryptographically secure RNG.
///
/// Returns `(identity_secret, id_commitment)` where the commitment is `PoseidonHash(identity_secret)`.
pub fn keygen() -> Result<(IdSecret, Fr), ZerokitMerkleTreeError> {
let mut rng = thread_rng();
let identity_secret = IdSecret::rand(&mut rng);
let id_commitment = poseidon_hash(&[*identity_secret.clone()])?;
Ok((identity_secret, id_commitment))
}
/// Generates an extended RLN identity compatible with Semaphore.
///
/// Returns `(identity_trapdoor, identity_nullifier, identity_secret, id_commitment)` where:
/// - `identity_secret = PoseidonHash(identity_trapdoor, identity_nullifier)`
/// - `id_commitment = PoseidonHash(identity_secret)`
pub fn extended_keygen() -> Result<(Fr, Fr, Fr, Fr), ZerokitMerkleTreeError> {
let mut rng = thread_rng();
let identity_trapdoor = Fr::rand(&mut rng);
let identity_nullifier = Fr::rand(&mut rng);
let identity_secret = poseidon_hash(&[identity_trapdoor, identity_nullifier])?;
let id_commitment = poseidon_hash(&[identity_secret])?;
Ok((
identity_trapdoor,
identity_nullifier,
identity_secret,
id_commitment,
))
}
/// Generates a deterministic RLN identity from a seed.
///
/// Uses ChaCha20 RNG seeded with Keccak-256 hash of the input.
/// Returns `(identity_secret, id_commitment)`. Same input always produces the same identity.
pub fn seeded_keygen(signal: &[u8]) -> Result<(Fr, Fr), ZerokitMerkleTreeError> {
// ChaCha20 requires a seed of exactly 32 bytes.
// We first hash the input seed signal to a 32 bytes array and pass this as seed to ChaCha20
let mut seed = [0; 32];
let mut hasher = Keccak::v256();
hasher.update(signal);
hasher.finalize(&mut seed);
let mut rng = ChaCha20Rng::from_seed(seed);
let identity_secret = Fr::rand(&mut rng);
let id_commitment = poseidon_hash(&[identity_secret])?;
Ok((identity_secret, id_commitment))
}
/// Generates a deterministic extended RLN identity from a seed, compatible with Semaphore.
///
/// Uses ChaCha20 RNG seeded with Keccak-256 hash of the input.
/// Returns `(identity_trapdoor, identity_nullifier, identity_secret, id_commitment)`.
/// Same input always produces the same identity.
pub fn extended_seeded_keygen(signal: &[u8]) -> Result<(Fr, Fr, Fr, Fr), ZerokitMerkleTreeError> {
// ChaCha20 requires a seed of exactly 32 bytes.
// We first hash the input seed signal to a 32 bytes array and pass this as seed to ChaCha20
let mut seed = [0; 32];
let mut hasher = Keccak::v256();
hasher.update(signal);
hasher.finalize(&mut seed);
let mut rng = ChaCha20Rng::from_seed(seed);
let identity_trapdoor = Fr::rand(&mut rng);
let identity_nullifier = Fr::rand(&mut rng);
let identity_secret = poseidon_hash(&[identity_trapdoor, identity_nullifier])?;
let id_commitment = poseidon_hash(&[identity_secret])?;
Ok((
identity_trapdoor,
identity_nullifier,
identity_secret,
id_commitment,
))
}

19
rln/src/protocol/mod.rs Normal file
View File

@@ -0,0 +1,19 @@
// This crate collects all the underlying primitives used to implement RLN
mod keygen;
mod proof;
mod slashing;
mod witness;
pub use keygen::{extended_keygen, extended_seeded_keygen, keygen, seeded_keygen};
pub use proof::{
bytes_be_to_rln_proof, bytes_be_to_rln_proof_values, bytes_le_to_rln_proof,
bytes_le_to_rln_proof_values, generate_zk_proof, generate_zk_proof_with_witness,
rln_proof_to_bytes_be, rln_proof_to_bytes_le, rln_proof_values_to_bytes_be,
rln_proof_values_to_bytes_le, verify_zk_proof, RLNProof, RLNProofValues,
};
pub use slashing::recover_id_secret;
pub use witness::{
bytes_be_to_rln_witness, bytes_le_to_rln_witness, compute_tree_root, proof_values_from_witness,
rln_witness_to_bigint_json, rln_witness_to_bytes_be, rln_witness_to_bytes_le, RLNWitnessInput,
};

345
rln/src/protocol/proof.rs Normal file
View File

@@ -0,0 +1,345 @@
use ark_ff::PrimeField;
use ark_groth16::{prepare_verifying_key, Groth16};
use ark_serialize::{CanonicalDeserialize, CanonicalSerialize};
use ark_std::{rand::thread_rng, UniformRand};
use num_bigint::BigInt;
use num_traits::Signed;
use super::witness::{inputs_for_witness_calculation, RLNWitnessInput};
use crate::{
circuit::{
iden3calc::calc_witness, qap::CircomReduction, Curve, Fr, Proof, VerifyingKey, Zkey,
COMPRESS_PROOF_SIZE,
},
error::ProtocolError,
utils::{bytes_be_to_fr, bytes_le_to_fr, fr_to_bytes_be, fr_to_bytes_le, FR_BYTE_SIZE},
};
/// Complete RLN proof.
///
/// Combines the Groth16 proof with its public values.
#[derive(Debug, PartialEq, Clone)]
pub struct RLNProof {
pub proof: Proof,
pub proof_values: RLNProofValues,
}
/// Public values for RLN proof verification.
///
/// Contains the circuit's public inputs and outputs. Used in proof verification
/// and identity secret recovery when rate limit violations are detected.
#[derive(Debug, PartialEq, Clone, Copy)]
pub struct RLNProofValues {
// Public outputs:
pub y: Fr,
pub nullifier: Fr,
pub root: Fr,
// Public Inputs:
pub x: Fr,
pub external_nullifier: Fr,
}
/// Serializes RLN proof values to little-endian bytes.
pub fn rln_proof_values_to_bytes_le(rln_proof_values: &RLNProofValues) -> Vec<u8> {
// Calculate capacity for Vec:
// 5 field elements: root, external_nullifier, x, y, nullifier
let mut bytes = Vec::with_capacity(FR_BYTE_SIZE * 5);
bytes.extend_from_slice(&fr_to_bytes_le(&rln_proof_values.root));
bytes.extend_from_slice(&fr_to_bytes_le(&rln_proof_values.external_nullifier));
bytes.extend_from_slice(&fr_to_bytes_le(&rln_proof_values.x));
bytes.extend_from_slice(&fr_to_bytes_le(&rln_proof_values.y));
bytes.extend_from_slice(&fr_to_bytes_le(&rln_proof_values.nullifier));
bytes
}
/// Serializes RLN proof values to big-endian bytes.
pub fn rln_proof_values_to_bytes_be(rln_proof_values: &RLNProofValues) -> Vec<u8> {
// Calculate capacity for Vec:
// 5 field elements: root, external_nullifier, x, y, nullifier
let mut bytes = Vec::with_capacity(FR_BYTE_SIZE * 5);
bytes.extend_from_slice(&fr_to_bytes_be(&rln_proof_values.root));
bytes.extend_from_slice(&fr_to_bytes_be(&rln_proof_values.external_nullifier));
bytes.extend_from_slice(&fr_to_bytes_be(&rln_proof_values.x));
bytes.extend_from_slice(&fr_to_bytes_be(&rln_proof_values.y));
bytes.extend_from_slice(&fr_to_bytes_be(&rln_proof_values.nullifier));
bytes
}
/// Deserializes RLN proof values from little-endian bytes.
///
/// Format: `[ root<32> | external_nullifier<32> | x<32> | y<32> | nullifier<32> ]`
///
/// Returns the deserialized proof values and the number of bytes read.
pub fn bytes_le_to_rln_proof_values(
bytes: &[u8],
) -> Result<(RLNProofValues, usize), ProtocolError> {
let mut read: usize = 0;
let (root, el_size) = bytes_le_to_fr(&bytes[read..])?;
read += el_size;
let (external_nullifier, el_size) = bytes_le_to_fr(&bytes[read..])?;
read += el_size;
let (x, el_size) = bytes_le_to_fr(&bytes[read..])?;
read += el_size;
let (y, el_size) = bytes_le_to_fr(&bytes[read..])?;
read += el_size;
let (nullifier, el_size) = bytes_le_to_fr(&bytes[read..])?;
read += el_size;
Ok((
RLNProofValues {
y,
nullifier,
root,
x,
external_nullifier,
},
read,
))
}
/// Deserializes RLN proof values from big-endian bytes.
///
/// Format: `[ root<32> | external_nullifier<32> | x<32> | y<32> | nullifier<32> ]`
///
/// Returns the deserialized proof values and the number of bytes read.
pub fn bytes_be_to_rln_proof_values(
bytes: &[u8],
) -> Result<(RLNProofValues, usize), ProtocolError> {
let mut read: usize = 0;
let (root, el_size) = bytes_be_to_fr(&bytes[read..])?;
read += el_size;
let (external_nullifier, el_size) = bytes_be_to_fr(&bytes[read..])?;
read += el_size;
let (x, el_size) = bytes_be_to_fr(&bytes[read..])?;
read += el_size;
let (y, el_size) = bytes_be_to_fr(&bytes[read..])?;
read += el_size;
let (nullifier, el_size) = bytes_be_to_fr(&bytes[read..])?;
read += el_size;
Ok((
RLNProofValues {
y,
nullifier,
root,
x,
external_nullifier,
},
read,
))
}
/// Serializes RLN proof to little-endian bytes.
///
/// Note: The Groth16 proof is always serialized in LE format (arkworks behavior),
/// while proof_values are serialized in LE format.
pub fn rln_proof_to_bytes_le(rln_proof: &RLNProof) -> Result<Vec<u8>, ProtocolError> {
// Calculate capacity for Vec:
// - 128 bytes for compressed Groth16 proof
// - 5 field elements for proof values (root, external_nullifier, x, y, nullifier)
let mut bytes = Vec::with_capacity(COMPRESS_PROOF_SIZE + FR_BYTE_SIZE * 5);
// Serialize proof (always LE format from arkworks)
rln_proof.proof.serialize_compressed(&mut bytes)?;
// Serialize proof values in LE
let proof_values_bytes = rln_proof_values_to_bytes_le(&rln_proof.proof_values);
bytes.extend_from_slice(&proof_values_bytes);
Ok(bytes)
}
/// Serializes RLN proof to big-endian bytes.
///
/// Note: The Groth16 proof is always serialized in LE format (arkworks behavior),
/// while proof_values are serialized in BE format. This creates a mixed-endian format.
pub fn rln_proof_to_bytes_be(rln_proof: &RLNProof) -> Result<Vec<u8>, ProtocolError> {
// Calculate capacity for Vec:
// - 128 bytes for compressed Groth16 proof
// - 5 field elements for proof values (root, external_nullifier, x, y, nullifier)
let mut bytes = Vec::with_capacity(COMPRESS_PROOF_SIZE + FR_BYTE_SIZE * 5);
// Serialize proof (always LE format from arkworks)
rln_proof.proof.serialize_compressed(&mut bytes)?;
// Serialize proof values in BE
let proof_values_bytes = rln_proof_values_to_bytes_be(&rln_proof.proof_values);
bytes.extend_from_slice(&proof_values_bytes);
Ok(bytes)
}
/// Deserializes RLN proof from little-endian bytes.
///
/// Format: `[ proof<128,LE> | root<32,LE> | external_nullifier<32,LE> | x<32,LE> | y<32,LE> | nullifier<32,LE> ]`
///
/// Returns the deserialized proof and the number of bytes read.
pub fn bytes_le_to_rln_proof(bytes: &[u8]) -> Result<(RLNProof, usize), ProtocolError> {
let mut read: usize = 0;
// Deserialize proof (always LE from arkworks)
let proof = Proof::deserialize_compressed(&bytes[read..read + COMPRESS_PROOF_SIZE])?;
read += COMPRESS_PROOF_SIZE;
// Deserialize proof values
let (values, el_size) = bytes_le_to_rln_proof_values(&bytes[read..])?;
read += el_size;
Ok((
RLNProof {
proof,
proof_values: values,
},
read,
))
}
/// Deserializes RLN proof from big-endian bytes.
///
/// Format: `[ proof<128,LE> | root<32,BE> | external_nullifier<32,BE> | x<32,BE> | y<32,BE> | nullifier<32,BE> ]`
///
/// Note: Mixed-endian format - proof is LE (arkworks), proof_values are BE.
///
/// Returns the deserialized proof and the number of bytes read.
pub fn bytes_be_to_rln_proof(bytes: &[u8]) -> Result<(RLNProof, usize), ProtocolError> {
let mut read: usize = 0;
// Deserialize proof (always LE from arkworks)
let proof = Proof::deserialize_compressed(&bytes[read..read + COMPRESS_PROOF_SIZE])?;
read += COMPRESS_PROOF_SIZE;
// Deserialize proof values
let (values, el_size) = bytes_be_to_rln_proof_values(&bytes[read..])?;
read += el_size;
Ok((
RLNProof {
proof,
proof_values: values,
},
read,
))
}
// zkSNARK proof generation and verification
/// Converts calculated witness (BigInt) to field elements.
fn calculated_witness_to_field_elements<E: ark_ec::pairing::Pairing>(
calculated_witness: Vec<BigInt>,
) -> Result<Vec<E::ScalarField>, ProtocolError> {
let modulus = <E::ScalarField as PrimeField>::MODULUS;
// convert it to field elements
let mut field_elements = vec![];
for w in calculated_witness.into_iter() {
let w = if w.sign() == num_bigint::Sign::Minus {
// Need to negate the witness element if negative
modulus.into()
- w.abs()
.to_biguint()
.ok_or(ProtocolError::BigUintConversion(w))?
} else {
w.to_biguint().ok_or(ProtocolError::BigUintConversion(w))?
};
field_elements.push(E::ScalarField::from(w))
}
Ok(field_elements)
}
/// Generates a zkSNARK proof from pre-calculated witness values.
///
/// Use this when witness calculation is performed externally.
pub fn generate_zk_proof_with_witness(
calculated_witness: Vec<BigInt>,
zkey: &Zkey,
) -> Result<Proof, ProtocolError> {
let full_assignment = calculated_witness_to_field_elements::<Curve>(calculated_witness)?;
// Random Values
let mut rng = thread_rng();
let r = Fr::rand(&mut rng);
let s = Fr::rand(&mut rng);
let proof = Groth16::<_, CircomReduction>::create_proof_with_reduction_and_matrices(
&zkey.0,
r,
s,
&zkey.1,
zkey.1.num_instance_variables,
zkey.1.num_constraints,
full_assignment.as_slice(),
)?;
Ok(proof)
}
/// Generates a zkSNARK proof from witness input using the provided circuit data.
pub fn generate_zk_proof(
zkey: &Zkey,
witness: &RLNWitnessInput,
graph_data: &[u8],
) -> Result<Proof, ProtocolError> {
let inputs = inputs_for_witness_calculation(witness)?
.into_iter()
.map(|(name, values)| (name.to_string(), values));
let full_assignment = calc_witness(inputs, graph_data)?;
// Random Values
let mut rng = thread_rng();
let r = Fr::rand(&mut rng);
let s = Fr::rand(&mut rng);
let proof = Groth16::<_, CircomReduction>::create_proof_with_reduction_and_matrices(
&zkey.0,
r,
s,
&zkey.1,
zkey.1.num_instance_variables,
zkey.1.num_constraints,
full_assignment.as_slice(),
)?;
Ok(proof)
}
/// Verifies a zkSNARK proof against the verifying key and public values.
///
/// Returns `true` if the proof is cryptographically valid, `false` if verification fails.
/// Note: Verification failure may occur due to proof computation errors, not necessarily malicious proofs.
pub fn verify_zk_proof(
verifying_key: &VerifyingKey,
proof: &Proof,
proof_values: &RLNProofValues,
) -> Result<bool, ProtocolError> {
// We re-arrange proof-values according to the circuit specification
let inputs = vec![
proof_values.y,
proof_values.root,
proof_values.nullifier,
proof_values.x,
proof_values.external_nullifier,
];
// Check that the proof is valid
let pvk = prepare_verifying_key(verifying_key);
let verified = Groth16::<_, CircomReduction>::verify_proof(&pvk, proof, &inputs)?;
Ok(verified)
}

View File

@@ -0,0 +1,55 @@
use ark_ff::AdditiveGroup;
use super::proof::RLNProofValues;
use crate::{circuit::Fr, error::ProtocolError, utils::IdSecret};
/// Computes identity secret from two (x, y) shares.
fn compute_id_secret(share1: (Fr, Fr), share2: (Fr, Fr)) -> Result<IdSecret, ProtocolError> {
// Assuming a0 is the identity secret and a1 = poseidonHash([a0, external_nullifier]),
// a (x,y) share satisfies the following relation
// y = a_0 + x * a_1
let (x1, y1) = share1;
let (x2, y2) = share2;
// If the two input shares were computed for the same external_nullifier and identity secret, we can recover the latter
// y1 = a_0 + x1 * a_1
// y2 = a_0 + x2 * a_1
if (x1 - x2) != Fr::ZERO {
let a_1 = (y1 - y2) / (x1 - x2);
let mut a_0 = y1 - x1 * a_1;
// If shares come from the same polynomial, a0 is correctly recovered and a1 = poseidonHash([a0, external_nullifier])
let id_secret = IdSecret::from(&mut a_0);
Ok(id_secret)
} else {
Err(ProtocolError::DivisionByZero)
}
}
/// Recovers identity secret from two proof shares with the same external nullifier.
///
/// When a user violates rate limits by generating multiple proofs in the same epoch,
/// their shares can be used to recover their identity secret through polynomial interpolation.
pub fn recover_id_secret(
rln_proof_values_1: &RLNProofValues,
rln_proof_values_2: &RLNProofValues,
) -> Result<IdSecret, ProtocolError> {
let external_nullifier_1 = rln_proof_values_1.external_nullifier;
let external_nullifier_2 = rln_proof_values_2.external_nullifier;
// We continue only if the proof values are for the same external nullifier
if external_nullifier_1 != external_nullifier_2 {
return Err(ProtocolError::ExternalNullifierMismatch(
external_nullifier_1,
external_nullifier_2,
));
}
// We extract the two shares
let share1 = (rln_proof_values_1.x, rln_proof_values_1.y);
let share2 = (rln_proof_values_2.x, rln_proof_values_2.y);
// We recover the secret
compute_id_secret(share1, share2)
}

354
rln/src/protocol/witness.rs Normal file
View File

@@ -0,0 +1,354 @@
use zeroize::Zeroize;
use super::proof::RLNProofValues;
use crate::{
circuit::Fr,
error::ProtocolError,
hashers::poseidon_hash,
utils::{
bytes_be_to_fr, bytes_be_to_vec_fr, bytes_be_to_vec_u8, bytes_le_to_fr, bytes_le_to_vec_fr,
bytes_le_to_vec_u8, fr_to_bytes_be, fr_to_bytes_le, to_bigint, vec_fr_to_bytes_be,
vec_fr_to_bytes_le, vec_u8_to_bytes_be, vec_u8_to_bytes_le, FrOrSecret, IdSecret,
FR_BYTE_SIZE,
},
};
/// Witness input for RLN proof generation.
///
/// Contains the identity credentials, merkle proof, rate-limiting parameters,
/// and signal binding data required to generate a Groth16 proof for the RLN protocol.
#[derive(Debug, PartialEq, Clone)]
pub struct RLNWitnessInput {
identity_secret: IdSecret,
user_message_limit: Fr,
message_id: Fr,
path_elements: Vec<Fr>,
identity_path_index: Vec<u8>,
x: Fr,
external_nullifier: Fr,
}
impl RLNWitnessInput {
pub fn new(
identity_secret: IdSecret,
user_message_limit: Fr,
message_id: Fr,
path_elements: Vec<Fr>,
identity_path_index: Vec<u8>,
x: Fr,
external_nullifier: Fr,
) -> Result<Self, ProtocolError> {
// Message ID range check
if message_id > user_message_limit {
return Err(ProtocolError::InvalidMessageId(
message_id,
user_message_limit,
));
}
// Merkle proof length check
let path_elements_len = path_elements.len();
let identity_path_index_len = identity_path_index.len();
if path_elements_len != identity_path_index_len {
return Err(ProtocolError::InvalidMerkleProofLength(
path_elements_len,
identity_path_index_len,
));
}
Ok(Self {
identity_secret,
user_message_limit,
message_id,
path_elements,
identity_path_index,
x,
external_nullifier,
})
}
pub fn identity_secret(&self) -> &IdSecret {
&self.identity_secret
}
pub fn user_message_limit(&self) -> &Fr {
&self.user_message_limit
}
pub fn message_id(&self) -> &Fr {
&self.message_id
}
pub fn path_elements(&self) -> &[Fr] {
&self.path_elements
}
pub fn identity_path_index(&self) -> &[u8] {
&self.identity_path_index
}
pub fn x(&self) -> &Fr {
&self.x
}
pub fn external_nullifier(&self) -> &Fr {
&self.external_nullifier
}
}
/// Serializes an RLN witness to little-endian bytes.
pub fn rln_witness_to_bytes_le(witness: &RLNWitnessInput) -> Result<Vec<u8>, ProtocolError> {
// Calculate capacity for Vec:
// - 5 fixed field elements: identity_secret, user_message_limit, message_id, x, external_nullifier
// - variable number of path elements
// - identity_path_index (variable size)
let mut bytes: Vec<u8> = Vec::with_capacity(
FR_BYTE_SIZE * (5 + witness.path_elements.len()) + witness.identity_path_index.len(),
);
bytes.extend_from_slice(&witness.identity_secret.to_bytes_le());
bytes.extend_from_slice(&fr_to_bytes_le(&witness.user_message_limit));
bytes.extend_from_slice(&fr_to_bytes_le(&witness.message_id));
bytes.extend_from_slice(&vec_fr_to_bytes_le(&witness.path_elements));
bytes.extend_from_slice(&vec_u8_to_bytes_le(&witness.identity_path_index));
bytes.extend_from_slice(&fr_to_bytes_le(&witness.x));
bytes.extend_from_slice(&fr_to_bytes_le(&witness.external_nullifier));
Ok(bytes)
}
/// Serializes an RLN witness to big-endian bytes.
pub fn rln_witness_to_bytes_be(witness: &RLNWitnessInput) -> Result<Vec<u8>, ProtocolError> {
// Calculate capacity for Vec:
// - 5 fixed field elements: identity_secret, user_message_limit, message_id, x, external_nullifier
// - variable number of path elements
// - identity_path_index (variable size)
let mut bytes: Vec<u8> = Vec::with_capacity(
FR_BYTE_SIZE * (5 + witness.path_elements.len()) + witness.identity_path_index.len(),
);
bytes.extend_from_slice(&witness.identity_secret.to_bytes_be());
bytes.extend_from_slice(&fr_to_bytes_be(&witness.user_message_limit));
bytes.extend_from_slice(&fr_to_bytes_be(&witness.message_id));
bytes.extend_from_slice(&vec_fr_to_bytes_be(&witness.path_elements));
bytes.extend_from_slice(&vec_u8_to_bytes_be(&witness.identity_path_index));
bytes.extend_from_slice(&fr_to_bytes_be(&witness.x));
bytes.extend_from_slice(&fr_to_bytes_be(&witness.external_nullifier));
Ok(bytes)
}
/// Deserializes an RLN witness from little-endian bytes.
///
/// Format: `[ identity_secret<32> | user_message_limit<32> | message_id<32> | path_elements<var> | identity_path_index<var> | x<32> | external_nullifier<32> ]`
///
/// Returns the deserialized witness and the number of bytes read.
pub fn bytes_le_to_rln_witness(bytes: &[u8]) -> Result<(RLNWitnessInput, usize), ProtocolError> {
let mut read: usize = 0;
let (identity_secret, el_size) = IdSecret::from_bytes_le(&bytes[read..])?;
read += el_size;
let (user_message_limit, el_size) = bytes_le_to_fr(&bytes[read..])?;
read += el_size;
let (message_id, el_size) = bytes_le_to_fr(&bytes[read..])?;
read += el_size;
let (path_elements, el_size) = bytes_le_to_vec_fr(&bytes[read..])?;
read += el_size;
let (identity_path_index, el_size) = bytes_le_to_vec_u8(&bytes[read..])?;
read += el_size;
let (x, el_size) = bytes_le_to_fr(&bytes[read..])?;
read += el_size;
let (external_nullifier, el_size) = bytes_le_to_fr(&bytes[read..])?;
read += el_size;
if bytes.len() != read {
return Err(ProtocolError::InvalidReadLen(bytes.len(), read));
}
Ok((
RLNWitnessInput::new(
identity_secret,
user_message_limit,
message_id,
path_elements,
identity_path_index,
x,
external_nullifier,
)?,
read,
))
}
/// Deserializes an RLN witness from big-endian bytes.
///
/// Format: `[ identity_secret<32> | user_message_limit<32> | message_id<32> | path_elements<var> | identity_path_index<var> | x<32> | external_nullifier<32> ]`
///
/// Returns the deserialized witness and the number of bytes read.
pub fn bytes_be_to_rln_witness(bytes: &[u8]) -> Result<(RLNWitnessInput, usize), ProtocolError> {
let mut read: usize = 0;
let (identity_secret, el_size) = IdSecret::from_bytes_be(&bytes[read..])?;
read += el_size;
let (user_message_limit, el_size) = bytes_be_to_fr(&bytes[read..])?;
read += el_size;
let (message_id, el_size) = bytes_be_to_fr(&bytes[read..])?;
read += el_size;
let (path_elements, el_size) = bytes_be_to_vec_fr(&bytes[read..])?;
read += el_size;
let (identity_path_index, el_size) = bytes_be_to_vec_u8(&bytes[read..])?;
read += el_size;
let (x, el_size) = bytes_be_to_fr(&bytes[read..])?;
read += el_size;
let (external_nullifier, el_size) = bytes_be_to_fr(&bytes[read..])?;
read += el_size;
if bytes.len() != read {
return Err(ProtocolError::InvalidReadLen(bytes.len(), read));
}
Ok((
RLNWitnessInput::new(
identity_secret,
user_message_limit,
message_id,
path_elements,
identity_path_index,
x,
external_nullifier,
)?,
read,
))
}
/// Converts RLN witness to JSON with BigInt string representation for witness calculator.
pub fn rln_witness_to_bigint_json(
witness: &RLNWitnessInput,
) -> Result<serde_json::Value, ProtocolError> {
use num_bigint::BigInt;
let mut path_elements = Vec::new();
for v in witness.path_elements.iter() {
path_elements.push(to_bigint(v).to_str_radix(10));
}
let mut identity_path_index = Vec::new();
witness
.identity_path_index
.iter()
.for_each(|v| identity_path_index.push(BigInt::from(*v).to_str_radix(10)));
let inputs = serde_json::json!({
"identitySecret": to_bigint(&witness.identity_secret).to_str_radix(10),
"userMessageLimit": to_bigint(&witness.user_message_limit).to_str_radix(10),
"messageId": to_bigint(&witness.message_id).to_str_radix(10),
"pathElements": path_elements,
"identityPathIndex": identity_path_index,
"x": to_bigint(&witness.x).to_str_radix(10),
"externalNullifier": to_bigint(&witness.external_nullifier).to_str_radix(10),
});
Ok(inputs)
}
/// Computes RLN proof values from witness input.
///
/// Calculates the public outputs (y, nullifier, root) that will be part of the proof.
pub fn proof_values_from_witness(
witness: &RLNWitnessInput,
) -> Result<RLNProofValues, ProtocolError> {
// y share
let a_0 = &witness.identity_secret;
let mut to_hash = [**a_0, witness.external_nullifier, witness.message_id];
let a_1 = poseidon_hash(&to_hash)?;
let y = *(a_0.clone()) + witness.x * a_1;
// Nullifier
let nullifier = poseidon_hash(&[a_1])?;
to_hash[0].zeroize();
// Merkle tree root computations
let root = compute_tree_root(
&witness.identity_secret,
&witness.user_message_limit,
&witness.path_elements,
&witness.identity_path_index,
)?;
Ok(RLNProofValues {
y,
nullifier,
root,
x: witness.x,
external_nullifier: witness.external_nullifier,
})
}
/// Computes the Merkle tree root from identity credentials and Merkle membership proof.
pub fn compute_tree_root(
identity_secret: &IdSecret,
user_message_limit: &Fr,
path_elements: &[Fr],
identity_path_index: &[u8],
) -> Result<Fr, ProtocolError> {
let mut to_hash = [*identity_secret.clone()];
let id_commitment = poseidon_hash(&to_hash)?;
to_hash[0].zeroize();
let mut root = poseidon_hash(&[id_commitment, *user_message_limit])?;
for i in 0..identity_path_index.len() {
if identity_path_index[i] == 0 {
root = poseidon_hash(&[root, path_elements[i]])?;
} else {
root = poseidon_hash(&[path_elements[i], root])?;
}
}
Ok(root)
}
/// Prepares inputs for witness calculation from RLN witness input.
pub(super) fn inputs_for_witness_calculation(
witness: &RLNWitnessInput,
) -> Result<[(&str, Vec<FrOrSecret>); 7], ProtocolError> {
let mut identity_path_index = Vec::with_capacity(witness.identity_path_index.len());
witness
.identity_path_index
.iter()
.for_each(|v| identity_path_index.push(Fr::from(*v)));
Ok([
(
"identitySecret",
vec![witness.identity_secret.clone().into()],
),
("userMessageLimit", vec![witness.user_message_limit.into()]),
("messageId", vec![witness.message_id.into()]),
(
"pathElements",
witness
.path_elements
.iter()
.cloned()
.map(Into::into)
.collect(),
),
(
"identityPathIndex",
identity_path_index.into_iter().map(Into::into).collect(),
),
("x", vec![witness.x.into()]),
("externalNullifier", vec![witness.external_nullifier.into()]),
])
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -1,7 +1,7 @@
// This crate provides cross-module useful utilities (mainly type conversions) not necessarily specific to RLN
use crate::circuit::Fr;
use crate::error::ConversionError;
use std::ops::Deref;
use ark_ff::PrimeField;
use ark_serialize::{CanonicalDeserialize, CanonicalSerialize};
use ark_std::UniformRand;
@@ -9,26 +9,29 @@ use num_bigint::{BigInt, BigUint};
use num_traits::Num;
use rand::Rng;
use ruint::aliases::U256;
use serde_json::json;
use std::io::Cursor;
use std::ops::Deref;
use zeroize::{Zeroize, ZeroizeOnDrop, Zeroizing};
use crate::{circuit::Fr, error::UtilsError};
/// Byte size of a field element aligned to 64-bit boundary, computed once at compile time.
pub const FR_BYTE_SIZE: usize = {
// Get the modulus bit size of the field
let modulus_bits: u32 = Fr::MODULUS_BIT_SIZE;
// Alignment boundary in bits for field element serialization
let alignment_bits: u32 = 64;
// Align to the next multiple of alignment_bits and convert to bytes
((modulus_bits + alignment_bits - (modulus_bits % alignment_bits)) / 8) as usize
};
#[inline(always)]
pub fn to_bigint(el: &Fr) -> BigInt {
BigUint::from(*el).into()
}
#[inline(always)]
pub const fn fr_byte_size() -> usize {
let mbs = <Fr as PrimeField>::MODULUS_BIT_SIZE;
((mbs + 64 - (mbs % 64)) / 8) as usize
}
#[inline(always)]
pub fn str_to_fr(input: &str, radix: u32) -> Result<Fr, ConversionError> {
pub fn str_to_fr(input: &str, radix: u32) -> Result<Fr, UtilsError> {
if !(radix == 10 || radix == 16) {
return Err(ConversionError::WrongRadix);
return Err(UtilsError::WrongRadix);
}
// We remove any quote present and we trim
@@ -45,21 +48,33 @@ pub fn str_to_fr(input: &str, radix: u32) -> Result<Fr, ConversionError> {
}
#[inline(always)]
pub fn bytes_le_to_fr(input: &[u8]) -> (Fr, usize) {
let el_size = fr_byte_size();
(
pub fn bytes_le_to_fr(input: &[u8]) -> Result<(Fr, usize), UtilsError> {
let el_size = FR_BYTE_SIZE;
if input.len() < el_size {
return Err(UtilsError::InsufficientData {
expected: el_size,
actual: input.len(),
});
}
Ok((
Fr::from(BigUint::from_bytes_le(&input[0..el_size])),
el_size,
)
))
}
#[inline(always)]
pub fn bytes_be_to_fr(input: &[u8]) -> (Fr, usize) {
let el_size = fr_byte_size();
(
pub fn bytes_be_to_fr(input: &[u8]) -> Result<(Fr, usize), UtilsError> {
let el_size = FR_BYTE_SIZE;
if input.len() < el_size {
return Err(UtilsError::InsufficientData {
expected: el_size,
actual: input.len(),
});
}
Ok((
Fr::from(BigUint::from_bytes_be(&input[0..el_size])),
el_size,
)
))
}
#[inline(always)]
@@ -67,7 +82,7 @@ pub fn fr_to_bytes_le(input: &Fr) -> Vec<u8> {
let input_biguint: BigUint = (*input).into();
let mut res = input_biguint.to_bytes_le();
//BigUint conversion ignores most significant zero bytes. We restore them otherwise serialization will fail (length % 8 != 0)
res.resize(fr_byte_size(), 0);
res.resize(FR_BYTE_SIZE, 0);
res
}
@@ -76,7 +91,7 @@ pub fn fr_to_bytes_be(input: &Fr) -> Vec<u8> {
let input_biguint: BigUint = (*input).into();
let mut res = input_biguint.to_bytes_be();
// For BE, insert 0 at the start of the Vec (see also fr_to_bytes_le comments)
let to_insert_count = fr_byte_size().saturating_sub(res.len());
let to_insert_count = FR_BYTE_SIZE.saturating_sub(res.len());
if to_insert_count > 0 {
// Insert multi 0 at index 0
res.splice(0..0, std::iter::repeat_n(0, to_insert_count));
@@ -88,8 +103,8 @@ pub fn fr_to_bytes_be(input: &Fr) -> Vec<u8> {
pub fn vec_fr_to_bytes_le(input: &[Fr]) -> Vec<u8> {
// Calculate capacity for Vec:
// - 8 bytes for normalized vector length (usize)
// - each Fr element requires fr_byte_size() bytes (typically 32 bytes)
let mut bytes = Vec::with_capacity(8 + input.len() * fr_byte_size());
// - each Fr element requires FR_BYTE_SIZE bytes (typically 32 bytes)
let mut bytes = Vec::with_capacity(8 + input.len() * FR_BYTE_SIZE);
// We store the vector length
bytes.extend_from_slice(&normalize_usize_le(input.len()));
@@ -106,8 +121,8 @@ pub fn vec_fr_to_bytes_le(input: &[Fr]) -> Vec<u8> {
pub fn vec_fr_to_bytes_be(input: &[Fr]) -> Vec<u8> {
// Calculate capacity for Vec:
// - 8 bytes for normalized vector length (usize)
// - each Fr element requires fr_byte_size() bytes (typically 32 bytes)
let mut bytes = Vec::with_capacity(8 + input.len() * fr_byte_size());
// - each Fr element requires FR_BYTE_SIZE bytes (typically 32 bytes)
let mut bytes = Vec::with_capacity(8 + input.len() * FR_BYTE_SIZE);
// We store the vector length
bytes.extend_from_slice(&normalize_usize_be(input.len()));
@@ -153,10 +168,10 @@ pub fn vec_u8_to_bytes_be(input: &[u8]) -> Vec<u8> {
}
#[inline(always)]
pub fn bytes_le_to_vec_u8(input: &[u8]) -> Result<(Vec<u8>, usize), ConversionError> {
pub fn bytes_le_to_vec_u8(input: &[u8]) -> Result<(Vec<u8>, usize), UtilsError> {
let mut read: usize = 0;
if input.len() < 8 {
return Err(ConversionError::InsufficientData {
return Err(UtilsError::InsufficientData {
expected: 8,
actual: input.len(),
});
@@ -164,7 +179,7 @@ pub fn bytes_le_to_vec_u8(input: &[u8]) -> Result<(Vec<u8>, usize), ConversionEr
let len = usize::try_from(u64::from_le_bytes(input[0..8].try_into()?))?;
read += 8;
if input.len() < 8 + len {
return Err(ConversionError::InsufficientData {
return Err(UtilsError::InsufficientData {
expected: 8 + len,
actual: input.len(),
});
@@ -175,10 +190,10 @@ pub fn bytes_le_to_vec_u8(input: &[u8]) -> Result<(Vec<u8>, usize), ConversionEr
}
#[inline(always)]
pub fn bytes_be_to_vec_u8(input: &[u8]) -> Result<(Vec<u8>, usize), ConversionError> {
pub fn bytes_be_to_vec_u8(input: &[u8]) -> Result<(Vec<u8>, usize), UtilsError> {
let mut read: usize = 0;
if input.len() < 8 {
return Err(ConversionError::InsufficientData {
return Err(UtilsError::InsufficientData {
expected: 8,
actual: input.len(),
});
@@ -186,7 +201,7 @@ pub fn bytes_be_to_vec_u8(input: &[u8]) -> Result<(Vec<u8>, usize), ConversionEr
let len = usize::try_from(u64::from_be_bytes(input[0..8].try_into()?))?;
read += 8;
if input.len() < 8 + len {
return Err(ConversionError::InsufficientData {
return Err(UtilsError::InsufficientData {
expected: 8 + len,
actual: input.len(),
});
@@ -197,26 +212,26 @@ pub fn bytes_be_to_vec_u8(input: &[u8]) -> Result<(Vec<u8>, usize), ConversionEr
}
#[inline(always)]
pub fn bytes_le_to_vec_fr(input: &[u8]) -> Result<(Vec<Fr>, usize), ConversionError> {
pub fn bytes_le_to_vec_fr(input: &[u8]) -> Result<(Vec<Fr>, usize), UtilsError> {
let mut read: usize = 0;
if input.len() < 8 {
return Err(ConversionError::InsufficientData {
return Err(UtilsError::InsufficientData {
expected: 8,
actual: input.len(),
});
}
let len = usize::try_from(u64::from_le_bytes(input[0..8].try_into()?))?;
read += 8;
let el_size = fr_byte_size();
let el_size = FR_BYTE_SIZE;
if input.len() < 8 + len * el_size {
return Err(ConversionError::InsufficientData {
return Err(UtilsError::InsufficientData {
expected: 8 + len * el_size,
actual: input.len(),
});
}
let mut res: Vec<Fr> = Vec::with_capacity(len);
for i in 0..len {
let (curr_el, _) = bytes_le_to_fr(&input[8 + el_size * i..8 + el_size * (i + 1)]);
let (curr_el, _) = bytes_le_to_fr(&input[8 + el_size * i..8 + el_size * (i + 1)])?;
res.push(curr_el);
read += el_size;
}
@@ -224,26 +239,26 @@ pub fn bytes_le_to_vec_fr(input: &[u8]) -> Result<(Vec<Fr>, usize), ConversionEr
}
#[inline(always)]
pub fn bytes_be_to_vec_fr(input: &[u8]) -> Result<(Vec<Fr>, usize), ConversionError> {
pub fn bytes_be_to_vec_fr(input: &[u8]) -> Result<(Vec<Fr>, usize), UtilsError> {
let mut read: usize = 0;
if input.len() < 8 {
return Err(ConversionError::InsufficientData {
return Err(UtilsError::InsufficientData {
expected: 8,
actual: input.len(),
});
}
let len = usize::try_from(u64::from_be_bytes(input[0..8].try_into()?))?;
read += 8;
let el_size = fr_byte_size();
let el_size = FR_BYTE_SIZE;
if input.len() < 8 + len * el_size {
return Err(ConversionError::InsufficientData {
return Err(UtilsError::InsufficientData {
expected: 8 + len * el_size,
actual: input.len(),
});
}
let mut res: Vec<Fr> = Vec::with_capacity(len);
for i in 0..len {
let (curr_el, _) = bytes_be_to_fr(&input[8 + el_size * i..8 + el_size * (i + 1)]);
let (curr_el, _) = bytes_be_to_fr(&input[8 + el_size * i..8 + el_size * (i + 1)])?;
res.push(curr_el);
read += el_size;
}
@@ -251,9 +266,9 @@ pub fn bytes_be_to_vec_fr(input: &[u8]) -> Result<(Vec<Fr>, usize), ConversionEr
}
#[inline(always)]
pub fn bytes_le_to_vec_usize(input: &[u8]) -> Result<Vec<usize>, ConversionError> {
pub fn bytes_le_to_vec_usize(input: &[u8]) -> Result<Vec<usize>, UtilsError> {
if input.len() < 8 {
return Err(ConversionError::InsufficientData {
return Err(UtilsError::InsufficientData {
expected: 8,
actual: input.len(),
});
@@ -263,24 +278,27 @@ pub fn bytes_le_to_vec_usize(input: &[u8]) -> Result<Vec<usize>, ConversionError
Ok(vec![])
} else {
if input.len() < 8 + nof_elem * 8 {
return Err(ConversionError::InsufficientData {
return Err(UtilsError::InsufficientData {
expected: 8 + nof_elem * 8,
actual: input.len(),
});
}
let elements: Vec<usize> = input[8..]
.chunks(8)
input[8..]
.chunks_exact(8)
.take(nof_elem)
.map(|ch| usize::from_le_bytes(ch[0..8].try_into().unwrap()))
.collect();
Ok(elements)
.map(|ch| {
ch.try_into()
.map(usize::from_le_bytes)
.map_err(UtilsError::FromSlice)
})
.collect()
}
}
#[inline(always)]
pub fn bytes_be_to_vec_usize(input: &[u8]) -> Result<Vec<usize>, ConversionError> {
pub fn bytes_be_to_vec_usize(input: &[u8]) -> Result<Vec<usize>, UtilsError> {
if input.len() < 8 {
return Err(ConversionError::InsufficientData {
return Err(UtilsError::InsufficientData {
expected: 8,
actual: input.len(),
});
@@ -290,17 +308,20 @@ pub fn bytes_be_to_vec_usize(input: &[u8]) -> Result<Vec<usize>, ConversionError
Ok(vec![])
} else {
if input.len() < 8 + nof_elem * 8 {
return Err(ConversionError::InsufficientData {
return Err(UtilsError::InsufficientData {
expected: 8 + nof_elem * 8,
actual: input.len(),
});
}
let elements: Vec<usize> = input[8..]
.chunks(8)
input[8..]
.chunks_exact(8)
.take(nof_elem)
.map(|ch| usize::from_be_bytes(ch[0..8].try_into().unwrap()))
.collect();
Ok(elements)
.map(|ch| {
ch.try_into()
.map(usize::from_be_bytes)
.map_err(UtilsError::FromSlice)
})
.collect()
}
}
@@ -322,19 +343,15 @@ pub fn normalize_usize_le(input: usize) -> [u8; 8] {
pub fn normalize_usize_be(input: usize) -> [u8; 8] {
let mut bytes = [0u8; 8];
let input_bytes = input.to_be_bytes();
bytes[..input_bytes.len()].copy_from_slice(&input_bytes);
let offset = 8 - input_bytes.len();
bytes[offset..].copy_from_slice(&input_bytes);
bytes
}
#[inline(always)] // using for test
pub fn generate_input_buffer() -> Cursor<String> {
Cursor::new(json!({}).to_string())
}
#[derive(
Debug, Zeroize, ZeroizeOnDrop, Clone, PartialEq, CanonicalSerialize, CanonicalDeserialize,
)]
pub struct IdSecret(ark_bn254::Fr);
pub struct IdSecret(Fr);
impl IdSecret {
pub fn rand<R: Rng + ?Sized>(rng: &mut R) -> Self {
@@ -345,26 +362,47 @@ impl IdSecret {
res
}
pub fn from_bytes_le(input: &[u8]) -> (Self, usize) {
let el_size = fr_byte_size();
pub fn from_bytes_le(input: &[u8]) -> Result<(Self, usize), UtilsError> {
let el_size = FR_BYTE_SIZE;
if input.len() < el_size {
return Err(UtilsError::InsufficientData {
expected: el_size,
actual: input.len(),
});
}
let b_uint = BigUint::from_bytes_le(&input[0..el_size]);
let mut fr = Fr::from(b_uint);
let res = IdSecret::from(&mut fr);
// Note: no zeroize on b_uint as it has been moved
(res, el_size)
Ok((res, el_size))
}
pub fn from_bytes_be(input: &[u8]) -> Result<(Self, usize), UtilsError> {
let el_size = FR_BYTE_SIZE;
if input.len() < el_size {
return Err(UtilsError::InsufficientData {
expected: el_size,
actual: input.len(),
});
}
let b_uint = BigUint::from_bytes_be(&input[0..el_size]);
let mut fr = Fr::from(b_uint);
let res = IdSecret::from(&mut fr);
// Note: no zeroize on b_uint as it has been moved
Ok((res, el_size))
}
pub(crate) fn to_bytes_le(&self) -> Zeroizing<Vec<u8>> {
let input_biguint: BigUint = self.0.into();
let mut res = input_biguint.to_bytes_le();
res.resize(fr_byte_size(), 0);
res.resize(FR_BYTE_SIZE, 0);
Zeroizing::new(res)
}
pub(crate) fn to_bytes_be(&self) -> Zeroizing<Vec<u8>> {
let input_biguint: BigUint = self.0.into();
let mut res = input_biguint.to_bytes_be();
let to_insert_count = fr_byte_size().saturating_sub(res.len());
let to_insert_count = FR_BYTE_SIZE.saturating_sub(res.len());
if to_insert_count > 0 {
// Insert multi 0 at index 0
res.splice(0..0, std::iter::repeat_n(0, to_insert_count));
@@ -403,7 +441,7 @@ impl Deref for IdSecret {
}
#[derive(Debug, Zeroize, ZeroizeOnDrop)]
pub enum FrOrSecret {
pub(crate) enum FrOrSecret {
IdSecret(IdSecret),
Fr(Fr),
}

File diff suppressed because it is too large Load Diff

288
rln/tests/ffi_utils.rs Normal file
View File

@@ -0,0 +1,288 @@
#[cfg(test)]
mod test {
use rand::Rng;
use rln::{ffi::ffi_utils::*, prelude::*};
#[test]
// Tests hash to field using FFI APIs
fn test_seeded_keygen_ffi() {
// We generate a new identity pair from an input seed
let seed_bytes: Vec<u8> = vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
let res = match ffi_seeded_key_gen(&seed_bytes.into()) {
CResult {
ok: Some(vec_cfr),
err: None,
} => vec_cfr,
CResult {
ok: None,
err: Some(err),
} => panic!("ffi_seeded_key_gen call failed: {}", err),
_ => unreachable!(),
};
let identity_secret = res.first().unwrap();
let id_commitment = res.get(1).unwrap();
// We check against expected values
let expected_identity_secret_seed_bytes = str_to_fr(
"0x766ce6c7e7a01bdf5b3f257616f603918c30946fa23480f2859c597817e6716",
16,
)
.unwrap();
let expected_id_commitment_seed_bytes = str_to_fr(
"0xbf16d2b5c0d6f9d9d561e05bfca16a81b4b873bb063508fae360d8c74cef51f",
16,
)
.unwrap();
assert_eq!(*identity_secret, expected_identity_secret_seed_bytes);
assert_eq!(*id_commitment, expected_id_commitment_seed_bytes);
}
#[test]
// Tests hash to field using FFI APIs
fn test_seeded_extended_keygen_ffi() {
// We generate a new identity tuple from an input seed
let seed_bytes: Vec<u8> = vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
let key_gen = match ffi_seeded_extended_key_gen(&seed_bytes.into()) {
CResult {
ok: Some(vec_cfr),
err: None,
} => vec_cfr,
CResult {
ok: None,
err: Some(err),
} => panic!("ffi_seeded_extended_key_gen call failed: {}", err),
_ => unreachable!(),
};
let identity_trapdoor = *key_gen[0];
let identity_nullifier = *key_gen[1];
let identity_secret = *key_gen[2];
let id_commitment = *key_gen[3];
// We check against expected values
let expected_identity_trapdoor_seed_bytes = str_to_fr(
"0x766ce6c7e7a01bdf5b3f257616f603918c30946fa23480f2859c597817e6716",
16,
)
.unwrap();
let expected_identity_nullifier_seed_bytes = str_to_fr(
"0x1f18714c7bc83b5bca9e89d404cf6f2f585bc4c0f7ed8b53742b7e2b298f50b4",
16,
)
.unwrap();
let expected_identity_secret_seed_bytes = str_to_fr(
"0x2aca62aaa7abaf3686fff2caf00f55ab9462dc12db5b5d4bcf3994e671f8e521",
16,
)
.unwrap();
let expected_id_commitment_seed_bytes = str_to_fr(
"0x68b66aa0a8320d2e56842581553285393188714c48f9b17acd198b4f1734c5c",
16,
)
.unwrap();
assert_eq!(identity_trapdoor, expected_identity_trapdoor_seed_bytes);
assert_eq!(identity_nullifier, expected_identity_nullifier_seed_bytes);
assert_eq!(identity_secret, expected_identity_secret_seed_bytes);
assert_eq!(id_commitment, expected_id_commitment_seed_bytes);
}
#[test]
// Test CFr FFI functions
fn test_cfr_ffi() {
let cfr_zero = ffi_cfr_zero();
let fr_zero = rln::circuit::Fr::from(0u8);
assert_eq!(*cfr_zero, fr_zero);
let cfr_one = ffi_cfr_one();
let fr_one = rln::circuit::Fr::from(1u8);
assert_eq!(*cfr_one, fr_one);
let cfr_int = ffi_uint_to_cfr(42);
let fr_int = rln::circuit::Fr::from(42u8);
assert_eq!(*cfr_int, fr_int);
let cfr_debug_str = ffi_cfr_debug(Some(&cfr_int));
assert_eq!(cfr_debug_str.to_string(), "42");
let key_gen = match ffi_key_gen() {
CResult {
ok: Some(vec_cfr),
err: None,
} => vec_cfr,
CResult {
ok: None,
err: Some(err),
} => panic!("ffi_key_gen call failed: {}", err),
_ => unreachable!(),
};
let mut id_secret_fr = *key_gen[0];
let id_secret_hash = IdSecret::from(&mut id_secret_fr);
let id_commitment = *key_gen[1];
let cfr_id_secret_hash = ffi_vec_cfr_get(&key_gen, 0).unwrap();
assert_eq!(*cfr_id_secret_hash, *id_secret_hash);
let cfr_id_commitment = ffi_vec_cfr_get(&key_gen, 1).unwrap();
assert_eq!(*cfr_id_commitment, id_commitment);
}
#[test]
// Test Vec<u8> FFI functions
fn test_vec_u8_ffi() {
let mut rng = rand::thread_rng();
let signal_gen: [u8; 32] = rng.gen();
let signal: Vec<u8> = signal_gen.to_vec();
let bytes_le = ffi_vec_u8_to_bytes_le(&signal.clone().into());
let expected_le = vec_u8_to_bytes_le(&signal);
assert_eq!(bytes_le.iter().copied().collect::<Vec<_>>(), expected_le);
let bytes_be = ffi_vec_u8_to_bytes_be(&signal.clone().into());
let expected_be = vec_u8_to_bytes_be(&signal);
assert_eq!(bytes_be.iter().copied().collect::<Vec<_>>(), expected_be);
let signal_from_le = match ffi_bytes_le_to_vec_u8(&bytes_le) {
CResult {
ok: Some(vec_u8),
err: None,
} => vec_u8,
CResult {
ok: None,
err: Some(err),
} => panic!("ffi_bytes_le_to_vec_u8 call failed: {}", err),
_ => unreachable!(),
};
assert_eq!(signal_from_le.iter().copied().collect::<Vec<_>>(), signal);
let signal_from_be = match ffi_bytes_be_to_vec_u8(&bytes_be) {
CResult {
ok: Some(vec_u8),
err: None,
} => vec_u8,
CResult {
ok: None,
err: Some(err),
} => panic!("ffi_bytes_be_to_vec_u8 call failed: {}", err),
_ => unreachable!(),
};
assert_eq!(signal_from_be.iter().copied().collect::<Vec<_>>(), signal);
}
#[test]
// Test Vec<CFr> FFI functions
fn test_vec_cfr_ffi() {
let vec_fr = [Fr::from(1u8), Fr::from(2u8), Fr::from(3u8), Fr::from(4u8)];
let vec_cfr: Vec<CFr> = vec_fr.iter().map(|fr| CFr::from(*fr)).collect();
let bytes_le = ffi_vec_cfr_to_bytes_le(&vec_cfr.clone().into());
let expected_le = vec_fr_to_bytes_le(&vec_fr);
assert_eq!(bytes_le.iter().copied().collect::<Vec<_>>(), expected_le);
let bytes_be = ffi_vec_cfr_to_bytes_be(&vec_cfr.clone().into());
let expected_be = vec_fr_to_bytes_be(&vec_fr);
assert_eq!(bytes_be.iter().copied().collect::<Vec<_>>(), expected_be);
let vec_cfr_from_le = match ffi_bytes_le_to_vec_cfr(&bytes_le) {
CResult {
ok: Some(vec_cfr),
err: None,
} => vec_cfr,
CResult {
ok: None,
err: Some(err),
} => panic!("ffi_bytes_le_to_vec_cfr call failed: {}", err),
_ => unreachable!(),
};
assert_eq!(vec_cfr_from_le.iter().copied().collect::<Vec<_>>(), vec_cfr);
let vec_cfr_from_be = match ffi_bytes_be_to_vec_cfr(&bytes_be) {
CResult {
ok: Some(vec_cfr),
err: None,
} => vec_cfr,
CResult {
ok: None,
err: Some(err),
} => panic!("ffi_bytes_be_to_vec_cfr call failed: {}", err),
_ => unreachable!(),
};
assert_eq!(vec_cfr_from_be.iter().copied().collect::<Vec<_>>(), vec_cfr);
}
#[test]
// Tests hash to field using FFI APIs
fn test_hash_to_field_ffi() {
let mut rng = rand::thread_rng();
let signal_gen: [u8; 32] = rng.gen();
let signal: Vec<u8> = signal_gen.to_vec();
let cfr_le_1 = match ffi_hash_to_field_le(&signal.clone().into()) {
CResult {
ok: Some(cfr),
err: None,
} => cfr,
CResult {
ok: None,
err: Some(err),
} => panic!("ffi_hash_to_field_le call failed: {}", err),
_ => unreachable!(),
};
let fr_le_2 = hash_to_field_le(&signal).unwrap();
assert_eq!(*cfr_le_1, fr_le_2);
let cfr_be_1 = match ffi_hash_to_field_be(&signal.clone().into()) {
CResult {
ok: Some(cfr),
err: None,
} => cfr,
CResult {
ok: None,
err: Some(err),
} => panic!("ffi_hash_to_field_be call failed: {}", err),
_ => unreachable!(),
};
let fr_be_2 = hash_to_field_be(&signal).unwrap();
assert_eq!(*cfr_le_1, fr_be_2);
assert_eq!(*cfr_le_1, *cfr_be_1);
assert_eq!(fr_le_2, fr_be_2);
let hash_cfr_le_1 = ffi_cfr_to_bytes_le(&cfr_le_1)
.iter()
.copied()
.collect::<Vec<_>>();
let hash_fr_le_2 = fr_to_bytes_le(&fr_le_2);
assert_eq!(hash_cfr_le_1, hash_fr_le_2);
let hash_cfr_be_1 = ffi_cfr_to_bytes_be(&cfr_be_1)
.iter()
.copied()
.collect::<Vec<_>>();
let hash_fr_be_2 = fr_to_bytes_be(&fr_be_2);
assert_eq!(hash_cfr_be_1, hash_fr_be_2);
assert_ne!(hash_cfr_le_1, hash_cfr_be_1);
assert_ne!(hash_fr_le_2, hash_fr_be_2);
}
#[test]
// Test Poseidon hash FFI
fn test_poseidon_hash_pair_ffi() {
let input_1 = Fr::from(42u8);
let input_2 = Fr::from(99u8);
let expected_hash = poseidon_hash(&[input_1, input_2]).unwrap();
let received_hash_cfr =
match ffi_poseidon_hash_pair(&CFr::from(input_1), &CFr::from(input_2)) {
CResult {
ok: Some(cfr),
err: None,
} => cfr,
CResult {
ok: None,
err: Some(err),
} => panic!("ffi_poseidon_hash_pair call failed: {}", err),
_ => unreachable!(),
};
assert_eq!(*received_hash_cfr, expected_hash);
}
}

View File

@@ -1,17 +1,13 @@
////////////////////////////////////////////////////////////
// Tests
////////////////////////////////////////////////////////////
#![cfg(not(feature = "stateless"))]
#[cfg(test)]
mod test {
use rln::hashers::{poseidon_hash, PoseidonHash};
use rln::{
circuit::{Fr, TEST_TREE_DEPTH},
poseidon_tree::PoseidonTree,
use rln::prelude::*;
use zerokit_utils::merkle_tree::{
FullMerkleTree, OptimalMerkleTree, ZerokitMerkleProof, ZerokitMerkleTree,
};
use utils::{FullMerkleTree, OptimalMerkleTree, ZerokitMerkleProof, ZerokitMerkleTree};
#[test]
// The test checked correctness for `FullMerkleTree` and `OptimalMerkleTree` with Poseidon hash
@@ -19,8 +15,8 @@ mod test {
let sample_size = 100;
let leaves: Vec<Fr> = (0..sample_size).map(Fr::from).collect();
let mut tree_full = FullMerkleTree::<PoseidonHash>::default(TEST_TREE_DEPTH).unwrap();
let mut tree_opt = OptimalMerkleTree::<PoseidonHash>::default(TEST_TREE_DEPTH).unwrap();
let mut tree_full = FullMerkleTree::<PoseidonHash>::default(DEFAULT_TREE_DEPTH).unwrap();
let mut tree_opt = OptimalMerkleTree::<PoseidonHash>::default(DEFAULT_TREE_DEPTH).unwrap();
for (i, leave) in leaves
.into_iter()
@@ -28,12 +24,12 @@ mod test {
.take(sample_size.try_into().unwrap())
{
tree_full.set(i, leave).unwrap();
let proof = tree_full.proof(i).expect("index should be set");
let proof = tree_full.proof(i).unwrap();
assert_eq!(proof.leaf_index(), i);
tree_opt.set(i, leave).unwrap();
assert_eq!(tree_opt.root(), tree_full.root());
let proof = tree_opt.proof(i).expect("index should be set");
let proof = tree_opt.proof(i).unwrap();
assert_eq!(proof.leaf_index(), i);
}
@@ -74,7 +70,7 @@ mod test {
let prev_r = tree.get_subtree_root(n, idx_r).unwrap();
let subroot = tree.get_subtree_root(n - 1, idx_sr).unwrap();
assert_eq!(poseidon_hash(&[prev_l, prev_r]), subroot);
assert_eq!(poseidon_hash(&[prev_l, prev_r]).unwrap(), subroot);
}
}
}

View File

@@ -3,18 +3,8 @@
#[cfg(test)]
mod test {
use ark_ff::BigInt;
use rln::circuit::{graph_from_folder, zkey_from_folder};
use rln::circuit::{Fr, TEST_TREE_DEPTH};
use rln::hashers::{hash_to_field_le, poseidon_hash};
use rln::poseidon_tree::PoseidonTree;
use rln::protocol::{
deserialize_proof_values, deserialize_witness, generate_proof, keygen,
proof_values_from_witness, rln_witness_from_json, rln_witness_from_values,
rln_witness_to_json, seeded_keygen, serialize_proof_values, serialize_witness,
verify_proof, RLNWitnessInput,
};
use rln::utils::str_to_fr;
use utils::{ZerokitMerkleProof, ZerokitMerkleTree};
use rln::prelude::*;
use zerokit_utils::merkle_tree::{ZerokitMerkleProof, ZerokitMerkleTree};
type ConfigOf<T> = <T as ZerokitMerkleTree>::Config;
@@ -24,14 +14,14 @@ mod test {
let leaf_index = 3;
// generate identity
let identity_secret_hash = hash_to_field_le(b"test-merkle-proof");
let id_commitment = poseidon_hash(&[identity_secret_hash]);
let rate_commitment = poseidon_hash(&[id_commitment, 100.into()]);
let identity_secret = hash_to_field_le(b"test-merkle-proof").unwrap();
let id_commitment = poseidon_hash(&[identity_secret]).unwrap();
let rate_commitment = poseidon_hash(&[id_commitment, 100.into()]).unwrap();
// generate merkle tree
let default_leaf = Fr::from(0);
let mut tree = PoseidonTree::new(
TEST_TREE_DEPTH,
DEFAULT_TREE_DEPTH,
default_leaf,
ConfigOf::<PoseidonTree>::default(),
)
@@ -52,7 +42,7 @@ mod test {
.into()
);
let merkle_proof = tree.proof(leaf_index).expect("proof should exist");
let merkle_proof = tree.proof(leaf_index).unwrap();
let path_elements = merkle_proof.get_path_elements();
let identity_path_index = merkle_proof.get_path_index();
@@ -79,7 +69,7 @@ mod test {
"0x0f57c5571e9a4eab49e2c8cf050dae948aef6ead647392273546249d1c1ff10f",
"0x1830ee67b5fb554ad5f63d4388800e1cfe78e310697d46e43c9ce36134f72cca",
]
.map(|e| str_to_fr(e, 16).unwrap())
.map(|str| str_to_fr(str, 16).unwrap())
.to_vec();
let expected_identity_path_index: Vec<u8> =
@@ -95,106 +85,77 @@ mod test {
fn get_test_witness() -> RLNWitnessInput {
let leaf_index = 3;
// Generate identity pair
let (identity_secret_hash, id_commitment) = keygen();
let (identity_secret, id_commitment) = keygen().unwrap();
let user_message_limit = Fr::from(100);
let rate_commitment = poseidon_hash(&[id_commitment, user_message_limit]);
let rate_commitment = poseidon_hash(&[id_commitment, user_message_limit]).unwrap();
//// generate merkle tree
let default_leaf = Fr::from(0);
let mut tree = PoseidonTree::new(
TEST_TREE_DEPTH,
DEFAULT_TREE_DEPTH,
default_leaf,
ConfigOf::<PoseidonTree>::default(),
)
.unwrap();
tree.set(leaf_index, rate_commitment).unwrap();
let merkle_proof = tree.proof(leaf_index).expect("proof should exist");
let merkle_proof = tree.proof(leaf_index).unwrap();
let signal = b"hey hey";
let x = hash_to_field_le(signal);
let x = hash_to_field_le(signal).unwrap();
// We set the remaining values to random ones
let epoch = hash_to_field_le(b"test-epoch");
let rln_identifier = hash_to_field_le(b"test-rln-identifier");
let external_nullifier = poseidon_hash(&[epoch, rln_identifier]);
let epoch = hash_to_field_le(b"test-epoch").unwrap();
let rln_identifier = hash_to_field_le(b"test-rln-identifier").unwrap();
let external_nullifier = poseidon_hash(&[epoch, rln_identifier]).unwrap();
rln_witness_from_values(
identity_secret_hash,
let message_id = Fr::from(1);
RLNWitnessInput::new(
identity_secret,
user_message_limit,
message_id,
merkle_proof.get_path_elements(),
merkle_proof.get_path_index(),
x,
external_nullifier,
user_message_limit,
Fr::from(1),
)
.unwrap()
}
#[test]
// We test a RLN proof generation and verification
fn test_witness_from_json() {
// We generate all relevant keys
let proving_key = zkey_from_folder();
let verification_key = &proving_key.0.vk;
let graph_data = graph_from_folder();
// We compute witness from the json input
let rln_witness = get_test_witness();
let rln_witness_json = rln_witness_to_json(&rln_witness).unwrap();
let rln_witness_deser = rln_witness_from_json(rln_witness_json).unwrap();
assert_eq!(rln_witness_deser, rln_witness);
// Let's generate a zkSNARK proof
let proof = generate_proof(proving_key, &rln_witness_deser, graph_data).unwrap();
let proof_values = proof_values_from_witness(&rln_witness_deser).unwrap();
// Let's verify the proof
let verified = verify_proof(verification_key, &proof, &proof_values);
assert!(verified.unwrap());
}
#[test]
// We test a RLN proof generation and verification
fn test_end_to_end() {
let rln_witness = get_test_witness();
let rln_witness_json = rln_witness_to_json(&rln_witness).unwrap();
let rln_witness_deser = rln_witness_from_json(rln_witness_json).unwrap();
assert_eq!(rln_witness_deser, rln_witness);
let witness = get_test_witness();
// We generate all relevant keys
let proving_key = zkey_from_folder();
let verification_key = &proving_key.0.vk;
let graph_data = graph_from_folder();
// Let's generate a zkSNARK proof
let proof = generate_proof(proving_key, &rln_witness_deser, graph_data).unwrap();
let proof = generate_zk_proof(proving_key, &witness, graph_data).unwrap();
let proof_values = proof_values_from_witness(&rln_witness_deser).unwrap();
let proof_values = proof_values_from_witness(&witness).unwrap();
// Let's verify the proof
let success = verify_proof(verification_key, &proof, &proof_values).unwrap();
let success = verify_zk_proof(&proving_key.0.vk, &proof, &proof_values).unwrap();
assert!(success);
}
#[test]
fn test_witness_serialization() {
// We test witness JSON serialization
let rln_witness = get_test_witness();
let rln_witness_json = rln_witness_to_json(&rln_witness).unwrap();
let rln_witness_deser = rln_witness_from_json(rln_witness_json).unwrap();
assert_eq!(rln_witness_deser, rln_witness);
let witness = get_test_witness();
// We test witness serialization
let ser = serialize_witness(&rln_witness).unwrap();
let (deser, _) = deserialize_witness(&ser).unwrap();
assert_eq!(rln_witness, deser);
let ser = rln_witness_to_bytes_le(&witness).unwrap();
let (deser, _) = bytes_le_to_rln_witness(&ser).unwrap();
assert_eq!(witness, deser);
// We test Proof values serialization
let proof_values = proof_values_from_witness(&rln_witness).unwrap();
let ser = serialize_proof_values(&proof_values);
let (deser, _) = deserialize_proof_values(&ser);
let proof_values = proof_values_from_witness(&witness).unwrap();
let ser = rln_proof_values_to_bytes_le(&proof_values);
let (deser, _) = bytes_le_to_rln_proof_values(&ser).unwrap();
assert_eq!(proof_values, deser);
}
@@ -204,10 +165,10 @@ mod test {
fn test_seeded_keygen() {
// Generate identity pair using a seed phrase
let seed_phrase: &str = "A seed phrase example";
let (identity_secret_hash, id_commitment) = seeded_keygen(seed_phrase.as_bytes());
let (identity_secret, id_commitment) = seeded_keygen(seed_phrase.as_bytes()).unwrap();
// We check against expected values
let expected_identity_secret_hash_seed_phrase = str_to_fr(
let expected_identity_secret_seed_phrase = str_to_fr(
"0x20df38f3f00496f19fe7c6535492543b21798ed7cb91aebe4af8012db884eda3",
16,
)
@@ -218,18 +179,15 @@ mod test {
)
.unwrap();
assert_eq!(
identity_secret_hash,
expected_identity_secret_hash_seed_phrase
);
assert_eq!(identity_secret, expected_identity_secret_seed_phrase);
assert_eq!(id_commitment, expected_id_commitment_seed_phrase);
// Generate identity pair using an byte array
let seed_bytes: &[u8] = &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
let (identity_secret_hash, id_commitment) = seeded_keygen(seed_bytes);
let (identity_secret, id_commitment) = seeded_keygen(seed_bytes).unwrap();
// We check against expected values
let expected_identity_secret_hash_seed_bytes = str_to_fr(
let expected_identity_secret_seed_bytes = str_to_fr(
"0x766ce6c7e7a01bdf5b3f257616f603918c30946fa23480f2859c597817e6716",
16,
)
@@ -240,19 +198,13 @@ mod test {
)
.unwrap();
assert_eq!(
identity_secret_hash,
expected_identity_secret_hash_seed_bytes
);
assert_eq!(identity_secret, expected_identity_secret_seed_bytes);
assert_eq!(id_commitment, expected_id_commitment_seed_bytes);
// We check again if the identity pair generated with the same seed phrase corresponds to the previously generated one
let (identity_secret_hash, id_commitment) = seeded_keygen(seed_phrase.as_bytes());
let (identity_secret, id_commitment) = seeded_keygen(seed_phrase.as_bytes()).unwrap();
assert_eq!(
identity_secret_hash,
expected_identity_secret_hash_seed_phrase
);
assert_eq!(identity_secret, expected_identity_secret_seed_phrase);
assert_eq!(id_commitment, expected_id_commitment_seed_phrase);
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,14 +1,7 @@
#[cfg(test)]
mod test {
use rln::utils::{
bytes_be_to_fr, bytes_be_to_vec_fr, bytes_be_to_vec_u8, bytes_be_to_vec_usize,
bytes_le_to_fr, bytes_le_to_vec_fr, bytes_le_to_vec_u8, bytes_le_to_vec_usize,
fr_to_bytes_be, fr_to_bytes_le, normalize_usize_be, normalize_usize_le, str_to_fr,
vec_fr_to_bytes_be, vec_fr_to_bytes_le, vec_u8_to_bytes_be, vec_u8_to_bytes_le,
};
use ark_std::{rand::thread_rng, UniformRand};
use rln::circuit::Fr;
use rln::prelude::*;
#[test]
fn test_normalize_usize_le() {
@@ -194,12 +187,12 @@ mod test {
// Test little-endian roundtrip
let le_bytes = fr_to_bytes_le(&fr);
let (reconstructed_le, _) = bytes_le_to_fr(&le_bytes);
let (reconstructed_le, _) = bytes_le_to_fr(&le_bytes).unwrap();
assert_eq!(fr, reconstructed_le);
// Test big-endian roundtrip
let be_bytes = fr_to_bytes_be(&fr);
let (reconstructed_be, _) = bytes_be_to_fr(&be_bytes);
let (reconstructed_be, _) = bytes_be_to_fr(&be_bytes).unwrap();
assert_eq!(fr, reconstructed_be);
}
}
@@ -320,8 +313,8 @@ mod test {
// They should be different (unless the value is symmetric)
if le_bytes != be_bytes {
// Verify they can both be reconstructed correctly
let (reconstructed_le, _) = bytes_le_to_fr(&le_bytes);
let (reconstructed_be, _) = bytes_be_to_fr(&be_bytes);
let (reconstructed_le, _) = bytes_le_to_fr(&le_bytes).unwrap();
let (reconstructed_be, _) = bytes_be_to_fr(&be_bytes).unwrap();
assert_eq!(fr, reconstructed_le);
assert_eq!(fr, reconstructed_be);
}
@@ -329,7 +322,27 @@ mod test {
#[test]
fn test_error_handling() {
// Test with valid length but insufficient data
// Test bytes_le_to_fr and bytes_be_to_fr with insufficient data
let short_bytes = vec![0u8; 10]; // Less than FR_BYTE_SIZE (32 bytes)
assert!(bytes_le_to_fr(&short_bytes).is_err());
assert!(bytes_be_to_fr(&short_bytes).is_err());
// Test with empty bytes
let empty_bytes = vec![];
assert!(bytes_le_to_fr(&empty_bytes).is_err());
assert!(bytes_be_to_fr(&empty_bytes).is_err());
// Test with exact size - should succeed
let exact_bytes = vec![0u8; FR_BYTE_SIZE];
assert!(bytes_le_to_fr(&exact_bytes).is_ok());
assert!(bytes_be_to_fr(&exact_bytes).is_ok());
// Test with more than enough data - should succeed
let extra_bytes = vec![0u8; FR_BYTE_SIZE + 10];
assert!(bytes_le_to_fr(&extra_bytes).is_ok());
assert!(bytes_be_to_fr(&extra_bytes).is_ok());
// Test with valid length but insufficient data for vector deserialization
let valid_length_invalid_data = vec![0u8; 8]; // Length 0, but no data
assert!(bytes_le_to_vec_u8(&valid_length_invalid_data).is_ok());
assert!(bytes_be_to_vec_u8(&valid_length_invalid_data).is_ok());

6
rustfmt.toml Normal file
View File

@@ -0,0 +1,6 @@
# Run cargo +nightly fmt to format with this configuration
edition = "2021" # use Rust 2021 edition
unstable_features = true # needed for group_imports
reorder_imports = true # sort imports alphabetically
imports_granularity = "Crate" # keep items from the same crate grouped together
group_imports = "StdExternalCrate" # group std, external, and local imports separately

View File

@@ -1,6 +1,6 @@
[package]
name = "zerokit_utils"
version = "0.7.0"
version = "1.0.0"
edition = "2021"
license = "MIT OR Apache-2.0"
description = "Various utilities for Zerokit"
@@ -16,18 +16,17 @@ ark-ff = { version = "0.5.0", default-features = false }
num-bigint = { version = "0.4.6", default-features = false }
pmtree = { package = "vacp2p_pmtree", version = "2.0.3", optional = true }
sled = "0.34.7"
serde_json = "1.0.141"
lazy_static = "1.5.0"
hex = "0.4.3"
rayon = "1.10.0"
serde_json = "1.0.145"
rayon = "1.11.0"
thiserror = "2.0"
[dev-dependencies]
hex = "0.4.3"
hex-literal = "1.1.0"
ark-bn254 = { version = "0.5.0", features = ["std"] }
num-traits = "0.2.19"
hex-literal = "0.4.1"
tiny-keccak = { version = "2.0.2", features = ["keccak"] }
criterion = { version = "0.7.0", features = ["html_reports"] }
criterion = { version = "0.8.0", features = ["html_reports"] }
[features]
default = []

View File

@@ -4,7 +4,7 @@ args = ["build", "--release"]
[tasks.test]
command = "cargo"
args = ["test", "--release"]
args = ["test", "--release", "--", "--nocapture"]
[tasks.bench]
command = "cargo"

View File

@@ -105,7 +105,7 @@ Add zerokit-utils as a dependency to your Cargo.toml file:
```toml
[dependencies]
zerokit-utils = "0.6.0"
zerokit-utils = "1.0.0"
```
## Building and Testing

View File

@@ -1,11 +1,13 @@
use std::{fmt::Display, str::FromStr};
use std::{fmt::Display, str::FromStr, sync::LazyLock};
use criterion::{criterion_group, criterion_main, Criterion};
use lazy_static::lazy_static;
use tiny_keccak::{Hasher as _, Keccak};
use zerokit_utils::{
FullMerkleConfig, FullMerkleTree, Hasher, OptimalMerkleConfig, OptimalMerkleTree,
ZerokitMerkleTree,
error::HashError,
merkle_tree::{
FullMerkleConfig, FullMerkleTree, Hasher, OptimalMerkleConfig, OptimalMerkleTree,
ZerokitMerkleTree,
},
};
#[derive(Clone, Copy, Eq, PartialEq)]
@@ -16,19 +18,20 @@ struct TestFr([u8; 32]);
impl Hasher for Keccak256 {
type Fr = TestFr;
type Error = HashError;
fn default_leaf() -> Self::Fr {
TestFr([0; 32])
}
fn hash(inputs: &[Self::Fr]) -> Self::Fr {
fn hash(inputs: &[Self::Fr]) -> Result<Self::Fr, HashError> {
let mut output = [0; 32];
let mut hasher = Keccak::v256();
for element in inputs {
hasher.update(element.0.as_slice());
}
hasher.finalize(&mut output);
TestFr(output)
Ok(TestFr(output))
}
}
@@ -46,18 +49,17 @@ impl FromStr for TestFr {
}
}
lazy_static! {
static ref LEAVES: Vec<TestFr> = {
let mut leaves = Vec::with_capacity(1 << 20);
for i in 0..(1 << 20) {
let mut bytes = [0u8; 32];
bytes[28..].copy_from_slice(&(i as u32).to_be_bytes());
leaves.push(TestFr(bytes));
}
leaves
};
static ref INDICES: Vec<usize> = (0..(1 << 20)).collect();
}
static LEAVES: LazyLock<Vec<TestFr>> = LazyLock::new(|| {
let mut leaves = Vec::with_capacity(1 << 20);
for i in 0..(1 << 20) {
let mut bytes = [0u8; 32];
bytes[28..].copy_from_slice(&(i as u32).to_be_bytes());
leaves.push(TestFr(bytes));
}
leaves
});
static INDICES: LazyLock<Vec<usize>> = LazyLock::new(|| (0..(1 << 20)).collect());
const NOF_LEAVES: usize = 8192;

View File

@@ -2,7 +2,7 @@ use std::hint::black_box;
use ark_bn254::Fr;
use criterion::{criterion_group, criterion_main, BatchSize, BenchmarkId, Criterion, Throughput};
use zerokit_utils::Poseidon;
use zerokit_utils::poseidon::Poseidon;
const ROUND_PARAMS: [(usize, usize, usize, usize); 8] = [
(2, 8, 56, 0),

11
utils/src/error.rs Normal file
View File

@@ -0,0 +1,11 @@
use super::poseidon::error::PoseidonError;
pub use crate::merkle_tree::{FromConfigError, ZerokitMerkleTreeError};
/// Errors that can occur during hashing operations.
#[derive(Debug, thiserror::Error)]
pub enum HashError {
#[error("Poseidon hash error: {0}")]
Poseidon(#[from] PoseidonError),
#[error("Generic hash error: {0}")]
Generic(String),
}

View File

@@ -1,10 +1,4 @@
pub mod poseidon;
pub use self::poseidon::*;
pub mod error;
pub mod merkle_tree;
pub use self::merkle_tree::*;
#[cfg(feature = "pmtree-ft")]
pub mod pm_tree;
#[cfg(feature = "pmtree-ft")]
pub use self::pm_tree::*;
pub mod poseidon;

View File

@@ -1,8 +1,12 @@
#[derive(thiserror::Error, Debug)]
use crate::error::HashError;
/// Errors that can occur during Merkle tree operations
#[derive(Debug, thiserror::Error)]
pub enum ZerokitMerkleTreeError {
#[error("Invalid index")]
InvalidIndex,
// InvalidProof,
#[error("Invalid indices")]
InvalidIndices,
#[error("Leaf index out of bounds")]
InvalidLeaf,
#[error("Level exceeds tree depth")]
@@ -15,13 +19,16 @@ pub enum ZerokitMerkleTreeError {
TooManySet,
#[error("Unknown error while computing merkle proof")]
ComputingProofError,
#[error("Invalid witness length (!= tree depth)")]
InvalidWitness,
#[error("Invalid merkle proof length (!= tree depth)")]
InvalidMerkleProof,
#[cfg(feature = "pmtree-ft")]
#[error("Pmtree error: {0}")]
PmtreeErrorKind(#[from] pmtree::PmtreeErrorKind),
#[error("Hash error: {0}")]
HashError(#[from] HashError),
}
/// Errors that can occur while creating Merkle tree from config
#[derive(Debug, thiserror::Error)]
pub enum FromConfigError {
#[error("Error while reading pmtree config: {0}")]
@@ -30,4 +37,6 @@ pub enum FromConfigError {
MissingPath,
#[error("Error while creating pmtree config: path already exists")]
PathExists,
#[error("Error while creating pmtree default temp path: {0}")]
IoError(#[from] std::io::Error),
}

View File

@@ -7,13 +7,12 @@ use std::{
use rayon::iter::{IntoParallelIterator, ParallelIterator};
use crate::merkle_tree::{
use super::{
error::{FromConfigError, ZerokitMerkleTreeError},
FrOf, Hasher, ZerokitMerkleProof, ZerokitMerkleTree, MIN_PARALLEL_NODES,
merkle_tree::{FrOf, Hasher, ZerokitMerkleProof, ZerokitMerkleTree, MIN_PARALLEL_NODES},
};
////////////////////////////////////////////////////////////
///// Full Merkle Tree Implementation
////////////////////////////////////////////////////////////
// Full Merkle Tree Implementation
/// Merkle tree with all leaf and intermediate hashes stored
#[derive(Clone, PartialEq, Eq, Debug)]
@@ -41,7 +40,7 @@ where
/// Element of a Merkle proof
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum FullMerkleBranch<H: Hasher> {
pub(crate) enum FullMerkleBranch<H: Hasher> {
/// Left branch taken, value is the right sibling hash.
Left(H::Fr),
@@ -51,7 +50,7 @@ pub enum FullMerkleBranch<H: Hasher> {
/// Merkle proof path, bottom to top.
#[derive(Clone, PartialEq, Eq)]
pub struct FullMerkleProof<H: Hasher>(pub Vec<FullMerkleBranch<H>>);
pub struct FullMerkleProof<H: Hasher>(Vec<FullMerkleBranch<H>>);
#[derive(Default)]
pub struct FullMerkleConfig(());
@@ -88,7 +87,7 @@ where
let mut cached_nodes: Vec<H::Fr> = Vec::with_capacity(depth + 1);
cached_nodes.push(default_leaf);
for i in 0..depth {
cached_nodes.push(H::hash(&[cached_nodes[i]; 2]));
cached_nodes.push(H::hash(&[cached_nodes[i]; 2]).map_err(Into::into)?);
}
cached_nodes.reverse();
@@ -165,13 +164,14 @@ where
let mut idx = self.capacity() + index - 1;
let mut nd = self.depth;
loop {
let parent = self.parent(idx).expect("parent should exist");
let parent = self
.parent(idx)
.ok_or(ZerokitMerkleTreeError::InvalidIndex)?;
nd -= 1;
if nd == n {
return Ok(self.nodes[parent]);
} else {
idx = parent;
continue;
}
}
}
@@ -226,7 +226,10 @@ where
J: ExactSizeIterator<Item = usize>,
{
let indices = indices.into_iter().collect::<Vec<_>>();
let min_index = *indices.first().expect("indices should not be empty");
if indices.is_empty() {
return Err(ZerokitMerkleTreeError::InvalidIndices);
}
let min_index = indices[0];
let leaves_vec = leaves.into_iter().collect::<Vec<_>>();
let max_index = start + leaves_vec.len();
@@ -290,9 +293,9 @@ where
fn verify(
&self,
hash: &FrOf<Self::Hasher>,
proof: &FullMerkleProof<H>,
merkle_proof: &FullMerkleProof<H>,
) -> Result<bool, ZerokitMerkleTreeError> {
Ok(proof.compute_root_from(hash) == self.root())
Ok(merkle_proof.compute_root_from(hash)? == self.root())
}
fn set_metadata(&mut self, metadata: &[u8]) -> Result<(), ZerokitMerkleTreeError> {
@@ -352,17 +355,20 @@ where
{
// Use parallel processing when the number of pairs exceeds the threshold
if end_parent - start_parent + 1 >= MIN_PARALLEL_NODES {
let updates: Vec<(usize, H::Fr)> = (start_parent..=end_parent)
#[allow(clippy::type_complexity)]
let updates: Result<Vec<(usize, H::Fr)>, ZerokitMerkleTreeError> = (start_parent
..=end_parent)
.into_par_iter()
.map(|parent| {
let left_child = self.first_child(parent);
let right_child = left_child + 1;
let hash = H::hash(&[self.nodes[left_child], self.nodes[right_child]]);
(parent, hash)
let hash = H::hash(&[self.nodes[left_child], self.nodes[right_child]])
.map_err(Into::into)?;
Ok((parent, hash))
})
.collect();
for (parent, hash) in updates {
for (parent, hash) in updates? {
self.nodes[parent] = hash;
}
} else {
@@ -371,7 +377,8 @@ where
let left_child = self.first_child(parent);
let right_child = left_child + 1;
self.nodes[parent] =
H::hash(&[self.nodes[left_child], self.nodes[right_child]]);
H::hash(&[self.nodes[left_child], self.nodes[right_child]])
.map_err(Into::into)?;
}
}
@@ -422,10 +429,13 @@ impl<H: Hasher> ZerokitMerkleProof for FullMerkleProof<H> {
}
/// Computes the Merkle root corresponding by iteratively hashing a Merkle proof with a given input leaf
fn compute_root_from(&self, hash: &FrOf<Self::Hasher>) -> FrOf<Self::Hasher> {
self.0.iter().fold(*hash, |hash, branch| match branch {
FullMerkleBranch::Left(sibling) => H::hash(&[hash, *sibling]),
FullMerkleBranch::Right(sibling) => H::hash(&[*sibling, hash]),
fn compute_root_from(
&self,
hash: &FrOf<Self::Hasher>,
) -> Result<FrOf<Self::Hasher>, ZerokitMerkleTreeError> {
self.0.iter().try_fold(*hash, |hash, branch| match branch {
FullMerkleBranch::Left(sibling) => H::hash(&[hash, *sibling]).map_err(Into::into),
FullMerkleBranch::Right(sibling) => H::hash(&[*sibling, hash]).map_err(Into::into),
})
}
}

View File

@@ -7,32 +7,30 @@
// Merkle tree implementations are adapted from https://github.com/kilic/rln/blob/master/src/merkle.rs
// and https://github.com/worldcoin/semaphore-rs/blob/d462a4372f1fd9c27610f2acfe4841fab1d396aa/src/merkle_tree.rs
//!
//! # TODO
//!
//! * Disk based storage backend (using mmaped files should be easy)
//! * Implement serialization for tree and Merkle proof
use crate::merkle_tree::error::ZerokitMerkleTreeError;
use std::{
fmt::{Debug, Display},
str::FromStr,
};
use super::error::ZerokitMerkleTreeError;
/// Enables parallel hashing when there are at least 8 nodes (4 pairs to hash), justifying the overhead.
pub const MIN_PARALLEL_NODES: usize = 8;
/// In the Hasher trait we define the node type, the default leaf
/// and the hash function used to initialize a Merkle Tree implementation
/// In the Hasher trait we define the node type, the default leaf,
/// and the hash function used to initialize a Merkle Tree implementation.
pub trait Hasher {
/// Type of the leaf and tree node
type Fr: Clone + Copy + Eq + Default + Debug + Display + FromStr + Send + Sync;
/// Error type for hash operations - must be convertible to ZerokitMerkleTreeError
type Error: Into<ZerokitMerkleTreeError> + std::error::Error + Send + Sync + 'static;
/// Returns the default tree leaf
fn default_leaf() -> Self::Fr;
/// Utility to compute the hash of an intermediate node
fn hash(input: &[Self::Fr]) -> Self::Fr;
fn hash(input: &[Self::Fr]) -> Result<Self::Fr, Self::Error>;
}
pub type FrOf<H> = <H as Hasher>::Fr;
@@ -85,7 +83,7 @@ pub trait ZerokitMerkleTree {
fn verify(
&self,
leaf: &FrOf<Self::Hasher>,
witness: &Self::Proof,
merkle_proof: &Self::Proof,
) -> Result<bool, ZerokitMerkleTreeError>;
fn set_metadata(&mut self, metadata: &[u8]) -> Result<(), ZerokitMerkleTreeError>;
fn metadata(&self) -> Result<Vec<u8>, ZerokitMerkleTreeError>;
@@ -100,5 +98,8 @@ pub trait ZerokitMerkleProof {
fn leaf_index(&self) -> usize;
fn get_path_elements(&self) -> Vec<FrOf<Self::Hasher>>;
fn get_path_index(&self) -> Vec<Self::Index>;
fn compute_root_from(&self, leaf: &FrOf<Self::Hasher>) -> FrOf<Self::Hasher>;
fn compute_root_from(
&self,
leaf: &FrOf<Self::Hasher>,
) -> Result<FrOf<Self::Hasher>, ZerokitMerkleTreeError>;
}

View File

@@ -4,8 +4,7 @@ pub mod full_merkle_tree;
pub mod merkle_tree;
pub mod optimal_merkle_tree;
pub use self::full_merkle_tree::{FullMerkleConfig, FullMerkleProof, FullMerkleTree};
pub use self::merkle_tree::{
FrOf, Hasher, ZerokitMerkleProof, ZerokitMerkleTree, MIN_PARALLEL_NODES,
};
pub use self::optimal_merkle_tree::{OptimalMerkleConfig, OptimalMerkleProof, OptimalMerkleTree};
pub use error::{FromConfigError, ZerokitMerkleTreeError};
pub use full_merkle_tree::{FullMerkleConfig, FullMerkleProof, FullMerkleTree};
pub use merkle_tree::{FrOf, Hasher, ZerokitMerkleProof, ZerokitMerkleTree, MIN_PARALLEL_NODES};
pub use optimal_merkle_tree::{OptimalMerkleConfig, OptimalMerkleProof, OptimalMerkleTree};

View File

@@ -2,13 +2,12 @@ use std::{cmp::max, collections::HashMap, fmt::Debug, str::FromStr};
use rayon::iter::{IntoParallelIterator, ParallelIterator};
use crate::merkle_tree::{
use super::{
error::{FromConfigError, ZerokitMerkleTreeError},
FrOf, Hasher, ZerokitMerkleProof, ZerokitMerkleTree, MIN_PARALLEL_NODES,
merkle_tree::{FrOf, Hasher, ZerokitMerkleProof, ZerokitMerkleTree, MIN_PARALLEL_NODES},
};
////////////////////////////////////////////////////////////
///// Optimal Merkle Tree Implementation
////////////////////////////////////////////////////////////
// Optimal Merkle Tree Implementation
/// The Merkle tree structure
#[derive(Clone, PartialEq, Eq, Debug)]
@@ -80,7 +79,7 @@ where
let mut cached_nodes: Vec<H::Fr> = Vec::with_capacity(depth + 1);
cached_nodes.push(default_leaf);
for i in 0..depth {
cached_nodes.push(H::hash(&[cached_nodes[i]; 2]));
cached_nodes.push(H::hash(&[cached_nodes[i]; 2]).map_err(Into::into)?);
}
cached_nodes.reverse();
@@ -198,7 +197,10 @@ where
J: ExactSizeIterator<Item = usize>,
{
let indices = indices.into_iter().collect::<Vec<_>>();
let min_index = *indices.first().expect("indices should not be empty");
if indices.is_empty() {
return Err(ZerokitMerkleTreeError::InvalidIndices);
}
let min_index = indices[0];
let leaves_vec = leaves.into_iter().collect::<Vec<_>>();
let max_index = start + leaves_vec.len();
@@ -249,10 +251,7 @@ where
let mut depth = self.depth;
loop {
i ^= 1;
witness.push((
self.get_node(depth, i),
(1 - (i & 1)).try_into().expect("0 or 1 expected"),
));
witness.push((self.get_node(depth, i), (1 - (i & 1)) as u8));
i >>= 1;
depth -= 1;
if depth == 0 {
@@ -267,11 +266,15 @@ where
}
/// Verifies a Merkle proof with respect to the input leaf and the tree root
fn verify(&self, leaf: &H::Fr, witness: &Self::Proof) -> Result<bool, ZerokitMerkleTreeError> {
if witness.length() != self.depth {
return Err(ZerokitMerkleTreeError::InvalidWitness);
fn verify(
&self,
leaf: &H::Fr,
merkle_proof: &Self::Proof,
) -> Result<bool, ZerokitMerkleTreeError> {
if merkle_proof.length() != self.depth {
return Err(ZerokitMerkleTreeError::InvalidMerkleProof);
}
let expected_root = witness.compute_root_from(leaf);
let expected_root = merkle_proof.compute_root_from(leaf)?;
Ok(expected_root.eq(&self.root()))
}
@@ -301,9 +304,9 @@ where
/// Computes the hash of a nodes two children at the given depth.
/// If the index is odd, it is rounded down to the nearest even index.
fn hash_couple(&self, depth: usize, index: usize) -> H::Fr {
fn hash_couple(&self, depth: usize, index: usize) -> Result<H::Fr, ZerokitMerkleTreeError> {
let b = index & !1;
H::hash(&[self.get_node(depth, b), self.get_node(depth, b + 1)])
H::hash(&[self.get_node(depth, b), self.get_node(depth, b + 1)]).map_err(Into::into)
}
/// Updates parent hashes after modifying a range of leaf nodes.
@@ -327,25 +330,29 @@ where
// Use parallel processing when the number of pairs exceeds the threshold
if current_index_max - current_index >= MIN_PARALLEL_NODES {
let updates: Vec<((usize, usize), H::Fr)> = (current_index..current_index_max)
#[allow(clippy::type_complexity)]
let updates: Result<
Vec<((usize, usize), H::Fr)>,
ZerokitMerkleTreeError,
> = (current_index..current_index_max)
.step_by(2)
.collect::<Vec<_>>()
.into_par_iter()
.map(|index| {
// Hash two child nodes at positions (current_depth, index) and (current_depth, index + 1)
let hash = self.hash_couple(current_depth, index);
let hash = self.hash_couple(current_depth, index)?;
// Return the computed parent hash and its position at
((parent_depth, index >> 1), hash)
Ok(((parent_depth, index >> 1), hash))
})
.collect();
for (parent, hash) in updates {
for (parent, hash) in updates? {
self.nodes.insert(parent, hash);
}
} else {
// Otherwise, fallback to sequential update for small ranges
for index in (current_index..current_index_max).step_by(2) {
let hash = self.hash_couple(current_depth, index);
let hash = self.hash_couple(current_depth, index)?;
self.nodes.insert((parent_depth, index >> 1), hash);
}
}
@@ -393,16 +400,16 @@ where
}
/// Computes the Merkle root corresponding by iteratively hashing a Merkle proof with a given input leaf
fn compute_root_from(&self, leaf: &H::Fr) -> H::Fr {
fn compute_root_from(&self, leaf: &H::Fr) -> Result<H::Fr, ZerokitMerkleTreeError> {
let mut acc: H::Fr = *leaf;
for w in self.0.iter() {
if w.1 == 0 {
acc = H::hash(&[acc, w.0]);
acc = H::hash(&[acc, w.0]).map_err(Into::into)?;
} else {
acc = H::hash(&[w.0, acc]);
acc = H::hash(&[w.0, acc]).map_err(Into::into)?;
}
}
acc
Ok(acc)
}
}

View File

@@ -1,4 +1,7 @@
#![cfg(feature = "pmtree-ft")]
pub mod sled_adapter;
pub use self::sled_adapter::SledDB;
pub use pmtree;
pub use sled::{Config, Mode};
pub use sled_adapter::SledDB;

View File

@@ -1,9 +1,7 @@
use pmtree::*;
use std::{collections::HashMap, thread, time::Duration};
use pmtree::*;
use sled::Db as Sled;
use std::collections::HashMap;
use std::thread;
use std::time::Duration;
pub struct SledDB(Sled);
@@ -19,17 +17,17 @@ impl SledDB {
}
match config.open() {
Ok(db) => Ok(SledDB(db)),
Err(e) if e.to_string().contains("WouldBlock") => {
Err(err) if err.to_string().contains("WouldBlock") => {
// try till the fd is freed
// sleep for 10^tries milliseconds, then recursively try again
thread::sleep(Duration::from_millis(10u64.pow(tries)));
Self::new_with_tries(config, tries + 1)
}
Err(e) => {
Err(err) => {
// On any other error, we return immediately.
Err(PmtreeErrorKind::DatabaseError(
DatabaseErrorKind::CustomError(format!(
"Cannot create database: {e} {config:#?}"
"Cannot create database: {err} {config:#?}"
)),
))
}
@@ -48,9 +46,9 @@ impl Database for SledDB {
fn load(config: Self::Config) -> PmtreeResult<Self> {
let db = match config.open() {
Ok(db) => db,
Err(e) => {
Err(err) => {
return Err(PmtreeErrorKind::DatabaseError(
DatabaseErrorKind::CustomError(format!("Cannot load database: {e}")),
DatabaseErrorKind::CustomError(format!("Cannot load database: {err}")),
))
}
};

Some files were not shown because too many files have changed in this diff Show More