R1cs-tutorial - Tutorial for writing constraints in the `arkworks` framework

Overview

Introduction to SNARK Development with `arkworks`

In this tutorial, we will learn how to write applications for use with state-of-the-art zkSNARKs using the arkworks ecosystem of SNARK libraries.

Prerequisites

Because the arkworks ecosystem uses the Rust programming language, this tutorial assumes some familiarity with the basics of Rust. We also assume basic familiarity with zkSNARK concepts, and in particular with the following terminology:

  • Public input/instance: a publicly known object that the verifier can check a zkSNARK proof against. For example, in a proof of membership in a Merkle tree, the Merkle tree root would be a public input.
  • Private input/witness: an object that is known only to the prover, for either efficiency or privacy reasons. In the Merkle tree example, the Merkle tree authentication path would be a private input.
  • Circuit: an encoding of a computation in a way that can be proven using a zkSNARK.
  • Gadget: subcircuits corresponding to useful computations that can be used to build up the full circuit. In the Merkle tree example, a hash function gadget would be used repeatedly.

Instructions

  1. Ensure that you have the latest version of Rust installed (1.51 at the time of writing). If you do not already have Rust installed, you can do so via rustup. Linux users, please note that arkworks relies on Rust 1.51, which might be more recent than the Rust version provided by your distribution's package repositories; hence, even if you have installed Rust via your package manager, please install the latest Rust via rustup.

  2. Clone this repository via git clone https://github.com/arkworks-rs/r1cs-tutorial.git

  3. (Optional) While Rust works out of the box with your text editor of choice, using Visual Studio Code along with the rust-analyzer plugin makes Rust development easier.

  4. (Optional) Join the Telegram channel for this tutorial and for the arkworks ecosystem to ask questions interactively.

  5. Proceed to the exercises below.

Exercises

In this tutorial, we will construct a SNARK-based rollup for a simple payments system. In the course of doing so, you will learn how to use arkworks libraries for writing constraint systems, how to debug these circuits for both correctness and performance, and finally how to plug these circuits into zkSNARKs.

First, checkout the main branch in the repository.

Exercise 1: Merkle Tree Example

We'll design a simple circuit for checking a Merkle tree membership path for a given leaf. Open merkle-tree-example/README.md.

Exercise 2: Validating a single transaction

We'll design a circuit for validating a single transaction in a simple account-based payment system. Open simple-payments/README.md to first learn more about the payment system, and then open rollup/README.md for the instructions for this exercise.

Exercise 3: Writing a rollup circuit

We'll design a circuit for a rollup for batch verification of transactions in the foregoing payment system. Open rollup/README.md for the instructions for this exercise.

Solutions

If you get stuck on one of the above exercises, or if you wish to compare your solution with ours, check out the solutions branch on this repository.

