Skip to content

Commit

Permalink
Fix examples.
Browse files Browse the repository at this point in the history
  • Loading branch information
mmaker committed Jan 26, 2024
1 parent effccf9 commit 249102b
Show file tree
Hide file tree
Showing 10 changed files with 100 additions and 258 deletions.
2 changes: 2 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

14 changes: 7 additions & 7 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -28,15 +28,14 @@ ark-ff = {version="0.4.0", optional=true}
ark-ec = {version="0.4.0", optional=true}
ark-serialize = {version="0.4.2", optional=true}
ark-crypto-primitives = {version="0.4.0", optional=true}
curve25519-dalek = {version="4.0.0", optional=true}
curve25519-dalek = {version="4.0.0", optional=true, features=["group"]}
# anemoi = {git = "https://github.com/anemoi-hash/anemoi-rust", optional=true}
group = {version="0.13.0", optional=true}

[features]
default = []
arkworks = ["dep:ark-ff", "dep:ark-ec", "dep:ark-serialize", "dep:ark-crypto-primitives"]
dalek = ["dep:curve25519-dalek"]
zkcrypto = ["dep:group"]
ark = ["dep:ark-ff", "dep:ark-ec", "dep:ark-serialize", "dep:ark-crypto-primitives"]
group = ["dep:group", "dep:curve25519-dalek"]
# anemoi = ["dep:anemoi"]

[dev-dependencies]
Expand All @@ -47,17 +46,18 @@ ark-curve25519 = "0.4.0"
hex = "0.4.3"
anyhow = { version = "1.0.75", features = ["backtrace"] }


[package.metadata.docs.rs]
rustdoc-args = [
"--html-in-header", "doc/katex-header.html",
"--cfg", "docsrs",
]
features = ["arkworks", "dalek"]
features = ["ark", "group"]

[[example]]
name = "schnorr"
required-features = ["arkworks"]
required-features = ["ark"]

[[example]]
name = "bulletproof"
required-features = ["arkworks"]
required-features = ["ark"]
80 changes: 39 additions & 41 deletions examples/bulletproof.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,37 +2,9 @@ use ark_ec::PrimeGroup;
use ark_ec::{AffineRepr, CurveGroup, VariableBaseMSM};
use ark_ff::Field;
use ark_std::log2;
use nimue::plugins::arkworks::*;
use nimue::{Arthur, Merlin, ProofError, ProofResult};
use nimue::plugins::ark::*;
use rand::rngs::OsRng;

fn fold_generators<A: AffineRepr>(
a: &[A],
b: &[A],
x: &A::ScalarField,
y: &A::ScalarField,
) -> Vec<A> {
a.iter()
.zip(b.iter())
.map(|(&a, &b)| (a * x + b * y).into_affine())
.collect()
}

/// Computes the inner prouct of vectors `a` and `b`.
///
/// Useless once https://github.com/arkworks-rs/algebra/pull/665 gets merged.
fn dot_prod<F: Field>(a: &[F], b: &[F]) -> F {
a.iter().zip(b.iter()).map(|(&a, &b)| a * b).sum()
}

/// Folds together `(a, b)` using challenges `x` and `y`.
fn fold<F: Field>(a: &[F], b: &[F], x: &F, y: &F) -> Vec<F> {
a.iter()
.zip(b.iter())
.map(|(&a, &b)| a * x + b * y)
.collect()
}

/// The IO Pattern of a bulleproof.
///
/// Defining this as a trait allows us to "attach" the bulletproof IO to
Expand All @@ -42,10 +14,11 @@ trait BulletproofIOPattern<G: CurveGroup> {
fn add_bulletproof(self, len: usize) -> Self;
}

