A pure Rust PLONK implementation using arkworks as a backend.

Related tags

Utilities ark-plonk
Overview

PLONK

Build Status Repository Documentation

This is a pure Rust implementation of the PLONK zk proving system

Usage

use ark_plonk::prelude::*;
use ark_ec::bls12::Bls12;
use rand_core::OsRng;


// Implement a circuit that checks:
// 1) a + b = c where C is a PI
// 2) a <= 2^6
// 3) b <= 2^5
// 4) a * b = d where D is a PI
// 5) JubJub::GENERATOR * e(JubJubScalar) = f where F is a Public Input
#[derive(Debug, Default)]
pub struct TestCircuit {
    a: Fr,
    b: Fr,
    c: Fr,
    d: Fr,
    e: JubJubScalar,
    f: JubJubAffine,
}
///XXX: TODO: Swap out JubJub for arkworks embedded curves
impl Circuit for TestCircuit {
    const CIRCUIT_ID: [u8; 32] = [0xff; 32];
    fn gadget(
        &mut self,
        composer: &mut StandardComposer,
    ) -> Result<(), Error> {
        let a = composer.add_input(self.a);
        let b = composer.add_input(self.b);
        // Make first constraint a + b = c
        composer.poly_gate(
            a,
            b,
            composer.zero_var(),
            Bls12::Fr::zero(),
            Bls12::Fr::one(),
            Bls12::Fr::one(),
            Bls12::Fr::zero(),
            Bls12::Fr::zero(),
            Some(-self.c),
        );
        // Check that a and b are in range
        composer.range_gate(a, 1 << 6);
        composer.range_gate(b, 1 << 5);
        // Make second constraint a * b = d
        composer.poly_gate(
            a,
            b,
            composer.zero_var(),
            Bls12::Fr::one(),
            Bls12::Fr::zero(),
            Bls12::Fr::zero(),
            Bls12::Fr::one(),
            Bls12::Fr::zero(),
            Some(-self.d),
        );

        let e = composer.add_input(self.e.into());
        let scalar_mul_result = composer
            .fixed_base_scalar_mul(e, dusk_jubjub::GENERATOR_EXTENDED);
        // Apply the constrain
        composer.assert_equal_public_point(scalar_mul_result, self.f);
        Ok(())
    }
    fn padded_circuit_size(&self) -> usize {
        1 << 11
    }
}

// Now let's use the Circuit we've just implemented!

let pp = PublicParameters::setup(1 << 12, &mut OsRng).unwrap();
// Initialize the circuit
let mut circuit = TestCircuit::default();
// Compile the circuit
let (pk, vd) = circuit.compile(&pp).unwrap();
// Prover POV
let proof = {
    let mut circuit = TestCircuit {
        a: Bls12::Fr::from(20u64),
        b: Bls12::Fr::from(5u64),
        c: Bls12::Fr::from(25u64),
        d: Bls12::Fr::from(100u64),
        e: JubJubScalar::from(2u64),
        f: JubJubAffine::from(
            dusk_jubjub::GENERATOR_EXTENDED * JubJubScalar::from(2u64),
        ),
    };
    circuit.gen_proof(&pp, &pk, b"Test").unwrap()
};
// Verifier POV
let public_inputs: Vec<PublicInputValue> = vec![
    Bls12::Fr::from(25u64).into(),
    Bls12::Fr::from(100u64).into(),
    JubJubAffine::from(
        dusk_jubjub::GENERATOR_EXTENDED * JubJubScalar::from(2u64),
    )
    .into(),
];
circuit::verify_proof(
    &pp,
    &vd.key(),
    &proof,
    &public_inputs,
    &vd.pi_pos(),
    b"Test",
).unwrap();

Features

This crate includes a variety of features which will briefly be explained below:

  • alloc: Enables the usage of an allocator and with it the capability of performing Proof constructions and verifications. Without this feature it IS NOT possible to prove or verify anything. Its absence only makes ark-plonk export certain fixed-size data structures such as Proof which can be useful in no_std envoirments where we don't have allocators either.
  • std: Enables std usage as well as rayon parallelisation in some proving and verifying ops.
  • trace: Enables the Circuit debugger tooling. This is essentially the capability of using the StandardComposer::check_circuit_satisfied function. The function will output information about each circuit gate until one of the gates does not satisfy the equation, or there are no more gates. If there is an unsatisfied gate equation, the function will panic and return the gate number.
  • trace-print: Goes a step further than trace and prints each gate component data, giving a clear overview of all the values which make up the circuit that we're constructing. The recommended method is to derive the std output, and the std error, and then place them in text file which can be used to efficiently analyse the gates.

Documentation