Comments
  • Pedersen Hash Improper Configuration

    Pedersen Hash Improper Configuration

    Summary of Bug

    Pedersen Hash Improper Configuration

    Version

    This tutorial's configuration of pedersen hash window (https://github.com/arkworks-rs/r1cs-tutorial/blob/main/merkle_tree_example/src/common.rs#L18):

    pub type TwoToOneHash = PedersenCRHCompressor<EdwardsProjective, TECompressor, TwoToOneWindow>;
    #[derive(Clone, PartialEq, Eq, Hash)]
    pub struct TwoToOneWindow;
    
    // `WINDOW_SIZE * NUM_WINDOWS` = 2 * 256 bits = enough for hashing two outputs.
    impl pedersen::Window for TwoToOneWindow {
        const WINDOW_SIZE: usize = 128;
        const NUM_WINDOWS: usize = 4;
    }
    
    pub type LeafHash = PedersenCRHCompressor<EdwardsProjective, TECompressor, LeafWindow>;
    
    #[derive(Clone, PartialEq, Eq, Hash)]
    pub struct LeafWindow;
    
    // `WINDOW_SIZE * NUM_WINDOWS` = 2 * 256 bits = enough for hashing two outputs.
    impl pedersen::Window for LeafWindow {
        const WINDOW_SIZE: usize = 144;
        const NUM_WINDOWS: usize = 4;
    }
    
    

    Which configure the window_size to N, and the num_windows to 4. This is not consistent with the arkworks test: (https://github.com/arkworks-rs/crypto-primitives/blob/main/src/merkle_tree/mod.rs#L463).

    From my understanding, this will introduce a potential security vulnerability.

    Happy to create a PR if this is confirmed by arkworks devs.

    Steps to Reproduce

    opened by stechu 7
  • Test for 'Verifying a single transaction'; minor improvements

    Test for 'Verifying a single transaction'; minor improvements

    Description

    When working on the exercises I encountered two annoying things:

    • cargo was continually complaining about some small problems (even after completing exercise)
    • 2nd exercise ('Verifying a single transaction') couldn't have been tested separately from the 3rd one

    This PR:

    • calms down cargo clippy as much as possible (i.e. after completing the exercises, there should be no warnings)
    • introduces UnaryRollup which is a simplified version of Rollup - this one serves for testing 2nd exercise
    • adds a unit test for the 2nd exercise using UnaryRollup
    • fixes rendering of some READMEs

    Checklist:

    • [x] Targeted PR against correct branch (main)
    • [x] Linked to Github issue with discussion and accepted design OR have an explanation in the PR that describes this work.
    • [ ] Wrote unit tests (n/a - typos and unit test itself)
    • [x] Updated relevant documentation in the code
    • [ ] Added a relevant changelog entry to the Pending section in CHANGELOG.md (n/a - seems to be unmaintained)
    • [x] Re-reviewed Files changed in the Github PR explorer
    opened by pmikolajczyk41 4
  • The compilation gets broken

    The compilation gets broken

    The whole project cannot be compiled, due to ark-crypto-primitives is always going to pull the latest commit from github. But it compiled while I used specified commit

    Platform: rust: 1.52.1 os: ubuntu 20.04

    Perhaps that Cargo.lock file can avoid this situation.

    opened by Dengjianping 1
  • Where can i ask question?

    Where can i ask question?

    image In Merkle tree example, the error shows the 'leaf_bytes' didn't implement 'ToBytesGadget'. But the 'leaf_bytes' is the default value. So how can I deal with it?

    opened by NaokiLH 0
  • Bug fix for `single_tx_validity_test`

    Bug fix for `single_tx_validity_test`

    Description

    Test of transaction with the wrong signing key in single_tx_validity_test fails without a new temp_state. Seems pretty self-explanatory.

    closes: NA


    Before we can merge this PR, please make sure that all the following items have been checked off. If any of the checklist items are not applicable, please leave them but write a little note why.

    • [x] Targeted PR against correct branch (main)
    • [x] Linked to Github issue with discussion and accepted design OR have an explanation in the PR that describes this work.
    • [x] ~~Wrote unit tests~~
    • [x] ~~Updated relevant documentation in the code)~~
    • [x] ~~Added a relevant changelog entry to the Pending section in CHANGELOG.md~~
    • [x] Re-reviewed Files changed in the Github PR explorer
    opened by aayux 0
  • Fix links, PR Template, spelling

    Fix links, PR Template, spelling

    Description

    corrects internal links and moves README to link correctly. Fixes some 404s on github (and local nav)


    Before we can merge this PR, please make sure that all the following items have been checked off. If any of the checklist items are not applicable, please leave them but write a little note why.

    • [x] Targeted PR against correct branch (main)
    • [x] ~~Linked to Github issue with discussion and accepted design OR have an explanation in the PR that describes this work.~~
    • [x] ~~Wrote unit tests~~
    • [x] Updated relevant documentation in the code
    • [x] ~~Added a relevant changelog entry to the Pending section in CHANGELOG.md~~
    • [x] Re-reviewed Files changed in the Github PR explorer
    opened by NukeManDan 0
  • Bump the dependency versions to 0.3

    Bump the dependency versions to 0.3

    Description

    @Dengjianping pointed out that the current Cargo.toml has used dependencies that are in conflict with each other. This PR cleans out these issues.

    closes: #4


    Before we can merge this PR, please make sure that all the following items have been checked off. If any of the checklist items are not applicable, please leave them but write a little note why.

    • [x] Targeted PR against correct branch (master)
    • [x] Linked to Github issue with discussion and accepted design OR have an explanation in the PR that describes this work.
    • [x] Re-reviewed Files changed in the Github PR explorer

    N/A:

    • [ ] Wrote unit tests
    • [ ] Updated relevant documentation in the code

    Discuss later:

    • [ ] Added a relevant changelog entry to the Pending section in CHANGELOG.md

    (Our current CHANGELOG is empty. We need to create one. )

    opened by weikengchen 0
  • Change the window size

    Change the window size

    Description

    This PR changes the window size of Pedersen to be more standard, as Shumo (@shechu) pointed out.

    This PR also does cargo fmt. ~Note that some tests in rollup seem not successful, which may need some attention.~ Just realize that they are intentional.

    closes: #2


    Before we can merge this PR, please make sure that all the following items have been checked off. If any of the checklist items are not applicable, please leave them but write a little note why.

    • [x] Targeted PR against correct branch (master)
    • [x] Linked to Github issue with discussion and accepted design OR have an explanation in the PR that describes this work.
    • [x] Updated relevant documentation in the code
    • [x] Re-reviewed Files changed in the Github PR explorer

    We may also need to clean up the CHANGELOG sometimes.

    opened by weikengchen 0
