├── 2023 ├── answers │ ├── MODULE_5_ANSWERS.md │ ├── MODULE_1_ANSWERS.md │ ├── MODULE_3_ANSWERS.md │ ├── MODULE_4_ANSWERS.md │ ├── MODULE_2_ANSWERS.md │ └── MODULE_6_ANSWERS.md ├── MODULE_8.md ├── MODULE_5.md ├── MODULE_1.md ├── MODULE_7.md ├── MODULE_6.md ├── MODULE_4.md ├── MODULE_3.md └── MODULE_2.md ├── 2024 ├── assets │ ├── sudoku.png │ ├── taxonomy.png │ ├── commitment.png │ ├── polygon-zkevm.png │ ├── bls-signatures.jpeg │ ├── program-to-proof.png │ ├── vitalik-circuit.png │ ├── elliptic-curve-pairings.jpeg │ └── polynomial-commitments-1.jpeg ├── week3_hack_and_experiment.md ├── week4_plonk.md ├── week5_frontier.md ├── faqs.md ├── week2_more_crypto_snarks_starks.md ├── week0_course_primer.md └── week1_cryptographic_basics.md ├── 2025 ├── README.md ├── reports │ └── README.md └── contributions │ └── README.md ├── .gitignore ├── .github ├── ISSUE_TEMPLATE │ └── standard-issue-template-.md └── pull_request_template.md └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store -------------------------------------------------------------------------------- /2024/assets/sudoku.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ethereum/zket-core-program/HEAD/2024/assets/sudoku.png -------------------------------------------------------------------------------- /2024/assets/taxonomy.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ethereum/zket-core-program/HEAD/2024/assets/taxonomy.png -------------------------------------------------------------------------------- /2024/assets/commitment.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ethereum/zket-core-program/HEAD/2024/assets/commitment.png -------------------------------------------------------------------------------- /2024/assets/polygon-zkevm.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ethereum/zket-core-program/HEAD/2024/assets/polygon-zkevm.png -------------------------------------------------------------------------------- /2024/assets/bls-signatures.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ethereum/zket-core-program/HEAD/2024/assets/bls-signatures.jpeg -------------------------------------------------------------------------------- /2024/assets/program-to-proof.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ethereum/zket-core-program/HEAD/2024/assets/program-to-proof.png -------------------------------------------------------------------------------- /2024/assets/vitalik-circuit.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ethereum/zket-core-program/HEAD/2024/assets/vitalik-circuit.png -------------------------------------------------------------------------------- /2024/assets/elliptic-curve-pairings.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ethereum/zket-core-program/HEAD/2024/assets/elliptic-curve-pairings.jpeg -------------------------------------------------------------------------------- /2023/answers/MODULE_5_ANSWERS.md: -------------------------------------------------------------------------------- 1 | This module is more open-ended and subject to frequent changes. Therefore, there will be no model answers provided. -------------------------------------------------------------------------------- /2024/assets/polynomial-commitments-1.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ethereum/zket-core-program/HEAD/2024/assets/polynomial-commitments-1.jpeg -------------------------------------------------------------------------------- /2025/README.md: -------------------------------------------------------------------------------- 1 | # 2025 Core Program Curriculum 2 | 3 | - [ ] TODO - Copy 2024 files over 4 | 5 | - [ ] TODO - Improve the content (add things that are suggested by community, e.g. STARKs etc.) 6 | 7 | - [ ] TODO - Improve this README 8 | -------------------------------------------------------------------------------- /2025/reports/README.md: -------------------------------------------------------------------------------- 1 | # 2025 Program Reports 2 | 3 | ![Core Program](https://img.shields.io/badge/Core-Program-blue) 4 | 5 | ## Reports for 2025 6 | 7 | This page indexes final reports for each program that took place in 2025. 8 | 9 | | Program | Report | 10 | | :-- | :-- | 11 | | Core Program Brazil 2025 | [Final Report](https://github.com/erc55/core-program-2025/blob/main/final-report.md) | 12 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/standard-issue-template-.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Standard issue template. 3 | about: To help users write a good issue. 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | ### Summary 11 | 12 | Describe the issue with the content here (e.g., a typo, incorrect code snippet, unclear explanation). 13 | 14 | ### Location 15 | 16 | - Module Name: 17 | - Section/Step: 18 | 19 | ### Proposed Correction 20 | 21 | If you have a suggestion for how to fix the issue, please include it here. 22 | 23 | ### Screenshots (if applicable) 24 | 25 | Attach any screenshots that might help explain the issue. 26 | 27 | ### Additional Context 28 | 29 | Add any other information that might be helpful, such as links to related tutorials or explanations. 30 | -------------------------------------------------------------------------------- /.github/pull_request_template.md: -------------------------------------------------------------------------------- 1 | ### Description 2 | 3 | Provide a concise description of the changes in this pull request (e.g., corrected a typo, improved an explanation, added a new example). 4 | 5 | ### Related Issues 6 | 7 | Mention any related issues here, using the `#issue_number` syntax. 8 | 9 | ### Affected Tutorials 10 | 11 | - Module Name: 12 | - Section/Step: 13 | 14 | ### Type of Change 15 | 16 | - [ ] Typo/grammar fix 17 | - [ ] Code correction (e.g., a bug in a code snippet) 18 | - [ ] New tutorial or section 19 | - [ ] Other (please describe): 20 | 21 | ### Testing 22 | 23 | Describe how you have tested these changes, if applicable. 24 | 25 | ### Checklist 26 | 27 | - [ ] I have performed a self-review of my own changes. 28 | - [ ] I have made corresponding changes to related documentation. 29 | -------------------------------------------------------------------------------- /2024/week3_hack_and_experiment.md: -------------------------------------------------------------------------------- 1 | # Week 3 - Hack and Experiment 2 | 3 | 1. Your code doesn't have to be pretty or have many functions, but should be presentable and runnable. 4 | 2. Don't reinvent the wheel, use existing libraries and tools. 5 | 3. Don't be afraid to ask for help from a mentor, but try to solve the problem yourself first. 6 | 4. Prepare your presentation and be ready to explain your code and how it works. 7 | 8 | # Project Ideas 9 | 10 | The following are some project ideas to get you started. 11 | 12 | ## 1. Token Mixer 13 | 14 | Reference the following starter code and instructions: 15 | - https://securitylab.github.io/cs251-fall21/ 16 | - https://securitylab.github.io/cs251-fall21/hw/proj4.pdf 17 | - https://securitylab.github.io/cs251-fall21/lectures/lecture13.pdf 18 | - https://learn.0xparc.org/materials/circom/learning-group-1/breaking-down-tornado 19 | 20 | ## 2. ZK Calculator 21 | 22 | Prove your calculation is correct, you may want to reference this: https://github.com/jtriley-eth/zk-calculator 23 | 24 | ## 3. ZK Battleship 25 | 26 | Read the following, understand how it works, and make your own ZK battleship game: https://github.com/darkforest-eth/circuits 27 | 28 | ## 4. Very Simple Rollup 29 | 30 | This is a good example, but yours can be even simpler: https://github.com/rollupnc/RollupNC 31 | 32 | Reference this PDF: https://securitylab.github.io/cs251-fall21/lectures/lecture17.pdf 33 | 34 | ## 5. Solve Some ZK Puzzles 35 | 36 | Solve these problems and present to us how you did it: https://zkhack.dev/puzzles/ 37 | 38 | ## 6. *OR YOUR OWN PROJECT* 39 | !!!!!! UNVEIL YOUR POWER ANON !!!!! 40 | 41 | # Helpful Toolkits to Use 42 | 43 | - https://github.com/privacy-scaling-explorations/zkp-app-boilerplate 44 | - https://battlezips.gitbook.io/battlezips/development/circom-tester 45 | - https://battlezips.gitbook.io/battlezips/development/hardhat-circom 46 | - https://battlezips.gitbook.io/battlezips/development/shield` 47 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Core Program 2 | 3 | > A Foundation for Tomorrow's Open-Source ProgCrypto Contributors 4 | 5 | Welcome to the Core Program curriculum repository, hosted by the Privacy and Scaling Explorations (PSE) team. This program covers the basics of programmable cryptography (ProgCrypto), including Zero-Knowledge Proofs (ZKPs), Fully Homomorphic Encryption (FHE), and Multiparty Computation (MPC). We aim to equip engineers and researchers to contribute to open-source cryptography projects. 6 | 7 | Designed for programmers with limited cryptography knowledge, this self-learning curriculum helps them learn the fundamentals and prepares them to contribute to the open-source community. 8 | 9 | ## Program Structure 10 | 11 | ### 2023 Curriculum 12 | 13 | All materials and documents related to the 2023 curriculum are in the `2023` folder. These provide historical context and foundational content. 14 | 15 | ### 2024 Curriculum 16 | 17 | All materials and documents related to the 2024 curriculum are in the `2024` folder. These provide historical context and foundational content. 18 | 19 | ### 2025 Curriculum 20 | 21 | The 2025 curriculum is currently being developed and can be found in the `2025` folder. We welcome contributions to this section. 22 | 23 | ## Contribution 24 | 25 | We encourage contributions to improve this content. Please follow these steps: 26 | 27 | 1. **Analyze the Content**: Review the existing materials. 28 | 2. **Report Issues**: Create an issue if you find errors or areas for improvement. 29 | 3. **Submit Pull Requests**: Submit a pull request with your changes once you are confident they will be approved. 30 | 31 | If an existing issue is not being worked on, feel free to address it and make a pull request. 32 | 33 | ### Issue and Pull Request Templates 34 | 35 | Templates for issues and pull requests are available under the `.github` directory. These templates will appear automatically when you create a new issue or pull request on GitHub. 36 | -------------------------------------------------------------------------------- /2024/week4_plonk.md: -------------------------------------------------------------------------------- 1 | # Week 4 - PLONK 2 | 3 | 4 | Recall that you should have some basic knowledge of Rust from completing [Rustlings](https://rustlings.cool/) in Week 0. The required exercise this week is to publish a blogpost on PLONK and present it at the end of the week with your group. 5 | 6 | 7 | ## Study 8 | 9 | When you start to learn ZK proof system, you are really advised to start from PLONK than any other proof system. There're a bunch of amazing articles out there, but instead of jumping into a rabbit hole, you should start with [Vitalik's blog post](https://vitalik.eth.limo/general/2019/09/22/plonk.html) and focus on reading it all. 10 | With this article you can understand what is widely used plonkish style of circuit arithmetization. For this article, you may be unable to understand all the details at once, but you should at least understand what this diagram mean: 11 | ![Vitalik's circuit](./assets/vitalik-circuit.png) 12 | 13 | Let's examine PLONK from a broader perspective compared to the detailed analysis in the paper. [ZKP MOOC Lec 5](https://www.youtube.com/watch?v=A0oZVEXav24) 14 | 15 | Read Plonkathon Referenced Version. If you want to challenge yourself, You can implement it. 16 | https://github.com/0xPARC/plonkathon/tree/reference 17 | 18 | 19 | ### Reference Material (optional) 20 | 21 | In order to understand PLONKathon, you might need to understand the following concepts, but only read it when you really feel like it. 22 | 23 | 1. There's the [website for plonkathon](https://plonkathon.com/), at this moment, you should already understand elliptic curve, pairing. You might need to understand Fiat-Shamir heuristic and Fast Fourier Transform to understand the code. They also have [video play list explaining each stage](https://www.youtube.com/playlist?list=PLNK7oFq6eaEzHNYHpQ_zbgPEBDhLmyfFb) 24 | 2. Schwartz Zippel Lemma https://brilliant.org/wiki/schwartz-zippel-lemma/ 25 | 3. Lagrange interpolation https://en.wikipedia.org/wiki/Lagrange_polynomial 26 | 4. FFT https://www.youtube.com/watch?v=h7apO7q16V0. Put it simply, FFT and Inverse FFT are turning polynomials from coefficient domain into evaluation domain and vice versa. 27 | 5. Fiat-Shamir heuristic. Put it simply, normally interactive proof is done by sending the challenge to the verifier and the verifier will send the challenge to the prover. It's a way to turn the interactive proof into non-interactive proof by hashing the existing computation trace and use it as the challenge. 28 | 6. Libraries for PLONK implementation, with a focus on production-level implementations: [Jellyfish](https://github.com/EspressoSystems/jellyfish), [Dusk-network](https://github.com/dusk-network/plonk) 29 | -------------------------------------------------------------------------------- /2023/MODULE_8.md: -------------------------------------------------------------------------------- 1 | # Module 8 - Open Source Contribution 2 | 3 | Welcome to Module 8! In the next three weeks, we will be asking you to contribute to open source projects in the ZK space. To get started, let's first take a look at what it means to contribute to open source. 4 | 5 | ## What is Open Source? 6 | 7 | Before you jump in, let's get clear on what open source means. Wikipedia defines Open Source software as the following: 8 | 9 | > Open source is source code that is made freely available for possible modification and redistribution. 10 | 11 | At its core, it's a community of people around the world that wants to write code, not for money, but because we believe that something should exist in the world and we want to share it with everyone! 12 | 13 | But beyond that, open source work can have a lot of benefits for career and professional growth as well. 14 | 15 | As the first step in this stage, please watch the following video. 16 | 17 | 🎥 **Kick-off Video**: [Watch here](https://drive.google.com/file/d/1T7ACbYl4joqrJg6dRxHaIYNNhWrftamB/view?usp=drive_link) 18 | 19 | 📊 **Presentation Slides**: [View here](https://docs.google.com/presentation/d/1wqyn6FnyINulTSEIWwZaVYak3ONbjTUi9shBOhAZkd8/edit?usp=sharing) 20 | 21 | ## Get Your Hands Dirty 22 | 23 | ### Curriculum Feedback 24 | 25 | First, let's get you comfortable with the open-source workflow. We've set up a curriculum repo for you to practice. Your feedback not only helps us but also lets you get the hang of things like pull requests. 26 | 27 | 1. Head to the [Summer Contribution Program Curriculum repo](https://github.com/adrianmcli/summer-contribution-program). 28 | 2. Drop your feedback under the Issues tab—bugs, comments, whatever. 29 | 3. Create a pull request to implement your suggestions. 30 | 31 | ### PSE Good First Issue Tracker 32 | 33 | Next, we've got a special issue tracker focused on PSE projects. This is another sandbox for you to practice open-source contributions while also helping us improve this tool. This can be your first code-related open source contribution! 34 | 35 | 1. Visit [PSE Good First Issue tracker](https://pse-gfis.vercel.app/). 36 | 2. Since it's open source, feel free to submit Issues and PRs [here](https://github.com/adrianmcli/pse-gfis). 37 | 38 | ### Choose Your PSE Project 39 | 40 | Finally, it's game time. Pick a project that resonates with you and dive in. This is where you apply what you've practiced and make a tangible impact. 41 | 42 | 1. Browse the [good first issue tracker](https://pse-gfis.vercel.app/). 43 | 2. Pick an issue and comment to let the maintainer know you're tackling it. 44 | 45 | 📣 Beyond this point, you'll largely be on your own. But if you get stuck or have questions, just shoot us a message on Discord! 46 | -------------------------------------------------------------------------------- /2023/answers/MODULE_1_ANSWERS.md: -------------------------------------------------------------------------------- 1 | ## Comprehension 2 | 3 | 1. **Three-Colouring Graph problem with Hats**: To prove possession of a valid three-coloring for a given graph, the solution is written on the ground with each node covered with hats. The verifier can check the color under two connected hats without seeing the entire solution. The prover thus proves knowledge of a valid coloring without revealing it. This can be repeated multiple times to increase confidence. This is an interactive proof. 4 | 5 | 2. **Ali Baba’s Cave analogy**: In the cave, there's a magical door leading to two passages. The prover demonstrates knowledge of the secret word to open the door by complying with the verifier's request to exit through a chosen passage, without revealing the word itself. This can be repeated multiple times to increase confidence. This is an interactive proof. 6 | 7 | 3. **The difference between interactive and non-interactive proofs**: 8 | - **Interactive Proofs**: Require back-and-forth communication between the prover and verifier during the proof process. 9 | - **Non-Interactive Proofs**: The prover can send a single message to the verifier, who can then ascertain the validity of the proof without any further interaction. 10 | 11 | ## Modular Arithmetic 12 | 13 | 1. $7\ \text{mod}\ 13 = 7$ 14 | 2. $15\ \text{mod}\ 13 = 2$ 15 | 3. $(7+15)\ \text{mod}\ 13 = (22)\ \text{mod}\ 13 = 9$ 16 | 4. $(7\ \text{mod}\ 13 + 15\ \text{mod}\ 13)\ \text{mod}\ 13 = (7+2)\ \text{mod}\ 13 = 9$ 17 | 18 | Since the results of the third and fourth calculations match, they do follow a "group structure." Notice that, it doesn't matter if you apply the `mod` immediately for each number (like in Q4) or at the end (like in Q3). 19 | 20 | ## Generators 21 | 22 | 1. **What does the term 'generator' mean?** 23 | A generator in a cyclic group is an element that, when repeatedly applied via the group's operation, produces every element in the group. 24 | 25 | 2. **Can you find a generator for this group?** 26 | Yes, in the group $(Z_{12}, +\ \text{mod}\ 12)$, the number 1 is a generator. Repeated addition by 1 modulo 12 produces every residue class. 27 | 28 | 3. **Are there other generators for this group? If yes, what are they?** 29 | Yes, there are other generators for this group. In $(Z_{12}, +\ \text{mod}\ 12)$, the numbers 5, 7, and 11 are also generators. You can verify this by checking that repeated addition by any of these numbers modulo 12 produces every residue class from 0 to 11. 30 | 31 | ## Implementing a Modular Arithmetic Calculator 32 | 33 | Here's a JavaScript function for the modular arithmetic calculator: 34 | 35 | ```javascript 36 | function modularCalculator(op, num1, num2, mod) { 37 | let result = 0; 38 | switch (op) { 39 | case '+': 40 | result = (num1 + num2) % mod; 41 | break; 42 | case '-': 43 | result = (num1 - num2) % mod; 44 | if (result < 0) result += mod; 45 | break; 46 | case '*': 47 | result = (num1 * num2) % mod; 48 | break; 49 | default: 50 | return "Invalid operation"; 51 | } 52 | return result; 53 | } 54 | 55 | modularCalculator('+', 10, 15, 12); // Should return: 1 56 | modularCalculator('-', 10, 15, 12); // Should return: 7 57 | modularCalculator('*', 10, 15, 12); // Should return: 6 58 | ``` 59 | 60 | These answers should align well with the content provided in the module, helping students to understand and practice the concepts of Zero-Knowledge Proofs and modular arithmetic. -------------------------------------------------------------------------------- /2023/answers/MODULE_3_ANSWERS.md: -------------------------------------------------------------------------------- 1 | ### Intro to Elliptic Curves 2 | 1. **What is the general equation for an elliptic curve?** 3 | - Answer: The equation of an elliptic curve is `y^2 = x^3 + ax + b`. 4 | 5 | 2. **How do you find the sum of two points P and Q on an elliptic curve?** 6 | - Answer: To add two points P and Q on an elliptic curve, you draw a line between P and Q, find the third point where that line intersects the curve, and then reflect that point over the x-axis to get the result of P + Q. 7 | 8 | 3. **What is the special point on the elliptic curve that serves as the identity element for addition?** 9 | - Answer: The identity element in elliptic curve addition is the point at infinity, often denoted as O. 10 | 11 | ### Elliptic Curve Cryptography (ECC) 12 | 1. **What is the primary advantage of ECC over traditional methods like RSA?** 13 | - Answer: ECC offers much shorter key lengths for the same level of security compared to traditional methods like RSA. This results in faster computations, less power consumption, and reduced storage and bandwidth requirements. 14 | 15 | 2. **How is the public key in ECC derived from the private key?** 16 | - Answer: In ECC, the public key is derived by multiplying the private key (a scalar) with a generator point G on the elliptic curve. The result is a point on the curve, which serves as the public key. 17 | 18 | 3. **What is the Elliptic Curve Discrete Logarithm Problem (ECDLP)?** 19 | - Answer: ECDLP is the problem of determining the scalar (private key) used to multiply the generator point G to arrive at a given point on the curve (public key). It's computationally difficult to solve, providing the security foundation for ECC. 20 | 21 | ### Schnorr Signatures and EdDSA 22 | 1. **What are the primary advantages of Schnorr Signatures?** 23 | - Answer: Schnorr Signatures are a type of digital signature scheme based on elliptic curves. They are important because of their simplicity, efficiency, and the ability to aggregate multiple signatures into a single one due to their linear structure. 24 | 25 | 2. **What differentiates EdDSA from traditional Schnorr signatures?** 26 | - Answer: EdDSA (Edwards-curve Digital Signature Algorithm) is a digital signature scheme that uses a specific type of elliptic curve called twisted Edwards curves. Unlike traditional DSA, EdDSA is deterministic, meaning the same message and private key will always produce the same signature. 27 | 28 | ### Pairing-Based Cryptography 29 | 1. **What is a pairing in the context of elliptic curve cryptography?** 30 | - Answer: In the context of elliptic curve cryptography, a pairing is a bilinear map that takes two points from an elliptic curve and maps them to a point in a finite field. This operation allows for certain cryptographic constructions that are not possible with just the elliptic curve operations. 31 | 32 | 2. **What are the three main properties of a bilinear map?** 33 | - Answer: The three main properties of a bilinear map are bilinearity, non-degeneracy, and computability. 34 | 35 | 3. **Name one cryptographic application that is enabled by pairings.** 36 | - Answer: Cryptographic applications enabled by pairings include BLS Signatures and Identity-Based Encryption (IBE). 37 | 38 | ### KZG Polynomial Commitments 39 | 1. **What is the primary purpose of a polynomial commitment scheme?** 40 | - Answer: The primary purpose of a polynomial commitment scheme is to allow a prover to commit to a polynomial in a way that they can later reveal specific evaluations of the polynomial without revealing the entire polynomial, and these evaluations can be verified against the original commitment. 41 | 42 | 2. **How is the commitment in the KZG scheme computed for a given polynomial and secret value?** 43 | - Answer: In the KZG scheme, the commitment to a polynomial `f(x)` is computed by evaluating the polynomial at a secret value `s` and then multiplying the result by the generator point `G` of the elliptic curve. 44 | 45 | 3. **Why are KZG polynomial commitments considered efficient and succinct?** 46 | - Answer: KZG polynomial commitments are considered efficient and succinct because they offer commitments and proofs that have a constant size, regardless of the degree of the polynomial. This results in compact representations and reduced computational overhead. 47 | 48 | ### Trusted Setups 49 | 1. **Why is the trusted setup phase crucial for the security of certain cryptographic protocols?** 50 | - Answer: The trusted setup phase is crucial because it involves generating initial parameters that are vital for the security of the protocol. If the setup is compromised, or if certain intermediate values (often called "toxic waste") are not properly discarded, they could be used to undermine the security of the system. 51 | 52 | 2. **How is the trusted setup related to zk-SNARKs?** 53 | - Answer: zk-SNARKs require a trusted setup to generate a common reference string (CRS) that is used by both the prover and verifier in the protocol. The security of zk-SNARKs relies on the fact that certain intermediate values during the CRS generation are destroyed, ensuring the integrity of the proofs. 54 | 55 | 3. **What are some of the challenges associated with trusted setups?** 56 | - Answer: Some challenges associated with trusted setups include the need for participants to trust that the setup was performed correctly and securely, the potential centralization of the setup process, and the need for transparency to gain trust from users. -------------------------------------------------------------------------------- /2023/answers/MODULE_4_ANSWERS.md: -------------------------------------------------------------------------------- 1 | ## Homomorphic Hiding 2 | 3 | 1. **Explain homomorphic hiding in your own words.** 4 | 5 | - Answer: Homomorphic hiding refers to a cryptographic commitment scheme that allows for specific operations to be performed on the committed data without revealing the data itself. In other words, you can perform computations on hidden values, and the results, when revealed, will be the same as if the computations were done on the original, non-hidden values. 6 | 7 | --- 8 | 9 | ## Arithmetic Circuits 10 | 11 | 1. **What is the primary purpose of converting a problem into an arithmetic circuit?** 12 | 13 | - Answer: Converting a problem into an arithmetic circuit allows for the representation of complex computations in a structured and standardized format. This "flattening" into simpler equations makes it easier to transform the computation into other representations, like R1CS, which are more amenable to zkSNARK constructions. 14 | 15 | 2. **What are the main components of an arithmetic circuit?** 16 | 17 | - Answer: The main components of an arithmetic circuit are gates (which perform operations like addition or multiplication), wires (which carry values between gates), and input/output ports (which define the inputs to and outputs from the circuit). 18 | 19 | --- 20 | 21 | ## Rank-1 Constraint System (R1CS) 22 | 23 | 1. **Describe the Rank-1 Constraint System (R1CS) in your own words.** 24 | 25 | - Answer: R1CS is a system of representing computations using a set of matrices. It takes the structure provided by arithmetic circuits and further simplifies it into a format where each constraint (or equation) ensures that specific operations are correctly performed. Each constraint is designed to be rank-1, meaning it can be represented with a single row or column in a matrix. 26 | 27 | 2. **Why is R1CS essential in the zkSNARK construction pipeline?** 28 | 29 | - Answer: R1CS is essential because it provides a bridge between arithmetic circuits and QAPs. It simplifies the computation into a format that can be efficiently transformed into a QAP, which is a polynomial representation suitable for zkSNARK proof generation. 30 | 31 | --- 32 | 33 | ## Quadratic Arithmetic Program (QAP) 34 | 35 | 1. **What is the primary goal of converting R1CS into a QAP?** 36 | 37 | - Answer: The primary goal is to represent the computation in a polynomial format. QAPs allow for the efficient generation and verification of zkSNARK proofs by leveraging the properties of polynomials. 38 | 39 | 2. **How does QAP aid in the zkSNARK proof generation process?** 40 | 41 | - Answer: QAPs provide a structured way to represent the computation such that proving knowledge of a solution (or satisfying assignment) to the computation becomes equivalent to proving knowledge of certain polynomial evaluations. This polynomial representation is amenable to the cryptographic techniques used in zkSNARKs. 42 | 43 | 3. **Why are polynomials central to the QAP representation?** 44 | 45 | - Answer: Polynomials are central because they offer properties that make the zkSNARK construction efficient. Operations on polynomials, like evaluation and interpolation, are used to generate and verify proofs. The structure of polynomials also allows for the creation of succinct and zero-knowledge proofs, which are the hallmarks of zkSNARKs. 46 | 47 | --- 48 | 49 | ## The Pinocchio Protocol 50 | 51 | 1. **Why is the Pinocchio Protocol considered a significant step towards practical zkSNARK construction?** 52 | 53 | - Answer: The Pinocchio Protocol was one of the first to demonstrate a practical construction of zkSNARKs. It provided a clear methodology for taking a computation, represented as a QAP, and generating a succinct, non-interactive proof of its correctness. 54 | 55 | 2. **How does the Pinocchio Protocol utilize QAP representations?** 56 | 57 | - Answer: The Pinocchio Protocol builds upon the QAP representation to generate zkSNARK proofs. The protocol uses the polynomial structure of QAPs, combined with cryptographic techniques like pairings on elliptic curves, to produce proofs that are both short in size and verifiable in a few milliseconds. 58 | 59 | 3. **What role do elliptic curve pairings play in the Pinocchio Protocol?** 60 | 61 | - Answer: Elliptic curve pairings provide the cryptographic foundation for the Pinocchio Protocol. They are used in the proof generation and verification processes, enabling the creation of proofs that are both zero-knowledge and succinct. Pairings allow for certain mathematical checks that make the verification of zkSNARK proofs efficient. 62 | 63 | --- 64 | 65 | ## Groth16 66 | 67 | 1. **What makes Groth16 a popular choice for zkSNARK constructions in blockchain technologies?** 68 | 69 | - Answer: Groth16 is popular because of its efficiency. It produces shorter proofs and requires less computational power for proof generation and verification compared to earlier zkSNARK constructions. This efficiency makes it well-suited for blockchain technologies where resource constraints are a concern. 70 | 71 | 2. **Describe the main advantage and disadvantage of the Groth16 proof system.** 72 | 73 | - **Advantage**: Groth16 is highly efficient, producing succinct proofs and allowing for fast verification. This makes it ideal for systems where performance is critical. 74 | - **Disadvantage**: Groth16 requires a circuit-specific trusted setup, which can be a significant downside for some use-cases due to the potential security risks associated with the setup phase. 75 | 76 | 3. **How does Groth16 differ from the original Pinocchio Protocol?** 77 | 78 | - Answer: Groth16 improves upon the Pinocchio Protocol by producing shorter proofs and allowing for faster verification. Additionally, while both require a trusted setup, Groth16's setup is circuit-specific, whereas the Pinocchio Protocol's setup is more general. 79 | 80 | --- 81 | 82 | ## PLONK 83 | 84 | 1. **What are the advantages of PLONK over Groth16?** 85 | 86 | - Answer: PLONK offers a "universal and updatable" trusted setup, eliminating the need for a new trusted setup for every circuit. This makes it more versatile and reduces the security concerns associated with multiple setup phases. Additionally, PLONK is designed to be more modular and flexible, allowing for easier integration with various cryptographic primitives. 87 | 88 | 2. **How does PLONK eliminate the need for a new trusted setup for every circuit?** 89 | 90 | - Answer: PLONK utilizes a universal trusted setup, which means that the setup phase is done once and can be used for any circuit of a given size or smaller. This contrasts with circuit-specific setups where a new setup is required for each new circuit. The universality of PLONK's setup reduces the overhead and potential security risks associated with multiple setups. 91 | -------------------------------------------------------------------------------- /2023/answers/MODULE_2_ANSWERS.md: -------------------------------------------------------------------------------- 1 | ### Written Questions 2 | 3 | 1. **Symmetric vs. Asymmetric Encryption**: 4 | - **Symmetric Encryption**: Uses the same key for both encryption and decryption. It is faster and less complex, but the key must be shared securely between parties. 5 | * *Use case*: Securely transmitting data over a trusted channel, such as an encrypted WiFi connection. 6 | - **Asymmetric Encryption**: Utilizes a pair of keys: a public key for encryption and a private key for decryption. It ensures that the private key does not need to be shared but is more computationally intensive. 7 | * *Use case*: Secure email systems like PGP, where the recipient's public key encrypts the message, and only the recipient's private key can decrypt it. 8 | 9 | 2. **Public-Key Cryptography and Key Exchange Protocols**: 10 | - *Answer*: Diffie-Hellman protocol allows two parties to generate a shared secret key securely over an untrusted network. It enhances security in a messaging application by enabling encrypted communication without sharing the actual keys. 11 | * *Use case*: Securely exchanging messages in apps like WhatsApp, allowing for end-to-end encryption. 12 | 13 | 3. **Hash Functions**: 14 | - *Answer*: SHA-256 is well-regarded for its resistance to collisions, preimage attacks, and speed. Poseidon, on the other hand, is tailored for cryptographic purposes with a more efficient arithmetic design. 15 | * *Unique advantage of Poseidon*: Its design is particularly suited for zero-knowledge proofs, providing more efficient computations in that context. 16 | 17 | 4. **Merkle Trees**: 18 | - *Answer*: Merkle trees help verify data in a large database efficiently by structuring the data into a binary tree where each leaf is a hash of a data block, and each non-leaf node is a hash of its child nodes. Verifying the inclusion of a specific block only requires the hashes along the path to the root, not the entire dataset. 19 | * *Use case*: Verifying transactions in a blockchain, where the Merkle root represents all transactions in a block. 20 | 21 | 5. **Cryptographic Commitments**: 22 | - *Answer*: Pedersen Commitments allow committing to a value without revealing it, maintaining transaction privacy in a blockchain protocol. By combining randomness with the actual value, it ensures the commitment is both hiding and binding. 23 | * *Use case*: Confidential transaction systems within blockchains like Monero to keep amounts private. 24 | 25 | 6. **Digital Signatures**: 26 | - *Answer*: To verify the authenticity of a digitally signed document, one must use the public key corresponding to the signer's private key to apply the signature verification algorithm. If verification succeeds, it proves the document was signed by the corresponding private key and has not been altered. 27 | 28 | ### Programming Challenges 29 | 30 | #### Challenge 1: Asymmetric Encryption and Digital Signature 31 | 32 | ```javascript 33 | const crypto = require('crypto'); 34 | 35 | // Asymmetric encryption 36 | const { publicKey, privateKey } = crypto.generateKeyPairSync('rsa', { modulusLength: 2048 }); 37 | 38 | // Encrypt 39 | const plaintext = 'This is a secret message.'; 40 | const encrypted = crypto.publicEncrypt(publicKey, Buffer.from(plaintext)); 41 | 42 | // Decrypt 43 | const decrypted = crypto.privateDecrypt(privateKey, encrypted); 44 | console.log('Decrypted message:', decrypted.toString()); 45 | 46 | // Create a digital signature 47 | const sign = crypto.createSign('SHA256'); 48 | sign.update(plaintext); 49 | sign.end(); 50 | const signature = sign.sign(privateKey); 51 | 52 | // Verify a digital signature 53 | const verify = crypto.createVerify('SHA256'); 54 | verify.update(plaintext); 55 | verify.end(); 56 | console.log('Signature valid:', verify.verify(publicKey, signature)); 57 | ``` 58 | 59 | #### Challenge 2: Hashing with SHA-256 and Poseidon 60 | 61 | ```javascript 62 | const crypto = require("crypto"); 63 | const poseidon = require("poseidon-encryption"); 64 | 65 | // SHA-256 66 | const data = "This is some data X."; 67 | const hash = crypto.createHash("sha256"); 68 | hash.update(data); 69 | const sha256Hash = hash.digest("hex"); 70 | console.log("SHA-256 Hash:", sha256Hash); 71 | 72 | // Poseidon 73 | const inputs = [1, 2, 3, 4, 5]; 74 | const poseidonHash = poseidon.poseidon(inputs); 75 | console.log("Poseidon Hash:", poseidonHash.toString()); 76 | ``` 77 | 78 | #### Challenge 3: Using a Simple Merkle Tree 79 | 80 | ```javascript 81 | const MerkleTree = require('merkletreejs'); 82 | const crypto = require('crypto'); 83 | 84 | function hashFunction(data) { 85 | const hash = crypto.createHash('sha256'); 86 | hash.update(data); 87 | return hash.digest(); 88 | } 89 | 90 | // Create tree 91 | const leaves = ['a', 'b', 'c', 'd'].map(x => hashFunction(x)); 92 | const tree = new MerkleTree.MerkleTree(leaves, hashFunction); 93 | const root = tree.getRoot().toString('hex'); 94 | console.log('Merkle Root:', root); 95 | 96 | // Generate and verify proof 97 | const leaf = hashFunction('b'); 98 | const proof = tree.getProof(leaf); 99 | console.log('Proof valid:', tree.verify(proof, leaf, tree.getRoot())); 100 | ``` 101 | 102 | #### Challenge 4: Implementing Pedersen Commitments 103 | 104 | ```javascript 105 | class PedersenCommitment { 106 | constructor() { 107 | // Set prime number (p) and generator (g) 108 | this.p = BigInt(23); // use a large prime in a real-world scenario 109 | this.g = BigInt(4); // use a large number in a real-world scenario 110 | this.h = null; 111 | this.r = null; 112 | this.s = null; 113 | } 114 | 115 | // Generate 'h' with a random number 'r' (h = g^r mod p) 116 | generateH() { 117 | this.r = BigInt(Math.floor(Math.random() * 10 + 1)); 118 | this.h = this.g ** this.r % this.p; 119 | } 120 | 121 | // Generate the commitment (g^s * h^r mod p) 122 | generateCommitment(s) { 123 | this.s = BigInt(s); 124 | return (this.g ** BigInt(s) * this.h ** this.r) % this.p; 125 | } 126 | 127 | // Reveal the secret number and random number (s, r) 128 | reveal() { 129 | return { s: this.s, r: this.r }; 130 | } 131 | 132 | // Verify the commitment (g^s * h^r mod p) 133 | verify(s, r, C) { 134 | return C === (this.g ** BigInt(s) * this.h ** BigInt(r)) % this.p; 135 | } 136 | } 137 | 138 | // Test the PedersenCommitment 139 | const pc = new PedersenCommitment(); 140 | pc.generateH(); 141 | 142 | // Party A: Generate a commitment 143 | let secretNumber = 7; 144 | let commitment = pc.generateCommitment(secretNumber); 145 | console.log("Commitment: ", commitment); 146 | 147 | // Party A: Reveal the secret and random number 148 | let reveal = pc.reveal(); 149 | console.log("Revealed: ", reveal); 150 | 151 | // Party B: Verify the commitment 152 | let verification = pc.verify(reveal.s, reveal.r, commitment); 153 | console.log("Verification: ", verification); 154 | ``` -------------------------------------------------------------------------------- /2024/week5_frontier.md: -------------------------------------------------------------------------------- 1 | # Week 5 - Frontier Technologies 2 | 3 | In this final week of the curriculum, we are going to take a more self-exploratory approach to some exciting topics and tools at the forefront of programmable cryptography. This will give you the flexibility to continue exploring PLONK if you need the extra time, but also new areas of exploration which may interest you. 4 | 5 | First, we will dive into some basics about MPC/FHE. Then we will look at some interesting tools and primitives like TLSNotary and ZKEmail. Keep in mind that the topics in this module continue to evolve at a rapid pace. We will only be able to touch on some basic concepts and the rest will be for you to explore. 6 | 7 | ## MPC/FHE 8 | 9 | Zero-knowledge proofs (ZKPs), Multi-Party Computation (MPC), and Fully Homomorphic Encryption (FHE) are all areas of research that have significant overlap with each other. So far, you have mostly focused on ZKPs, but learning about MPC/FHE will allow you to see things from a new perspective. 10 | 11 | ### Multi-Party Computation (MPC) 12 | 13 | [Secure Multi-Party Computation](https://en.wikipedia.org/wiki/Secure_multi-party_computation) or MPC for short, is a protocol that allows multiple entities to jointly compute a function without revealing their individual inputs. 14 | 15 | The classic example of MPC is the [Yao's Millionaires' Problem](https://en.wikipedia.org/wiki/Yao%27s_Millionaires%27_problem). This is a thought experiment in which two millionaires are interested in knowing which of them is richer without revealing their actual wealth. 16 | 17 | MPC is also used to generate the secret value and the Common Reference String (CRS) for a trusted setup in a distributed manner, where multiple parties collaborate to generate the parameters without any single party having access to the entire secret value. 18 | 19 | Start here with a blog post from PSE: [Secure Multi-Party Computation](https://mirror.xyz/privacy-scaling-explorations.eth/v_KNOV_NwQwKV0tb81uBS4m-rbs-qJGvCx7WvwP4sDg) 20 | 21 | When you are done, feel free to browse these (optional) additional resources at your own pace: 22 | 23 | - [Introduction to Multi-Party Computation (MPC or SMPC) [5:43]](https://www.youtube.com/watch?v=90jcXCHsBF0) 24 | - [Sharing Knowledge without Sharing Data by Azer Bestavros [32:08]](https://www.youtube.com/watch?v=P2MmO458xu4) 25 | - [Accessible and Scalable: Secure Multi-Party Computation](https://multiparty.org/) 26 | - [Intro to MPC (Javascript tutorial and examples)](https://github.com/multiparty/jiff/blob/master/tutorials/0-intro-to-mpc.md) 27 | - [A Crash Course on MPC by Daniel Escudero](https://medium.com/applied-mpc/a-crash-course-on-mpc-part-0-311fae2ce184) 28 | - [An Introduction to Secret-Sharing-Based Secure Multiparty Computation ](https://eprint.iacr.org/2022/062.pdf) 29 | - [A Pragmatic Introduction to Secure Multi-Party Computation](https://securecomputation.org/docs/pragmaticmpc.pdf) 30 | 31 | ### Fully Homomorphic Encryption (FHE) 32 | 33 | Another fascinating and growing area of research is the concept of [Fully Homomorphic Encryption (FHE)](https://en.wikipedia.org/wiki/Homomorphic_encryption#Fully_homomorphic_encryption). Technically, FHE as a concept is a subset of homomorphic hidings (the Wikipedia article linked above reflects this). 34 | 35 | The properties of FHE are quite interesting, even though much work still needs to be done to make it viable for production. To get started learning about FHE, read the two-part blog post below to get a general lay of the land: 36 | 37 | - [Zero to Start: Applied Fully Homomorphic Encryption (FHE) Part 1](https://mirror.xyz/privacy-scaling-explorations.eth/D8UHFW1t48x2liWb5wuP6LDdCRbgUH_8vOFvA0tNDJA) 38 | - [Zero to Start: Applied Fully Homomorphic Encryption (FHE) Part 2](https://mirror.xyz/privacy-scaling-explorations.eth/wQZqa9acMdGS7LTXmKX-fR05VHfkgFf9Wrjso7XxDzs) 39 | 40 | After you are done reading that, please go through the following: 41 | 42 | #### Tutorials and Examples 43 | - **[Zama FHE Tutorials](https://github.com/zama-ai/awesome-zama?tab=readme-ov-file#tutorials)**: A list of Fully Homomorphic Encryption (FHE) resources created by Zama. 44 | - **[Homomorphic Encryption Example](https://github.com/homenc/HElib/tree/master/examples)**: Example codes using the HElib library. HElib is an open-source software library that implements homomorphic encryption. 45 | - **[Microsoft SEAL Examples](https://github.com/Microsoft/SEAL/tree/main/native/examples)**: Example codes and tutorials for Microsoft SEAL. Microsoft SEAL is an easy-to-use and powerful homomorphic encryption library. 46 | 47 | #### Key Papers and Articles 48 | - **[Gentry's Original Paper on FHE](https://eprint.iacr.org/2009/616.pdf)**: The foundational paper by Craig Gentry that introduced the first practical FHE scheme. 49 | - **[Homomorphic Encryption Standardization](https://homomorphicencryption.org/standard)**: Ongoing efforts and papers aimed at standardizing homomorphic encryption schemes. 50 | - **[Jeremy Kun's Overview on FHE](https://www.jeremykun.com/2024/05/04/fhe-overview/)**: A detailed blog post that provides an excellent overview of FHE concepts and advancements. 51 | #### Current Research 52 | - **[FHE.org Community](https://fhe.org)**: A hub for researchers and developers working on advancing FHE and other secure computation techniques. 53 | - **[TII Survey on FHE](https://eprint.iacr.org/2022/1602.pdf)**: A comprehensive survey paper that provides an in-depth overview of the current state of FHE research. 54 | 55 | ## TLSNotary 56 | 57 | [TLSNotary](https://tlsnotary.org/) is a protocol that allows you to prove to a third party that you have received certain data from a web server, without allowing the third party to see the data itself. This is particularly useful for verifying the authenticity of the data you’ve received, such as bank statements or signed documents, without exposing sensitive information. 58 | It enables a client to prove data provenance—that data was honestly obtained from a specific server—while preserving privacy through Multi-Party Computation (MPC), without revealing the actual content to third parties or relying on a single trusted intermediary. 59 | 60 | For a brief overview, watch this video: [Verify Private Data with TLSNotary Plugins](https://www.youtube.com/watch?v=SDjmjiqmUFw) 61 | 62 | We also encourage you to take a look at the following: 63 | 64 | - [Explanatory Blog Post](https://pluto.xyz/blog/web-proof-techniques-mpc-mode) 65 | - [GitHub Organization](https://github.com/tlsnotary) 66 | - [Main Website](https://tlsnotary.org/) 67 | 68 | ## ZKEmail 69 | 70 | The [ZKEmail](https://github.com/zkemail) project is a fascinating application of Zero-Knowledge Proofs with traditional protocols (like emails and DKIM). A simple intersection of new and old technologies allow for fascinating new use-cases like treating emails as a wallet or even a peer-to-peer network of transfer. 71 | 72 | For a brief introduction, have a look at this short video: [Zuconnect 2023 ZK Day: ZK Email 73 | (11:40)](https://www.youtube.com/watch?v=3jCKdxQ9Pfw) 74 | 75 | Have a look at the following: 76 | 77 | - [Technical explanatory blog post](https://blog.aayushg.com/zkemail/) 78 | - [Github Organization](https://github.com/zkemail) 79 | - [Main Website](https://prove.email/) 80 | -------------------------------------------------------------------------------- /2024/faqs.md: -------------------------------------------------------------------------------- 1 | # FAQs for program participants 2 | 3 |
4 | How should I prepare for the program before it begins? 5 | The program is structured to guide students through a carefully designed progression. Our Telegram group contains a wealth of shared content from like-minded community members that you may find interesting and beneficial. 6 | 7 | \ 8 | We recommend setting aside sufficient time to maximize your study efforts and adjusting your schedule to participate in office hours and other events. 9 | 10 |
11 | 12 |
13 | Where will the co-working space be located for weekly on-site meetings? 14 | The location varies depending on the country. 15 | The official venue details for each country will be shared with participants soon. 16 | 17 | In the meantime, here are the regions where the in-person sessions will take place in each country: 18 | 19 | - **Argentina**: Palermo area 20 | - **Costa Rica**: San Pedro, San Jose 21 | - **Ecuador**: El Vecino, Cuenca 22 | - **Japan**: Yotsuya, Tokyo 23 | - **Korea**: Itaewon, Seoul 24 | - **Taiwan**: Datong District, Taipei City 25 |
26 | 27 |
28 | Should I install any specific software on my computer before starting the program? 29 | The golden rule is to install the software you are most comfortable using. You will need a code editor (we recommend Visual Studio Code). Instructions for installing any additional libraries and packages will be provided in the accompanying materials. 30 | 31 | \ 32 | Depending on your expertise and background, you may choose to follow a more advanced technical path compared to other participants in the course. 33 | 34 |
35 | 36 |
37 | Are there any fees associated with attending the in-person sessions? 38 | No. However co-working space facilities vary from country to country. Ask the community manager in your country about the availability of free drinks, etc. All venues in the various countries are conveniently located near excellent lunch spots and have easy access to transportation. 39 |
40 | 41 |
42 | How will mentorship be provided? Will there be scheduled office hours? 43 | Mentorship will be region-specific, with designated office hours for LatAm and Asia where mentors will be available for consultation. Additional office hours may be offered based on interest and availability. 44 | 45 | \ 46 | The schedules are not yet finalized but will be communicated to participants well in advance. 47 | 48 |
49 | 50 |
51 | Will there be any assessments or evaluations during the program? 52 | No, there will not be any assessments or evaluations during the program. It is a self-paced program designed for you to make the most of it on your own. 53 |
54 | 55 |
56 | I’m working on a project involving ZK technologies. Can I ask questions about my project? 57 | Yes! This program aims to expand knowledge and awareness of programmable cryptography. We’re excited to learn about what you’re building, and we are committed to creating an environment where you can share insights from the program as well as your personal projects and experiences. 58 |
59 | 60 |
61 | What are the prerequisites for joining the program? 62 | Once students pass the screening and interview process, they have met the primary prerequisites for joining the program. Additionally, comprehensive readings and documentation have been shared in the public Telegram group to help students prepare and stay informed. 63 |
64 | 65 |
66 | Will there be any recommended reading or resources provided before the program starts? 67 | We will only provide the official program materials, which will be shared well in advance to allow participants ample time for self-study. Furthermore, participants can enhance their understanding during the in-person sessions and consult during office hours for any additional support. 68 |
69 | 70 |
71 | What is the daily schedule like during the in-person sessions? 72 | The official schedule will vary for each country. Your Community Manager will communicate the schedule ahead of time and inform you of any changes. Generally, the co-working day starts in the morning and ends in the afternoon, followed by a small Happy Hour gathering. 73 |
74 | 75 |
76 | What is the expected time commitment each week? 77 | The provided materials are designed to require a full 40 hours per week commitment. However, we understand that everyone's responsibilities vary, and the time you can dedicate may differ. 78 | 79 | \ 80 | Also, we strongly suggest planning to attend the in-person events, as they offer an excellent opportunity to collaborate, network, and gain the maximum benefits from the program. 81 | 82 |
83 | 84 |
85 | Will there be opportunities to collaborate with other participants? 86 | Yes! Although a significant part of the program is self-paced, we are providing infrastructure for you to collaborate with other participants in your country, your region, and even from other countries and regions running the program. 87 |
88 | 89 |
90 | How will feedback be given on our work and projects? 91 | Office hours are a great resource if you have questions or need advice on your work and projects. Mentors will provide feedback as needed, and the program will feature experienced guests who can also offer assistance. 92 | 93 | \ 94 | The in-person days are another excellent opportunity for feedback and consultation. Mentors and guests will be available throughout the day to help. 95 | 96 |
97 | 98 |
99 | Can I participate in the program remotely if I am unable to attend the in-person sessions? 100 | Yes, you can participate in the program remotely if you are unable to attend the in-person sessions even though it's advisable to attend as many in-person sessions as possible to maximize the benefits. 101 | 102 | \ 103 | Keep in mind that there can be rewards for active participation in the program - including the in-person activities 104 | 105 |
106 | 107 |
108 | Will there be any guest speakers or industry experts involved in the program? 109 | Yes. There will be talks from mentors and other industry experts throughout the program. 110 |
111 | 112 |
113 | How can I access the program's online materials and resources? 114 | All program materials will be shared ahead of time, following a carefully planned structure for each week. 115 |
116 | 117 |
118 | What should I bring with me to the in-person sessions? 119 | You should bring your computer and essentials for a day in a co-working space. Please note that the program does not cover lunch or snacks during the day. 120 |
121 | 122 |
123 | Will a co-working space be provided, in addition to the weekly on-site meetings? 124 | No physical co-working space will be provided apart from the weekly on-site meetings. However, you will have access to a private Discord server where program participants, mentors, and students from your country, as well as others from different countries and regions, can collaborate virtually. 125 |
126 | -------------------------------------------------------------------------------- /2023/MODULE_5.md: -------------------------------------------------------------------------------- 1 | # Module 5 - PSE Protocols 2 | 3 | Congratulations on completing the first four modules. From this point onwards, we will focus more on practical application and actual coding rather than theory. Therefore, in this module, we will be covering a few of the protocols developed within the Privacy and Scaling Explorations (PSE) team. 4 | 5 | Rather than delving into the intricate details of how each project works, we will present a brief overview of each one, followed by links to the relevant documentation and resources. This approach will equip you with the context to independently study and navigate through the documentation. 6 | 7 | ## Introductory Video 8 | 9 | A previous PSE grantee (Jack Gilcrest) created a video for the recent EthGlobal Paris hackathon to explain some of the projects mentioned below. This is a great start and it is recommended that you view this video first. 10 | 11 | 👉 [**Semaphore, Unirep, RLN Explained [22:33]**](https://drive.google.com/file/d/1JQKDRhGsgNDfRrzy86n6wSCc1Xo1-F1F/view) 12 | 13 | Please be aware that a wealth of videos on each of the protocols, such as Semaphore or UniRep, can be found online. A quick search on YouTube using these terms is likely to yield several results, offering additional content for those interested in delving deeper into these subjects. 14 | 15 | ## Semaphore 16 | 17 | **Github**: https://github.com/semaphore-protocol 18 | **Website**: https://semaphore.appliedzkp.org/ 19 | 20 | Semaphore allows users to prove their membership in a group and transmit anonymous data, such as votes or feedback, without revealing their identities. 21 | 22 | This is a very general concept that can be applied to many use-cases. In fact, many of the projects discussed below are built on top of the Semaphore protocol. 23 | 24 | This video is a good overview of the Semaphore protocol: 25 | 26 | 👉 [**Anonymous Signalling on Ethereum by Cedoor | Devcon Bogotá [15:30]**](https://www.youtube.com/watch?v=dxAfL91Sbw4&ab_channel=EthereumFoundation) 27 | 28 | ## UniRep 29 | 30 | **Github**: https://github.com/Unirep 31 | **Website**: https://developer.unirep.io/ 32 | 33 | Building on top of Semaphore, UniRep extends the concept of anonymous groups by allowing small amounts of data to be associated with anonymous users. Where Semaphore allows one to prove they are part of a group, UniRep allows one to prove *something* about the anonymous user. 34 | 35 | One simple example of this is a system where Twitter can attest to a user's number of followers. The user can then prove to others that they have at least a certain number of followers while remaining anonymous. 36 | 37 | This video is a good overview of the UniRep protocol: 38 | 39 | 👉 [**Chance Hudson - Robust Anonymous UX with the UniRep Protocol [17:01]**](https://www.youtube.com/watch?v=hGQlgS9s6P8) 40 | 41 | 42 | ## Rate-Limiting Nullifier (RLN) 43 | 44 | **Github**: https://github.com/Rate-Limiting-Nullifier 45 | **Website**: https://rate-limiting-nullifier.github.io/rln-docs/ 46 | 47 | An anonymous environment can bring new challenges to group coordination. One such problem is spam-protection. RLN takes a novel cryptographic approach in which those who exceed the rate limit, can be penalized either by withdrawing the offender's stake or revealing their secrets. 48 | 49 | This video is a good overview of the RLN protocol: 50 | 51 | 👉 **[Rate Limiting Nullifier by AtHeartEngineer | Devcon Bogotá [7:03]](https://www.youtube.com/watch?v=vrNiPBfbLw0)** 52 | 53 | ## Newer Projects 54 | 55 | The following projects are a bit newer, and their documentation and APIs might not be stable or very complete yet. However, these are some of the projects that the PSE team is excited about bringing more attention to in the near future. As such, we have included them in this module for your benefit. 56 | 57 | **NOTE**: The exercise section below does not necessarily apply to the following projects. However, you are free to include them if you have extra time to do so. 58 | 59 | ## Bandada 60 | 61 | **Github**: https://github.com/privacy-scaling-explorations/bandada 62 | **Website**: https://bandada.pse.dev/ 63 | 64 | Bandada is a backend and frontend stack to assist in managing anonymous Semaphore groups. It is aimed at developers who want to build privacy-based applications and integrate anonymity sets, as well as anyone that wants to create and manage anonymous groups. 65 | 66 | It enables anonymous signaling, such as voting, messaging, login, or endorsing, in various use cases like private organizations, GitHub repository contributors, and groups of wallets holding a specific NFT, for example. 67 | 68 | ## CryptKeeper 69 | 70 | Github: https://github.com/CryptKeeperZK 71 | 72 | CryptKeeper is a browser extension that generates Semaphore and RLN proofs for websites, providing a secure and portable solution for managing anonymous identity secrets across different applications. 73 | 74 | It simplifies the integration of zero-knowledge (ZK) identities and proofs into applications, allowing developers to focus on building the front-end and logic of their applications. 75 | 76 | By handling complex aspects of cryptography, circuits, caching, and storage, CryptKeeper enables users to interact with decentralized applications (dapps) without revealing their private identity secrets. It is aimed at building secure community standards for the growing ZK ecosystem. 77 | 78 | ## TLSNotary 79 | 80 | **Github**: https://github.com/tlsnotary/tlsn 81 | **Website**: https://tlsnotary.org/ 82 | 83 | TLSNotary allows you to export data from any web application and prove facts about it without compromising on privacy. With TLSNotary, you can create cryptographic proofs of authenticity for any data on the web, even your own private data. 84 | 85 | One may assume that TLSNotary requires a “man-in-the-middle” setup where the Notary snoops on the connection with the webserver. Fortunately, this is not true! Data is kept private even from the Notary. 86 | 87 | # 💪 Exercises 88 | 89 | ## Written Questions 90 | 91 | ### Specific Questions 92 | 93 | Here are also a few specific questions to answer: 94 | 95 | 1. What does a nullifier do and why is it important? 96 | 2. What does a trapdoor do and why is it important? 97 | 3. Can you compare and contrast Semaphore, UniRep, and RLN? 98 | 4. What key cryptographic concepts do you see being used in these projects? 99 | 100 | ### General Questions 101 | 102 | For each of the projects (Semaphore, UniRep, RLN) listed above, answer the following: 103 | 104 | 1. **Explain the Motivation and Functionality in Detail**: What drove the creation of this project, and what does it primarily do? Explain its core functionality and goals in your own words. 105 | 2. **Provide Example Use-Cases**: Identify and describe some practical use-cases that can be built with this project. How can it be applied in real-world scenarios? Can you explain these use-cases to someone without a technical background? 106 | 4. **Hurdles to Overcome**: What are some downsides to the project? Are there requirements that might make adoption difficult? Reflect on potential improvements to the project. 107 | 5. **Circuit Analysis (Optional)**: Where applicable, take a look at the circuits used within the project. Although you may not yet be familiar with the syntax of Circom, try your best to explain what is happening within them. 108 | 6. **Hands-On Implementation (Optional)**: If time permits, create a simple prototype or demo using the project. Provide a brief explanation of what you built and how it illustrates a feature of the project. 109 | 110 | Items 4 and 5 might be quite challenging, so do not feel obligated to complete these. However, completing them will give you a more refined understanding of how these protocols work. 111 | 112 | **Optional** - Answer the same questions above (where applicable) for the projects mentioned under "Newer Projects". -------------------------------------------------------------------------------- /2024/week2_more_crypto_snarks_starks.md: -------------------------------------------------------------------------------- 1 | # Week 2 - More Crypto, SNARKs, and STARKs 2 | 3 | ## Practical 4 | 5 | ### Circom Crash Course (build from command line; ZKU course) 6 | 7 | There are [excellent resources available like ZKU course](https://zku.gnomio.com/) to learn Circom. [The week 2 of ZKU course](https://zku.gnomio.com/mod/assign/view.php?id=119) introduces the merkle tree and token mixer. Finish week2 part1 - Hashes and Merkle Tree and part2 - Tornado Cash. You may find the curated material useful to understand the concepts better. Semaphore is optional but recommended. 8 | 9 | ### Reference Material (optional) 10 | 11 | 1. https://circom.erhant.me/ 12 | 13 | ## Study 14 | 15 | ### KZG Polynomial Commitments (keep this simple and black-boxed) 16 | 17 | Polynomial Commitments are cryptographic tools that allow the hiding of some coefficients while revealing others. They're used in various cryptographic proofs and blockchain protocols. For a better understanding of Polynomial Commitments 18 | The intuition of KZG is that it is a commitment scheme. It is used to commit to a polynomial and later reveal a certain point on that polynomial. All your input data "lock" a specific polynomial. 19 | 20 | ![KZG](./assets/polynomial-commitments-1.jpeg) 21 | 22 | Read this article for an introduction: 23 | - [KZG Commitments by Inevitable Ethereum](https://www.inevitableeth.com/home/concepts/kzg-commitment) 24 | 25 | Read this article for a more in-depth mathematical look into how it works (optional): 26 | - [KZG polynomial commitments by Dankrad Feist](https://dankradfeist.de/ethereum/2020/06/16/kate-polynomial-commitments.html) 27 | 28 | If you prefer to read some code, check out this article: 29 | - [Explaining KZG Commitment with Code Walkthrough by Kai Jun Eer](https://kaijuneer.medium.com/explaining-kzg-commitment-with-code-walkthrough-216638a620c9) 30 | 31 | ### Trusted Setup 32 | 33 | Trusted setup is a process to generate a bunch of different points on elliptic curve. You can use these points with polynomial commitment schemes. Each point has same generator but different power. You can use these points to represent the variable terms in the polynomial. Therefore, the result of the polynomial commitment scheme with trusted setup is also a point on the elliptic curve. [Read this article by inevitable Ethereum to understand the concept better](https://www.inevitableeth.com/en/home/concepts/pcs-trusted-setup) 34 | 35 | ### STARKs and SNARKs 36 | 37 | STARKs and SNARKs are two types of zero-knowledge proofs system. The proof system requires witness, initial statement, circuit. We'll explain them in the next section. Normally the proof generated is a bunch of byte and it's a few mathematic objects. The proof can be verified by the verifier by running some verification functions on these mathematic objects. 38 | 39 | zkSTARK and zkSNARK are in fact adjectives. They describe the type of proof system. It doesn't necessarily need to be zk. You don't need to know the detail of how they work at the moment, but you need to know they are adjective to describe the proof system and when we say Blah is a zkSNARKs, it means it's a proof system that requires a prover and a verifier, and the prover can prove something to the verifier without revealing the information. 40 | 41 | 1. Zero-Knowledge: Verifier cannot know what is verified except true/false. 42 | 2. Succinct: Proof needs to be short and can be verified quickly. 43 | 3. Non-Interactive: Prover and Verifier do not need to interact back and forth in order to verify. 44 | 4. ARgument: Need to match the nature of Soundness, almost impossible to lie to a Verifier. 45 | 5. (of) Knowledge: Knowledge is required to produce proof. 46 | 47 | They can also be used together. Polygon zkEVM and zkSync Boojum, for example, uses zkSTARKs for individual proofs and zkSNARKs for the aggregated proof to "prove all the previous proofs are generated correctly", therefore aggregate several zkSTARKs. 48 | ![polygon-zkevm](./assets/polygon-zkevm.png) 49 | [Source](https://docs.polygon.technology/zkEVM/architecture/) 50 | 51 | You can also read [this article in 10 mins](https://medium.com/@ramsesfv/starks-vs-snarks-d2e09c4e6069) explains the really high level difference between STARKs and SNARKs. 52 | 53 | ### From Computation to ZKPs 54 | 55 | There's a circuit diagram from [Vitalik's blog post](https://vitalik.eth.limo/general/2019/09/22/plonk.html), you will be asked to read it in week4. For now let's focus only on a diagram from the article. It's a circuit below. It's arithmetic, so the gate is addition and multiplication. This represents `x^3 + x + 5 = 35` and x is the only "input" here. It should be `3` to satisfy the gate. For the first gate, it should be `9` if you have to label the value for it. because `3 * 3 = 9`. All the values you label on the gate between are "witness". The answer and operation of each gate actually constrain the value of the witness, so this circuit is a constraint system. How to prove the circuit is correctly filled? You can either prove the gate correctly compute (gate constraint) or prove the neighbor gate (permutation constraint) is consistent. That's the main part of the proof. While in the formal proof system, all of your computation should be in polynomial. 56 | ![Vitalik's circuit](./assets/vitalik-circuit.png) 57 | 58 | The process of converting a program to a proof is: 59 | 60 | 1. convert program to a bunch of constraints, and your input have to satisfy these constraints. like `x * x = 16` then `x = 4` if x is an positive integer. 61 | 2. With this constraint and input number, you try to prove the constraint really satisfy. In the case of PLONK, the main part of your proof are every gate is correctly compute and every neighbor gate is consistent. You just compute it in polynomial. That's why it seems complicated. 62 | 63 | You can apply many arithmetization techniques to convert a program to a proof. There are R1CS, Plonkish, AIR. You can also have different combination of proving scheme like Polynomial IOP and PCS in below diagram. 64 | 65 | ![Program to Proof](./assets/program-to-proof.png) 66 | [Source](https://rdi.berkeley.edu/zk-learning/assets/lecture14.pdf) 67 | 68 | There're really a lot of combinations like below taxonomy shows, but you don't need to know all of them at the moment. 69 | ![Taxonomy](./assets/taxonomy.png) 70 | [Source](https://people.cs.georgetown.edu/jthaler/ProofsArgsAndZK.pdf) 71 | 72 | ### Groth16 (keep this simple and black-boxed) 73 | 74 | Groth16 is one of the famous zkSNARKs. Just remember that its biggest advantage is its proof size is small. That's why it's widely used in many blockchain projects. We won't learn the detail here, but you can read this article to understand how it works: 75 | [Groth16](https://www.zeroknowledgeblog.com/index.php/groth16) 76 | 77 | ### STARKs and FRI 78 | 79 | STARKs are a type of zero-knowledge proof system that is post-quantum secure. It usually involves larger proof size and faster proof size. There are two articles written by Vitalik that explain STARKs in detail. You can read them here: 80 | 1. https://vitalik.eth.limo/general/2017/11/09/starks_part_1.html 81 | 2. https://vitalik.eth.limo/general/2017/11/22/starks_part_2.html 82 | 3. **Optional article**: https://vitalik.eth.limo/general/2018/07/21/starks_part_3.html 83 | 84 | 85 | #### Optional Resources (For Deepening Your Understanding) 86 | 87 | - **[Stark Anatomy](https://aszepieniec.github.io/stark-anatomy/)** 88 | This six-part tutorial series dives into the mechanics of the STARK proof system. It’s designed for a technically-inclined audience with a basic understanding of mathematics and programming. 89 | 90 | - **[Exploring Circle STARKs](https://vitalik.eth.limo/general/2024/07/23/circlestarks.html)** 91 | An introduction to Circle STARKs, an optimization that enhances the efficiency and scalability of STARK proofs using structured polynomial commitments. 92 | 93 | 94 | # 💪 Exercises 95 | 96 | 1. What is a proof system? 97 | 2. What is input, witness, circuit, and proof? 98 | 3. How does program convert to proof? 99 | -------------------------------------------------------------------------------- /2023/MODULE_1.md: -------------------------------------------------------------------------------- 1 | # Module 1 - Intro to ZK 2 | 3 | Welcome aboard! You've just embarked on an incredible journey into the realm of Zero-Knowledge Proofs (ZKPs). This fascinating aspect of cryptography provides the backbone for various privacy-preserving technologies. Notably, it's used in Ethereum, one of the most well-known blockchain platforms. 4 | 5 | In this module, our primary goal is to introduce you to key concepts of ZKPs, such as soundness, completeness, and zero-knowledge itself. Additionally, we aim to cultivate your understanding of basic modular arithmetic through hands-on examples and exercises, which will prove vital for the subsequent modules. 6 | 7 | Let’s get started! 8 | 9 | ## Tips to Learn Zero Knowledge 10 | 11 | One really useful mental model to learn zero knowledge is to blackbox the concepts so that you don't get intimidated by the complexity of the topic. This doesn't mean you ignore the details, but rather, you focus on understanding the high-level concepts first and then dive into the details later. 12 | 13 | When you study the topic for the first time, only read the required reading. Skip the optional reading unless you are really curious about the details. This will help you to understand the topic without getting overwhelmed by the details. 14 | 15 | ## A Primer for Zero Knowledge Proofs 16 | 17 | Before we delve into the core content of the module, consider acquainting yourself with some high-level concepts of Zero-Knowledge Proofs. The following introductory articles will help you build a robust foundational understanding: 18 | 19 | - [Zero-knowledge proofs | ethereum.org](https://ethereum.org/en/zero-knowledge-proofs/) 20 | - [A Primer on Zero-Knowledge Proofs 🔏](https://medium.com/hackernoon/a-primer-on-zero-knowledge-proofs-892e6e277142) 21 | - [Zero Knowledge Proofs: An illustrated primer [Part 1]](https://blog.cryptographyengineering.com/2014/11/27/zero-knowledge-proofs-illustrated-primer/) 22 | - [Zero Knowledge Proofs: An illustrated primer [Part 2]](https://blog.cryptographyengineering.com/2017/01/21/zero-knowledge-proofs-an-illustrated-primer-part-2/) 23 | 24 | You **DO NOT** have to read all of these articles, they are simply a starting point. However, throughout this course, we will provide you with a set of reflection questions to check your understanding. 25 | 26 | :::info 27 | **🤔 Consider the following:** 28 | 1. What are Zero-Knowledge Proofs? 29 | 2. What are the principles of soundness, completeness, and zero-knowledge? 30 | 3. What distinguishes interactive from non-interactive proofs? 31 | ::: 32 | 33 | ## Thought Experiments 34 | 35 | Engaging with these thought experiments will make abstract concepts more tangible and facilitate a deeper understanding of ZKPs. Each of these examples offers a unique perspective on the concept of zero-knowledge proofs: 36 | 37 | - [Example 1: Where’s Waldo?](https://medium.com/swlh/a-zero-knowledge-proof-for-wheres-wally-930c21e55399) 38 | - [Example 2: Colored Balls (interactive)](https://en.wikipedia.org/wiki/Zero-knowledge_proof#Two_balls_and_the_colour-blind_friend) 39 | - [Example 3: Sudoku (non-interactive)](https://www.wisdom.weizmann.ac.il/~naor/PAPERS/SUDOKU_DEMO/) 40 | 41 | :::info 42 | **🤔 Consider the following:** 43 | 1. Which example did you find most enlightening, and why? 44 | 2. How do these examples demonstrate the principles of zero-knowledge proofs? 45 | 3. Can you think of any potential applications of these concepts in everyday life? 46 | ::: 47 | 48 | ## Use-Cases and Applications 49 | 50 | To connect theory with practice, let's delve into the practical implications of ZKPs. The following resources illustrate how ZKPs are employed in real-world applications, particularly in the domain of blockchain: 51 | 52 | - [Ethereum Use Cases for ZKPs](https://ethereum.org/en/zero-knowledge-proofs/#use-cases-for-zero-knowledge-proofs) 53 | - [More Applications](https://link.springer.com/article/10.1007/s42452-019-0989-z#Sec4) 54 | 55 | :::info 56 | **🤔 Consider the following:** 57 | 1. Which application of ZKP do you find most intriguing, and why? 58 | 2. Can you imagine any other potential applications of ZKP? 59 | ::: 60 | 61 | ## Supplemental Materials on ZKPs [optional] 62 | 63 | For more content (especially for those who prefer videos), check out the following: 64 | 65 | - Video Lectures: 66 | - ['Introduction to Zero Knowledge Proofs' - Elena Nadolinski [19:59]](https://www.youtube.com/watch?v=BT88s7_VtC8) 67 | - [ZKP MOOC Lecture 1: Introduction and History of ZKP [1:38:32]](https://www.youtube.com/watch?v=uchjTIlPzFo) 68 | - [ZK Whiteboard Sessions - Module One: What is a SNARK? by Dan Boneh [42:08]](https://youtu.be/h-94UhJLeck) 69 | - [Detailed Explanation of Zero-Knowledge Proofs](https://youtu.be/9je336QIqAQ?t=650) 70 | - [Thinking in Zero Knowledge](https://mirror.xyz/0x3FD6f213ae1B8a7B6bd8f14BE9BF316a5e5A5d28/VTGpmEYLKIslUPf66VQzHUneB0R7EhMpJJ_mGrMvTwY) 71 | 72 | By this point in the module, you should have a broad and multifaceted understanding of ZKPs. However, we're not done yet. Next, we'll tackle some key mathematical concepts that underpin this topic. 73 | 74 | ## Number Theory [self research] 75 | 76 | Building a strong foundation in number theory is essential for understanding upcoming modules. The following module from Khan Academy provides an excellent introduction to this topic: 77 | 78 | - [An Introduction to Modular Math by Khan Academy](https://www.khanacademy.org/computing/computer-science/cryptography/modarithmetic/a/what-is-modular-arithmetic) 79 | 80 | Below are topics that you will need to research independently (or with a teammate). This could mean searching these specific terms on Google, YouTube, Wikipedia, or even asking ChatGPT. 81 | 82 | Don't forget to reach out to your team and the mentors on Discord when you're stuck! 83 | 84 | ### Topics to Research 85 | 86 | - Fundamentals: 87 | - Prime Numbers and Composite Numbers 88 | - Greatest Common Divisors (GCD) 89 | 90 | - Modular Arithmetic and Congruence 91 | - What is modular arithmetic? 92 | - Exploring congruence classes 93 | 94 | - Group Theory 95 | - What is a group structure? 96 | - What is a group operation? 97 | 98 | - Diving Deeper: 99 | - What is a finite group? 100 | - What is a cyclic group? 101 | - What is a generator? 102 | - What are finite fields? 103 | 104 | :::info 105 | **🤔 Consider the following:** 106 | 1. Which of these concepts did you find most challenging, and why? 107 | 2. Can you explain these concepts in your own words? 108 | ::: 109 | 110 | # 💪 Exercises 111 | 112 | Here are the exercises for this module. Collaborate with your team to find the answers, and remember to support each other! 113 | 114 | ## Comprehension 115 | 116 | Summarize each of the following concepts in a few sentences: 117 | 118 | 1. Three-Colouring Graph problem with Hats 119 | 2. Ali Baba’s Cave analogy 120 | 3. The difference between interactive and non-interactive proofs 121 | 122 | ## Modular Arithmetic 123 | 124 | Solve the following problems and gain a practical understanding of modular arithmetic: 125 | 126 | 1. $7\ mod\ 13$ 127 | 2. $15\ mod\ 13$ 128 | 3. $(7+15)\ mod\ 13$ 129 | 4. $(7\ mod\ 13 + 15\ mod\ 13)\ mod\ 13$ 130 | 131 | If the results of the third and fourth calculations match, they follow a "group structure". Can you determine if these do? 132 | 133 | ## Generators 134 | 135 | Consider the cyclic group $(Z_{12}, +\ mod\ 12)$, commonly referred to as the "additive group of integers modulo 12". Address the following points: 136 | 137 | 1. What does the term 'generator' mean? 138 | 2. Can you find a generator for this group? 139 | 3. Are there other generators for this group? If yes, what are they? 140 | 141 | ## Implementing a Modular Arithmetic Calculator 142 | 143 | Your task is to implement a simple modular arithmetic calculator in JavaScript. The calculator should support three operations: addition, subtraction, and multiplication. 144 | 145 | The function `modularCalculator` should take four parameters: 146 | - A string, `op`, indicating the operation. It will be one of '+', '-', or '*'. 147 | - Two integers, `num1` and `num2`, which are the operands for the operation. 148 | - An integer, `mod`, which is the modulus. 149 | 150 | The function should return the result of performing the indicated operation on `num1` and `num2`, then taking the result modulo `mod`. 151 | 152 | Remember, the result of subtraction could be negative, and in this case, you should add `mod` to the result to ensure it's positive. 153 | 154 | For addition and multiplication, remember that JavaScript's % operator gives the remainder, not the modulus, but these will be the same for positive numbers. 155 | 156 | **Code Template:** 157 | 158 | ```javascript 159 | function modularCalculator(op, num1, num2, mod) { 160 | // Your code here 161 | } 162 | 163 | modularCalculator('+', 10, 15, 12); // Should return: 1 164 | modularCalculator('-', 10, 15, 12); // Should return: 7 165 | modularCalculator('*', 10, 15, 12); // Should return: 6 166 | ``` 167 | 168 | Feel free to use `console.log` statements in your code to verify that your function is working as expected. For convenience, consider using https://repljs.com/ and pasting in the above code snippet to get started. 169 | 170 | ## Conclusion 171 | By the end of this module, you will have gained an understanding of the fundamental concepts in Zero-Knowledge Proofs (ZKPs). These principles will guide you in your journey towards mastering the advanced topics that will be covered in the following modules. 172 | -------------------------------------------------------------------------------- /2023/MODULE_7.md: -------------------------------------------------------------------------------- 1 | # Module 7 - Circuit Writing Crash Course 2 | 3 | Welcome to Module 7 of the program! From here, things become more self-guided, leading into the contribution stage of our program. This means fewer specific instructions and more freedom to explore areas that interest you. 4 | 5 | In the next two weeks, we aim to help you get comfortable with reading and writing Circom circuits. The first week provides a list of learning materials and challenges (see below), while the second week invites you to create your own circuit ideas. 6 | 7 | It’s normal to have different levels of comfort with this material, and that’s okay. Remember, this is just one step in a lifelong learning process. 8 | 9 | Open-source community members often work to improve things just for the sake of improvement. That’s a value we hope to instill in you as well. 10 | 11 | So the most crucial advice is to **go at your own pace and enjoy the process 🤗**. Going slow to understand thoroughly is better than rushing and getting frustrated. 12 | 13 | Without further ado, let’s start with a quick overview (including an explanation of what Circom, Halo2, and Noir). 14 | 15 | **Start here:** 16 | 17 | 👉 **[A beginner’s intro to coding zero-knowledge proofs](https://dev.to/spalladino/a-beginners-intro-to-coding-zero-knowledge-proofs-c56)** 18 | 19 | Enjoy the journey! 20 | 21 | ## A note about **Halo2** 22 | 23 | Some of you might choose to focus on Halo2 for this portion of the program (instead of Circom). This is great because Halo2 is one of the up-and-coming ecosystems for circuit development. 24 | 25 | However, since it is quite new, there are far fewer resources for learning how to use it. You will not only require a good knowledge of Rust (the programming language), you will also need to be comfortable looking through documentation and reaching out to others for help. 26 | 27 | All of the Circom challenges below can be attempted via Halo2, but you will be required to figure out how to adapt them for Halo2. 28 | 29 | To get you started, here are some of the resources we recommend you go through: 30 | 31 | **Tutorial and Lectures** 32 | 33 | 1. Read Consensys Diligence’s **[introductory article on Halo2](https://consensys.io/diligence/blog/2023/07/endeavors-into-the-zero-knowledge-halo2-proving-system/)**. 34 | 2. Read Axiom’s **[Getting Started with Halo2](https://docs.axiom.xyz/zero-knowledge-proofs/getting-started-with-halo2)**. 35 | 3. Read Axiom’s **[Halo2 Cheatsheet](https://hackmd.io/@axiom/HyoXzD7Zh)**. 36 | 4. Work through 0xParc’s **[Halo2 lecture series](https://learn.0xparc.org/materials/halo2/learning-group-1/introduction)**. 37 | 5. (Optional) [An encyclopedia of halo2](https://halo2.club/) 38 | 39 | **Reference Material** 40 | 41 | 1. Use the **[Halo2 Book](https://zcash.github.io/halo2/)** for reference. This **[Simple Example](https://zcash.github.io/halo2/user/simple-example.html)** can be a good start. 42 | 2. Reference **[this presentation](https://docs.google.com/presentation/d/1UpMo2Ze5iwzpwICPoKkeT04-xGFRp7ZzVPhgnidr-vs/edit#slide=id.p)** for details on PLONKish arithmetization and Halo2. 43 | 44 | # **Module 7 - Week 1** 45 | 46 | For this week, we have three major modules for you to work through. Notice that the modules are not denoted by date. You should work through them at your own pace, and if there are items here that you would like to skip, feel free to do so as well. 47 | 48 | ## **1. Review and Foundations** 49 | 50 | ### **1.1 Learn** 51 | 52 | - Review the concepts in Module 6 of the previous stage. 53 | - As a reminder, read through this **[introductory article](https://dev.to/tonyolendo/the-complete-full-stack-guide-to-getting-started-with-zero-knowledge-proofs-using-circom-and-zk-snarks-part-2-58o)**. 54 | - Read through the official **[Circom Language](https://docs.circom.io/circom-language/signals/)** documentation. 55 | - Read and understand the official **[Basic Circuits](https://docs.circom.io/more-circuits/more-basic-circuits/)**. 56 | - Work through the **[first workshop](https://learn.0xparc.org/materials/circom/learning-group-1/circom-1)** from 0xParc’s Circom Workshop series. 57 | - Read and understand the **[Sudoku Solution Proof Circuit](https://github.com/zku-cohort-3/zkPuzzles/blob/fa89bf49ae4a8ffe57a05b3df2137ac65d01abe2/circuits/sudoku.circom)** featured in the previous module. 58 | 59 | ### **1.2 Challenges** 60 | 61 | Consider the basic arithmetic and hash functions needed for the following challenges. 62 | 63 | - **Challenge 1**: Write a Circuit to Prove You Know an Input to a Hash 64 | - **Challenge 2**: Write a Circuit to Prove You Know the Private Key to a Public Key 65 | 66 | ## **2. Building Basic Circuits** 67 | 68 | ### **2.1 Learn** 69 | 70 | - Work through the **[second workshop](https://learn.0xparc.org/materials/circom/learning-group-1/circom-2)** from 0xParc’s Circom Workshop series. 71 | - Work through the **[Week 2](https://zku.gnomio.com/mod/assign/view.php?id=119)** and **[Week 3](https://zku.gnomio.com/mod/assign/view.php?id=121)** assignments from the ZKU course. 72 | - Click the “Access as a guest” button to read the content. 73 | 74 | ### **2.2 Challenges** 75 | 76 | - **Challenge 1**: Prove Membership of an Element in a Merkle Tree 77 | - **Challenge 2**: Prove You Are Part of a Group 78 | - _Note_: Think about cryptographic methods for proving membership in a particular set or group. 79 | 80 | ## **3. How Token Mixers Work** 81 | 82 | ### **3.1 Learn** 83 | 84 | - Watch **[Breaking Down Tornado Cash](https://learn.0xparc.org/materials/circom/learning-group-1/breaking-down-tornado)** workshop by 0xParc. 85 | - Watch **[Poseidon-Tornado and Unit Testing](https://www.youtube.com/watch?v=-N6lI6kD65M)** by Chih-Cheng Liang. 86 | - Follow along with \*\*[his notes](https://hackmd.io/ISJ8sw7HTgysMNe0hW8iTA?view). 87 | - Study **[Tornado Cash Circuits](https://github.com/tornadocash/tornado-core)**. 88 | - Watch **[this video](https://www.youtube.com/watch?v=tJjDVlnkmyA&list=PL_SqG412uYVYtEM8B8xNccFyhrGsMV1MG&index=9)** covering the Tornado Cash whitepaper by Darth Cy. 89 | - If the whitepaper section is too dry, consider fast-forwarding to the “Implementation Planning” part of the video. 90 | - Consider watching other videos in Darth Cy’s **[Tornado Cash series](https://www.youtube.com/playlist?list=PL_SqG412uYVYtEM8B8xNccFyhrGsMV1MG)**. 91 | - The **[final video](https://www.youtube.com/watch?v/4wyRZc_tKjw&list=PL_SqG412uYVYtEM8B8xNccFyhrGsMV1MG)** in the series is particularly enlightening (although quite long). 92 | - Reflect on what nullifiers are and how they are used to keep anonymity in Tornado Cash. 93 | 94 | ### **3.2 Challenges** 95 | 96 | - **Challenge 1**: Create a Token Mixer 97 | - _Note_: Attempt to make a barebones simplified version of a token mixer circuit. If you have time, try to make the smart contracts and a frontend for it too. 98 | 99 | ## **4. Bonus Content** 100 | 101 | ### **4.1 Semaphore and RLN** 102 | 103 | Take a look at the circuits from **[Semaphore](https://github.com/semaphore-protocol/semaphore/tree/main/packages/circuits)** and **[RLN](https://github.com/Rate-Limiting-Nullifier/circom-rln)** and try to understand how they work. 104 | 105 | ### **4.2 Battlezips** 106 | 107 | Previous PSE grantee, **[jp4g.eth](https://twitter.com/jp4g_)**, has an excellent series on Battlezips. This is the ZK version of the classic **[Battleship board game]()**. 108 | 109 | All **[five videos](https://www.youtube.com/playlist?list=PLWACGbvIsEgn44LlTiPgVkOC4nG8tnJX-)** combined is only about 1.5 hours long. The **[channel](https://www.youtube.com/@battlezipszeroknowledgecra7405/playlists)** itself also has some videos on Noir and Halo2, for those who are interested. 110 | 111 | # **Module 7 - Week 2** 112 | 113 | Now it’s time to get acquainted with open-source, Github, and starting your own project! 114 | 115 | ## **Day 1 - Stage 1 Curriculum Feedback** 116 | 117 | One of the ultimate goals of this program is to encourage you to explore the world of open-source development. As such, we will take one day away from the technical content and ask you for your feedback on the Stage 1 curriculum. 118 | 119 | It’s important to keep in mind that this is the first time this program has been run. So there are likely many issues and inefficiencies you have experienced so far and we would like to hear about them. 120 | 121 | Some of the most famous open-source programmers started their open-source careers just correcting spelling and grammar mistakes. No change is too small! This exercise is meant to get you acquainted with the Github workflow. 122 | 123 | If you’re not familiar with Git and Github, please take a look at **[this video](https://www.youtube.com/watch?v=tRZGeaHPoaw)** for a quick introduction to Git and Github. 124 | 125 | For making a pull request, checkout **[this video](https://www.youtube.com/watch?v=8lGpZkjnkt4)**. 126 | 127 | Finally, check out **[this article](https://www.freecodecamp.org/news/how-to-use-git-best-practices-for-beginners/)** on best practices with Git and Github. 128 | 129 | ### **Steps** 130 | 131 | Once you feel ready, please attempt the following: 132 | 133 | 1. Take a look at this **[repository](https://github.com/adrianmcli/summer-contribution-program)**. 134 | 2. File an “Issue” under the issue tab with what you’d like to improve (or a problem you want to point out). 135 | 3. Engage in conversation with the repository maintainer. 136 | 4. Volunteer to take up an issue and submit a “pull request” (PR). 137 | - _Note_: You’ll need to fork and clone the repo first, and then make a new branch. This is explained in the pull request video above. 138 | 5. Wait for some feedback and make changes as necessary. 139 | 6. See your changes get merged! 140 | 141 | As with the rest of this program, this part is also an experiment. So please bear with us throughout this process! 142 | 143 | ## **Day 2 to Day 5 - Explore your own project!** 144 | 145 | For the rest of this week, we invite you to come up with your own ideas! Please talk to your mentors (and each other) and come up with something you would like to build. 146 | 147 | Feel free to take some inspiration from the projects you’ve learned about in this course. Sometimes, a small variation on an existing project can be just as exciting! 148 | 149 | ### **Steps** 150 | 151 | 1. Analyze everything you’ve learned so far, as well as projects that you’ve come across. 152 | 2. Come up with a few ideas for what you want to build. 153 | 3. Engage mentors (and peers) for feedback on your idea. 154 | 4. Create a new repository on [Github](https://github.com/new). 155 | 5. Create issues for each of the tasks required to complete this project (this will be your TODO list). 156 | 6. Get started building and remember to practice good [Git hygiene](https://grotoned.medium.com/git-hygiene-fadf533eb256)! 157 | -------------------------------------------------------------------------------- /2023/MODULE_6.md: -------------------------------------------------------------------------------- 1 | # Module 6 - Intro to Circuits 2 | 3 | As you know from Module 4, one of the first steps of creating zero knowledge proofs is to convert your problem into circuits. There are currently two popular ways of writing circuits, Circom and Halo2. 4 | 5 | Circom is a language designed specifically for writing zk-SNARK circuits. It plays a crucial role in creating zero-knowledge proofs, allowing for privacy and scalability in blockchain applications. Halo2, on the other hand, is a newer framework that offers some unique advantages. While it may not have as many resources available for learning, it's gaining traction in the community. 6 | 7 | 8 | Given that Circom has been around longer, in this module, we will focus on getting you setup with Circom and to start writing some simple circuits with it. 9 | 10 | ## 1. Getting Started with Circom 11 | 12 | To get started, we will go through a few of the pages of the Circom 2 documentation: 13 | 14 | 1. [**Installation [of Circom and SnarkJS]**](https://docs.circom.io/getting-started/installation/) 15 | 2. [**Writing Circuits**](https://docs.circom.io/getting-started/writing-circuits/) 16 | 3. [**Compiling Circuits**](https://docs.circom.io/getting-started/compiling-circuits/) ([note for Apple Silicon users](https://github.com/iden3/circom/issues/201)) 17 | 4. [**Computing the Witness**](https://docs.circom.io/getting-started/computing-the-witness/) 18 | 5. [**Proving Circuits**](https://docs.circom.io/getting-started/proving-circuits/) 19 | 20 | You might also find the following tutorials useful: 21 | 22 | - https://github.com/enricobottazzi/ZKverse 23 | - https://www.samsclass.info/141/proj/C523.htm 24 | 25 | ## 2. Circom Crash Course 💪 26 | 27 | Now that you have a basic idea of Circom and SnarkJS, let's play around with it a bit more. **This section will include questions that you should answer for this module.** 28 | 29 | The content below is an updated and adapted version of a [set of exercises](https://zku.gnomio.com/mod/assign/view.php?id=117) from ZK University (ZKU). You can still access the original content if you click the "Access as a guest" button in the link above, but we will continue here: 30 | 31 | 1. Fork and clone this repo: https://github.com/adrianmcli/week1 32 | 2. Go into the Q2 directory and run `npm install` 33 | 34 | ### 2.1 Trusted Setup 35 | 36 | In the `contracts/circuits` folder, you will find `HelloWorld.circom`. Run the bash script `scripts/compile-HelloWorld.sh` to compile the circuit. Answer the following questions: 37 | 38 | 1. What does the circuit in `HelloWorld.circom` do? 39 | 2. Lines 7-12 of `compile-HelloWorld.sh` download a file called `powersOfTau28_hez_final_10.ptau` for Phase 1 trusted setup. What is a Powers of Tau ceremony? Explain why this is important in the setup of zk-SNARK applications. 40 | 3. Line 24 of `compile-HelloWorld.sh` makes a random entropy contribution as a Phase 2 trusted setup. How are Phase 1 and Phase 2 trusted setup ceremonies different from each other? 41 | 42 | ### 2.2 Non-Quadratic Constraints 43 | 44 | Here, you will learn about an important restriction on Circom circuits. 45 | 46 | 1. In the empty `scripts/compile-Multiplier3-groth16.sh`, create a script to compile `contracts/circuits/Multiplier3.circom` and create a verifier contract modelled after `compile-HelloWorld.sh`. 47 | 2. Try to run `compile-Multiplier3-groth16.sh`. You should encounter an `error[T3001]` with the circuit as-is. Explain what the error means and how it arises. 48 | 3. Modify `Multiplier3.circom` to perform a multiplication of three input signals under the restrictions of circom. 49 | 50 | ### 2.3 Groth16 and PLONK 51 | 52 | In the empty `scripts/compile-Multiplier3-plonk.sh`, create a script to compile `circuit/Multiplier3.circom` using PLONK in SnarkJS. Add a `_plonk` suffix to the build folder and the output contract to distinguish the two sets of output. 53 | 54 | 1. You will encounter an error `zkey file is not groth16` if you just change `snarkjs groth16 setup` to `snarkjs plonk setup`. Resolve this error and answer the following question: *How is the process of compiling with PLONK different from compiling with Groth16?* 55 | 2. What are the practical differences between Groth16 and PLONK? Hint: compare and contrast the resulting contracts and running time of unit tests (see the next question below) from the two protocols. 56 | 57 | ### 2.4 Verify and Test 58 | 59 | So far we have not tested our circuit yet. While you can verify your circuit in the terminal using `snarkjs groth16 fullprove`, you can also do so directly in a Node.js script. We will practice doing so by creating some unit tests to try out our verifier contract(s): 60 | 61 | 1. Running `npx hardhat test` will prompt an `error HH606`. Before we can test our verifier contracts with hardhat, we must modify the Solidity version. In `scripts/bump-solidity.js`, we have already written the regular expressions to modify `HelloWorldVerifier.sol`. Add some code to `bump-solidity.js` to do the same for your new contract for `Multiplier3`. 62 | 2. You can now perform the unit tests for `HelloWorldVerifier` by running `npm run test`. Add comments to explain what each line in `test/test.js` is doing. 63 | 3. In `test/test.js`, add the unit tests for `Multiplier3` for both the Groth16 and PLONK versions. Ensure all tests pass (for `HelloWorld`, `Multiplier3 with Groth16`, and `Multiplier3 with PLONK`). 64 | 65 | #### Hint: SnarkJS API for Solidity Call Data Export 66 | 67 | The value returned by `plonk.exportSolidityCallData(proof, publicSignals)` can be found [here](https://github.com/iden3/snarkjs/blob/master/src/plonk_exportsoliditycalldata.js) and it is a little non-standard. You might need to do some string manipulation: 68 | 69 | ```javascript 70 | let rawCalldata = await plonk.exportSolidityCallData(proof, publicSignals); 71 | 72 | // fix string by replacing "][" with ", " 73 | const fixedStr = rawCalldata.replace(/\]\[/g, ", "); 74 | 75 | // convert the calldata string into an array of BigInts 76 | const fixedArray = fixedStr 77 | .replace(/["[\]\s]/g, "") 78 | .split(",") 79 | .map((x) => BigInt(x).toString()); 80 | 81 | // drop the last element of the array (the inputs) 82 | const calldata = [...fixedArray.slice(0, -1)]; 83 | ``` 84 | 85 | ### 2.5 Circuit Libraries 86 | 87 | In this section, you will be learning about libraries that you can import to create more complicated circuits. The original exercises are found in the Q3 directory, however we will present the code here for your convenience. 88 | 89 | #### Tip: For this section, use [**zkREPL**](https://zkrepl.dev/) for quick compiling and testing of circuits 90 | 91 | ### 2.5.1 circomlib 92 | 93 | [circomlib](https://github.com/iden3/circomlib) is the official library of circuit templates released by iden3, the creator of Circom. One important template included is [comparators.circom](https://github.com/iden3/circomlib/blob/master/circuits/comparators.circom), which implements value comparisons between two numbers. 94 | 95 | Here is `LessThan10.circom`: 96 | 97 | ```circom 98 | pragma circom 2.1.4; 99 | 100 | include "circomlib/comparators.circom"; 101 | 102 | template LessThan10() { 103 | signal input in; 104 | signal output out; 105 | 106 | component lt = LessThan(32); 107 | 108 | lt.in[0] <== in; 109 | lt.in[1] <== 10; 110 | 111 | out <== lt.out; 112 | } 113 | 114 | component main { public [ in ] } = LessThan10(); 115 | 116 | /* INPUT = { 117 | "in": "10" 118 | } */ 119 | ``` 120 | 121 | - `LessThan10.circom` implements a circuit that verifies an input is less than 10 using the [LessThan](https://github.com/iden3/circomlib/blob/master/circuits/comparators.circom#L89) template. Study how the template is used in this circuit. What does the 32 in Line 9 stand for? 122 | - What are the possible outputs for the `LessThan` template and what do they mean respectively? If you cannot figure this out by reading the code alone, feel free to compile the circuit and test with different input values. 123 | - Proving a number is within a range without revealing the actual number could be useful in applications like proving our income when applying for a credit card. In the following code `RangeProof.circom`, create a template that uses `GreaterEqThan` and `LessEqThan` to perform a range proof. 124 | 125 | Here is the initial template for `RangeProof.circom`: 126 | 127 | ```circom 128 | pragma circom 2.1.4; 129 | 130 | include "circomlib/comparators.circom"; 131 | 132 | template RangeProof(n) { 133 | assert(n <= 252); 134 | signal input in; // this is the number to be proved inside the range 135 | signal input range[2]; // the two elements should be the range, i.e. [lower bound, upper bound] 136 | signal output out; 137 | 138 | component lt = LessEqThan(n); 139 | component gt = GreaterEqThan(n); 140 | 141 | // [assignment] insert your code here 142 | } 143 | 144 | component main { public [ range ] } = RangeProof(32); 145 | 146 | /* INPUT = { 147 | "in": "5", 148 | "range": ["1", "10"] 149 | } */ 150 | ``` 151 | 152 | ### 2.5.2 circomlib-matrix and Sudoku 153 | 154 | [circomlib-matrix](https://github.com/socathie/circomlib-matrix) is a library covering basic matrix operations, modelled after circomlib, and created by our very own PSE member, Cathie So. Matrix operations can be useful in puzzles (e.g. [zkPuzzles](https://github.com/zku-cohort-3/zkPuzzles), [zkGames](https://github.com/vplasencia/zkGames)), image processing (e.g [zkPhoto](https://github.com/socathie/zkPhoto)), and machine learning (e.g. [zk-mnist](https://github.com/0xZKML/zk-mnist), [zk-ml](https://github.com/zk-ml/linear-regression-demo)). Let’s take a look at matrix operations in action in a Sudoku circuit. 155 | 156 | Modify the following code so that it implements the check on the inputs to be between 0 and 9 (inclusive) using your RangeProof template from above. 157 | 158 | 👉 [**sudoku.circom**](https://gist.github.com/adrianmcli/776d86438592c0486603f04ac6cee26e) 159 | 160 | Paste the above code into zkREPL to start working with it. Good luck on your final challenge of this module! 161 | 162 | ## Further Reading 163 | 164 | Congratulations on reaching the end of this module. If you have extra time, it is ***highly recommended*** that you go through the following tutorial by PSE member, Vivian Plasencia: 165 | 166 | 👉 [**How to create a Zero Knowledge DApp: From zero to production**](https://vivianblog.hashnode.dev/how-to-create-a-zero-knowledge-dapp-from-zero-to-production) 167 | 168 | It not only takes you through the process of creating your own circuits, but also guides you in the compilation of the associated smart contracts and the building of your frontend. 169 | 170 | ## Conclusion 171 | 172 | This marks the end of this module and also the first stage of this program. The aim of the program was to give a broad overview of the technical theory, mathematical background, and hands-on practical usage of the technology underlying the future of Ethereum's scaling and privacy. 173 | 174 | Going forward, we will practice more with writing circuits and eventually have you contribute to the open source community with your new skills! -------------------------------------------------------------------------------- /2023/MODULE_4.md: -------------------------------------------------------------------------------- 1 | # Module 4 - zkSNARKs 2 | 3 | In this module, we will "look under the hood" of zkSNARKs and acquire an understanding of how zkSNARKs are constructed. To set the stage, we will introduce the concepts of homomorphic hiding and blind evaluation. 4 | 5 | Then we will go through the process of converting a computation into a zkSNARK, starting from arithmetic circuits, to R1CS and QAP. Finally, we will explore some common proof systems like Groth16 and Plonk. 6 | 7 | ## 1. From Computation to QAP 8 | 9 | Now that you have a general idea of the topics above, let's turn to the "pipeline" of a zkSNARK construction. 10 | 11 | The goal of our construction is to be able to create a proof that a particular computation was properly executed. In order to do that, we must first transform it into a special form. 12 | 13 | ### 1.1 Arithmetic Circuits 14 | 15 | First, we need to convert our problem into something called an [arithmetic circuit](https://en.wikipedia.org/wiki/Arithmetic_circuit_complexity). This allows us to take an equation and "flatten" it into a series of simpler equations. Read the following: 16 | 17 | - The **Arithmetic Circuits** section of this [**Electric Coin article**](https://electriccoin.co/blog/snark-explain5/) 18 | - The **Flattening** section of this [**0xParc article**](https://learn.0xparc.org/materials/circom/additional-learning-resources/R1CS%20Explainer#step-1-flattening) 19 | - The following two posts in this series by Maurizio Binello: 20 | - [**From Theory to Practice**](https://www.zeroknowledgeblog.com/index.php/the-pinocchio-protocol/from-theory-to-practice) 21 | - [**One line, one operation**](https://www.zeroknowledgeblog.com/index.php/the-pinocchio-protocol/one-line-one-operation) 22 | 23 | ### 1.2 Rank-1 Constraint System (R1CS) 24 | 25 | Once we have this arithmetic circuit in the form as explained above, we can proceed to convert it into a representation of matrices and vertices known as the Rank-1 Constraint System (R1CS). 26 | 27 | To understand how it works, read the following resources: 28 | 29 | - [**R1CS: A Day in the Life of a few Equations**](https://learn.0xparc.org/materials/circom/additional-learning-resources/r1cs%20explainer/) - This 0xParc article was mentioned above, ensure you read this in full as it is a very friendly introduction to R1CS. 30 | - [**R1CS by Maurizio Binello**](https://www.zeroknowledgeblog.com/index.php/the-pinocchio-protocol/r1cs) - This is a continuation of Maurizio Binello's series of blog posts mentioned above. You might want to revisit the other pages in this series. 31 | 32 | ### 1.3 Quadratic Arithmetic Program (QAP) 33 | 34 | R1CS helped to reduce our computation into a set of matrices and vertices. But now, we need to convert it into a format called QAP. 35 | 36 | For understanding this, we turn to the following resources: 37 | 38 | - [**Explaining SNARKs Part V: From Computations to Polynomials**](https://electriccoin.co/blog/snark-explain5/) - A continuation of the Electric Coin blog series. 39 | - [**QAP by Maurizio Binello**](https://www.zeroknowledgeblog.com/index.php/the-pinocchio-protocol/qap) - A continuation of Maurizio Binello's blog series. 40 | - [**Quadratic Arithmetic Programs: from Zero to Hero**](https://medium.com/@VitalikButerin/quadratic-arithmetic-programs-from-zero-to-hero-f6d558cea649) - Vitalik Buterin's article on getting to a QAP representation. Feel free to start from the "R1CS to QAP" section. 41 | 42 | ## 2. Proof Systems 43 | 44 | Two common proof systems you should know about are Groth16 and PLONK. They are significant improvements over the Pinocchio proving system. Here is a very brief [overview](https://docs.gnark.consensys.net/Concepts/schemes_curves) of the two and their tradeoffs. 45 | 46 | ### 2.1 Groth16 47 | 48 | The efficiency of Groth16 is very hard to beat, and as such it has become a de-facto standard in many blockchain technologies that require an efficient proof system. However, the requirement of a circuit-specific trusted setup is a significant downside for some use-cases. 49 | 50 | We may skip the details of Groth16 but just keep in mind that the advantage is its small proof size. The disadvantage is that it requires a circuit specific trusted setup. These days, we have much more advanced proof systems that improve upon these trade-offs. Nevertheless, Groth16 continues to be used in a lot of existing projects. 51 | 52 | #### Optional Reading 53 | 54 | Here are a couple articles to understand how Groth16 works: 55 | 56 | - [Groth16 by Remco Bloemen](https://xn--2-umb.com/22/groth16/) - A very light article that covers the full life cycle of the Groth16 proving system. 57 | - [Groth16 by Maurizio Binello](http://www.zeroknowledgeblog.com/index.php/groth16) - A continuation of the blog series above that you should be well acquainted with. 58 | 59 | ### 2.2 PLONK 60 | 61 | PLONK has fast become one of the favourite proof systems because of its "universal and updateable" trusted setup, eliminating the need to have a new trusted setup for every circuit. 62 | 63 | Here are a couple resources to understand how PLONK works: 64 | 65 | - [Understanding PLONK by Vitalik Buterin](https://vitalik.eth.limo/general/2019/09/22/plonk.html) 66 | - [How does PLONK work? by David Wong](https://cryptologie.net/article/529/how-does-plonk-work-part-1-whats-plonk/) 67 | - [How PLONK Works: Part 1 by CoinGeek](https://coingeek.com/how-plonk-works-part-1/) 68 | - [How PLONK Works: Part 2 by CoinGeek](https://coingeek.com/how-plonk-works-part-2/) 69 | 70 | ## 3. Additional Study 71 | 72 | In the above, we have drawn very heavily from blog posts written by Vitalik Buterin, Electric Coin, and Maurizio Binello. However, these are only some of the many pathways towards understanding zkSNARK construction. 73 | 74 | Since it is always helpful to take a look at the same problem from different angles, we recommend you visit the following resources: 75 | 76 | - [**Why and How zk-SNARK Works**](https://medium.com/@imolfar/why-and-how-zk-snark-works-1-introduction-the-medium-of-a-proof-d946e931160) (highly recommended) - Originally [**a paper**](https://arxiv.org/abs/1906.07221) by Maksym Petkus, it dives into the specifics of how a zkSNARK is constructed, it has been converted to a series of blog posts for easy consumption. 77 | - [**ZK Whiteboard Sessions**](https://zkhack.dev/whiteboard/) - There are three videos by Dan Boneh (he's the B in BLS Signatures) providing a very compelling introduction to zkSNARKs. I highly recommend at least watching ***What is a SNARK?*** and ***Building a SNARK (Part I)***. 78 | - [**The MoonMath Manual for zkSNARKs**](https://leastauthority.com/community-matters/moonmath-manual/) - This is a free online textbook PDF that explains many of the necessary concepts. It is an excellent reference guide whenever you need to dive into specific topics. 79 | 80 | ### 3.1 Homomorphic Hiding and Blind Evaluation 81 | 82 | Let's start by looking into the concepts of homomorphic hiding and blind evaluation. Although not directly related to zkSNARKs, it is one of the main ingredients or concepts that make zkSNARKs possible. 83 | 84 | This blog series from Electric Coin is a good start: 85 | 86 | - [Explaining SNARKs Part I: Homomorphic Hidings by Electric Coin Co.](https://electriccoin.co/blog/snark-explain/) 87 | - [Explaining SNARKs Part II: Blind Evaluation of Polynomials](https://electriccoin.co/blog/snark-explain2/) 88 | 89 | ASecuritySite.com also has some helpful interactive examples that go along with these two blog posts: 90 | 91 | - [zkSNARK (Homomorphic Hiding)](https://asecuritysite.com/zero/zksnark01) 92 | - [zkSNARK (Blind Evaluation Problem)](https://asecuritysite.com/zero/zksnark02) 93 | 94 | ### 3.2 The Pinocchio Protocol 95 | 96 | The Pinocchio Protocol was first described in a paper in 2013, [**Pinocchio: Nearly Practical Verifiable Computation**](https://eprint.iacr.org/2013/279). As the name suggests, it was a big step towards the practical construction of zkSNARKs that we know today. It builds upon the QAP representations we described above and it is also here where elliptic curve pairings become relevant again. 97 | 98 | Admittedly, the details from here get even more technical than before. So it is important to start with a focused article before moving onwards. 99 | 100 | Therefore, read Vitalik's article, [**zk-SNARKs: Under the Hood**](https://medium.com/@VitalikButerin/zk-snarks-under-the-hood-b33151a013f6). This article was designed to follow his two other blog posts (on [QAP](https://medium.com/@VitalikButerin/quadratic-arithmetic-programs-from-zero-to-hero-f6d558cea649) and [Pairings](https://medium.com/@VitalikButerin/exploring-elliptic-curve-pairings-c73c1864e627)), so feel free to revisit those articles if you need to. 101 | 102 | Once you have done this, check out Maurizio Binello's page on the [**history of the Pinocchio paper**](https://www.zeroknowledgeblog.com/index.php/the-pinocchio-protocol). You can then jump back into the series by reading the page on [Hiding](https://www.zeroknowledgeblog.com/index.php/the-pinocchio-protocol/hiding) (which follows after the page on QAP) and continue by clicking "Next" at the bottom of each page. 103 | 104 | Finally, Part VI of the Electric Coin series provides a brief sketch of the protocol. While Part VII ties it all up with elliptic curve pairing concepts. Both of these are worth a read: 105 | 106 | - [**Explaining SNARKs Part VI: The Pinocchio Protocol**](https://electriccoin.co/blog/snark-explain6/) 107 | - [**Explaining SNARKs Part VII: Pairings of Elliptic Curves**](https://electriccoin.co/blog/snark-explain7/) 108 | 109 | # 💪 Exercises 110 | 111 | Answer the following questions (in as much detail as you like). 112 | 113 | ## Homomorphic Hiding 114 | 115 | 1. Explain homomorphic hiding in your own words. 116 | 117 | ## Arithmetic Circuits 118 | 119 | 1. What is the primary purpose of converting a problem into an arithmetic circuit? 120 | 2. What are the main components of an arithmetic circuit? 121 | 122 | ## Rank-1 Constraint System (R1CS) 123 | 124 | 1. Describe the Rank-1 Constraint System (R1CS) in your own words. 125 | 2. Why is R1CS essential in the zkSNARK construction pipeline? 126 | 127 | ## Quadratic Arithmetic Program (QAP) 128 | 129 | 1. What is the primary goal of converting R1CS into a QAP? 130 | 2. How does QAP aid in the zkSNARK proof generation process? 131 | 3. Why are polynomials central to the QAP representation? 132 | 133 | ## The Pinocchio Protocol 134 | 135 | 1. Why is the Pinocchio Protocol considered a significant step towards practical zkSNARK construction? 136 | 2. How does the Pinocchio Protocol utilize QAP representations? 137 | 3. What role do elliptic curve pairings play in the Pinocchio Protocol? 138 | 139 | ## Groth16 140 | 141 | 1. What makes Groth16 a popular choice for zkSNARK constructions in blockchain technologies? 142 | 2. Describe the main advantage and disadvantage of the Groth16 proof system. 143 | 3. How does Groth16 differ from the original Pinocchio Protocol? 144 | 145 | ## PLONK 146 | 147 | 1. What are the advantages of PLONK over Groth16? What are the disadvantages? 148 | 2. How does PLONK eliminate the need for a new trusted setup for every circuit? 149 | -------------------------------------------------------------------------------- /2023/MODULE_3.md: -------------------------------------------------------------------------------- 1 | # Module 3 - Crypto Essentials: Elliptic Curves and More 2 | 3 | Welcome to Module 3. First, we will explore the key concepts behind elliptic curves and their importance in modern cryptography. Then we will take you deeper into more advanced topics like bilinear maps, pairing-based cryptography, and KZG polynomial commitments, multi-party computation. 4 | 5 | ## Intro to Elliptic Curve Cryptography 6 | 7 | Elliptic curve cryptography builds upon traditional cryptographic principles by applying them to the mathematical structure of elliptic curves. 8 | 9 | For example, there exists an **Elliptic Curve Discrete Log Problem (ECDLP)**. By using elliptic curves, it has certain benefits over the regular Discrete Log Problem (DLP). These links are a good place to start: 10 | 11 | - [Elliptic Curves - Computerphile [8:41]](https://www.youtube.com/watch?v=NF1pwjL9-DE) 12 | - [A (relatively easy to understand) primer on elliptic curve cryptography](https://blog.cloudflare.com/a-relatively-easy-to-understand-primer-on-elliptic-curve-cryptography/) 13 | 14 | **Elliptic Curve Digital Signature Algorithm (ECDSA)** extends the traditional Digital Signature Algorithm (DSA) by incorporating elliptic curves as well, enabling stronger security with shorter key lengths. This makes the algorithm more efficient and suitable for constrained environments. ECDSA is widely used in various secure communication protocols, including SSL/TLS. 15 | 16 | The following StackExchange answer goes over the differences between some of the most popular digital signature protocols. It also leads into our next topic, which is another type of digital signature called the Edwards-curve Digital Signature Algorithm (EdDSA). 17 | 18 | - [What is the difference between the RSA, DSA, and ECDSA keys that ssh uses?](https://askubuntu.com/a/1000928/733503) 19 | 20 | ## Schnorr Signatures and EdDSA (Optional) 21 | 22 | EdDSA modifies and extends the Schnorr signature scheme to provide additional benefits. So it is crucial to first get an understanding of Schnorr signatures. 23 | 24 | ### EC-Schnorr Signatures 25 | 26 | Schnorr signatures can also be extended to elliptic curves. A key benefit is their linear structure, which allows for multi-signature aggregation. 27 | 28 | - [Introduction to Schnorr Signatures with Elichai Turkel](https://www.youtube.com/watch?v=XKatSGCZ-gE) 29 | - [What Is a Schnorr Signature? (by Chainlink)](https://blog.chain.link/schnorr-signature/) 30 | - [What The Heck Is Schnorr (by Rajarshi Maitra)](https://medium.com/bitbees/what-the-heck-is-schnorr-52ef5dba289f) 31 | - [Introduction to Schnorr Signatures (more technical)](https://tlu.tarilabs.com/cryptography/introduction-schnorr-signatures) 32 | 33 | Let's dive into EdDSA and see how it builds on concepts found in Schnorr Signatures. 34 | 35 | ### Edwards-curve Digital Signature Algorithm (EdDSA) 36 | 37 | Unlike Schnorr signatures, which may use a random value for generating the signature, EdDSA takes a deterministic approach. It hashes the private key and the message together to produce the randomness, ensuring repeatability. 38 | 39 | 40 | Suppose we have a private key `k` and a message `m`. In EdDSA, we would compute: 41 | - `r = HASH(k || m)` 42 | - `R = r * G` 43 | where `G` is the base point on the curve and `R` is another point on the curve. 44 | 45 | Just like Schnorr, the signature in EdDSA is a pair `(R, s)`, where: 46 | - `s = (r + HASH(R || A || m) * k) mod q` 47 | 48 | The verification checks: 49 | - `s * G = R + HASH(R || A || m) * A` 50 | 51 | With the values `A` (public key), `m` (message), and the signature values `R` and `s`, verification would involve checking that the left-hand and right-hand sides of the above equation match. 52 | 53 | For more on EdDSA, check out the following links: 54 | 55 | - [EdDSA and Ed25519](https://cryptobook.nakov.com/digital-signatures/eddsa-and-ed25519) 56 | - [What's an EdDSA?](https://duo.com/labs/tech-notes/whats-an-eddsa) 57 | - [Digital Signatures - ECDSA, EdDSA and Schnorr [19:50]](https://www.youtube.com/watch?v=S77ES52AGVg) 58 | 59 | ## Pairing-Based Cryptography (PBC) 60 | 61 | Many of the following topics will depend upon what is called pairing-based cryptography. 62 | You can imagine pairing as the multiplication of elliptic curves. The original elliptic curve operation is homomorphically additive but not homomorphically multiplicative. Pairing is a way to mimic this "multiplication". 63 | 64 | This is largely used in zk, especially during the verification stage. 65 | 66 | ![Pairing](./assets/elliptic-curve-pairings.jpeg) 67 | [Source](https://www.inevitableeth.com/home/concepts/elliptic-curve-pairings) 68 | 69 | If you would like to know more about it, you can check out the following resources: 70 | 71 | - **[Exploring Elliptic Curve Pairings by Vitalik Buterin (optional)](https://medium.com/@VitalikButerin/exploring-elliptic-curve-pairings-c73c1864e627)** - This resource builds upon the knowledge you learned above regarding elliptic curves and sets the stage for the topics discussed below. It is an excellent introduction to the topic. 72 | - **[Pairings or Bilinear Maps by Alin Tomescu](https://alinush.github.io/2022/12/31/pairings-or-bilinear-maps.html)** - This resource begins with an introduction to the three fundamental properties of bilinear maps. Building on this foundation, it further explores applications such as the Tripartite Diffie-Hellman protocol, BLS signatures, and Identity-Based Encryption (IBE). 73 | 74 | Make sure you read these two articles in full before proceeding. 75 | 76 | ### Bilinear Maps Deep Dive [Optional] 77 | 78 | For those who desire a deeper dive into bilinear maps and pairings, check out these resources: 79 | 80 | - [Intro to Bilinear Maps by John Bethencourt (28 slides)](https://people.csail.mit.edu/alinush/6.857-spring-2015/papers/bilinear-maps.pdf) 81 | - [ZK and NIZK from Bilinear Maps (part1) - Jens Groth [36:04]](https://www.youtube.com/watch?v=_mAKh7LFPOU) 82 | - [Pairings in Cryptography by Dan Boneh [1:29:48]](https://www.youtube.com/watch?v=8WDOpzxpnTE) 83 | - **Note:** This video is very long and technical, but can be a helpful reference. 84 | 85 | ## BLS Signatures 86 | 87 | BLS (Boneh-Lynn-Shacham) signatures are a type of cryptographic signature scheme that allows for efficient aggregation of individual signatures into a single signature. It also makes use of pairing-based cryptography. 88 | 89 | The intuition of BLS is that it is an aggregation signature. The image below shows how the public key and signature are aggregated. The advantage is that all signatures can be verified at once. That's why it is commonly used in consensus protocols. 90 | ![BLS](./assets/bls-signatures.jpeg) 91 | 92 | ### Optional Reading 93 | 94 | The following articles offer a great introduction to BLS signatures and why they are important for the scaling of Ethereum (more specifically, the Beacon Chain): 95 | 96 | - [Upgrading Ethereum (chapter on BLS Signatures) by Ben Edgington](https://eth2book.info/capella/part2/building_blocks/signatures/) 97 | - [What is the BLS signature scheme? by David Wong](https://www.cryptologie.net/article/472/what-is-the-bls-signature-scheme/) 98 | - [BLS Signatures by Alon Muroch - Overview (Part 1)](https://alonmuroch-65570.medium.com/bls-signatures-part-1-overview-47d9eebf1c75) 99 | - [BLS Signatures by Alon Muroch - Key Concepts of Pairings (Part 2)](https://alonmuroch-65570.medium.com/bls-signatures-part-2-key-concepts-of-pairings-27a8a9533d0c) 100 | - [BLS Signatures by Remco Bloemen](https://xn--2-umb.com/22/bls-signatures/) 101 | - [BLS Signature Aggregation: Under the Hood by Stu](https://mirror.xyz/0x6afeB3d9E380787e7D0a17Fc3CA764Bb885014FA/D3g-4UPRLkAnug-p6AZYfjgXWo-psaTulyu3SaL35vg) 102 | 103 | ## KZG Polynomial Commitments 104 | 105 | Polynomial Commitments are cryptographic tools that allow the hiding of some coefficients while revealing others. They're used in various cryptographic proofs and blockchain protocols. For a better understanding of Polynomial Commitments 106 | The intuition of KZG is that it is a commitment scheme. It is used to commit to a polynomial and later reveal a certain point on that polynomial. All your input data "lock" a specific polynomial. 107 | 108 | ![KZG](./assets/polynomial-commitments-1.jpeg) 109 | 110 | Read this article: 111 | - [KZG commitment by Inevitable Ethereum](https://www.inevitableeth.com/home/concepts/kzg-commitment) 112 | 113 | ### Optional Reading 114 | 115 | - [Polynomials](https://vitalik.eth.limo/general/2021/01/26/snarks.html#polynomials) section of Vitalik's article on zk-SNARKs. 116 | - [KZG in Practice: Polynomial Commitment Schemes and Their Usage in Scaling Ethereum](https://scroll.io/blog/kzg) 117 | 118 | KZG Polynomial Commitments is another technology that relies on pairing-based cryptography. The protocol is built upon pairing-friendly elliptic curves and bilinear properties. With this protocol, both the proof and commitment size is constant, no matter the degree of the polynomial being used. 119 | 120 | Scroll's zk-rollup implementation makes use of this commitment scheme to commit to computations executed on an L2. While Ethereum’s Proto-Danksharding proposal ([EIP-4844](https://www.eip4844.com)) uses it to commit to data blobs. 121 | 122 | - [KZG in Practice by Scroll](https://scroll.io/blog/kzg) 123 | - [KZG Polynomial Commitments by Dankrad Feist](https://dankradfeist.de/ethereum/2020/06/16/kate-polynomial-commitments.html) 124 | - [KZG Polynomial Commitments by Alin Tomescu](https://alinush.github.io/kzg) 125 | 126 | ## Trusted Setup 127 | 128 | The concept of a trusted setup is an important part of the KZG Polynomial commitment scheme, and indeed part of the wider culture of Ethereum. Here are a few resources to learn more about trusted setups. 129 | 130 | The intuition of a trusted setup is that it is a process to generate a bunch of points on the elliptic curve, and the prover will input these points to the polynomial commitment. Therefore the output is a point on the curve as well. Specifically, the generation of these points require many people join and discard the secret value (which they used to create the point). It should not be possible to generate the points without this. That's why it is called a trusted setup. 131 | 132 | ### Optional Reading 133 | 134 | - [How do trusted setups work? by Vitalik Buterin](https://vitalik.eth.limo/general/2022/03/14/trustedsetup.html) 135 | - [On-Chain Trusted Setup Ceremony by a16zcrypto](https://a16zcrypto.com/posts/article/on-chain-trusted-setup-ceremony/) 136 | - [The KZG Ceremony - or How I Learnt to Stop Worrying and Love Trusted Setups by Carl Beekhuizen [27:27]](https://www.youtube.com/watch?v=dTBy661ubgg) 137 | - [Trusted Setup by 0xParc [48:42]](https://learn.0xparc.org/materials/circom/learning-group-1/trusted-setup/) 138 | 139 | ### Multi-Party Computation (MPC) [Optional] 140 | 141 | [Secure Multi-Party Computation](https://en.wikipedia.org/wiki/Secure_multi-party_computation) or MPC for short, is a protocol that allows multiple entities to jointly compute a function without revealing their individual inputs. 142 | 143 | The classic example of MPC is the [Yao's Millionaire Problem](https://en.wikipedia.org/wiki/Yao%27s_Millionaires%27_problem). This is a thought experiment in which two millionaires are interested in knowing which of them is richer without revealing their actual wealth. 144 | 145 | MPC can be used to generate the secret value and the SRS for a trusted setup in a distributed manner, where multiple parties collaborate to generate the parameters without any single party having access to the entire secret value. 146 | 147 | - [Introduction to Multi-Party Computation (MPC or SMPC) [5:43]](https://www.youtube.com/watch?v=90jcXCHsBF0) 148 | - [Sharing Knowledge without Sharing Data by Azer Bestavros [32:08]](https://www.youtube.com/watch?v=P2MmO458xu4) 149 | - [Accessible and Scalable: Secure Multi-Party Computation](https://multiparty.org/) 150 | - [Intro to MPC (Javascript tutorial and examples)](https://github.com/multiparty/jiff/blob/master/tutorials/0-intro-to-mpc.md) 151 | 152 | # 💪 Exercises 153 | 154 | Answer the following questions (in as much detail as you desire): 155 | 156 | ## Intro to Elliptic Curves 157 | 158 | 1. What is the general equation for an elliptic curve? 159 | 2. How do you find the sum of two points P and Q on an elliptic curve? 160 | 3. What is the special point on the elliptic curve that serves as the identity element for addition? 161 | 162 | ## Elliptic Curve Cryptography 163 | 164 | 1. What is the primary advantage of ECC over traditional methods like RSA? 165 | 2. How is the public key in ECC derived from the private key? 166 | 3. What is the Elliptic Curve Discrete Logarithm Problem (ECDLP)? 167 | 168 | ## Schnorr Signatures and EdDSA 169 | 170 | 1. What are the primary advantages of Schnorr Signatures? 171 | 2. What differentiates EdDSA from traditional Schnorr signatures? 172 | 173 | ## Pairing-Based Cryptography 174 | 175 | 1. What is a pairing in the context of elliptic curve cryptography? 176 | 2. What are the three main properties of a bilinear map? 177 | 3. Name one cryptographic application that is enabled by pairings. 178 | 179 | ## KZG Polynomial Commitments 180 | 181 | 1. What is the primary purpose of a polynomial commitment scheme? 182 | 2. How is the commitment in the KZG scheme computed for a given polynomial and secret value? 183 | 3. Why are KZG polynomial commitments considered efficient and succinct? 184 | 185 | ## Trusted Setup 186 | 187 | 1. Why is the trusted setup phase crucial for the security of certain cryptographic protocols? 188 | 2. How is the trusted setup related to zk-SNARKs? 189 | 3. What are some of the challenges associated with trusted setups? 190 | -------------------------------------------------------------------------------- /2024/week0_course_primer.md: -------------------------------------------------------------------------------- 1 | # Week 0 - The Course Primer 2 | 3 | This is the pre-requisite module to be completed *before* the program begins. Everything in this module was designed to be easy to learn without much need for external mentorship support. However, if you find that you need additional support, don't hesitate to reach out! 4 | 5 | **Complete this module in its entirety before the program begins! ⚠️📚⚠️** 6 | 7 | ## Getting Help 8 | 9 | It's important to ask questions early and often. Many of the topics discussed are complex, and reaching out to others for different perspectives can be very helpful. The following section details how and where to ask questions. 10 | 11 | ### How to Ask Questions 12 | 13 | When asking questions, it is important to consider several things before sending them off: 14 | 15 | - **Structure for the Reader**: 📋 Organize your question clearly to make it easy to follow. 16 | - **Describe the Problem**: 🛠️ Clearly explain the problem you are facing, including the issues or errors you have encountered. 17 | - **Detail Your Attempts**: 🔍 Mention what you have already tried to solve the problem. 18 | - **Provide Context**: 🌐 If relevant, give enough context, including code snippets or examples, so the reader can replicate the situation. 19 | - **Specify Your Environment**: 💻 Mention your development environment, tools, and versions, if applicable. 20 | - **Be Polite and Patient**: 🙏 Remember to be courteous and patient while waiting for a response. 21 | 22 | ### Where to Ask Questions 23 | 24 | - [Core Program Discord](https://discord.gg/Xd6wdU2QJg) - This is a good place to start as other students will have likely encountered similar questions and be able to help out. 25 | - [PSE Discord](https://discord.com/invite/sF5CT5rzrR) - This is the Discord chat for the entire PSE team. It consists of experts in the space doing active research and can answer some of your most technical questions. We recommend posting in the "#❓ask-any-question" channel. 26 | - [Core Program Telegram](https://t.me/+h6P9q5Ia0vdlMDYx) - Some of you might prefer Telegram. While this might be less focused than Discord, it's still worth posting your questions here if you are looking for more help. 27 | 28 | ### How to Work with GitHub PR Workflow? 29 | 30 | It's important to understand how to work with GitHub PR workflow in core program. Watch this [3 minutes video](https://youtu.be/jRLGobWwA3Y?si=6uZrn8mrd30QnUtW) to understand how to work with GitHub PR workflow. 31 | 32 | ```mermaid 33 | sequenceDiagram 34 | participant Developer 35 | participant GitHub 36 | participant Reviewer 37 | participant Maintainer 38 | 39 | Developer->>GitHub: Create branch and make changes 40 | Developer->>GitHub: Push branch to repository 41 | Developer->>GitHub: Open a pull request (PR) 42 | GitHub->>Reviewer: Notify reviewer of PR 43 | Reviewer->>GitHub: Review code and leave comments 44 | Developer->>GitHub: Address comments and push updates 45 | Reviewer->>GitHub: Approve changes 46 | GitHub->>Maintainer: Notify maintainer of approved PR 47 | Maintainer->>GitHub: Merge PR into main branch 48 | GitHub->>Developer: Notify developer of merged PR 49 | GitHub->>Team: Update branch status and notify team 50 | ``` 51 | 52 | ## Course Info 53 | 54 | This course was originally designed to help build the next generation of open-source contributors in the space of Zero Knowledge Proofs (ZKPs). The scope has since expanded to include concepts like Multi-Party Computation (MPC) and Fully Homomorphic Encryption (FHE). These topics can be encapsulated under a broader umbrella called Programmable Cryptography (ProgCrypto). 55 | 56 | It's not only enough to know the fundamentals of ProgCrypto, but it's necessary to understand the culture of open-source development, public goods, and how to use Git and Github effectively. 57 | 58 | ### Open-Source Culture, Git, and Github 59 | 60 | A good summary of open-source culture, Git, and GitHub can be found in the following presentation by Adrian Li (the original author of this curriculum). 61 | 62 | 🎥 **The Way of Open Source (video) [18:28]**: [Watch here](https://drive.google.com/file/d/1T7ACbYl4joqrJg6dRxHaIYNNhWrftamB/view?usp=drive_link) 63 | 64 | 📊 **The Way of Open Source (slides)**: [View here](https://docs.google.com/presentation/d/1wqyn6FnyINulTSEIWwZaVYak3ONbjTUi9shBOhAZkd8/edit?usp=sharing) 65 | 66 | Take some time to watch the video and afterwards review the following links as further reference: 67 | 68 | - [**Git Cheat Sheet (by Github)**](https://education.github.com/git-cheat-sheet-education.pdf) - A concise list of common commands provided by Github Education. 69 | - [**Comparing Git Workflow (by Atlassian)**](https://www.atlassian.com/git/tutorials/comparing-workflows) - This article by Atlassian compares popular workflows when using Git. For this course, a basic Feature Branching workflow should be sufficient. 70 | 71 | ## Prerequisite Knowledge 72 | 73 | A useful approach to learning complex topics is to "blackbox" the concepts. This means focusing on high-level ideas first and saving the detailed exploration for later. This way, you won't get intimidated by the complexity. 74 | 75 | When studying a topic for the first time, only read the required materials. Skip the optional readings unless you're particularly curious about the details. This strategy will help you grasp the main concepts without feeling overwhelmed. 76 | 77 | ### A Primer for Zero Knowledge Proofs 78 | 79 | Before we delve into the core content of the module, consider acquainting yourself with some high-level concepts of Zero-Knowledge Proofs. Skim the following introductory articles to build a strong foundational understanding: 80 | 81 | - [Zero-knowledge proofs | ethereum.org](https://ethereum.org/en/zero-knowledge-proofs/) 82 | - [A Primer on Zero-Knowledge Proofs 🔏](https://medium.com/hackernoon/a-primer-on-zero-knowledge-proofs-892e6e277142) 83 | - [Zero Knowledge Proofs: An illustrated primer [Part 1]](https://blog.cryptographyengineering.com/2014/11/27/zero-knowledge-proofs-illustrated-primer/) 84 | - [Zero Knowledge Proofs: An illustrated primer [Part 2]](https://blog.cryptographyengineering.com/2017/01/21/zero-knowledge-proofs-an-illustrated-primer-part-2/) 85 | 86 | Then let's look at a graphic explanation about the Zero-Knowledge proofs generic workflow: 87 | 88 | ```mermaid 89 | sequenceDiagram 90 | participant Issuer 91 | participant Prover 92 | participant Verifier 93 | 94 | Issuer->>Prover: Issue secret and public data 95 | Prover->>Verifier: Send proof 96 | Verifier->>Prover: Verify proof 97 | Verifier->>Verifier: Check validity 98 | Verifier->>Issuer: Confirm verification result 99 | ``` 100 | 101 | Throughout this course, we will provide you with a set of reflection questions to check your understanding. 102 | 103 | :::info 104 | **🤔 Consider the following:** 105 | 1. What are Zero-Knowledge Proofs? 106 | 2. What are the principles of soundness, completeness, and zero-knowledge? 107 | 3. What distinguishes interactive from non-interactive proofs? 108 | ::: 109 | 110 | ## Practical 111 | 112 | Since many ZK proof systems are written in Rust, take the time to learn Rust with [Rustlings](https://rustlings.cool/). It is a game with nearly 100 challenges. You are required to finish it before the start of the program. 113 | 114 | ### Thought Experiments 115 | 116 | Engaging with these thought experiments will make abstract concepts more tangible and facilitate a deeper understanding of ZKPs. Each of these examples offers a unique perspective on the concept of zero-knowledge proofs: 117 | 118 | - [Example 1: Where’s Waldo?](https://medium.com/swlh/a-zero-knowledge-proof-for-wheres-wally-930c21e55399) 119 | - [Example 2: Colored Balls (interactive)](https://en.wikipedia.org/wiki/Zero-knowledge_proof#Two_balls_and_the_colour-blind_friend) 120 | - [Example 3: Sudoku (non-interactive)](https://www.wisdom.weizmann.ac.il/~naor/PAPERS/SUDOKU_DEMO/) 121 | 122 | :::info 123 | **🤔 Consider the following:** 124 | 1. Which example did you find most enlightening, and why? 125 | 2. How do these examples demonstrate the principles of zero-knowledge proofs? 126 | 3. Can you think of any potential applications of these concepts in everyday life? 127 | 4. Can you explain these thought experiments to someone non-technical? Try it with a friend or family member! 128 | ::: 129 | 130 | ### Use-Cases and Applications 131 | 132 | To connect theory with practice, let's explore the practical applications of ZKPs. The following resources illustrate how ZKPs are employed in real-world applications, particularly in the domain of blockchain: 133 | 134 | - [Ethereum Use Cases for ZKPs](https://ethereum.org/en/zero-knowledge-proofs/#use-cases-for-zero-knowledge-proofs) 135 | - [More Applications](https://link.springer.com/article/10.1007/s42452-019-0989-z#Sec4) 136 | 137 | :::info 138 | **🤔 Consider the following:** 139 | 1. Which application of ZKP do you find most intriguing, and why? 140 | 2. Can you imagine any other potential applications of ZKP? 141 | ::: 142 | 143 | ### Supplemental materials on ZKPs [optional] 144 | 145 | For more content (especially for those who prefer videos), check out the following: 146 | 147 | - Video Lectures: 148 | - ['Introduction to Zero Knowledge Proofs' - Elena Nadolinski [19:59]](https://www.youtube.com/watch?v=BT88s7_VtC8) 149 | - [ZKP MOOC Lecture 1: Introduction and History of ZKP [1:38:32]](https://www.youtube.com/watch?v=uchjTIlPzFo) 150 | - [ZK Whiteboard Sessions - Module One: What is a SNARK? by Dan Boneh [42:08]](https://youtu.be/h-94UhJLeck) 151 | - [Detailed Explanation of Zero-Knowledge Proofs](https://youtu.be/9je336QIqAQ?t=650) 152 | - [Thinking in Zero Knowledge](https://mirror.xyz/0x3FD6f213ae1B8a7B6bd8f14BE9BF316a5e5A5d28/VTGpmEYLKIslUPf66VQzHUneB0R7EhMpJJ_mGrMvTwY) 153 | - [LambdaWorks](https://github.com/lambdaclass/lambdaworks) This is a library where you're allowed to read the implementation of snark/stark cryptographic primitive. If you're more of a person who likes to read code, this is a good place to find out how things are done. 154 | 155 | By this point in the module, you should have a broad and multifaceted understanding of ZKPs. However, we're not done yet. Next, we'll tackle some key mathematical concepts that underpin this topic. 156 | 157 | ### Number Theory 158 | 159 | Building a solid foundation in number theory is essential for understanding the upcoming modules. The following module from Khan Academy provides an excellent introduction to this topic: 160 | 161 | - [An Introduction to Modular Math by Khan Academy](https://www.khanacademy.org/computing/computer-science/cryptography/modarithmetic/a/what-is-modular-arithmetic) 162 | 163 | Below are topics that you will need to research independently (or with a teammate). This could mean searching these specific terms on Google, YouTube, Wikipedia, or even asking ChatGPT. 164 | 165 | Don't forget to reach out for help when you're stuck! 166 | 167 | ### Topics to Research 168 | 169 | - Fundamentals: 170 | - Prime Numbers and Composite Numbers 171 | - Greatest Common Divisors (GCD) 172 | 173 | - Modular Arithmetic and Congruence 174 | - What is modular arithmetic? 175 | - Exploring congruence classes 176 | 177 | - Group Theory 178 | - What is a group structure? 179 | - What is a group operation? 180 | 181 | - Diving Deeper: 182 | - What is a finite group? 183 | - What is a cyclic group? 184 | - What is a generator? 185 | - What are finite fields? 186 | 187 | :::info 188 | **🤔 Consider the following:** 189 | 1. Which of these concepts did you find most challenging, and why? 190 | 2. Can you explain these concepts in your own words? 191 | ::: 192 | 193 | ## 💪 Exercises 194 | 195 | Here are the exercises for this module. Collaborate with others to find the answers, and remember to support each other! 196 | 197 | ### Comprehension 198 | 199 | Summarize each of the following concepts in a few sentences: 200 | 201 | 1. Three-Colouring Graph problem with Hats 202 | 2. Ali Baba’s Cave analogy 203 | 3. The difference between interactive and non-interactive proofs 204 | 205 | ### Modular Arithmetic 206 | 207 | Solve the following problems and gain a practical understanding of modular arithmetic: 208 | 209 | 1. $7\ mod\ 13$ 210 | 2. $15\ mod\ 13$ 211 | 3. $(7+15)\ mod\ 13$ 212 | 4. $(7\ mod\ 13 + 15\ mod\ 13)\ mod\ 13$ 213 | 214 | If the results of the third and fourth calculations match, they follow a "group structure". Can you determine if these do? 215 | 216 | ### Generators 217 | 218 | Consider the cyclic group $(Z_{12}, +\ mod\ 12)$, commonly referred to as the "additive group of integers modulo 12". Address the following points: 219 | 220 | 1. What does the term 'generator' mean? 221 | 2. Can you find a generator for this group? 222 | 3. Are there other generators for this group? If yes, what are they? 223 | 224 | ### Implementing a Modular Arithmetic Calculator 225 | 226 | Your task is to implement a simple modular arithmetic calculator in JavaScript (or similar high-level language of your choice). The calculator should support three operations: addition, subtraction, and multiplication. 227 | 228 | The function `modularCalculator` should take four parameters: 229 | - A string, `op`, indicating the operation. It will be one of '+', '-', or '*'. 230 | - Two integers, `num1` and `num2`, which are the operands for the operation. 231 | - An integer, `mod`, which is the modulus. 232 | 233 | The function should return the result of performing the indicated operation on `num1` and `num2`, then taking the result modulo `mod`. 234 | 235 | Remember, the result of subtraction could be negative, and in this case, you should add `mod` to the result to ensure it's positive. 236 | 237 | For addition and multiplication, remember that JavaScript's `%` operator gives the remainder, not the modulus, but these will be the same for positive numbers. 238 | 239 | **Code Template:** 240 | 241 | ```javascript 242 | function modularCalculator(op, num1, num2, mod) { 243 | // Your code here 244 | } 245 | 246 | modularCalculator('+', 10, 15, 12); // Should return: 1 247 | modularCalculator('-', 10, 15, 12); // Should return: 7 248 | modularCalculator('*', 10, 15, 12); // Should return: 6 249 | ``` 250 | 251 | Feel free to use `console.log` statements in your code to verify that your function is working as expected. For convenience, consider using https://repljs.com/ and pasting in the above code snippet to get started. 252 | 253 | ## Conclusion 254 | 255 | Congratulations on completing the Course Primer! You now have the foundational knowledge to dive deeper into Zero Knowledge Proofs and related cryptographic technologies. 256 | 257 | Remember to stay curious, collaborate with peers, practice regularly, and be patient with your learning process. We're excited to see your progress and contributions to Programmable Cryptography. Good luck, and don't forget to reach out for help whenever needed! 258 | -------------------------------------------------------------------------------- /2025/contributions/README.md: -------------------------------------------------------------------------------- 1 | # ZKET Core Program 2025: Contributions 2 | 3 | ![Core Program](https://img.shields.io/badge/Core-Program-blue) 4 | 5 | ## Contributions During the Core Program 6 | 7 | Throughout the Core Program, several talented hackers and teams came together to push the boundaries of cryptographic solutions and blockchain innovation. Their contributions spanned various areas and technologies. These projects not only showcased the technical expertise of the participants but also demonstrate the collaborative spirit essential to solving real-world challenges in decentralized ecosystems. 8 | 9 | ## **Core Program 2025 Projects** 10 | 11 | This is a complete list of contributions made by the program participants. 12 | 13 | | Project Name | Project Description | 14 | | :--------------------------------------------------------------------------------------------------------------- | :------------------ | 15 | | [RISC Zero REVM Integration](#risc-zero-revm-integration) 🇧🇷 | Zero-knowledge EVM bytecode execution using RISC Zero zkVM and revm library. | 16 | | [ZK Air Drop](#zk-air-drop) 🇧🇷 | Private airdrop claims using zero-knowledge proofs and Merkle trees. | 17 | | [Farewell](#farewell) 🇧🇷 | Farewell is a proof-of-concept dApp that allows people to leave posthumous encrypted messages to their loved ones. | 18 | | [Circom circuit verification with Clean](#circom-circuit-verification-with-clean) 🇧🇷 | Verification of Circom circuits in Clean | 19 | | [Post-Quantum Smart Account](#post-quantum-smart-account) 🇧🇷 | Smart Account (EIP-4337 Account Abstraction) that uses post-quantum cryptography (PQC) signatures | 20 | | [zkintro Portuguese Translation](#zkintro-portuguese-translation) 🇧🇷 | Translation of zkintro's first chapter to Brazilian Portuguese. | 21 | | [FHE VWAP Auction (FHEVM Full-Stack)](#fhe-vwap-auction) 🇧🇷 | Privacy-preserving batch auction on EVM using FHE; computes VWAP on-chain. | 22 | | [ZKP Minicourse](#zkp-minicourse) 🇧🇷 | ZKP minicourse in Portuguese aiming at the presentation at SBC | 23 | | [ZKCMP](#zkcmp) 🇧🇷 | Zero-knowledge Consent-Management CLI that issues, proves and verifies data-sharing consent totally offline with the Polygon ID JS-SDK. | 24 | 25 | --- 26 | 27 | ### RISC Zero REVM Integration 28 | 29 | **Contributors:** 30 | 31 | - Antonio Viggiano - [@aviggiano](https://github.com/aviggiano) 32 | 33 | **Project Description:** 34 | This project demonstrates the integration between RISC Zero zkVM and the revm Ethereum Virtual Machine library, enabling zero-knowledge proof generation for EVM bytecode execution. The implementation showcases how to execute smart contracts privately while maintaining verifiable correctness through zkSNARKs, opening possibilities for private smart contract execution, EVM-compatible rollups, cross-chain verification, and auditing tools. 35 | 36 | The main objective of this proof-of-concept is to showcase how a Zero-Knowledge Bug Bounty Program (ZKBBP) can be built. In such a system, a whitehat proves knowledge of a private bytes input $I$ that, when sent to a public function $F$ on public bytecode $B$, produces a public $true$ output. The proof reveals only commitments (hashes of code and calldata), ensuring the exploit input remains secret until disclosure is negotiated. Verifiers (on-chain or off-chain) can check the ZK receipt and be assured the claim is valid without ever learning the exploit itself. 37 | 38 | This minimal implementation provides the scaffold for building more advanced ZKBBPs where: Arbitrary EVM bytecode can be executed under proof, vulnerability classes can be modeled as verifiable predicates, and payout mechanisms can be automated on-chain once proofs are verified. 39 | 40 | **Technical Stack:** 41 | 42 | - Rust 43 | - RISC Zero zkVM 44 | - revm (Rust EVM implementation) 45 | - Ethereum Virtual Machine 46 | - Zero-Knowledge Proofs (zkSNARKs) 47 | 48 | **Project Goals:** 49 | 50 | - Demonstrate seamless integration between RISC Zero and revm 51 | - Enable private smart contract execution with proof generation 52 | - Provide foundation for EVM-compatible zero-knowledge applications 53 | - Showcase cross-chain verification capabilities 54 | - Create auditing tools for contract behavior verification 55 | 56 | **GitHub Link:** 57 | [https://github.com/risc0/demos/pull/52](https://github.com/risc0/demos/pull/52) 58 | 59 | **Other Links:** 60 | N/A 61 | 62 | --- 63 | 64 | ### ZK Air Drop 65 | 66 | **Contributors:** 67 | 68 | - Arthur F. Abeilice - [@afa7789](https://github.com/afa7789) 69 | 70 | **Project Description:** 71 | ZK Air Drop enables any eligible user to privately claim tokens from an airdrop using zero-knowledge proofs and Merkle trees. The user’s wallet address is included in the Merkle tree, and a ZK proof is generated off-chain to prove eligibility without revealing the full list or identity. The proof can be used to claim tokens from any wallet, anywhere, ensuring privacy and flexibility for claimants. 72 | 73 | **Technical Stack:** 74 | 75 | - Solidity 76 | - Circom 77 | - Next.js 78 | - TypeScript 79 | - Ethers.js 80 | - Foundry 81 | - Zero-Knowledge Proofs (Groth16) snarkjs 82 | 83 | **Project Goals:** 84 | 85 | - Allow private, universal token claims for airdrops 86 | - Enable proof generation for any wallet address in the Merkle tree 87 | - Prevent double-claims and Sybil attacks with ZK verification 88 | - Provide a simple web interface for proof generation and claiming 89 | 90 | **GitHub Link:** 91 | [https://github.com/afa7789/zk-token-distributor](https://github.com/afa7789/zk-token-distributor) 92 | 93 | **Other Links:** 94 | N/A 95 | 96 | --- 97 | 98 | ### Farewell 99 | 100 | **Contributors:** 101 | 102 | - Pedro G. M. R. Alves - [@pdroalves](https://www.iampedro.com) 103 | 104 | **Project Description:** 105 | Farewell is a proof-of-concept dApp that allows people to leave posthumous encrypted messages for their loved ones. Using blockchain smart contracts combined with [fhEVM](https://github.com/zama-ai/fhevm), the system securely stores secret shares of keys and encrypted payloads. A “check-in” mechanism ensures that messages are only released after a period of user inactivity, making Farewell a cryptographic time capsule designed to endure for decades. 106 | 107 | **Technical Stack:** 108 | 109 | - Solidity 110 | - Hardhat 111 | - fhEVM 112 | - React (frontend) 113 | 114 | **Project Goals:** 115 | 116 | - Provide a reliable and private mechanism for leaving encrypted messages that will only be released after death or prolonged inactivity. 117 | - Leverage blockchain persistence and cryptography to ensure fairness, security, and decentralization. 118 | - Explore integration of FHE and ZK proofs (e.g., ZKMail) for privacy-preserving proofs of delivery. 119 | 120 | **GitHub Link:** 121 | [github.com/pdroalves/farewell-core](https://github.com/pdroalves/farewell-core) 122 | 123 | **Other Links:** 124 | [Live demo](https://www.iampedro.com/farewell) 125 | 126 | --- 127 | 128 | ### Circom circuit verification with Clean 129 | 130 | **Contributors:** 131 | 132 | - Christiano Braga - [@christianobraga](https://github.com/ChristianoBraga) 133 | - Semar Augusto Martins - [@semaraugusto](https://github.com/semaraugusto) 134 | 135 | **Project Description:** 136 | 137 | ZK circuit verification is a major task in software engineering for ZK protocols. Given a verification framework, one needs to: 138 | 1. specify the circuit in the framework specification language; 139 | 2. state the pre and post-conditions of the circuit (as in [Hoare Logic](https://cs.stanford.edu/people/eroberts/courses/soco/projects/2008-09/tony-hoare/logic.html)); 140 | 3. prove the circuit's soundness and completeness using the verification framework. Quoting [https://blog.zksecurity.xyz/posts/clean/](https://blog.zksecurity.xyz/posts/clean/): 141 | - Soundness: if the prover can exhibit any witness that satisfies the constraints and lookup relations defined by the circuit, then some specification property holds over that witness. Proving this property ensures that the circuit is not underconstrained. 142 | - Completeness: for every possible input, an honest prover can always exhibit a witness that satisfies the constraints and lookup relations defined by the circuit. Proving this property ensures that the circuit is not overconstrained. 143 | 144 | We took a deep dive in Lean 4 and Clean in the 2nd. half of the program and interacted with Clean's team to understand their approach. These interactions lead to jointly concluding the specification and proof (of soundness and completeness) of Circomlib's [`Num2Bits`](https://github.com/Verified-zkEVM/clean/blob/62eb4edde2855c0403df9ad7e8d0c0a391958103/Clean/Circomlib/Bitify.lean#L135). Our team alone [proved](https://github.com/ChristianoBraga/clean/blob/ff2f656a325c974dfcf3ec9df4795584db85a36f/Clean/Circomlib/Comparators.lean#L46) the soundness and completeness of Circom's circuit [`IsZero`](https://github.com/Verified-zkEVM/clean/blob/62eb4edde2855c0403df9ad7e8d0c0a391958103/Clean/Circomlib/Comparators.lean#L14). This lead to [PR 265](https://github.com/Verified-zkEVM/clean/pull/265) at Clean's github. 145 | 146 | **Technical Stack:** 147 | 148 | - [Lean 4](https://lean-lang.org/) 149 | - [Clean](https://github.com/Verified-zkEVM/clean/) 150 | 151 | **Project Goals:** 152 | 153 | 1. Prove Circom circuits sound and complete. 154 | 2. Learn about theorem proving with Clean. 155 | 156 | **GitHub Link:** 157 | [https://github.com/ChristianoBraga/clean](https://github.com/ChristianoBraga/clean) 158 | 159 | **Other Links:** 160 | N/A 161 | 162 | --- 163 | 164 | ### Post-Quantum Smart Account 165 | 166 | **Contributors:** 167 | 168 | - Flavio de Freitas Gouvea Neto - [@freitasgouvea](https://github.com/freitasgouvea) 169 | 170 | **Project Description:** 171 | This project implements a Smart Account (EIP-4337 Account Abstraction) that uses post-quantum cryptography (PQC) signatures for transaction authorization. Instead of verifying heavy PQC signatures directly on-chain, the verification is performed off-chain and proven through a zero-knowledge proof (ZK). The smart contract only validates the proof, ensuring that the account owner has authorized the UserOperation. This approach combines quantum resistance, efficiency, and compatibility with Ethereum infrastructure. 172 | 173 | **Technical Stack:** 174 | 175 | - Go (PQC key generation and signature) 176 | - Dilithium (NIST PQC standard) 177 | - Zero-Knowledge proof framework (TBD) 178 | - Solidity (Smart Account contract implementation) 179 | - Ethereum (EIP-4337 Account Abstraction) 180 | 181 | **Project Goals:** 182 | 183 | - Implement PQC-based signature generation in Go for UserOperations. 184 | - Develop a ZK circuit to prove PQC signature validity without revealing computation. 185 | - Adapt a Smart Account contract to integrate the ZK verifier. 186 | - Demonstrate an end-to-end flow: UserOperation → PQC Signature → ZK Proof → On-chain Verification → Transaction Execution. 187 | 188 | **GitHub Link:** 189 | [PQ Signer](https://github.com/freitasgouvea/pq-signer-go) 190 | 191 | **Other Links:** 192 | N/A 193 | 194 | --- 195 | 196 | ### zkintro Portuguese Translation 197 | 198 | **Contributors:** 199 | 200 | - Thiago Rocha - [@thiagorochatr](https://thiagorochatr.com) 201 | 202 | **Project Description:** 203 | Translated the first chapter of `zkintro` into Brazilian Portuguese, preserving the original structure and formatting to improve accessibility for Portuguese-speaking readers. 204 | 205 | **Technical Stack:** 206 | 207 | - Markdown 208 | - Git 209 | - GitHub 210 | 211 | **Project Goals:** 212 | 213 | - Provide a high-quality PT-BR translation for zkintro's first chapter 214 | - Maintain parity with the original and update as upstream evolves 215 | 216 | **GitHub Link:** 217 | [https://github.com/zkintro/zkintro/pull/4](https://github.com/zkintro/zkintro/pull/4) 218 | 219 | **Other Links:** 220 | https://zkintro.com/ 221 | 222 | --- 223 | 224 | ### FHE VWAP Auction 225 | 226 | **Contributors:** 227 | 228 | - Thiago Rocha - [@thiagorochatr](https://thiagorochatr.com) 229 | 230 | **Project Description:** 231 | Privacy-preserving batch auction using Fully Homomorphic Encryption (FHE) on EVM. Sellers escrow Base tokens; buyers submit bids with encrypted prices. The VWAP (Volume-Weighted Average Price) is computed homomorphically on-chain and revealed via the FHEVM decryption oracle. Settlement occurs at the final public VWAP. 232 | 233 | **Technical Stack:** 234 | 235 | - Solidity 236 | - Hardhat 237 | - FHEVM 0.8.x 238 | - @zama-fhe/relayer-sdk (frontend) 239 | - Next.js 240 | - Tailwind CSS 241 | - TypeScript 242 | - Node.js (>= 20) 243 | - MetaMask (EIP-6963) 244 | 245 | **Project Goals:** 246 | 247 | - Implement an FHE-based VWAP batch auction on EVM 248 | - Perform on-chain encrypted aggregation with single oracle decryption 249 | - Provide a full-stack monorepo and generated ABIs for the frontend 250 | - Support localhost and Sepolia deployments with tests and coverage 251 | - Ship a usable dApp with MetaMask integration and network helpers 252 | 253 | **GitHub Link:** 254 | [https://github.com/thiagorochatr/FHEVWAP](https://github.com/thiagorochatr/FHEVWAP) 255 | 256 | **Other Links:** 257 | N/A 258 | 259 | --- 260 | 261 | ### ZKP Minicourse 262 | 263 | **Contributors:** 264 | 265 | - Alexandre Braga 266 | - Rayan Gustavo Lima - [@rayangustavo](https://github.com/rayangustavo) 267 | 268 | **Project Description:** 269 | This minicourse, delivered in Portuguese, introduces software developers to Zero-Knowledge Proofs (ZKPs), focusing on practical techniques and real-world frameworks to design circuits, generate and verify proofs, and integrate them into traditional software workflows. Aimed at programmers with little cryptography background, it lowers the entry barrier to ZKPs, encourages specialized training, and fosters collaboration between researchers and practitioners. The course is designed to be presented at a major conference, such as the SBC, addressing the current shortage of accessible educational resources in this field. 270 | 271 | **Technical Stack:** 272 | 273 | - LaTeX 274 | 275 | **Project Goals:** 276 | 277 | - Present zero-knowledge proof concepts and techniques to programmers with little experience in cryptography. 278 | - Show how ZKP frameworks can be integrated with traditional software development tools. 279 | - Show software developers, through simple techniques and tutorials with real tools, how to develop ZKP circuits, generate proofs, and verify them. 280 | - Facilitate deeper study of cryptography in the future. 281 | - Foster collaboration between researchers and practitioners in generating knowledge in this field. 282 | 283 | **GitHub Link:** 284 | [https://github.com/rayangustavo/zkp-minicurso](https://github.com/rayangustavo/zkp-minicurso) 285 | 286 | **Other Links:** 287 | https://pt.overleaf.com/read/wqgjnqfqwhyw#c0f386 288 | 289 | --- 290 | 291 | ### ZKCMP 292 | 293 | **Contributors:** 294 | 295 | - Diogo Silveira Mendonça – [@diogosmendonca](https://github.com/diogosmendonca) 296 | 297 | **Project Description:** 298 | ZKCMP (Zero-Knowledge Consent-Management Platform) is a TypeScript CLI that demonstrates the entire consent life-cycle with zero-knowledge proofs. 299 | It issues a ConsentCredential containing hashed Brazilian CPF/CNPJ (or any national IDs), generates five AtomicQuerySigV2 proofs, and verifies them—all without touching a blockchain. 300 | Optionally, the public Merkle-tree state can be persisted to MongoDB so proofs remain valid across sessions. 301 | 302 | **Technical Stack:** 303 | 304 | - TypeScript / Node.js 305 | - Polygon ID JS-SDK 306 | - Poseidon / Groth16 circuits (`.wasm` + `.zkey`) 307 | - MongoDB (optional persistence) 308 | - tsx, Inquirer, chalk (CLI UX) 309 | 310 | **Project Goals:** 311 | 312 | - Provide a reference implementation for privacy-preserving data-sharing consent. 313 | - Let companies prove—without revealing DIDs—which data fields were authorised and when, shielding them from liability if a third-party processor is breached. 314 | 315 | **GitHub Link:** 316 | 317 | 318 | **Other Links:** 319 | N/A 320 | -------------------------------------------------------------------------------- /2023/MODULE_2.md: -------------------------------------------------------------------------------- 1 | # Module 2 - Crypto Primitives: Encryption, Hash Functions, and Beyond 2 | 3 | Welcome to Module 2! As we delve deeper into the world of cryptography and zero-knowledge proofs, this module will introduce you to encryption, hash functions, and various advanced cryptographic concepts. By mastering these core building blocks, we will better understand the practical implementation of these technologies in areas like blockchain and beyond. 4 | 5 | # Detailed Self Study 6 | 7 | The following is a list of topics for you to research and learn about. At the bottom of each section is a set of questions for you to check your understanding. Try to make sure that you can confidently answer the questions before moving on. Feel free to reach out on Discord if you are struggling with a certain topic. 8 | 9 | ## Symmetric vs. Asymmetric Encryption 10 | 11 | Encryption is a technique used to encode data, making it readable only to those who possess the correct decryption key. There are two main types of encryption - symmetric and asymmetric, each serving different purposes and with their own strengths and weaknesses. 12 | 13 | **Symmetric Encryption** - Also known as single-key encryption, this method involves using the same key for both encryption and decryption. The most widely used symmetric encryption algorithm is Advanced Encryption Standard (AES). 14 | 15 | **Asymmetric Encryption** - Also known as public-key encryption, this method uses a pair of keys: one for encryption and another for decryption. The RSA algorithm is one of the best-known public-key algorithms. 16 | 17 | The key difference between the two is the number of keys used: symmetric encryption uses one key for both encrypting and decrypting, while asymmetric encryption uses a different key for each (one public, one private). For a deeper understanding of symmetric and asymmetric encryption, please explore these resources: 18 | - [Symmetric vs. Asymmetric Encryption – What are differences?](https://www.ssl2buy.com/wiki/symmetric-vs-asymmetric-encryption-what-are-differences) 19 | - [AES Explained (Advanced Encryption Standard) - Computerphile [14:13]](https://www.youtube.com/watch?v=O4xNJsjtN6E) 20 | - [Prime Numbers & RSA Encryption Algorithm - Computerphile [15:06]](https://www.youtube.com/watch?v=JD72Ry60eP4) 21 | - [What Is AES Encryption and How Does It Work?](https://www.simplilearn.com/tutorials/cryptography-tutorial/aes-encryption) 22 | - [What is RSA encryption and how does it work?](https://www.comparitech.com/blog/information-security/rsa-encryption/) 23 | 24 | 25 | :::info 26 | **🤔 Consider the following:** 27 | 1. What is the primary difference between symmetric and asymmetric encryption? 28 | 2. Can you briefly explain how AES (Advanced Encryption Standard) works? 29 | 3. What makes RSA a popular choice for public-key encryption? 30 | ::: 31 | 32 | ## DLP-based Public-Key Cryptography 33 | While RSA encryption is based on the hardness of the factoring problem, there is another public key cryptography system based on hardness of Discrete Logarithm Problem (DLP). 34 | 35 | 1. **Discrete Log Problem (DLP):** This is a cornerstone problem in public-key cryptography and underlies many key exchange and encryption algorithms. Understanding DLP provides a foundation for the remaining topics. 36 | - [The Discrete Logarithm Problem - Khan Academy [1:55]](https://youtu.be/SL7J8hPKEWY) 37 | - [Public key cryptography using discrete logarithms](https://www.di-mgt.com.au/public-key-crypto-discrete-logs-0.html) 38 | 39 | 2. **Diffie-Hellman Key Exchange:** This is one of the earliest practical implementations of key exchange protocols based on the Discrete Log Problem. It's critical to understand how secure communication can be established over insecure channels. 40 | 41 | This protocol is significant as it enables secure communication over insecure channels by allowing two parties to generate a shared secret key, which can then be used for encryption and decryption of messages 42 | - [Secret Key Exchange (Diffie-Hellman) - Computerphile [8:39]](https://www.youtube.com/watch?v=NmM9HA2MQGI) 43 | - [Diffie Hellman -the Mathematics bit- Computerphile [7:04]](https://youtu.be/Yjrfm_oRO0w) 44 | - [Implementation of Diffie-Hellman Algorithm 45 | ](https://www.geeksforgeeks.org/implementation-diffie-hellman-algorithm/) 46 | 47 | 3. **ElGamal Encryption:** This is a public-key encryption method that utilizes the principles of DLP. This will allow you to see a practical application of these abstract concepts in a real-world encryption scheme. 48 | - [Intro to the ElGamal Cryptosystem [8:20]](https://www.youtube.com/watch?v=oQqr8d5s3Uk) 49 | - [The ElGamal Algorithm: a simple example [6:38]](https://www.youtube.com/watch?v=4xVCrTb_1II) 50 | - [ElGamal Encryption Algorithm](https://www.geeksforgeeks.org/elgamal-encryption-algorithm/) 51 | 52 | :::info 53 | **🤔 Consider the following:** 54 | 1. What is the Discrete Logarithm Problem (DLP)? 55 | 2. How does the Diffie-Hellman protocol work? 56 | 3. What is the main idea behind ElGamal encryption? 57 | 4. Can you name a drawback of using DLP-based systems? 58 | ::: 59 | 60 | ## Hash Functions 61 | 62 | A hash function takes an input and returns a fixed-size string of bytes. **SHA-256** and **Poseidon** are popular cryptographic hash functions in our context, with Poseidon specifically designed for arithmetic-friendly operations, benefiting certain applications in blockchains. 63 | 64 | The primary characteristics of a good hash function are [preimage resistance](https://en.wikipedia.org/wiki/Preimage_attack), second preimage resistance, and [collision resistance](https://en.wikipedia.org/wiki/Collision_resistance), ensuring data security and integrity. In blockchain technology, hash functions create an unalterable, unique representation of each block's content, contributing to the immutability and transparency of the system. 65 | 66 | Explore these resources to further your understanding: 67 | - [What Is SHA-256 Algorithm & How It Works](https://www.ssldragon.com/blog/sha-256-algorithm/) 68 | - [How is SHA-256 used in blockchain, and why?](https://www.educative.io/answers/how-is-sha-256-used-in-blockchain-and-why) 69 | - [Poseidon: A new hash function for zero-knowledge proof systems](https://eprint.iacr.org/2019/458.pdf) 70 | - [USENIX Security '21 - Poseidon: A New Hash Function for Zero-Knowledge Proof Systems [10:45]](https://www.youtube.com/watch?v=hUx3WpDV_l0) 71 | - This video is quite technical, but the first few minutes provide a good explanation for the motivation behind the Poseidon hash function. 72 | 73 | :::info 74 | **🤔 Consider the following:** 75 | 1. What is a hash function and what are its primary uses in cryptography? 76 | 2. How does the SHA-256 hashing algorithm function, in simple terms? 77 | 3. What is the Poseidon hash function and why is it particularly useful in ZKPs? 78 | ::: 79 | 80 | ## Merkle Trees 81 | 82 | A Merkle tree is a core component of blockchain and cryptography. It's a binary tree filled with cryptographic hashes. This structure enables efficient and secure verification of the contents of large data structures. To understand more about Merkle trees, read the following: 83 | - [How Merkle Trees Enable the Decentralized Web! [10:05]](https://www.youtube.com/watch?v=3giNelTfeAk) 84 | - [Merkle Trees and Merkle Roots Explained](https://academy.binance.com/en/articles/merkle-trees-and-merkle-roots-explained) 85 | - [Visualizing Efficient Merkle Trees for Zero-Knowledge Proofs](https://kndrck.co/posts/efficient-merkletrees-zk-proofs/) 86 | - [The Ultimate Merkle Tree Guide in Solidity](https://soliditydeveloper.com/merkle-tree) 87 | 88 | 89 | :::info 90 | **🤔 Consider the following:** 91 | 1. Can you describe the structure of a Merkle tree? 92 | 2. How are Merkle trees used within the blockchain context? 93 | 3. Why are Merkle trees useful for efficient and secure verification of large data structures? 94 | ::: 95 | 96 | ## Cryptographic Commitments 97 | 98 | Cryptographic commitments are essential in cryptography and blockchain technology as they allow for selective hiding and revealing of information. This feature ensures data privacy while still enabling verification processes. 99 | 100 | It helps achieve secure and efficient verification of transactions in blockchain protocols. In such contexts, sensitive information, such as transaction details or user identities, is hidden while revealing others for the verifier to authenticate the transactions. 101 | 102 | You can break down the concept of commitment into two parts: commit and open (reveal). 103 | 104 | ![commitment scheme](./assets/commitment.png) 105 | [Source](https://zecrey.medium.com/commmitment-schemes-in-zecrey-e6c446e2da97) 106 | 107 | There is always a commit phase and a reveal phase, in other words you first encrypt a secret and then reveal it later. 108 | 109 | ### Pedersen Commitments (Optional) 110 | Pedersen Commitments are a type of cryptographic primitive that allows you to commit to a certain value while keeping it hidden, with the ability to disclose the committed value later. They're often used to achieve privacy-preserving properties in cryptographic protocols. For more on Pedersen Commitments, review these materials: 111 | 112 | - [Pedersen Commitments](https://asecuritysite.com/encryption/ped) 113 | - [What is a Pedersen Commitment?](https://crypto.stackexchange.com/questions/64437/what-is-a-pedersen-commitment) 114 | 115 | As a final touch on this section, [this video [10:32]](https://www.youtube.com/watch?v=IkNZWJFcfcU) provides a brief yet comprehensive summary of the fundamental concepts discussed in this section. 116 | 117 | :::info 118 | **🤔 Consider the following:** 119 | 1. What is the main purpose of Cryptographic Commitments? 120 | 2. What type of information does a Polynomial Commitment hide and reveal? 121 | 3. How do Pedersen Commitments contribute to privacy in cryptography? 122 | 4. Why are Cryptographic Commitments important in blockchain technology? 123 | ::: 124 | 125 | ## Digital Signatures 126 | 127 | Digital signatures ensure the integrity and authenticity of digital messages or documents. By providing a means to verify the origin and confirm that the content has not been altered, digital signatures play a pivotal role in maintaining trust in digital communications. 128 | 129 | In PKC, anyone can encrypt their message with the receiver's public key, and only the receiver can decrypt the message with their private key. In digital signatures, on the other hand, if a signer generates a signature for a message using their private key, anyone can validate it using the signer's public key. Therefore, the message of the signature is made public, which distinguishes it from cryptographic commitments. 130 | 131 | Start your exploration of digital signatures with this intuitive video: 132 | - [What are Digital Signatures? - Computerphile [10:16]](https://www.youtube.com/watch?v=s22eJ1eVLTU) 133 | 134 | **Schnorr Signature**: Schnorr signatures are a digital signature scheme known for their simplicity and efficiency. 135 | - [Schnorr Digital Signature (by GeeksForGeeks)](https://www.geeksforgeeks.org/schnorr-digital-signature/) 136 | - [Schnorr Digital Signature [4:58]](https://www.youtube.com/watch?v=mV9hXEFUB6A) 137 | 138 | **Exploring DSA**: Get a deep dive into the Digital Signature Algorithm (DSA) and its significance in bolstering internet security. Through the listed resources, understand the mechanics of DSA and its use cases. 139 | - [Digital Signature Algorithm (DSA) in Cryptography](https://www.simplilearn.com/tutorials/cryptography-tutorial/digital-signature-algorithm) 140 | - [Digital Signature Algorithm (DSA) - Cryptography [5:46]](https://www.youtube.com/watch?v=iS1nK4G6EtA) 141 | - [Digital Signature Algorithm (DSA) explained with example [24:32]](https://www.youtube.com/watch?v=MtT3NBfpV5Q) 142 | 143 | :::info 144 | **🤔 Consider the following:** 145 | 1. Can you describe what digital signatures are and why they are essential in digital communications? 146 | 2. Explain the workings of the Digital Signature Algorithm (DSA). 147 | ::: 148 | 149 | # 💪 Exercises 150 | 151 | ## Written Questions 152 | 153 | 1. **Symmetric vs. Asymmetric Encryption**: What are the key differences between symmetric and asymmetric encryption? Provide a practical use case for each. 154 | 2. **Public-Key Cryptography and Key Exchange Protocols**: How can the Diffie-Hellman protocol enhance security in a messaging application? 155 | 3. **Hash Functions**: What features make SHA-256 and Poseidon good hash functions for ensuring data integrity? Mention one unique advantage of Poseidon. 156 | 4. **Merkle Trees**: Explain how Merkle trees can help verify data in a large database efficiently. 157 | 5. **Cryptographic Commitments**: How can Pedersen Commitments be used in a blockchain protocol to maintain transaction privacy? 158 | 6. **Digital Signatures**: How can you verify the authenticity of a digitally signed document? 159 | 160 | ## Programming Challenges 161 | 162 | In these challenges, you'll implement cryptographic methods in a Node.js environment. You will need the following packages, which you can install using NPM: 163 | 164 | ```bash 165 | npm install merkletreejs poseidon-encryption ffjavascript 166 | ``` 167 | 168 | ### Challenge 1: Asymmetric Encryption and Digital Signature 169 | 170 | In this challenge, you will use the `crypto` built-in library in Node.js to implement asymmetric encryption. Your task is to encrypt and decrypt some sample text, generate a digital signature for the encrypted message, and then verify it. This simulates a secure message exchange where you want to ensure the confidentiality and authenticity of the messages. 171 | 172 | ```javascript 173 | const crypto = require('crypto'); 174 | 175 | // Asymmetric encryption 176 | const { publicKey, privateKey } = crypto.generateKeyPairSync('rsa', { modulusLength: 2048 }); 177 | 178 | // Encrypt 179 | const plaintext = 'This is a secret message.'; 180 | // TODO: Use the publicKey to encrypt the plaintext message. Remember that RSA encryption is public key encryption. 181 | 182 | // Decrypt 183 | // TODO: Use the privateKey to decrypt the encrypted message. The result should be the original plaintext. 184 | 185 | // Create a digital signature 186 | const sign = crypto.createSign('SHA256'); 187 | sign.update(plaintext); 188 | sign.end(); 189 | // TODO: Use the privateKey to sign the plaintext message. This will generate a digital signature. 190 | 191 | // Verify a digital signature 192 | const verify = crypto.createVerify('SHA256'); 193 | verify.update(plaintext); 194 | verify.end(); 195 | // TODO: Use the publicKey to verify the signature. It should return true if the signature is valid. 196 | ``` 197 | 198 | Tip: The `crypto` library has specific functions for encryption, decryption, signing, and verifying. Look up the library documentation for examples and usage [here](https://nodejs.org/api/crypto.html). 199 | 200 | ### Challenge 2: Hashing with SHA-256 and Poseidon 201 | 202 | For this challenge, your task is to compute the SHA-256 and Poseidon hashes of some input data. You will then observe how the hash value changes drastically even with a small change in the input data. This is an important property of cryptographic hash functions called ["avalanche effect"](https://en.wikipedia.org/wiki/Avalanche_effect). 203 | 204 | ```javascript 205 | const crypto = require("crypto"); 206 | const poseidon = require("poseidon-encryption"); 207 | 208 | // SHA-256 209 | const data = "This is some data X."; 210 | // TODO: Compute the SHA-256 hash of the data and print it. Try changing the data slightly and observe the changes in the hash. 211 | 212 | // Poseidon 213 | const inputs = [1, 2, 3, 4]; 214 | // TODO: Compute the Poseidon hash of the inputs and print it. Remember that Poseidon accepts an array of integers as input. 215 | ``` 216 | 217 | Tip: Use the `.digest('hex')` method of the `hash` object to print the hash in a human-readable format. As for the `poseidon-encryption` package, there lacks good documentation but have a look at the source code [here](https://github.com/weijiekoh/circomlib/tree/feat/poseidon-encryption) for some hints (pay special attention to the tests for example usage). 218 | 219 | ### Challenge 3: Using a Simple Merkle Tree 220 | 221 | In this challenge, you will use the 'merkletreejs' library to construct a simple Merkle Tree from some input data. You will then generate a proof for a leaf node and verify it. This task is analogous to verifying a transaction in a block in a blockchain. 222 | 223 | ```javascript 224 | const MerkleTree = require('merkletreejs'); 225 | const crypto = require('crypto'); 226 | 227 | function hashFunction(data) { 228 | const hash = crypto.createHash('sha256'); 229 | hash.update(data); 230 | return hash.digest(); 231 | } 232 | 233 | // Create tree 234 | const leaves = ['a', 'b', 'c', 'd'].map(x => hashFunction(x)); 235 | // TODO: Build the Merkle tree using the leaves and hashFunction. Compute the root of the tree and print it. 236 | 237 | // Generate and verify proof 238 | const leaf = hashFunction('b'); 239 | // TODO: Generate a proof for the leaf 'b' and verify it against the root of the tree. It should return true if the leaf is part of the tree. 240 | ``` 241 | 242 | Tip: Refer to the `merkletreejs` library [documentation](https://github.com/merkletreejs/merkletreejs) for the functions needed to build the tree, generate the proof, and verify it. 243 | 244 | ### Challenge 4: Implementing Pedersen Commitments 245 | 246 | This challenge is a little more involved, but should be more rewarding. Here, you will be creating a Javascript object capable of Pedersen Commitments. This template should get you started: 247 | 248 | ```javascript 249 | class PedersenCommitment { 250 | constructor() { 251 | // Set prime number (p) and generator (g) 252 | this.p = BigInt(23); // use a large prime in a real-world scenario 253 | this.g = BigInt(4); // use a large number in a real-world scenario 254 | this.h = null; 255 | this.r = null; 256 | this.s = null; 257 | } 258 | 259 | // Generate 'h' with a random number 'r' (h = g^r mod p) 260 | generateH() { 261 | // TODO: Generate a random number r (and save it to this.r) 262 | // TODO: Calculate h using g, r and p (and save it to this.h) 263 | } 264 | 265 | // Generate the commitment (g^s * h^r mod p) 266 | generateCommitment(s) { 267 | // TODO: Convert s to BigInt (and save it to this.s) 268 | // TODO: Calculate and return the commitment using g, s, h, r and p 269 | } 270 | 271 | // Reveal the secret number and random number (s, r) 272 | reveal() { 273 | // TODO: Return the secret and random number 274 | } 275 | 276 | // Verify the commitment (g^s * h^r mod p) 277 | verify(s, r, C) { 278 | // TODO: Verify the commitment by recalculating it and comparing with C 279 | } 280 | } 281 | 282 | // Test the PedersenCommitment 283 | const pc = new PedersenCommitment(); 284 | pc.generateH(); 285 | 286 | // Party A: Generate a commitment 287 | let secretNumber = 7; 288 | let commitment = pc.generateCommitment(secretNumber); 289 | console.log("Commitment: ", commitment); 290 | 291 | // Party A: Reveal the secret and random number 292 | let reveal = pc.reveal(); 293 | console.log("Revealed: ", reveal); 294 | 295 | // Party B: Verify the commitment 296 | let verification = pc.verify(reveal.s, reveal.r, commitment); 297 | console.log("Verification: ", verification); 298 | ``` 299 | 300 | If everything worked properly, the final output should read: 301 | 302 | ``` 303 | Verification: true 304 | ``` 305 | 306 | Congrats on reaching the end of this module! 307 | 308 | ## Conclusion 309 | 310 | In summary, we've ventured through some very important cryptographic primitives, gaining insights into encryption, hash functions, Merkle trees, and more. These components underpin blockchain technologies and zero-knowledge proofs. Moving forward, our next module will navigate the fascinating field of elliptic curve cryptography. 311 | -------------------------------------------------------------------------------- /2023/answers/MODULE_6_ANSWERS.md: -------------------------------------------------------------------------------- 1 | # Module 6 Answers 2 | 3 | ### 2.1 Trusted Setup 4 | 5 | 1. What does the circuit in `HelloWorld.circom` do? 6 | - *Answer*: It multiplies two input signals to produce an output signal. 7 | 2. Lines 7-12 of `compile-HelloWorld.sh` download a file called `powersOfTau28_hez_final_10.ptau` for Phase 1 trusted setup. What is a Powers of Tau ceremony? Explain why this is important in the setup of zk-SNARK applications. 8 | - *Answer*: The trusted setup ceremony MPC schemes are interactive protocols involving multiple parties who contribute randomness to iteratively construct the common reference string (CRS). The key to this technique is that all parties need to keep their inputs (their sampled randomness) hidden. As long as the answer talks about the setup ceremony it’s ok, no need to be Powers of Tau specific. 9 | 3. Line 24 of `compile-HelloWorld.sh` makes a random entropy contribution as a Phase 2 trusted setup. How are Phase 1 and Phase 2 trusted setup ceremonies different from each other? 10 | - *Answer*: Phase 1 is universal, Phase 2 is circuit-specific. 11 | 12 | ### 2.2 Non-Quadratic Constraints 13 | 14 | Here, you will learn about an important restriction on Circom circuits. 15 | 16 | 1. In the empty `scripts/compile-Multiplier3-groth16.sh`, create a script to compile `contracts/circuits/Multiplier3.circom` and create a verifier contract modeled after `compile-HelloWorld.sh`. 17 | ```bash 18 | #!/bin/bash 19 | 20 | # [assignment] create your own bash script to compile Multiplier3.circom modeling after compile-HelloWorld.sh below 21 | 22 | cd contracts/circuits 23 | 24 | mkdir Multiplier3 25 | 26 | if [ -f ./powersOfTau28_hez_final_10.ptau ]; then 27 | echo "powersOfTau28_hez_final_10.ptau already exists. Skipping." 28 | else 29 | echo 'Downloading powersOfTau28_hez_final_10.ptau' 30 | wget https://hermez.s3-eu-west-1.amazonaws.com/powersOfTau28_hez_final_10.ptau 31 | fi 32 | 33 | echo "Compiling Multiplier3.circom..." 34 | 35 | # compile circuit 36 | 37 | circom Multiplier3.circom --r1cs --wasm --sym -o Multiplier3 38 | snarkjs r1cs info Multiplier3/Multiplier3.r1cs # print the number of constraints in Multiplier3.r1cs 39 | 40 | # Start a new zkey and make a contribution 41 | 42 | snarkjs groth16 setup Multiplier3/Multiplier3.r1cs powersOfTau28_hez_final_10.ptau Multiplier3/circuit_0000.zkey 43 | snarkjs zkey contribute Multiplier3/circuit_0000.zkey Multiplier3/circuit_final.zkey --name="1st Contributor Name" -v -e="random text" 44 | snarkjs zkey export verificationkey Multiplier3/circuit_final.zkey Multiplier3/verification_key.json 45 | 46 | # generate solidity contract 47 | snarkjs zkey export solidityverifier Multiplier3/circuit_final.zkey ../Multiplier3Verifier.sol 48 | 49 | cd ../.. 50 | ``` 51 | 2. Try to run `compile-Multiplier3-groth16.sh`. You should encounter an `error[T3001]` with the circuit as-is. Explain what the error means and how it arises. 52 | - *Answer*: The error is a non-quadratic constraint. You should use an intermediate signal to do the multiplication of two input signals first, and then the third. 53 | 3. Modify `Multiplier3.circom` to perform a multiplication of three input signals under the restrictions of circom. 54 | ```circom 55 | pragma circom 2.0.0; 56 | 57 | // [assignment] Modify the circuit below to perform a multiplication of three signals 58 | 59 | template Multiplier3 () { 60 | 61 | // Declaration of signals. 62 | signal input a; 63 | signal input b; 64 | signal input c; 65 | signal temp; 66 | signal output d; 67 | 68 | // Constraints. 69 | temp <== a * b; 70 | d <== temp * c; 71 | } 72 | 73 | component main = Multiplier3(); 74 | ``` 75 | 76 | ### 2.3 Groth16 and PLONK 77 | 78 | In the empty `scripts/compile-Multiplier3-plonk.sh`, create a script to compile `circuit/Multiplier3.circom` using PLONK in SnarkJS. Add a `_plonk` suffix to the build folder and the output contract to distinguish the two sets of output. 79 | 80 | 1. You will encounter an error `zkey file is not groth16` if you just change `snarkjs groth16 setup` to `snarkjs plonk setup`. Resolve this error and answer the following question: *How is the process of compiling with PLONK different from compiling with Groth16?* 81 | - *Answer*: Phase 2 (circuit-specific) contribution not required. 82 | 3. What are the practical differences between Groth16 and PLONK? Hint: compare and contrast the resulting contracts and running time of unit tests (see the next question below) from the two protocols. 83 | - *Answer*: PLONK contract size is larger, gas cost is higher, and verification is time longer. 84 | 85 | ### 2.4 Verify and Test 86 | 87 | So far we have not tested our circuit yet. While you can verify your circuit in the terminal using `snarkjs groth16 fullprove`, you can also do so directly in a Node.js script. We will practice doing so by creating some unit tests to try out our verifier contract(s): 88 | 89 | 1. Running `npx hardhat test` will prompt an `error HH606`. Before we can test our verifier contracts with hardhat, we must modify the Solidity version. In `scripts/bump-solidity.js`, we have already written the regular expressions to modify `HelloWorldVerifier.sol`. Add some code to `bump-solidity.js` to do the same for your new contract for `Multiplier3`. 90 | 91 | ```bash 92 | const fs = require("fs"); 93 | const solidityRegex = /pragma solidity \^\d+\.\d+\.\d+/ 94 | 95 | const groth16VerifierRegex = /contract Groth16Verifier/ 96 | 97 | let content = fs.readFileSync("./contracts/HelloWorldVerifier.sol", { encoding: 'utf-8' }); 98 | let bumped = content.replace(solidityRegex, 'pragma solidity ^0.8.0'); 99 | bumped = bumped.replace(groth16VerifierRegex, 'contract HelloWorldVerifier'); 100 | 101 | fs.writeFileSync("./contracts/HelloWorldVerifier.sol", bumped); 102 | 103 | // [assignment] add your own scripts below to modify the other verifier contracts you will build during the assignment 104 | 105 | // Multiplier2 (with Groth16) 106 | let content2 = fs.readFileSync("./contracts/Multiplier3Verifier.sol", { encoding: 'utf-8' }); 107 | let bumped2 = content2.replace(solidityRegex, 'pragma solidity ^0.8.0'); 108 | bumped2 = bumped2.replace(groth16VerifierRegex, 'contract Multiplier3Verifier'); 109 | 110 | fs.writeFileSync("./contracts/Multiplier3Verifier.sol", bumped2); 111 | 112 | // Multiplier3 (with Plonk) 113 | const plonkVerifierRegex = /contract PlonkVerifier/ 114 | 115 | let content3 = fs.readFileSync("./contracts/Multiplier3Verifier_plonk.sol", { encoding: 'utf-8' }); 116 | let bumped3 = content3.replace(solidityRegex, 'pragma solidity ^0.8.0'); 117 | bumped3 = bumped3.replace(plonkVerifierRegex, 'contract Multiplier3Verifier_plonk'); 118 | 119 | fs.writeFileSync("./contracts/Multiplier3Verifier_plonk.sol", bumped3); 120 | ``` 121 | 122 | 2. You can now perform the unit tests for `HelloWorldVerifier` by running `npm run test`. Add comments to explain what each line in `test/test.js` is doing. 123 | 3. In `test/test.js`, add the unit tests for `Multiplier3` for both the Groth16 and PLONK versions. Ensure all tests pass (for `HelloWorld`, `Multiplier3 with Groth16`, and `Multiplier3 with PLONK`). 124 | 125 | `test/test.js`: 126 | 127 | ```javascript 128 | const { expect, assert } = require("chai"); 129 | const { ethers } = require("hardhat"); 130 | const { groth16, plonk } = require("snarkjs"); 131 | 132 | const wasm_tester = require("circom_tester").wasm; 133 | 134 | const F1Field = require("ffjavascript").F1Field; 135 | const Scalar = require("ffjavascript").Scalar; 136 | exports.p = Scalar.fromString( 137 | "21888242871839275222246405745257275088548364400416034343698204186575808495617" 138 | ); 139 | const Fr = new F1Field(exports.p); 140 | 141 | describe("HelloWorld", function () { 142 | this.timeout(100000000); 143 | let Verifier; 144 | let verifier; 145 | 146 | beforeEach(async function () { 147 | Verifier = await ethers.getContractFactory("HelloWorldVerifier"); 148 | verifier = await Verifier.deploy(); 149 | await verifier.deployed(); 150 | }); 151 | 152 | it("Circuit should multiply two numbers correctly", async function () { 153 | const circuit = await wasm_tester("contracts/circuits/HelloWorld.circom"); 154 | 155 | const INPUT = { 156 | a: 2, 157 | b: 3, 158 | }; 159 | 160 | const witness = await circuit.calculateWitness(INPUT, true); 161 | 162 | //console.log(witness); 163 | 164 | assert(Fr.eq(Fr.e(witness[0]), Fr.e(1))); 165 | assert(Fr.eq(Fr.e(witness[1]), Fr.e(6))); 166 | }); 167 | 168 | it("Should return true for correct proof", async function () { 169 | //[assignment] Add comments to explain what each line is doing 170 | 171 | // create a proof and public signals from the circuit and some input 172 | const { proof, publicSignals } = await groth16.fullProve( 173 | { a: "2", b: "3" }, 174 | "contracts/circuits/HelloWorld/HelloWorld_js/HelloWorld.wasm", 175 | "contracts/circuits/HelloWorld/circuit_final.zkey" 176 | ); 177 | 178 | // print out "c" in the circuit (i.e. the result of the private inputs) 179 | console.log("2x3 =", publicSignals[0]); 180 | 181 | // create a string of the calldata for the verifier contract 182 | const calldata = await groth16.exportSolidityCallData(proof, publicSignals); 183 | 184 | // convert the calldata string into an array of BigInts 185 | const argv = calldata 186 | .replace(/["[\]\s]/g, "") 187 | .split(",") 188 | .map((x) => BigInt(x).toString()); 189 | 190 | const a = [argv[0], argv[1]]; 191 | const b = [ 192 | [argv[2], argv[3]], 193 | [argv[4], argv[5]], 194 | ]; 195 | const c = [argv[6], argv[7]]; 196 | const Input = argv.slice(8); 197 | 198 | expect(await verifier.verifyProof(a, b, c, Input)).to.be.true; 199 | }); 200 | it("Should return false for invalid proof", async function () { 201 | let a = [0, 0]; 202 | let b = [ 203 | [0, 0], 204 | [0, 0], 205 | ]; 206 | let c = [0, 0]; 207 | let d = [0]; 208 | expect(await verifier.verifyProof(a, b, c, d)).to.be.false; 209 | }); 210 | }); 211 | 212 | describe("Multiplier3 with Groth16", function () { 213 | beforeEach(async function () { 214 | //[assignment] insert your script here 215 | Verifier = await ethers.getContractFactory("Multiplier3Verifier"); 216 | verifier = await Verifier.deploy(); 217 | await verifier.deployed(); 218 | }); 219 | 220 | it("Circuit should multiply three numbers correctly", async function () { 221 | //[assignment] insert your script here 222 | const circuit = await wasm_tester("contracts/circuits/Multiplier3.circom"); 223 | 224 | const INPUT = { 225 | a: 2, 226 | b: 3, 227 | c: 4, 228 | }; 229 | 230 | const witness = await circuit.calculateWitness(INPUT, true); 231 | 232 | assert(Fr.eq(Fr.e(witness[0]), Fr.e(1))); 233 | assert(Fr.eq(Fr.e(witness[1]), Fr.e(24))); 234 | }); 235 | 236 | it("Should return true for correct proof", async function () { 237 | //[assignment] insert your script here 238 | 239 | const { proof, publicSignals } = await groth16.fullProve( 240 | { a: "2", b: "3", c: "4" }, 241 | "contracts/circuits/Multiplier3/Multiplier3_js/Multiplier3.wasm", 242 | "contracts/circuits/Multiplier3/circuit_final.zkey" 243 | ); 244 | 245 | console.log("2x3x4 =", publicSignals[0]); 246 | 247 | const calldata = await groth16.exportSolidityCallData(proof, publicSignals); 248 | 249 | const argv = calldata 250 | .replace(/["[\]\s]/g, "") 251 | .split(",") 252 | .map((x) => BigInt(x).toString()); 253 | 254 | const a = [argv[0], argv[1]]; 255 | const b = [ 256 | [argv[2], argv[3]], 257 | [argv[4], argv[5]], 258 | ]; 259 | const c = [argv[6], argv[7]]; 260 | 261 | const Input = argv.slice(8); 262 | 263 | expect(await verifier.verifyProof(a, b, c, Input)).to.be.true; 264 | }); 265 | 266 | it("Should return false for invalid proof", async function () { 267 | //[assignment] insert your script here 268 | let a = [0, 0]; 269 | let b = [ 270 | [0, 0], 271 | [0, 0], 272 | ]; 273 | let c = [0, 0]; 274 | let d = [0]; 275 | expect(await verifier.verifyProof(a, b, c, d)).to.be.false; 276 | }); 277 | }); 278 | 279 | describe("Multiplier3 with PLONK", function () { 280 | beforeEach(async function () { 281 | //[assignment] insert your script here 282 | Verifier = await ethers.getContractFactory("Multiplier3Verifier_plonk"); 283 | verifier = await Verifier.deploy(); 284 | await verifier.deployed(); 285 | }); 286 | 287 | it("Should return true for correct proof", async function () { 288 | //[assignment] insert your script here 289 | const { proof, publicSignals } = await plonk.fullProve( 290 | { a: "2", b: "3", c: "4" }, 291 | "contracts/circuits/Multiplier3_plonk/Multiplier3_js/Multiplier3.wasm", 292 | "contracts/circuits/Multiplier3_plonk/circuit_final.zkey" 293 | ); 294 | 295 | console.log("2x3x4 =", publicSignals[0]); 296 | 297 | let rawCalldata = await plonk.exportSolidityCallData(proof, publicSignals); 298 | 299 | // fix string by replacing "][" with ", " 300 | const fixedStr = rawCalldata.replace(/\]\[/g, ", "); 301 | 302 | // convert the calldata string into an array of BigInts 303 | const fixedArray = fixedStr 304 | .replace(/["[\]\s]/g, "") 305 | .split(",") 306 | .map((x) => BigInt(x).toString()); 307 | 308 | // drop the last element of the array (the inputs) 309 | const calldata = [...fixedArray.slice(0, -1)]; 310 | 311 | expect(await verifier.verifyProof(calldata, publicSignals)).to.be.true; 312 | }); 313 | 314 | it("Should return false for invalid proof", async function () { 315 | //[assignment] insert your script here 316 | let calldata = new Array(24).fill(0); 317 | let publicSignals = [0]; 318 | expect(await verifier.verifyProof(calldata, publicSignals)).to.be.false; 319 | }); 320 | }); 321 | ``` 322 | 323 | ### 2.5 Circuit Libraries 324 | 325 | In this section, you will be learning about libraries that you can import to create more complicated circuits. The original exercises are found in the Q3 directory, however we will present the code here for your convenience. 326 | 327 | #### Tip: For this section, use [**zkREPL**](https://zkrepl.dev/) for quick compiling and testing of circuits 328 | 329 | ### 2.5.1 circomlib 330 | 331 | - `LessThan10.circom` implements a circuit that verifies an input is less than 10 using the [LessThan](https://github.com/iden3/circomlib/blob/master/circuits/comparators.circom#L89) template. Study how the template is used in this circuit. What does the 32 in Line 9 stand for? 332 | - *Answer*: Maximum number of bits of the input. 333 | - What are the possible outputs for the `LessThan` template and what do they mean respectively? If you cannot figure this out by reading the code alone, feel free to compile the circuit and test with different input values. 334 | - *Answer*: 1 if true, 0 if false 335 | - Proving a number is within a range without revealing the actual number could be useful in applications like proving our income when applying for a credit card. In the following code `RangeProof.circom`, create a template that uses `GreaterEqThan` and `LessEqThan` to perform a range proof. 336 | 337 | Answer for `RangeProof.circom`: 338 | 339 | ```circom 340 | pragma circom 2.1.4; 341 | 342 | include "circomlib/comparators.circom"; 343 | 344 | template RangeProof(n) { 345 | assert(n <= 252); 346 | signal input in; // this is the number to be proved inside the range 347 | signal input range[2]; // the two elements should be the range, i.e. [lower bound, upper bound] 348 | signal output out; 349 | signal result; 350 | 351 | component lt = LessEqThan(n); 352 | component gt = GreaterEqThan(n); 353 | 354 | // Check if in is greater or equal to the lower bound 355 | gt.in[0] <== in; 356 | gt.in[1] <== range[0]; 357 | 358 | // Check if in is less or equal to the upper bound 359 | lt.in[0] <== in; 360 | lt.in[1] <== range[1]; 361 | 362 | // The result is 1 if both conditions also return 1 363 | out <== gt.out * lt.out; 364 | } 365 | 366 | component main { public [ range ] } = RangeProof(32); 367 | 368 | /* INPUT = { 369 | "in": "5", 370 | "range": ["1", "10"] 371 | } */ 372 | ``` 373 | 374 | ### 2.5.2 circomlib-matrix and Sudoku 375 | 376 | ```circom 377 | pragma circom 2.1.4; 378 | 379 | include "https://github.com/socathie/circomlib-matrix/blob/master/circuits/matAdd.circom"; 380 | include "https://github.com/socathie/circomlib-matrix/blob/master/circuits/matElemMul.circom"; 381 | include "https://github.com/socathie/circomlib-matrix/blob/master/circuits/matElemSum.circom"; 382 | include "https://github.com/socathie/circomlib-matrix/blob/master/circuits/matElemPow.circom"; 383 | include "circomlib/poseidon.circom"; 384 | include "circomlib/comparators.circom"; 385 | 386 | template RangeProof(n) { 387 | assert(n <= 252); 388 | signal input in; // this is the number to be proved inside the range 389 | signal input range[2]; // the two elements should be the range, i.e. [lower bound, upper bound] 390 | signal output out; 391 | signal result; 392 | 393 | component lt = LessEqThan(n); 394 | component gt = GreaterEqThan(n); 395 | 396 | // Check if in is greater or equal to the lower bound 397 | gt.in[0] <== in; 398 | gt.in[1] <== range[0]; 399 | 400 | // Check if in is less or equal to the upper bound 401 | lt.in[0] <== in; 402 | lt.in[1] <== range[1]; 403 | 404 | // The result is 1 if both conditions also return 1 405 | out <== gt.out * lt.out; 406 | } 407 | 408 | template sudoku() { 409 | signal input puzzle[9][9]; // 0 where blank 410 | signal input solution[9][9]; // 0 where original puzzle is not blank 411 | signal output out; 412 | 413 | // check whether the solution is zero everywhere the puzzle has values (to avoid trick solution) 414 | 415 | component mul = matElemMul(9,9); 416 | 417 | //[assignment] hint: you will need to initialize your RangeProof components here 418 | component puzRange[9][9]; 419 | component solRange[9][9]; 420 | for (var i=0; i<9; i++) { 421 | for (var j=0; j<9; j++) { 422 | puzRange[i][j] = RangeProof(32); 423 | puzRange[i][j].range[0] <== 0; 424 | puzRange[i][j].range[1] <== 9; 425 | solRange[i][j] = RangeProof(32); 426 | solRange[i][j].range[0] <== 0; 427 | solRange[i][j].range[1] <== 9; 428 | } 429 | } 430 | 431 | for (var i=0; i<9; i++) { 432 | for (var j=0; j<9; j++) { 433 | puzRange[i][j].in <== puzzle[i][j]; 434 | solRange[i][j].in <== puzzle[i][j]; 435 | assert(puzRange[i][j].out == 1); 436 | assert(solRange[i][j].out == 1); 437 | mul.a[i][j] <== puzzle[i][j]; 438 | mul.b[i][j] <== solution[i][j]; 439 | } 440 | } 441 | for (var i=0; i<9; i++) { 442 | for (var j=0; j<9; j++) { 443 | mul.out[i][j] === 0; 444 | } 445 | } 446 | 447 | // sum up the two inputs to get the full solution and square the full solution 448 | 449 | component add = matAdd(9,9); 450 | 451 | for (var i=0; i<9; i++) { 452 | for (var j=0; j<9; j++) { 453 | add.a[i][j] <== puzzle[i][j]; 454 | add.b[i][j] <== solution[i][j]; 455 | } 456 | } 457 | 458 | component square = matElemPow(9,9,2); 459 | 460 | for (var i=0; i<9; i++) { 461 | for (var j=0; j<9; j++) { 462 | square.a[i][j] <== add.out[i][j]; 463 | } 464 | } 465 | 466 | // check all rows and columns and blocks sum to 45 and sum of squares = 285 467 | 468 | component row[9]; 469 | component col[9]; 470 | component block[9]; 471 | component rowSq[9]; 472 | component colSq[9]; 473 | component blockSq[9]; 474 | 475 | 476 | for (var k=0; k<9; k++) { 477 | row[k] = matElemSum(1,9); 478 | col[k] = matElemSum(1,9); 479 | block[k] = matElemSum(3,3); 480 | 481 | rowSq[k] = matElemSum(1,9); 482 | colSq[k] = matElemSum(1,9); 483 | blockSq[k] = matElemSum(3,3); 484 | 485 | for (var i=0; i<9; i++) { 486 | row[k].a[0][i] <== add.out[k][i]; 487 | col[k].a[0][i] <== add.out[i][k]; 488 | 489 | rowSq[k].a[0][i] <== square.out[k][i]; 490 | colSq[k].a[0][i] <== square.out[i][k]; 491 | } 492 | var x = 3*(k%3); 493 | var y = 3*(k\3); 494 | for (var i=0; i<3; i++) { 495 | for (var j=0; j<3; j++) { 496 | block[k].a[i][j] <== add.out[x+i][y+j]; 497 | blockSq[k].a[i][j] <== square.out[x+i][y+j]; 498 | } 499 | } 500 | row[k].out === 45; 501 | col[k].out === 45; 502 | block[k].out === 45; 503 | 504 | rowSq[k].out === 285; 505 | colSq[k].out === 285; 506 | blockSq[k].out === 285; 507 | } 508 | 509 | // hash the original puzzle and emit so that the dapp can listen for puzzle solved events 510 | 511 | component poseidon[9]; 512 | component hash; 513 | 514 | hash = Poseidon(9); 515 | 516 | for (var i=0; i<9; i++) { 517 | poseidon[i] = Poseidon(9); 518 | for (var j=0; j<9; j++) { 519 | poseidon[i].inputs[j] <== puzzle[i][j]; 520 | } 521 | hash.inputs[i] <== poseidon[i].out; 522 | } 523 | 524 | out <== hash.out; 525 | } 526 | 527 | component main = sudoku(); 528 | 529 | /* INPUT = { 530 | "puzzle": [ 531 | ["1", "0", "0", "0", "0", "0", "0", "0", "0"], 532 | ["0", "8", "0", "0", "0", "0", "0", "0", "0"], 533 | ["0", "0", "6", "0", "0", "0", "0", "0", "0"], 534 | ["0", "0", "0", "5", "0", "0", "0", "0", "0"], 535 | ["0", "0", "0", "0", "3", "0", "0", "0", "0"], 536 | ["0", "0", "0", "0", "0", "1", "0", "0", "0"], 537 | ["0", "0", "0", "0", "0", "0", "9", "0", "0"], 538 | ["0", "0", "0", "0", "0", "0", "0", "7", "0"], 539 | ["0", "0", "0", "0", "0", "0", "0", "0", "5"] 540 | ], 541 | "solution": [ 542 | ["0", "7", "4", "2", "8", "5", "3", "9", "6"], 543 | ["2", "0", "5", "3", "9", "6", "4", "1", "7"], 544 | ["3", "9", "0", "4", "1", "7", "5", "2", "8"], 545 | ["4", "1", "7", "0", "2", "8", "6", "3", "9"], 546 | ["5", "2", "8", "6", "0", "9", "7", "4", "1"], 547 | ["6", "3", "9", "7", "4", "0", "8", "5", "2"], 548 | ["7", "4", "1", "8", "5", "2", "0", "6", "3"], 549 | ["8", "5", "2", "9", "6", "3", "1", "0", "4"], 550 | ["9", "6", "3", "1", "7", "4", "2", "8", "0"] 551 | ] 552 | } */ 553 | ``` 554 | -------------------------------------------------------------------------------- /2024/week1_cryptographic_basics.md: -------------------------------------------------------------------------------- 1 | # Week 1 - Cryptographic Basics 2 | 3 | ## Practical 4 | 5 | In each of our modules, we will have a practical component so that you can get some hands-on experience as soon as possible. In this module, we will first start with some basics about circuit writing with Circom. 6 | 7 | ### Getting Started with Circom 8 | 9 | #### Understanding how a Circom circuit integrates to a system or application 10 | Let's see the workflow to have an overview of how a Circom circuit integrates into an App project: 11 | ```mermaid 12 | sequenceDiagram 13 | participant Developer 14 | participant Circom 15 | participant User 16 | participant App 17 | participant ProverModule 18 | participant Verifier 19 | 20 | Developer->>Circom: Writes circuit definition 21 | Developer->>Circom: Compiles circuit 22 | Developer->>Circom: Runs Trusted Setup 23 | Circom->>Developer: Return the ZK artifacts 24 | Developer->>ProverModule: Installs Witness calculator & Proving key 25 | Developer->>Verifier: Deploys contract or service with .vkey.json 26 | User->>App: Inputs data for proof generation 27 | App->>ProverModule: Sends inputs & proving key 28 | ProverModule->>ProverModule: Generates cryptographic proof 29 | ProverModule->>App: Returns proof 30 | App->>Verifier: Sends proof for verification 31 | Verifier->>App: Verifies proof and returns result 32 | App->>User: Displays verification result 33 | ``` 34 | ##### Artifacts (generated by the Circom compiler) 35 | - **Witness calculator:** This is typically used to generate the witness from the input data based on the compiled circuit. This witness is a representation of the intermediate values of the circuit computation, it can be generated (depending in the project needs) for Webassembly (.wasm), Javascript (.js), binary for snarkjs (.wtns + .r1cs), etc. 36 | - **Proving/Verification keys:** The key files necessary for generating and verifying proofs. It is produced during the trusted setup phase of the circuit using Groth16, PLONK, etc. The files are **.zkey** for the proving key file and **.vkey.json** for verifying. 37 | - **Contract:** This is the smart contract to be deployed to a blockchain or DLT to use it to verify the proofs generated from the App using the PowerModule, normally generated in Solidity (.sol) format. 38 | 39 | Now we are able to understand the general idea of how to use build and integrate Circom circuits, we can start with the technical application. 40 | 41 | #### Syntax & zkrepl 42 | 43 | In order to get used to writing circuits, we will start with [zkREPL](https://zkrepl.dev/), which is an online REPL that allows you to write and compile Circom circuits in the browser (with no setup required). There are many good videos on Circom, such as this one: 44 | 45 | - [Circom Workshop 1 by 0xParc [1:31:06]](https://learn.0xparc.org/materials/circom/learning-group-1/circom-1/) - A very good introduction to Circom circuits. 46 | 47 | However, we recommend you work through a few of the following example scenarios with zkREPL first. This way you can gain some familiarity with the syntax without having to setup the environment and dig into too much detail. Afterwards, you can review the video and fill in any gaps. 48 | 49 | #### Hello World - Addition 50 | 51 | This is one of the simplest examples of a ZK circuit. This circuit checks that the `sum` is the addition of two numbers `a` and `b`. Copy-and-paste the following into zkREPL, and compile it in the browser. 52 | 53 | ```circom 54 | pragma circom 2.1.6; 55 | 56 | template AdditionProof() { 57 | // declaration of signals 58 | signal input a; 59 | signal input b; 60 | signal output sum; 61 | 62 | // constraint 63 | sum <== a + b; 64 | } 65 | 66 | component main = AdditionProof(); 67 | 68 | /* INPUT = { 69 | "a": 3, 70 | "b": 5 71 | } */ 72 | ``` 73 | 74 | Note that the `a` and `b` are the private inputs. 75 | 76 | ### Write a circuit to prove multiplication 77 | 78 | From there, let's try to write a circuit to prove the multiplication of two numbers! 79 | 80 | Once that works, try to make a circuit to prove the multiplication of three numbers. 81 | 82 | Make sure to save these circuits and present them at the end of the week. 83 | 84 | ### Write a circuit to prove input to hash 85 | 86 | Now let's take it to the next level, we will write a circuit to prove the input to a hash. In order to do this, we will use the Poseidon hashing algorithm. You will need to include the following line at the top: 87 | 88 | ```circom 89 | include "circomlib/poseidon.circom"; 90 | ``` 91 | 92 | Here's how you'd use the Poseidon hashing function: 93 | 94 | ```circom 95 | component hasher = Poseidon(1); 96 | hasher.inputs[0] <== preimage; 97 | hashOutput <== hasher.out; 98 | ``` 99 | 100 | You might want to research what a `component` is in the Circom syntax. 101 | 102 | Use this as the input: 103 | 104 | ```circom 105 | /* INPUT = { 106 | "preimage": "12345", 107 | "hash": "4267533774488295900887461483015112262021273608761099826938271132511348470966" 108 | } */ 109 | ``` 110 | 111 | Save the full answer to be submitted at the end of this module! 112 | 113 | ### Write a circuit to add two numbers on an elliptic curve 114 | 115 | We don't dive in the details of elliptic curves in this module, but we can still write a simple circuit to add two numbers on an elliptic curve by importing the `babyjub.circom` file and add the points together. 116 | Link to this code is [here](https://gist.github.com/NOOMA-42/1a9040d49a0a828075971cb50acc4adb) 117 | 118 | ```circom 119 | // Code modified from circomlib test 120 | pragma circom 2.1.6; 121 | 122 | include "circomlib/circuits/babyjub.circom"; 123 | 124 | template AddNumOnEllipticCurve() { 125 | signal input x1; 126 | signal input y1; 127 | signal input x2; 128 | signal input y2; 129 | // To check xout yout 130 | signal input xout; 131 | signal input yout; 132 | component babyAdd = BabyAdd(); 133 | babyAdd.x1 <== x1; 134 | babyAdd.y1 <== y1; 135 | babyAdd.x2 <== x2; 136 | babyAdd.y2 <== y2; 137 | xout === babyAdd.xout; 138 | yout === babyAdd.yout; 139 | } 140 | 141 | component main = AddNumOnEllipticCurve(); 142 | 143 | /* INPUT = { 144 | "x1": "17777552123799933955779906779655732241715742912184938656739573121738514868268", 145 | "y1": "2626589144620713026669568689430873010625803728049924121243784502389097019475", 146 | "x2": "17777552123799933955779906779655732241715742912184938656739573121738514868268", 147 | "y2": "2626589144620713026669568689430873010625803728049924121243784502389097019475", 148 | "xout": "6890855772600357754907169075114257697580319025794532037257385534741338397365", 149 | "yout": "4338620300185947561074059802482547481416142213883829469920100239455078257889" 150 | } */ 151 | ``` 152 | 153 | ### Write a circuit to prove inclusion in Merkle tree 154 | 155 | TheBC01 has a good example of a Merkle tree circuit [here](https://github.com/TtheBC01/zkSNARK-playground/blob/main/examples/merkle-tree/tree.circom) 156 | 157 | The main component is Poseidon hash. Poseidon hash maps sequences of elements to a fixed-length sequence of elements. You can use it to hash messages of arbitrary length or fixed length (such as in a Merkle tree, where typically two elements are hashed). Here you initialize the Poseidon hash with n = 2 158 | 159 | You may also need a Mux. Mux is a component that takes two inputs and outputs one of them based on a selector. In this case, the selector is the index of the element in the Merkle tree. 160 | ```circom 161 | poseidons[i] = Poseidon(2); 162 | mux[i] = MultiMux1(2); 163 | ``` 164 | 165 | ### Tips 166 | 167 | You can always reference circomlib for examples of how to use existing circuits. You can find the circomlib [here](https://github.com/iden3/circomlib). Writing a simple circuit is not too difficult, but it can be a bit tricky to get the constraints right and optimize the circuit. circomlib has many examples that you can use as a reference. 168 | 169 | ## Study 170 | 171 | ### Symmetric vs Asymmetric Encryption (AES, RSA) 172 | 173 | Encryption is a technique used to encode data, making it readable only to those who possess the correct decryption key. There are two main types of encryption - symmetric and asymmetric, each serving different purposes and with their own strengths and weaknesses. 174 | 175 | **Symmetric Encryption** - Also known as single-key encryption, this method involves using the same key for both encryption and decryption. The most widely used symmetric encryption algorithm is Advanced Encryption Standard (AES). 176 | 177 | **Asymmetric Encryption** - Also known as public-key encryption, this method uses a pair of keys: one for encryption and another for decryption. The RSA algorithm is one of the best known public-key algorithms. 178 | 179 | ```mermaid 180 | --- 181 | title: Symmetric vs Asymmetric Encryption 182 | --- 183 | graph TD 184 | subgraph Asymmetric Encryption 185 | A2[Plaintext] -->|Encrypt with Public Key| B2[Ciphertext] 186 | B2 -->|Decrypt with Private Key| C2[Plaintext] 187 | D2[Public Key] 188 | E2[Private Key] 189 | A2 -- Public Key --> D2 190 | D2 -.-> B2 191 | B2 -.-> E2 192 | E2 -.-> C2 193 | end 194 | subgraph Symmetric Encryption 195 | A1[Plaintext] -->|Encrypt with Secret Key| B1[Ciphertext] 196 | B1 -->|Decrypt with Secret Key| C1[Plaintext] 197 | D1[Secret Key] 198 | A1 -- Shared Secret Key --> D1 199 | D1 -.-> C1 200 | end 201 | 202 | classDef symmetric fill:#FFDDDD,stroke:#FF0000,stroke-width:2px; 203 | classDef asymmetric fill:#DDFFDD,stroke:#00FF00,stroke-width:2px; 204 | 205 | class SymmetricEncryption symmetric; 206 | class AsymmetricEncryption asymmetric; 207 | 208 | ``` 209 | 210 | The key difference between the two is the number of keys used: symmetric encryption uses one key for both encrypting and decrypting, while asymmetric encryption uses a different key for each (one public, one private). For a deeper understanding of symmetric and asymmetric encryption, please explore these resources: 211 | - [Symmetric vs. Asymmetric Encryption – What are differences?](https://www.ssl2buy.com/wiki/symmetric-vs-asymmetric-encryption-what-are-differences) 212 | - [AES Explained (Advanced Encryption Standard) - Computerphile [14:13]](https://www.youtube.com/watch?v=O4xNJsjtN6E) 213 | - [Prime Numbers & RSA Encryption Algorithm - Computerphile [15:06]](https://www.youtube.com/watch?v=JD72Ry60eP4) 214 | - [What Is AES Encryption and How Does It Work?](https://www.simplilearn.com/tutorials/cryptography-tutorial/aes-encryption) 215 | - [What is RSA encryption and how does it work?](https://www.comparitech.com/blog/information-security/rsa-encryption/) 216 | 217 | 218 | :::info 219 | **🤔 Consider the following:** 220 | 1. What is the primary difference between symmetric and asymmetric encryption? 221 | 2. Can you briefly explain how AES (Advanced Encryption Standard) works? 222 | 3. What makes RSA a popular choice for public-key encryption? 223 | ::: 224 | 225 | ### Hash Functions, Merkle Trees 226 | 227 | #### Hash Functions 228 | 229 | A hash function takes an input and returns a fixed-size string of bytes. **SHA-256** and **Poseidon** are popular cryptographic hash functions in our context, with Poseidon specifically designed for arithmetic-friendly operations, benefiting certain applications in blockchains. 230 | 231 | The primary characteristics of a good hash function are [preimage resistance](https://en.wikipedia.org/wiki/Preimage_attack), second preimage resistance, and [collision resistance](https://en.wikipedia.org/wiki/Collision_resistance), ensuring data security and integrity. In blockchain technology, hash functions create an unalterable, unique representation of each block's content, contributing to the immutability and transparency of the system. 232 | 233 | ```mermaid 234 | flowchart TB 235 | subgraph Inputs 236 | A1["Input 1: 'Hello World'"] 237 | A2["Input 2: 'Hello'"] 238 | A3["Input 3: '123456'"] 239 | A4["Input 4: 'Blockchain'"] 240 | end 241 | 242 | subgraph Poseidon Hash Function 243 | Poseidon["Poseidon Hash"] 244 | end 245 | 246 | subgraph Outputs 247 | B1["Hash Output 1: 9f86d081884c7d659a2feaa0c55ad015..."] 248 | B2["Hash Output 2: e0ac3600c813991f82cdbb3f707d7898..."] 249 | B3["Hash Output 3: a83e50450ac94b2c8fd1bc73f540dbdb..."] 250 | B4["Hash Output 4: 0fb2e6a2b3470e2a69d0b13e4b75d28e..."] 251 | end 252 | 253 | A1 -->|Input 1| Poseidon 254 | A2 -->|Input 2| Poseidon 255 | A3 -->|Input 3| Poseidon 256 | A4 -->|Input 4| Poseidon 257 | 258 | Poseidon -->|Hash 1| B1 259 | Poseidon -->|Hash 2| B2 260 | Poseidon -->|Hash 3| B3 261 | Poseidon -->|Hash 4| B4 262 | 263 | ``` 264 | 265 | Explore these resources to further your understanding: 266 | - [What Is SHA-256 Algorithm & How It Works](https://www.ssldragon.com/blog/sha-256-algorithm/) 267 | - [How is SHA-256 used in blockchain, and why?](https://www.educative.io/answers/how-is-sha-256-used-in-blockchain-and-why) 268 | - [Poseidon: A new hash function for zero-knowledge proof systems](https://eprint.iacr.org/2019/458.pdf) 269 | - [USENIX Security '21 - Poseidon: A New Hash Function for Zero-Knowledge Proof Systems [10:45]](https://www.youtube.com/watch?v=hUx3WpDV_l0) 270 | - This video is quite technical, but the first few minutes provide a good explanation for the motivation behind the Poseidon hash function. 271 | 272 | :::info 273 | **🤔 Consider the following:** 274 | 1. What is a hash function and what are its primary uses in cryptography? 275 | 2. How does the SHA-256 hashing algorithm function, in simple terms? 276 | 3. What is the Poseidon hash function and why is it particularly useful in ZKPs? 277 | ::: 278 | 279 | #### Merkle Trees 280 | 281 | A Merkle tree is a core component of blockchain and cryptography. It's a binary tree filled with cryptographic hashes. This structure enables efficient and secure verification of the contents of large data structures. 282 | ```mermaid 283 | flowchart TB 284 | subgraph "Merkle Tree" 285 | A0["Leaf 1: Tx1 Hash"] 286 | A1["Leaf 2: Tx2 Hash"] 287 | A2["Leaf 3: Tx3 Hash"] 288 | A3["Leaf 4: Tx4 Hash"] 289 | 290 | B0["Hash of (Leaf 1 + Leaf 2)"] 291 | B1["Hash of (Leaf 3 + Leaf 4)"] 292 | 293 | C0["Merkle Root: Hash of (B0 + B1)"] 294 | 295 | A0 -->|Hash| B0 296 | A1 -->|Hash| B0 297 | A2 -->|Hash| B1 298 | A3 -->|Hash| B1 299 | 300 | B0 -->|Hash| C0 301 | B1 -->|Hash| C0 302 | end 303 | 304 | subgraph "Ethereum" 305 | StateRoot["State Root"] 306 | TxRoot["Transaction Root"] 307 | ReceiptRoot["Receipt Root"] 308 | end 309 | 310 | C0 -->|Stored in| TxRoot 311 | TxRoot -->|Verification| EthereumApp["Smart Contract or App"] 312 | EthereumApp -->|Prove Validity| Verifier 313 | 314 | ``` 315 | 316 | To understand more about Merkle trees, read the following: 317 | - [How Merkle Trees Enable the Decentralized Web! [10:05]](https://www.youtube.com/watch?v=3giNelTfeAk) 318 | - [Merkle Trees and Merkle Roots Explained](https://academy.binance.com/en/articles/merkle-trees-and-merkle-roots-explained) 319 | - [Visualizing Efficient Merkle Trees for Zero-Knowledge Proofs](https://kndrck.co/posts/efficient-merkletrees-zk-proofs/) 320 | - [The Ultimate Merkle Tree Guide in Solidity](https://soliditydeveloper.com/merkle-tree) 321 | 322 | 323 | :::info 324 | **🤔 Consider the following:** 325 | 1. Can you describe the structure of a Merkle tree? 326 | 2. How are Merkle trees used within the blockchain context? 327 | 3. Why are Merkle trees useful for efficient and secure verification of large data structures? 328 | ::: 329 | 330 | ### Digital Signatures (Schnorr) 331 | 332 | Digital signatures ensure the integrity and authenticity of digital messages or documents. By providing a means to verify the origin and confirm that the content has not been altered, digital signatures play a pivotal role in maintaining trust in digital communications. 333 | 334 | In PKC (Public Key Cryptography), anyone can encrypt their message with the receiver's public key, and only the receiver can decrypt the message with their private key. In digital signatures, on the other hand, if a signer generates a signature for a message using their private key, anyone can validate it using the signer's public key. Therefore, the message of the signature is made public, which distinguishes it from cryptographic commitments. 335 | 336 | ```mermaid 337 | sequenceDiagram 338 | participant Sender as Sender 339 | participant PrivateKey as Sender's Private Key (sk) 340 | participant Message as Message 341 | participant PublicKey as Receiver's Public Key (pk) 342 | participant Receiver as Receiver 343 | participant Verifier as Verifier (Any Third-Party) 344 | 345 | Note over Sender, Receiver: Public Key Cryptography (PKC) 346 | Sender->>PublicKey: Gets Receiver's Public Key (pk) 347 | Sender->>Message: Encrypts Message with Receiver's Public Key 348 | Sender->>Receiver: Sends Encrypted Message 349 | Receiver->>PrivateKey: Decrypts Message using Private Key (sk) 350 | 351 | Note over Sender, Verifier: Digital Signatures 352 | Sender->>Message: Signs Message using Sender's Private Key (sk) 353 | Sender->>Verifier: Sends Signed Message and Sender's Public Key 354 | Verifier->>Sender: Validates Signature using Sender's Public Key 355 | ``` 356 | 357 | Start your exploration of digital signatures with this intuitive video: 358 | - [What are Digital Signatures? - Computerphile [10:16]](https://www.youtube.com/watch?v=s22eJ1eVLTU) 359 | 360 | **Schnorr Signature**: Schnorr signatures are a digital signature scheme known for their simplicity and efficiency. 361 | - [Schnorr Digital Signature (by GeeksForGeeks)](https://www.geeksforgeeks.org/schnorr-digital-signature/) 362 | - [Schnorr Digital Signature [4:58]](https://www.youtube.com/watch?v=mV9hXEFUB6A) 363 | 364 | **Exploring DSA**: Get a deep dive into the Digital Signature Algorithm (DSA) and its significance in bolstering internet security. Through the listed resources, understand the mechanics of DSA and its use cases. 365 | - [Digital Signature Algorithm (DSA) in Cryptography](https://www.simplilearn.com/tutorials/cryptography-tutorial/digital-signature-algorithm) 366 | - [Digital Signature Algorithm (DSA) - Cryptography [5:46]](https://www.youtube.com/watch?v=iS1nK4G6EtA) 367 | - [Digital Signature Algorithm (DSA) explained with example [24:32]](https://www.youtube.com/watch?v=MtT3NBfpV5Q) 368 | 369 | :::info 370 | **🤔 Consider the following:** 371 | 1. Can you describe what digital signatures are and why they are essential in digital communications? 372 | 2. Explain the workings of the Digital Signature Algorithm (DSA). 373 | ::: 374 | 375 | ### DLP-based Public-Key Cryptography (DLP, DH, Elgamal) 376 | 377 | While RSA encryption is based on the hardness of factoring problem, there is another public key cryptography system based on hardness of Discrete Logarithm Problem (DLP). 378 | 379 | 1. **Discrete Log Problem (DLP):** This is a cornerstone problem in public-key cryptography and underlies many key exchange and encryption algorithms. Understanding DLP provides a foundation for the remaining topics. 380 | - [The Discrete Logarithm Problem - Khan Academy [1:55]](https://youtu.be/SL7J8hPKEWY) 381 | - [Public key cryptography using discrete logarithms](https://www.di-mgt.com.au/public-key-crypto-discrete-logs-0.html) 382 | 383 | 2. **Diffie-Hellman Key Exchange:** This is one of the earliest practical implementations of key exchange protocols based on the Discrete Log Problem. It's critical to understand how secure communication can be established over insecure channels. 384 | 385 | This protocol is significant as it enables secure communication over insecure channels by allowing two parties to generate a shared secret key, which can then be used for encryption and decryption of messages 386 | - [Secret Key Exchange (Diffie-Hellman) - Computerphile [8:39]](https://www.youtube.com/watch?v=NmM9HA2MQGI) 387 | - [Diffie Hellman -the Mathematics bit- Computerphile [7:04]](https://youtu.be/Yjrfm_oRO0w) 388 | - [Implementation of Diffie-Hellman Algorithm 389 | ](https://www.geeksforgeeks.org/implementation-diffie-hellman-algorithm/) 390 | 391 | 3. **ElGamal Encryption:** This is a public-key encryption method that utilizes the principles of DLP. This will allow you to see a practical application of these abstract concepts in a real-world encryption scheme. 392 | - [Intro to the ElGamal Cryptosystem [8:20]](https://www.youtube.com/watch?v=oQqr8d5s3Uk) 393 | - [The ElGamal Algorithm: a simple example [6:38]](https://www.youtube.com/watch?v=4xVCrTb_1II) 394 | - [ElGamal Encryption Algorithm](https://www.geeksforgeeks.org/elgamal-encryption-algorithm/) 395 | 396 | #### The ElGamal workflow sample 397 | ##### Key Generation (Alice - message receiver) 398 | | Step | Description | 399 | | --- | --- | 400 | | Select **p** | **p** is avery large prime number | 401 | | Find a primitive root of *p*:g | | 402 | | Choose a random intenger **a** as her private key | 1<**a**<**p**-1 | 403 | | Compute **e**: **e**=**g**^**a** mod **p** | | 404 | | **Public key: (p,g,e)** | | 405 | 406 | ##### Encryption (Bob - message sender) 407 | | Step | Description | 408 | | --- | --- | 409 | | Plaintext: m | m