There are two main types of documentation in this repository:

  • Crate documentation. This provides info about all of the functions that the library provides, as well as the documentation regarding the data structures that it exports. To check this, please feel free to go to the documentation page or run make doc or make doc-internal.

  • Notes. This is a specific subset of documentation which explains the key mathematical concepts of PLONK and how they work with mathematical demonstrations. To check it, run make doc and open the resulting docs, which will be located under /target with your browser.

Performance

TODO

Acknowledgements

Licensing

This code is licensed under Mozilla Public License Version 2.0 (MPL-2.0). Please see LICENSE for further info.

About

Initial implementation created by Kev, Carlos and Luke at Dusk Network. Redesigned by the rust zkp team to have a backend which is compatible with the arkworks suite. This allows us to leverage the multitude of curves and optimised algebra present in various arkworks repositories.

Contributing

  • If you want to contribute to this repository/project please, check CONTRIBUTING.md
  • If you want to report a bug or request a new feature addition, please open an issue on this repository.
Comments
  • Refactor Public Inputs and add them to the transcript

    Refactor Public Inputs and add them to the transcript

    In this PR we have added the Public Inputs to the transcript as the first step of the prove and verify algorithms. They have been added as the evaluations of the PI polynomial over the used domain (n field elements).

    Close #133

    T-bug T-refactor 
    opened by davidnevadoc 15
  • Add `big_arith_gate` and conditional point negate

    Add `big_arith_gate` and conditional point negate

    This PR adds the following gate:

    • big_arith_gate enforces (a*b)*q_m + a*q_l + b*q_r + d*q_4 + q_c + PI + q_o * c = 0 and returns c
    • big_arith compute and enforces c = (a*b)*q_m + a*q_l + b*q_r + d*q_4 + q_c + PI, and returns c
    • conditional_point_neg returns -point if bit = 1 and point if bit = 0

    Thanks for review!

    opened by tsunrise 14
  • Refactor away from PairingEngine + misc type changes

    Refactor away from PairingEngine + misc type changes

    Summary of changes:

    1. Refactor anything that is only dependent on the scalar field to not depend on PairingEngine (unfortunately this means there's a lot of E::Fr -> F changes in the diff)
    2. Move dependence on TEModelParams to other places and not Circuit/StandardComposer. In practice this means (I think) the implementation of the fixed-base ECC gadget is determined later, and the variable-base ECC gadget depends on the params but not the rest of the circuit.
    3. Suggested change to remove the TranscriptWrapper type
    4. Minor change to Permutation generic types (can be reversed)
    5. Some other minor tweaks to types (can be reversed). I was mostly just experimenting to see what might be slightly cleaner.

    In summary this PR is not really ready to be merged, but open to input and feedback.

    opened by joebebel 12
  • Not enough variety in `add_dummy_constraints` can cause commitment errors for circuits of length 2^k before padding

    Not enough variety in `add_dummy_constraints` can cause commitment errors for circuits of length 2^k before padding

    The function add_dummy_constraints uses two arithmetic gates to add witnesses to the circuit. If the circuit itself also uses only arithmetic gates AND the total number of gates is a power of 2, then the circuit is never padded with 0s and the q_arith vector becomes constant which causes an error when committing to q_arith_poly.

    Although this is unlikely to happen in a production circuit with many gates it can easily happen in tests of small subcircuits.

    Until we implement lookups, all gates (including range, logic, etc.) resolve to arithmetic gates, so it might be tricky to make this work until lookups are enabled and we have a second "elemental" gate. But there may be a way to do it sooner by using an arithmetic selector value > 1.

    opened by lopeetall 9
  • Better Test Framework / Making `gadget_tester` Public

    Better Test Framework / Making `gadget_tester` Public

    I really like the gadget_tester in ark-plonk, which makes writing end-to-end tests much easier, but this gadget is pub(crate) so user cannot access it...

    I believe many users will end up writing their own gadgets (for gadgets, I mean any function that includes StandardComposer as a parameter). Can we make the following public:

    • gadget_tester
    • batch_test!

    If there is any reason that prevents doing so, shall we have a good testing framework? Writing end-to-end tests for a gadget from scratch is a bit verbose.

    Thanks!

    opened by tsunrise 8
  • Fix CI missing `uses` parameter in Run clippy

    Fix CI missing `uses` parameter in Run clippy

    In #38 an error was introduced in the CI so that it wasn't possible to run them since they were panicking before starting.

    • Edit the CI config and move clippy to a sepparated job.
    • Edit the CI config and add global RUSTFLAGS env var.
    • Edit the CI config and use better toolchain config.

    Resolves: #39

    Co-authored-by: Brandon H. Gomes [email protected]

    opened by CPerezz 8
  • Consolidate naming for arithmetic Composer gates

    Consolidate naming for arithmetic Composer gates

    I see the naming convention as follows:

    • The methods that have a _gate sufix (add_gate, mul_gate...) do not compute values, they receive as input the relevant wire values and selectors of the gate and check that the equation holds. The methods that do not have the _gate sufix (add, mul...) compute the output value w_o and always generate a satisfied constraint.
    • The methods with big_ prefix receive a 4th wire, those without the prefix don´t.

    I think big_arith and big_arith_gate fit in the same family as poly_gate so we should choose a common name for all of them: poly or arith.

    Originally posted by @davidnevadoc in https://github.com/rust-zkp/ark-plonk/pull/43#discussion_r758801320

    D-easy P-medium T-design T-refactor 
    opened by CPerezz 7
  • Todd/is eq gate

    Todd/is eq gate

    Adds some gates that can be useful in combination with conditional selection.  They are 

    • is-zero-gate Has one input variable and one output variable.  The output variable is constrained to have the value 1 if the input is zero and to have the value 0 if the input is non-zero.
    • is-eq-gate has two input variables and an output variable which is constrained to have the value 1 if the two inputs have equal values and 0 otherwise.

    The gates were added in the boolean submodule of the constraint_system module.  This seemed logical to me but should be checked.  

    closes #76

    D-medium 
    opened by GhostOfGauss 6
  • Fix broken doc link

    Fix broken doc link

    The broken link is coming from the plonk-book. We need investigation into why it won't work.

    At the moment it is a blocker so we will ignore the infra-link on the PR's

    cc: @CPerezz @mathcrypto @markulf

    P-medium T-bug T-refactor 
    opened by LukePearson1 5
  • Update and Extend Documentation

    Update and Extend Documentation

    Starting with broken links. But any other kind of documentation is also welcome. Might by its very nature, documentation is never finished, be broken up into multiple pull requests.

    opened by markulf 5
  • Define library design.

    Define library design.

    Currently this library has only an implementation of PLONK. In the coming weeks, we will be using the core functional to power gadgets as discussed in #54, and a hashing library. The initial idea was to have these as separate libraries under the organisation. However, given the past difficulty of juggling lots of version updates, I think we should consider placing gadgets and hashing inside this one repo as modules. I see this as a successful approach in many projects.

    It may also help with the exposing of witness values inside of variables, such with the mod_arith gadget that would be needed for the implementation of reinforced concrete. However, this warrants more thought wrt the exposing of modules.

    WDYT? @bhgomes @lopeetall @CPerezz @NoCtrlZ @tsunrise @julesdesmit @joebebel @EDGDrummond @stechu @iquerejeta @davidnevadoc @drewstone @GhostOfGauss @mathcrypto @markulf

    opened by LukePearson1 5
  • poseidon hash

    poseidon hash

    This PR implements 2-in-1-out Poseidon hash circuit with <200 constraints.

    It has the following components:

    • a degree 5 custom gate
    • a circuit implementation of Poseidon with this custom gate
    opened by zhenfeizhang 0
  • [WIP] Short Weierstrass curve support

    [WIP] Short Weierstrass curve support

    We need some short weierstrass support for some things, so here is a WIP (only curve addition, not scalar mul yet)

    I did some traits magic to allow for compile-time selection of TE or SW for the embedded curve (there may be better ways to do it, though)

    I also added the polynomial commitment back into the new CircuitParameters that StandardComposer is generic over, but this is not necessary, it could go back to adding PolynomialCommitment later in the process.

    Until Rust merges Chalk type inference, some of the type syntax is crazy, but in the future it should be better.

    Feedback welcome :)

    opened by joebebel 0
  • Increase blinding

    Increase blinding

    Increases the default blinding so that it works with PC schemes that are both naturally hiding or not. Introduces 2 uncessary rows for the case that the PC scheme is naturally hiding.

    opened by CarloModicaPortfolio 0
  • Proper transcript handling

    Proper transcript handling

    After the discussion on how to properly add the Public Inputs to the transcript (#134 ) we found that other parts of the code were also mishandling the transcript. For the addition of custom gate related evaluations:

    • https://github.com/ZK-Garage/plonk/blob/377c45f2a7e516007ac407255364af29b7decbec/plonk-core/src/proof_system/proof.rs#L288-L295

    This issue should be addressed together with the new design for custom gates in #128

    opened by davidnevadoc 0
  • Use batch commitment scheme and commit only polynomial linear combination

    Use batch commitment scheme and commit only polynomial linear combination

    • Create linear combination of "aw" and "saw" polynomials and commit to it instead of every single polynomial
    • Use batched version of polynomial commitment scheme to reduce number of pairing checks
    T-feature T-performance 
    opened by akinovak 1
Owner
rust-zkp
Work group of Zero Knowledge Crypto developers
rust-zkp
Pure rust implementation of jq

XQ JQ reimplemented purely in Rust. Caution This program is under development. You probably want to use the original implementation of jq, or pure Go

null 181 Jan 4, 2023
Svix - A pure Rust and fully tested KSUID implementation

Svix - Webhooks as a service Svix-KSUID (Rust) A pure Rust and fully tested KSUID implementation This library is fully compatible with Segment's KSUID

Svix 48 Jan 3, 2023
Pure rust implementation of python's random module with compatible generator behaviour.

pyrand Pure rust implementation of (parts of) python's random module with compatible PRNG behaviour: seeding with equivalent values will yield identic

Stefan V. 4 Feb 10, 2024
A principled BSDF pathtracer with an abstracted backend. Perfect for rendering procedural content.

This is a port of the excellent GLSL_Pathtracer to Rust utilizing an abstracted, trait based backend. Perfect for rendering procedural content. Rust F

Markus Moenig 5 Nov 23, 2022
A Zincati lock backend for stateful workloads.

This repository is deprecated. We realized CoreOS is probably not a good fit for us. The repository will be kept up on the off chance that this is use

Open Computing Facility 6 Dec 7, 2022
Rustymind is a driver and parser for NeuroSky MindWave EEG headset written in pure Rust.

Rustymind is a driver and parser for NeuroSky MindWave EEG headset written in pure Rust. You can use it to connect, interact, and plot real time data from the headset.

Junjun Dong 34 Sep 13, 2022
A program written in pure Rust to query music info from mpd and display it in a notification.

musinfo A program written in pure Rust to query music info from mpd and display it in a notification. Note: Cover art is expected to be placed at /tmp

Cpt.Howdy 10 Aug 16, 2022
Wait Service is a pure rust program to test and wait on the availability of a service.

Wait Service Wait Service is a pure rust program to test and wait on the availability of a service.

Magic Len (Ron Li) 3 Jan 18, 2022
mollusc is a collection of pure-Rust libraries for parsing, interpreting, and analyzing LLVM.

mollusc is a collection of pure-Rust libraries for parsing, interpreting, and analyzing LLVM.

William Woodruff 50 Dec 2, 2022
Program a Raspberry Pi Pico with pure Rust

pi-pico-rs Program a Raspberry Pi Pico with pure Rust. Get Started Install the latest version of Rust and the thumbv6m-none-eabi target. This is the p

Gerald Nash 5 Jul 29, 2022
Pure Rust library for Apache ZooKeeper built on tokio

zookeeper-async Async Zookeeper client written 100% in Rust, based on tokio. This library is intended to be equivalent with the official (low-level) Z

Kamil Rojewski 16 Dec 16, 2022
A bare metal STM32F103C8T6/STM32F103 MCU program written in pure Rust

A bare metal (register level) STM32F103C8T6/STM32F103 MCU program written in pure Rust without any IDE, SDK, HAL or library, and no assembly code, the only tool required is the Rust compiler.

Hema Shushu 105 Dec 18, 2022
Garden monitoring system using m328p Arduino Uno boards. 100% Rust [no_std] using the avr hardware abstraction layer (avr-hal)

uno-revive-rs References Arduino Garden Controller Roadmap uno-revive-rs: roadmap Components & Controllers 1-2 Uno R3 m328p Soil moisture sensor: m328

Ethan Gallucci 1 May 4, 2022
🦀 Rust-based implementation of a Snowflake Generator which communicates using gRPC

Clawflake Clawflake is a Rust application which implements Twitter Snowflakes and communicates using gRPC. Snowflake ID numbers are 63 bits integers s

n1c00o 5 Oct 31, 2022
A naive buffered/sync channel implementation in Rust, using the queue data structure

buffered-queue-rs Introduction This is my attempt at a simple and very naive buffered/synced queue implementation in Rust. The base thread-safe queue

Dhruv 4 Jul 22, 2023
RTIC monotonic implementation using the RP2040's Timer peripheral

rp2040-monotonic RTIC monotonic implementation using the RP2040's Timer peripheral. Documentation License Licensed under either of Apache License, Ver

Emil Fresk 6 Nov 24, 2022
k-mer counter in Rust using the rust-bio and rayon crates

krust is a k-mer counter written in Rust and run from the command line that will output canonical k-mers and their frequency across the records in a f

null 14 Jan 7, 2023
This crate allows you to safely initialize Dynamically Sized Types (DST) using only safe Rust.

This crate allows you to safely initialize Dynamically Sized Types (DST) using only safe Rust.

Christofer Nolander 11 Dec 22, 2022
A working example of multi targets compilation for Rust using Github Actions.

A working example of multi targets compilation for Rust using Github Actions. Supports Windows, MacOSX, x86_64, ARM and Raspberry PI Linux.

Nicolas Vanhoren 41 Dec 17, 2022