impl<G: CurveGroup> BulletproofIOPattern<G> for ArkGroupIOPattern<G> {
/// The IO of the bulletproof statement (the sole commitment)
impl<G, H> BulletproofIOPattern<G> for IOPattern<H>
where G: CurveGroup, H: DuplexHash, IOPattern<H>: GroupIOPattern<G>{
/// The IO of the bulletproof statement
fn bulletproof_statement(self) -> Self {
self.add_points(1, "Ped-commit")
self.add_points(1, "Pedersen commitment")
}

/// The IO of the bulletproof protocol
Expand Down Expand Up @@ -143,6 +116,33 @@ fn verify<G: CurveGroup>(
}
}

fn fold_generators<A: AffineRepr>(
a: &[A],
b: &[A],
x: &A::ScalarField,
y: &A::ScalarField,
) -> Vec<A> {
a.iter()
.zip(b.iter())
.map(|(&a, &b)| (a * x + b * y).into_affine())
.collect()
}

/// Computes the inner prouct of vectors `a` and `b`.
///
/// Useless once https://github.com/arkworks-rs/algebra/pull/665 gets merged.
fn dot_prod<F: Field>(a: &[F], b: &[F]) -> F {
a.iter().zip(b.iter()).map(|(&a, &b)| a * b).sum()
}

/// Folds together `(a, b)` using challenges `x` and `y`.
fn fold<F: Field>(a: &[F], b: &[F], x: &F, y: &F) -> Vec<F> {
a.iter()
.zip(b.iter())
.map(|(&a, &b)| a * x + b * y)
.collect()
}

fn main() {
use ark_curve25519::EdwardsProjective as G;
use ark_std::UniformRand;
Expand All @@ -154,13 +154,11 @@ fn main() {
let size = 8;

// initialize the IO Pattern putting the domain separator ("example.com")
let io_pattern = ArkGroupIOPattern::<G>::new("example.com")
// add the IO of the bulletproof statement (the commitment)
.bulletproof_statement()
// (optional) process the data so far, filling the block till the end.
.ratchet()
// add the IO of the bulletproof protocol (the transcript)
.add_bulletproof(size);
let iopattern = IOPattern::new("example.com");
// add the IO of the bulletproof statement
let iopattern = BulletproofIOPattern::<G>::bulletproof_statement(iopattern).ratchet();
// add the IO of the bulletproof protocol (the transcript)
let iopattern = BulletproofIOPattern::<G>::add_bulletproof(iopattern, size);

// the test vectors
let a = (0..size).map(|x| F::from(x as u32)).collect::<Vec<_>>();
Expand All @@ -181,7 +179,7 @@ fn main() {
let statement = G::msm_unchecked(&g, &a) + G::msm_unchecked(&h, &b) + u * ab;
let witness = (&a[..], &b[..]);

let mut arthur = io_pattern.to_arthur();
let mut arthur = iopattern.to_arthur();
arthur.public_points(&[statement]).unwrap();
arthur.ratchet().unwrap();
let proof = prove(&mut arthur, generators, &statement, witness).expect("Error proving");
Expand All @@ -191,7 +189,7 @@ fn main() {
hex::encode(proof)
);

let mut verifier_transcript = io_pattern.to_merlin(proof);
let mut verifier_transcript = iopattern.to_merlin(proof);
verifier_transcript.public_points(&[statement]).unwrap();
verifier_transcript.ratchet().unwrap();
verify(&mut verifier_transcript, generators, size, &statement).expect("Invalid proof");
Expand Down
53 changes: 37 additions & 16 deletions examples/schnorr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,30 @@
///
use ark_ec::{CurveGroup, PrimeGroup};
use ark_std::UniformRand;
use nimue::plugins::arkworks::*;
use nimue::Arthur;
use nimue::{DuplexHash, ProofResult};
use nimue::plugins::ark::*;
use rand::rngs::OsRng;

/// Extend the IO pattern with the Schnorr protocol.
trait SchnorrIOPattern<G: CurveGroup> {
/// Adds the entire Schnorr protocol to the IO pattern (statement and proof).
fn add_schnorr_io(self) -> Self;
}

impl<G, H> SchnorrIOPattern<G> for IOPattern<H>
where
G: CurveGroup,
H: DuplexHash,
IOPattern<H>: GroupIOPattern<G> {
fn add_schnorr_io(self) -> Self {
self.add_points(1, "P")
.add_points(1, "X")
.ratchet()
.add_points(1, "commitment (K)")
.challenge_scalars(1, "challenge (c)")
.add_scalars(1, "response (r)")
}
}

/// The key generation algorithm otuputs
/// a secret key `sk` in $\mathbb{Z}_p$
/// and its respective public key `pk` in $\mathbb{G}$.
Expand Down Expand Up @@ -72,16 +91,23 @@ where
for<'a> Merlin<'a, H>: GroupReader<G>,
{
// Read the protocol from the transcript:
let [K]: [G; 1] = merlin.next_points().unwrap();
let [c]: [G::ScalarField; 1] = merlin.challenge_scalars().unwrap();
let [r]: [G::ScalarField; 1] = merlin.challenge_scalars().unwrap();
let [K] = merlin.next_points().unwrap();
let [c] = merlin.challenge_scalars().unwrap();
let [r] = merlin.next_scalars().unwrap();

// Check the verification equation, otherwise return a verification error.
// The type ProofError is an enum that can report:
// - InvalidProof: the proof is not valid
// - InvalidIO: the transcript does not match the IO pattern
// - SerializationError: there was an error serializing/deserializing an element
if P * r == K + X * c {
Ok(())
} else {
Err(nimue::ProofError::InvalidProof)
}

// from here, another proof can be verified using the same merlin instance
// and proofs can be composed.
}

#[allow(non_snake_case)]
Expand All @@ -90,18 +116,13 @@ fn main() {
// Set the group:
type G = ark_curve25519::EdwardsProjective;
// Set the hash function (commented out other valid choices):
type H = nimue::hash::Keccak;
// type H = nimue::legacy::DigestBridge<blake2::Blake2s256>;
// type H = nimue::legacy::DigestBridge<sha2::Sha256>;
// type H = nimue::hash::Keccak;
type H = nimue::hash::legacy::DigestBridge<blake2::Blake2s256>;
// type H = nimue::hash::legacy::DigestBridge<sha2::Sha256>;

// Set up the IO for the protocol transcript with domain separator "nimue::examples::schnorr"
let io = ArkGroupIOPattern::<G, H>::new("nimue::examples::schnorr")
.add_points(1, "P")
.add_points(1, "X")
.ratchet()
.add_points(1, "commitment (K)")
.challenge_scalars(1, "challenge (c)")
.add_scalars(1, "response (r)");
let io = IOPattern::<H>::new("nimue::examples::schnorr");
let io = SchnorrIOPattern::<G>::add_schnorr_io(io);

// Set up the elements to prove
let P = G::generator();
Expand Down
5 changes: 1 addition & 4 deletions src/hash/legacy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,6 @@
//! `squeeze_unchecked` will use the squeeze oracle to output `output.len()` bytes,
//! and finally `squeeze_end` will set the state `cv` to the current squeeze digest and length.
//!
use core::mem::size_of;

use digest::{core_api::BlockSizeUser, typenum::Unsigned, Digest, FixedOutputReset, Reset};
use generic_array::GenericArray;
use zeroize::Zeroize;
Expand Down Expand Up @@ -119,7 +116,7 @@ impl<D: BlockSizeUser + Digest + Clone + FixedOutputReset> Default for DigestBri

impl<D: BlockSizeUser + Digest + Clone + FixedOutputReset> DuplexHash<u8> for DigestBridge<D> {
fn new(tag: [u8; 32]) -> Self {
debug_assert!(size_of::<D::OutputSize>() >= 32);
// debug_assert!(size_of::<D::OutputSize>() >= 32);
let mut bridge = Self::default();
bridge.absorb_unchecked(&tag);
bridge
Expand Down
5 changes: 4 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,8 @@ mod arthur;
mod errors;
/// Hash functions traits and implmentations.
pub mod hash;
/// IO Pattern
mod iopattern;
/// Verifier state and transcript deserialization.
mod merlin;
/// APIs for common zkp libraries.

Check warning on line 135 in src/lib.rs

View workflow job for this annotation

GitHub Actions / deploy

unresolved link to `plugins::arkworks`

Check warning on line 135 in src/lib.rs

View workflow job for this annotation

GitHub Actions / deploy

unresolved link to `plugins::dalek`
Expand All @@ -143,8 +145,9 @@ pub mod traits;
pub use arthur::Arthur;
pub use errors::{IOPatternError, ProofError, ProofResult};
pub use hash::{DuplexHash, Unit};
pub use iopattern::IOPattern;
pub use merlin::Merlin;
pub use safe::{IOPattern, Safe};
pub use safe::Safe;
pub use traits::*;

/// Default random number generator used ([`rand::rngs::OsRng`]).
Expand Down
3 changes: 2 additions & 1 deletion src/merlin.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use crate::errors::IOPatternError;
use crate::hash::{DuplexHash, Unit};
use crate::safe::{IOPattern, Safe};
use crate::iopattern::IOPattern;
use crate::safe::Safe;
use crate::traits::{ByteTranscript, ByteTranscriptReader};
use crate::DefaultHash;

Expand Down
Loading

0 comments on commit 249102b

Please sign in to comment.