Owner
arkworks
An ecosystem for developing and programming with zkSNARKs
arkworks
Arkworks circuits for verifiable time-lock encryption

zk-timelock This repo contains arithmetic circuits for verifiable time-lock encryption made using arkworks-rs toolkit. For more details on such an enc

Timofey 68 Apr 5, 2023
Implements ERC-5564 for the bn254 curve using arkworks-rs

erc-5564-bn254 Uses the arkworks-rs suite of libraries, and utilities from rln Usage Note: this scheme should be used with the fork of circom-rln. use

Aaryamann Challani 21 Sep 8, 2023
A CosmWasm Tutorial by Terra Academy.

CosmWasm Starter Pack This is a template to build smart contracts in Rust to run inside a Cosmos SDK module on all chains that enable it. To understan

Tantatorn Suksangwarn 1 Dec 24, 2021
A tutorial for an NFT Market Place Built with Near Protocol and React.js

nft-marketplace-part-1 A tutorial for an NFT Market Place built using Near Protocol and React.js. Preview To run this app locally, follow below steps:

Kohwo Orien 5 Jun 29, 2022
A template for writing CMSIS-Pack flash algorithms in Rust

Flash Algorithm Template This is a flash algorithm template for writing CMSIS-Pack flash algorithms in Rust. It can be used to generate new flash algo

probe.rs 5 Feb 11, 2023
Glommio Messaging Framework (GMF) is a high-performance RPC system designed to work with the Glommio framework.

Glommio Messaging Framework (GMF) The GMF library is a powerful and innovative framework developed for facilitating Remote Procedure Calls (RPCs) in R

Mohsen Zainalpour 29 Jun 13, 2023
Easy to use cryptographic framework for data protection: secure messaging with forward secrecy and secure data storage. Has unified APIs across 14 platforms.

Themis provides strong, usable cryptography for busy people General purpose cryptographic library for storage and messaging for iOS (Swift, Obj-C), An

Cossack Labs 1.6k Dec 30, 2022
An extensible open-source framework for creating private/permissioned blockchain applications

Exonum Status: Project info: Community: Exonum is an extensible open-source framework for creating blockchain applications. Exonum can be used to crea

Exonum 1.2k Jan 1, 2023
Bindings to the macOS Security.framework

macOS/iOS Security framework for Rust Documentation Bindings to the Apple's Security.framework. Allows use of TLS and Keychain from Rust. License Lice

Kornel 172 Dec 24, 2022
⚓ Solana Sealevel Framework

Anchor ⚓ Anchor is a framework for Solana's Sealevel runtime providing several convenient developer tools. Rust eDSL for writing Solana programs IDL s

Project Serum 2.6k Jan 2, 2023
A framework for creating PoC's for Solana Smart Contracts in a painless and intuitive way

Solana PoC Framework DISCLAIMER: any illegal usage of this framework is heavily discouraged. Most projects on Solana offer a more than generous bug bo

Neodyme 165 Dec 18, 2022
Microunit is a decentralized unit orchestration framework.

Microunit is a decentralized unit orchestration framework.

Engula 13 Oct 10, 2021
The Voting example based on MoonZoon and Solana + Anchor framework.

The Voting example based on MoonZoon and Solana + Anchor framework.

Martin Kavík 6 Aug 13, 2022
A lightweight and flexible framework to build your tailored blockchain applications.

TRINCI Blockchain Core A lightweight and flexible framework to build your tailored blockchain applications. Requirements The required dependencies to

Affidaty S.p.A. 11 Sep 26, 2022
This is a port in the arkwork framework of the original implementation in bellperson of Snarkpack.

Snarpack on arkwork This is a port in the arkwork framework of the original implementation in bellperson of Snarkpack. Note both works are derived fro

Nicolas Gailly 13 Aug 5, 2022
nAssets are Nova Finance’s framework for building programmable assets.

nAssets are Nova Finance’s framework for building programmable assets. nAssets can be used to tokenize and store collective forms of value while also instructing assets to yield, exchange or rebalance.

Nova Finance 45 Dec 28, 2021
Node implementation for aleph blockchain built with Substrate framework

This repository contains the Rust implementation of Aleph Zero blockchain node based on the Substrate framework. Aleph Zero is an open-source layer 1

Aleph Zero Foundation 55 Dec 15, 2022
A simple frontend web app in the seed.rs Rust framework.

Seed Quickstart Basic Rust-only template for your new Seed app. 1. Create a new project You can use cargo generate to use this template. $ cargo gener

null 0 Dec 24, 2021
Implementation of Proof of Existence consensus using Substrate Framework, Frame, Pallets, RUST

Substrate Node Template A fresh FRAME-based Substrate node, ready for hacking ?? Getting Started Follow the steps below to get started with the Node T

Vijayendra Gaur 1 Jun 8, 2022