<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Yu Jiang Tham on Medium]]></title>
        <description><![CDATA[Stories by Yu Jiang Tham on Medium]]></description>
        <link>https://medium.com/@yujiangtham?source=rss-999ab4bada2c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ZRAt5XKPsCBRYus_bPlijw.png</url>
            <title>Stories by Yu Jiang Tham on Medium</title>
            <link>https://medium.com/@yujiangtham?source=rss-999ab4bada2c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 08:36:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@yujiangtham/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Building a Zero Knowledge web app with Halo 2 and Wasm (part 2)]]></title>
            <link>https://medium.com/@yujiangtham/building-a-zero-knowledge-web-app-with-halo-2-and-wasm-part-2-379477444dc3?source=rss-999ab4bada2c------2</link>
            <guid isPermaLink="false">https://medium.com/p/379477444dc3</guid>
            <category><![CDATA[cryptocurrency]]></category>
            <category><![CDATA[zkp]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[zero-knowledge]]></category>
            <category><![CDATA[zero-knowledge-proofs]]></category>
            <dc:creator><![CDATA[Yu Jiang Tham]]></dc:creator>
            <pubDate>Fri, 28 Apr 2023 19:25:50 GMT</pubDate>
            <atom:updated>2023-04-28T19:25:50.129Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Continuing from the </em><a href="https://medium.com/@yujiangtham/building-a-zero-knowledge-web-app-with-halo-2-and-wasm-part-1-80858c8d16ee"><em>previous article</em></a><em> where we built a Zero Knowledge circuit in Halo 2, we now move on to compiling it to WebAssembly and integrating it into a Next.js web app.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oGeF7RDi0l8sdHiR_80V2g.png" /><figcaption>Part two of the hamster chronicles.</figcaption></figure><h3>Recap</h3><p>In the <a href="https://medium.com/@yujiangtham/building-a-zero-knowledge-web-app-with-halo-2-and-wasm-part-1-80858c8d16ee">previous article</a>, we laid the foundation for our Hammster app by building a ZK circuit using Halo 2 that would take in two private inputs of length-8 binary arrays and a public input of their Hamming distance and generate a zkSNARK proof. We also built a function that would take in that zkSNARK proof plus a public input of a claimed Hamming distance and output if the proof and public input were valid or not.</p><p>Please ensure that you’ve completed the Prerequisites section in <a href="https://medium.com/@yujiangtham/building-a-zero-knowledge-web-app-with-halo-2-and-wasm-part-1-80858c8d16ee">part 1</a> before continuing.</p><h3>What we’ll be building today</h3><p>Today, we’ll be taking the circuit that we built, adding some ways for JavaScript to interact with the circuit through WebAssembly bindings, and building an output that we can use in our Next.js project.</p><p>Demo of the completed web app: <a href="https://hammster.vercel.app/">https://hammster.vercel.app/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t7gRjCvATvF4CggLptMonQ.png" /><figcaption>Working demo of the Hammster ZK web app.</figcaption></figure><p>Github repo: <a href="https://github.com/ytham/hammster">https://github.com/ytham/hammster</a></p><h3>High-level architecture</h3><p>Here’s a high-level architecture diagram of our Hammster app. As you can see, everything is done in the front end, and we don’t use the Next.js backend server for anything.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/721/1*_AxaRKW6oGO6kRJdqxEeTw.png" /><figcaption>Hammster app high-level architecture</figcaption></figure><p>And here we have a system interaction diagram detailing the interactions between the web interface, Wasm bindings, and compiled ZK circuit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/561/1*c8OUGfbBctCOxRzx9Fs-Vg.png" /><figcaption>Hammster system interaction diagram</figcaption></figure><p>The setup params and proof are both stored in the browser’s localStorage so that the values can be used in the verify stage later.</p><h3>Adding our future Wasm module</h3><p>We’ll first modify our lib.rs file to include a new wasm module that we’ll be building:</p><pre>// file: circuits/src/lib.rs<br><br>pub mod hammster;<br>pub mod wasm;</pre><h3>Creating our Wasm module</h3><p>We’ll need to create a new file called wasm.rs and add the following use directives:</p><pre>// file: circuits/src/wasm.rs<br><br>use std::io::BufReader;<br>use crate::hammster::{calculate_hamming_distance, create_circuit, empty_circuit, generate_setup_params, generate_keys, generate_proof, verify};<br>use halo2_proofs::{<br>    poly::commitment::Params, <br>    pasta::{Fp, EqAffine}, <br>    plonk::keygen_vk<br>};<br>use js_sys::Uint8Array;<br>use wasm_bindgen::prelude::*;</pre><h3>Building for Wasm</h3><p>In order to use wasm-pack to build a Wasm package, you’ll need to create a file circuits/.cargo/config with the following contents, replacing the target = &quot;aarch64-apple-darwin&quot; section with whatever architecture your computer is running.</p><pre>// file: circuits/.cargo/config<br><br>[target.wasm32-unknown-unknown]<br>rustflags = [&quot;-C&quot;, &quot;target-feature=+atomics,+bulk-memory,+mutable-globals&quot;]<br><br>[unstable]<br>build-std = [&quot;panic_abort&quot;, &quot;std&quot;]<br><br>[build]<br>target = &quot;aarch64-apple-darwin&quot;</pre><p>Additionally, we’ll want to edit our package.json file to add a script that uses wasm-pack to compile our circuit to Wasm with JS interface adapters.</p><pre>// file: package.json<br><br>...<br>  &quot;scripts&quot;: {<br>    &quot;dev&quot;: &quot;next dev&quot;,<br>    &quot;build&quot;: &quot;next build&quot;,<br>    &quot;start&quot;: &quot;next start&quot;,<br>    &quot;lint&quot;: &quot;next lint&quot;,<br>    &quot;build:wasm&quot;: &quot;cd circuits &amp;&amp; wasm-pack build --target web --out-dir ../src/lib/wasm &amp;&amp; cd ..&quot;<br>  },<br>...</pre><p>This will allow us to compile to Wasm by running yarn build:wasm later, but we still need to add functions in order to run our commands.</p><p>We’ll also want to add our dependencies to package.json as well:</p><pre>// file: package.json<br><br>...<br>  &quot;dependencies&quot;: {<br>    &quot;@emotion/react&quot;: &quot;^11.10.6&quot;,<br>    &quot;@mantine/core&quot;: &quot;^6.0.8&quot;,<br>    &quot;@mantine/form&quot;: &quot;^6.0.8&quot;,<br>    &quot;@mantine/hooks&quot;: &quot;^6.0.8&quot;,<br>    &quot;@mantine/notifications&quot;: &quot;^6.0.8&quot;,<br>    &quot;@types/node&quot;: &quot;18.15.9&quot;,<br>    &quot;@types/react&quot;: &quot;18.0.29&quot;,<br>    &quot;@types/react-dom&quot;: &quot;18.0.11&quot;,<br>    &quot;eslint&quot;: &quot;8.36.0&quot;,<br>    &quot;eslint-config-next&quot;: &quot;13.2.4&quot;,<br>    &quot;next&quot;: &quot;13.2.4&quot;,<br>    &quot;react&quot;: &quot;18.2.0&quot;,<br>    &quot;react-dom&quot;: &quot;18.2.0&quot;,<br>    &quot;typescript&quot;: &quot;5.0.2&quot;<br>  }<br>...</pre><p>And then install the dependencies:</p><blockquote><em>yarn install</em></blockquote><h3>Utility functions</h3><p>In order to log to the Javascript console in the functions that we’ll create, we can utilize the following code that was lifted from the <a href="https://rustwasm.github.io/docs/wasm-bindgen/examples/console-log.html">wasm-bindgen guide</a>:</p><pre>// file: circuits/src/wasm.rs<br><br>#[wasm_bindgen]<br>extern &quot;C&quot; {<br>    #[wasm_bindgen(js_namespace = console)]<br>    fn log(s: &amp;str);<br>}</pre><p>This copies an input vector to an output Uint8Array:</p><pre>// file: circuits/src/wasm.rs<br><br>fn copy_vec_to_u8arr(v: &amp;Vec&lt;u8&gt;) -&gt; Uint8Array {<br>    let u8_arr = Uint8Array::new_with_length(v.len() as u32);<br>    u8_arr.copy_from(v);<br>    u8_arr<br>} </pre><h3>Wasm interface</h3><p>We’ll now be creating three functions, one that runs a setup, one for generating a proof, and one for verifying the proof.</p><p>For the setup_params function, we take in a k parameter which, if you recall, sets a bound on the max number of rows of the circuit (2^k). The tradeoff for having a higher k value is that proving and verifying times will be longer, whereas if the k value is too low then your circuit won’t compile. In our case, the k value is 6, which we’ll pass in from the web frontend side. This gives us a little extra flexibility, but we could technically merge this setup_params with our proof_generate function if we wanted to.</p><pre>// file: circuits/src/wasm.rs<br><br>#[wasm_bindgen]<br>pub fn setup_params(k: u32) -&gt; Uint8Array {<br>    log(&quot;running setup&quot;);<br>    <br>    // Generate setup params<br>    let params = generate_setup_params(k); <br>    let mut buf = vec![];<br>    params.write(&amp;mut buf).expect(&quot;Can write params&quot;);<br><br>    copy_vec_to_u8arr(&amp;buf)<br>}</pre><p>Our proof_generate function takes in our two vectors from the JS frontend as well as the setup params byte array that was output from our setup_params function, transform the inputs, and generate the zkSNARK proof, and output it as a Uint8Array.</p><pre>// file: circuits/src/wasm.rs<br><br>#[wasm_bindgen]<br>pub fn proof_generate(<br>    a: &amp;[u8], <br>    b: &amp;[u8], <br>    params_bytes: &amp;[u8]<br>) -&gt; Uint8Array {<br>    log(&quot;proving...&quot;);<br>    <br>    let params = Params::&lt;EqAffine&gt;::read(&amp;mut BufReader::new(params_bytes)).expect(&quot;params should not fail to read&quot;);<br><br>    // Turn slices into vectors and calculate hamming distance<br>    let a_vec: Vec&lt;u64&gt; = a.to_vec().iter().map(|x| *x as u64).collect();<br>    let b_vec: Vec&lt;u64&gt; = b.to_vec().iter().map(|x| *x as u64).collect();<br>    let hamming_dist = calculate_hamming_distance(a_vec.clone(), b_vec.clone());<br><br>    // Generate proving key<br>    let empty_circuit = empty_circuit();<br>    let (pk, _vk) = generate_keys(&amp;params, &amp;empty_circuit);<br>    <br>    // Generate proof<br>    let hammster_circuit = create_circuit(a_vec, b_vec);<br>    let proof = generate_proof(&amp;params, &amp;pk, hammster_circuit, &amp;hamming_dist);<br>    <br>    copy_vec_to_u8arr(&amp;proof)<br>}</pre><p>Finally, our proof_verify function will take in the params and proof from the frontend as well as a user-input hamming distance value. After transforming the values into the shape that the verify function requires, it will return a boolean value of whether the proof was verified or not.</p><pre>// file: circuits/src/wasm.rs<br><br>#[wasm_bindgen]<br>pub fn proof_verify(<br>    params_bytes: &amp;[u8], <br>    hamming_dist: u32, <br>    proof: &amp;[u8]<br>) -&gt; bool {<br>    log(&quot;verifying...&quot;);<br><br>    let params = Params::&lt;EqAffine&gt;::read(&amp;mut BufReader::new(params_bytes)).expect(&quot;params should not fail to read&quot;);<br><br>    // Generate verifying key<br>    let empty_circuit = empty_circuit();<br>    let vk = keygen_vk(&amp;params, &amp;empty_circuit).expect(&quot;vk should not fail to generate&quot;);<br><br>    // Transform params for verify function<br>    let hamming_dist_fp = vec![Fp::from(hamming_dist as u64)];<br>    let proof_vec = proof.to_vec();<br><br>    // Verify the proof and public input<br>    let ret_val = verify(&amp;params, &amp;vk, &amp;hamming_dist_fp, proof_vec);<br>    match ret_val {<br>        Err(_) =&gt; false,<br>        _ =&gt; true,<br>    }<br>}</pre><h4>Compiling to Wasm</h4><p>Now that we’ve gotten our Wasm code written, we can use wasm-pack to generate a folder that includes our Wasm file along with a JavaScript interface. Since we’ve already added our script to package.json earlier, we ensure we’re in the root of directory of our Next.js project and run:</p><blockquote><em>yarn build:wasm</em></blockquote><p>This will output all of the required files to src/lib/wasm.</p><h3>Building out the frontend</h3><p>We’re using the <a href="https://mantine.dev/">Mantine</a> components library to build out a lot of the frontend components, which will save us a lot of time. Let’s start by adding the required items to our _app.tsx file:</p><pre>// file: src/pages/_app.tsx<br><br>import &#39;@/styles/globals.css&#39;<br>import type { AppProps } from &#39;next/app&#39;<br>import { MantineProvider } from &#39;@mantine/core&#39;;<br>import { Notifications } from &#39;@mantine/notifications&#39;;<br><br>export default function App({ Component, pageProps }: AppProps) {<br>  return (<br>    &lt;MantineProvider withNormalizeCSS withGlobalStyles&gt;<br>      &lt;Notifications /&gt;<br>      &lt;Component {...pageProps} /&gt;<br>    &lt;/MantineProvider&gt;<br>  )<br>}</pre><p>We’ll also need to create this index.tsx file that shows the main UI:</p><pre>// file: src/pages/index.tsx<br><br>import Head from &#39;next/head&#39;<br>import { Grid, SegmentedControl, Space, Stack, Text, Title } from &#39;@mantine/core&#39;<br>import Link from &#39;next/link&#39;<br>import { ProveForm } from &#39;@/components/ProveForm&#39;<br>import { useState } from &#39;react&#39;<br>import { VerifyForm } from &#39;@/components/VerifyForm&#39;<br><br>export default function Home() {<br>  const [page, setPage] = useState(&quot;prove&quot;);<br><br>  const renderProveOrVerify = () =&gt; {<br>    // Renders the page based on the SegmentedControl selection<br>    if (page === &quot;verify&quot;) { <br>      return &lt;VerifyForm /&gt;;<br>    }<br>    return &lt;ProveForm /&gt;<br>  }<br><br>  return (<br>    &lt;&gt;<br>      &lt;Head&gt;<br>        &lt;title&gt;Hammster&lt;/title&gt;<br>        &lt;meta name=&quot;description&quot; content=&quot;Hammster, the hamming distance ZK app.&quot; /&gt;<br>        &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1&quot; /&gt;<br>        &lt;link rel=&quot;icon&quot; href=&quot;/favicon.ico&quot; /&gt;<br>      &lt;/Head&gt;<br>      &lt;Stack align=&#39;center&#39; justify=&#39;center&#39; mih=&quot;100vh&quot; style={{<br>        background: &#39;url(https://medium.com/hammster-corner.png)&#39;,<br>        backgroundRepeat: &#39;no-repeat&#39;,<br>        backgroundAttachment: &#39;fixed&#39;,<br>        backgroundPosition: &#39;right bottom&#39;,<br>        backgroundSize: &#39;50%&#39;,<br>        padding: &quot;0 20px&quot;,<br>      }}&gt;<br>        &lt;Grid justify=&#39;center&#39;&gt;<br>          &lt;Grid.Col xs={10} sm={8} md={6}&gt;<br>            &lt;Stack align=&#39;center&#39; spacing=&quot;xl&quot;&gt;<br>              &lt;Title order={1} ff={&quot;helvetica neue&quot;}&gt;<br>                Hammster<br>              &lt;/Title&gt;<br>              &lt;Text&gt;<br>                Hammster is written in &lt;Link href=&quot;https://halo2.dev/&quot;&gt;Halo2&lt;/Link&gt;. It takes two 8-length vector inputs of <br>                binary digits and their &lt;Link href=&quot;https://en.wikipedia.org/wiki/Hamming_distance&quot;&gt;Hamming distance&lt;/Link&gt; and <br>                generates a proof that the two inputs are the claimed hamming distance away from each other. Please note that <br>                this currently does not work on mobile.<br>              &lt;/Text&gt;<br>              &lt;SegmentedControl <br>                value={page}<br>                onChange={setPage}<br>                data={[<br>                  { value: &quot;prove&quot;, label: &quot;Prove&quot; },<br>                  { value: &quot;verify&quot;, label: &quot;Verify&quot; },<br>                ]}<br>              /&gt;<br>              { renderProveOrVerify() }<br>            &lt;/Stack&gt;<br>          &lt;/Grid.Col&gt;<br>        &lt;/Grid&gt;<br>        <br>        &lt;Space h=&quot;16vh&quot; /&gt;<br>        <br>        &lt;Stack spacing={0} style={{<br>          position: &quot;fixed&quot;,<br>          left: &quot;8px&quot;,<br>          bottom: &quot;8px&quot;,<br>          padding: &quot;8px 20px&quot;,<br>          borderRadius: &quot;8px&quot;,<br>          boxShadow: &quot;0px 6px 12px rgba(0, 0, 0, 0.1)&quot;,<br>        }}&gt;<br>          &lt;Text&gt;<br>            &lt;Link href=&quot;https://medium.com/@yujiangtham/building-a-zero-knowledge-web-app-with-halo-2-and-wasm-part-1-80858c8d16ee&quot;&gt;Tutorial&lt;/Link&gt;<br>          &lt;/Text&gt;<br>          &lt;Text&gt;<br>            &lt;Link href=&quot;https://github.com/ytham/hammster&quot;&gt;Github&lt;/Link&gt;<br>          &lt;/Text&gt;<br>        &lt;/Stack&gt;<br>      &lt;/Stack&gt;<br>    &lt;/&gt;<br>  )<br>}</pre><p>Obviously, some of the includes are not yet there yet, but we’ll be building those shortly! In the meantime, we’ll also need to save this transparent .png of a hamster to be used in the bottom right corner of our index.tsx page. Save it to public/hammster-corner.png</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/412/1*3KYRNmrmSrfY1w-nOCSptA.png" /><figcaption>Right click and save this as hammster-corner.png</figcaption></figure><h4>Helper components</h4><p>We need to add two components that will take care of the input forms and the Hamming distance calculations.</p><p>The BinaryInput component utilizes Mantine <a href="https://mantine.dev/core/pin-input/">PinInput</a>, which gives us separate number inputs for each digit instead of a single input box. We pass in the form object (which we’ll be creating below in the ProveForm component) into our props.</p><pre>// file: src/components/BinaryInput.tsx<br><br>import { Group, PinInput, Text } from &quot;@mantine/core&quot;<br><br>export const BinaryInput = (props: any) =&gt; {<br>  return (<br>    &lt;Group&gt;<br>      &lt;Text&gt;<br>        Input {props.inputNum}<br>      &lt;/Text&gt;<br>      &lt;PinInput type={/^[0-1]+/} length={8} placeholder=&quot;0&quot; styles={<br>          {<br>            input: {<br>              backgroundColor: &#39;#def&#39;,<br>              color: &#39;#345&#39;,<br>              fontWeight: 400,<br>              fontSize: &#39;1.05rem&#39;,<br>            },<br>          }<br>        } <br>        {...props.form.getInputProps(`input${props.inputNum}`)}<br>      /&gt;<br>    &lt;/Group&gt;<br>  )<br>}</pre><p>Our next helper component calculates the Hamming distance from the two inputs as well. We also pass in the same form object from ProveForm below and perform some operations to check the values and calculate the Hamming distance from those values.</p><pre>// file: src/components/HammingDistance.tsx<br><br>import { Text } from &quot;@mantine/core&quot;<br><br>export const HammingDistance = (props: any) =&gt; {<br>  if (props.form === undefined) {<br>    return null;<br>  }<br><br>  const calculateHammingDistance = () =&gt; {    <br>    // Pad our inputs to 8 digits<br>    let input0 = props.form.values.input0;<br>    if (input0.length &lt; 8) {<br>      input0 = input0.padStart(8, &#39;0&#39;);<br>    }<br>    let input1 = props.form.values.input1;<br>    if (input1.length &lt; 8) {<br>      input1 = input1.padStart(8, &#39;0&#39;);<br>    }<br><br>    // Parse each item in each array to binary values<br>    const input0arr = input0.split(&#39;&#39;).map((x: string) =&gt; parseInt(x, 2));<br>    const input1arr = input1.split(&#39;&#39;).map((x: string) =&gt; parseInt(x, 2));<br><br>    // Calculate the hamming distance by comparing the two arrays<br>    let hammingDistance = 0;<br>    for (let i = 0; i &lt; input0arr.length; i++) {<br>      if (input0arr[i] !== input1arr[i]) {<br>        hammingDistance++;<br>      }<br>    }<br>    return hammingDistance;<br>  }<br><br>  return (<br>    &lt;Text align=&quot;center&quot;&gt;<br>      Hamming distance: &lt;b&gt;{calculateHammingDistance()}&lt;/b&gt; <br>      &lt;Text fz=&quot;xs&quot;&gt;<br>        (remember this number!)<br>      &lt;/Text&gt;<br>    &lt;/Text&gt;<br>  )<br>}</pre><h4>Form for generating a proof</h4><p>Now that we’ve built out some of the helper components, we can get to work on the meat of the frontend. Our ProveForm component displays a form that accepts two binary inputs and calculates the Hamming distance of those inputs.</p><p>Once the user clicks the <em>Generate &amp; Save Proof</em> button, we load the Wasm library, run setup, save the setup params to localStorage, generate the proof, and then save the proof to localStorage as well. The user must remember the calculated Hamming distance number for the input into the Verify section.</p><pre>// file: src/components/ProveForm.tsx<br><br>import { useState } from &quot;react&quot;<br>import { Group, Input, Stack, Text } from &quot;@mantine/core&quot;<br>import { BinaryInput } from &quot;./BinaryInput&quot;<br>import { useForm } from &quot;@mantine/form&quot;<br>import { HammingDistance } from &quot;./HammingDistance&quot;<br>import { notifications } from &#39;@mantine/notifications&#39;;<br>import * as hm from &#39;../lib/wasm/hammster.js&#39;<br><br>import { Group, Input, Stack, Text } from &quot;@mantine/core&quot;<br>import { BinaryInput } from &quot;./BinaryInput&quot;<br>import { useForm } from &quot;@mantine/form&quot;<br>import { HammingDistance } from &quot;./HammingDistance&quot;<br>import { notifications } from &#39;@mantine/notifications&#39;;<br>import * as hm from &#39;../lib/wasm/hammster.js&#39;<br><br>export const ProveForm = () =&gt; {<br>  const form = useForm({<br>    initialValues: {<br>      input0: &#39;&#39;,<br>      input1: &#39;&#39;,<br>    },<br>  })<br><br>  const submit = async (values: any) =&gt; {<br>    console.log(values);<br><br>    // Set up hammster Wasm<br>    await hm.default();<br><br>    // Run setup<br>    const params = hm.setup_params(6);<br>    try {<br>      localStorage.setItem(&quot;setupParams&quot;, params.toString());<br>    } catch (err) {<br>      console.log(err);<br>      notifications.show({<br>        title: &quot;Error&quot;,<br>        message: &quot;Failed to save setup params&quot;,<br>        color: &quot;red&quot;,<br>      })<br>      return;<br>    }<br><br>    // Parse inputs<br>    const input0arr = values.input0.split(&#39;&#39;).map((x: string) =&gt; parseInt(x, 2));<br>    const input1arr = values.input1.split(&#39;&#39;).map((x: string) =&gt; parseInt(x, 2));<br>    <br>    // Generate the proof<br>    console.log(&quot;generating proof&quot;);<br>    const proof = hm.proof_generate(input0arr, input1arr, params);<br>    if (proof.length === 0) {<br>      notifications.show({<br>        title: &quot;Error&quot;,<br>        message: &quot;Failed to generate proof&quot;,<br>        color: &quot;red&quot;,<br>      })<br>      return;<br>    }<br><br>    // Save proof to localStorage<br>    try {<br>      localStorage.setItem(&quot;proof&quot;, proof.toString());<br>      console.log(&quot;saved to localStorage&quot;);<br>    } catch (err) {<br>      console.log(err);<br>      notifications.show({<br>        title: &quot;Error&quot;,<br>        message: &quot;Failed to save proof&quot;,<br>        color: &quot;red&quot;,<br>      })<br>      return;<br>    }<br><br>    // Show notification to user<br>    notifications.show({<br>      title: &quot;Success!&quot;,<br>      message: &quot;Setup params &amp; proof saved to localStorage&quot;,<br>      color: &quot;green&quot;,<br>    });<br>  }<br>  <br>  return (<br>    &lt;form onSubmit={form.onSubmit(submit)}&gt;<br>      &lt;Stack align=&#39;center&#39; w=&#39;100%&#39; style={{<br>        backgroundColor: &quot;rgba(200,230,255,0.25)&quot;,<br>        backdropFilter: &#39;blur(8px)&#39;,<br>        border: &quot;2px solid #eee&quot;,<br>        borderRadius: &quot;8px&quot;,<br>        padding: &quot;16px&quot;,<br>        boxShadow: &quot;0px 12px 36px rgba(0, 0, 0, 0.2)&quot;,<br>      }}&gt;<br>        &lt;Text&gt;<br>          Input two 8-bit binary values below. Remember the calculated hamming distance value for the Verify section.<br>        &lt;/Text&gt;<br>        &lt;Stack align=&#39;flex-end&#39;&gt;<br>          &lt;BinaryInput inputNum={0} form={form} /&gt;<br>          &lt;BinaryInput inputNum={1} form={form} /&gt;<br>        &lt;/Stack&gt;<br>        &lt;HammingDistance form={form} /&gt;<br>        &lt;Group&gt;<br>          &lt;Input <br>            type=&quot;submit&quot; <br>            value=&quot;Generate &amp; Save Proof&quot; <br>            disabled={form.values.input0.length !== 8 || form.values.input1.length !== 8} <br>          /&gt;<br>        &lt;/Group&gt;<br>      &lt;/Stack&gt;<br>    &lt;/form&gt;<br>  )<br>}</pre><h4>Form for verifying the proof</h4><p>Our VerifyForm component only has one input, which is the Hamming distance that was used as the public input for the proof generated earlier. We first check if there is any proof saved to localStorage, and if not, will disable the <em>Verify Proof</em> button.</p><p>When the user inputs the Hamming distance and clicks the <em>Verify Proof</em>, we grab the setup params and proof from localStorage, run it through the verifier, and surface a notification if the proof and public params was valid or not.</p><pre>// file: src/components/VerifyForm.tsx<br><br>import { useEffect, useState } from &quot;react&quot;;<br>import { Input, Stack, Text, TextInput } from &quot;@mantine/core&quot;<br>import { useForm } from &quot;@mantine/form&quot;<br>import { notifications } from &quot;@mantine/notifications&quot;;<br>import * as hm from &#39;../lib/wasm/hammster.js&#39;<br><br>export const VerifyForm = () =&gt; {<br>  const [hasProof, setHasProof] = useState(false);<br><br>  // Check if we have a proof saved to localStorage yet<br>  useEffect(() =&gt; {<br>    const proof = localStorage.getItem(&quot;proof&quot;);<br>    if (proof) {<br>      setHasProof(true);<br>      return;<br>    }<br>  }, []);<br><br>  const form = useForm({<br>    initialValues: {<br>      hammingDist: &#39;&#39;,<br>    },<br>    validate: {<br>      hammingDist: (value) =&gt; {<br>        const parsedValue = parseInt(value);<br>        if (isNaN(parsedValue)) {<br>          return &#39;Must be a number&#39;;<br>        }<br>        if (parsedValue &lt; 0 || parsedValue &gt; 8) {<br>          return &#39;Must be between 0 and 8&#39;;<br>        }<br>        return null;<br>      },<br>    },<br>  })<br><br>  const submit = async (values: any) =&gt; {<br>    console.log(values);<br><br>    // Get setup params from localStorage<br>    const paramsString = localStorage.getItem(&quot;setupParams&quot;);<br>    if (!paramsString) {<br>      console.log(&quot;No params found&quot;);<br>      return;<br>    }<br>    const params = Uint8Array.from((paramsString as string).split(&#39;,&#39;).map((x: string) =&gt; parseInt(x)));<br><br>    // Get proof from localStorage<br>    const proofString = localStorage.getItem(&quot;proof&quot;);<br>    if (!proofString) {<br>      console.log(&quot;No proof found&quot;);<br>      return;<br>    }<br>    const proof = Uint8Array.from((proofString as string).split(&#39;,&#39;).map((x: string) =&gt; parseInt(x)));<br><br>    // Set up hammster Wasm<br>    await hm.default();<br><br>    // Verify the proof<br>    const result = hm.proof_verify(params, values.hammingDist, proof);<br>    <br>    // Show a notification based on the result of the proof verification<br>    if (result) {<br>      notifications.show({<br>        title: &quot;Success!&quot;,<br>        message: &quot;Proof verified successfully!&quot;,<br>        color: &quot;green&quot;,<br>      });<br>    } else {<br>      notifications.show({<br>        title: &quot;Error&quot;,<br>        message: `Proof with hamming distance of ${values.hammingDist} failed to verify`,<br>        color: &quot;red&quot;,<br>      });<br>    }<br>  }<br><br>  return (<br>    &lt;form onSubmit={form.onSubmit(submit)}&gt;<br>      &lt;Stack align=&#39;center&#39; w=&#39;100%&#39; style={{<br>        backgroundColor: &quot;rgba(200,230,255,0.25)&quot;,<br>        backdropFilter: &#39;blur(8px)&#39;,<br>        border: &quot;2px solid #eee&quot;,<br>        borderRadius: &quot;8px&quot;,<br>        padding: &quot;16px&quot;,<br>        boxShadow: &quot;0px 12px 36px rgba(0, 0, 0, 0.2)&quot;,<br>      }}&gt;<br>        &lt;Text&gt;<br>          Input the hamming distance from the Prove section.<br>        &lt;/Text&gt;<br>        &lt;TextInput <br>          label=&quot;Hamming Distance&quot; <br>          placeholder=&quot;[0,8]&quot; <br>          styles={<br>            {<br>              input: {<br>                backgroundColor: &#39;#def&#39;,<br>                color: &#39;#345&#39;,<br>                fontWeight: 400,<br>                fontSize: &#39;0.95rem&#39;,<br>              },<br>            }<br>          }<br>          {...form.getInputProps(&#39;hammingDist&#39;)} <br>        /&gt;<br>        &lt;Input <br>          type=&quot;submit&quot; <br>          value=&quot;Verify Proof&quot; <br>          disabled={!hasProof || form.values.hammingDist.length !== 1} <br>        /&gt;<br>      &lt;/Stack&gt;<br>    &lt;/form&gt;<br>  )<br>}</pre><h3>Trying it out</h3><p>You should now be able to, from the root of the project directory, start the web server and try out the app:</p><blockquote><em>yarn dev</em></blockquote><p>Open up a web browser to http://localhost:3000 in order to load the web app and give it a try!</p><h3>Conclusion</h3><p>Glad you made it this far! To recap, we started off with building a Halo 2 circuit, compiled it to Wasm, and then built a web app around it. If you found it informative, please clap and share so that others can also find these articles as well! Follow me on <a href="https://twitter.com/DarkForestHam">Twitter</a> and here on Medium for more ZK content. Cheers!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=379477444dc3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Zero Knowledge web app with Halo 2 and Wasm (part 1)]]></title>
            <link>https://medium.com/@yujiangtham/building-a-zero-knowledge-web-app-with-halo-2-and-wasm-part-1-80858c8d16ee?source=rss-999ab4bada2c------2</link>
            <guid isPermaLink="false">https://medium.com/p/80858c8d16ee</guid>
            <category><![CDATA[zero-knowledge-proofs]]></category>
            <category><![CDATA[zkp]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[zero-knowledge]]></category>
            <category><![CDATA[cryptocurrency]]></category>
            <dc:creator><![CDATA[Yu Jiang Tham]]></dc:creator>
            <pubDate>Wed, 26 Apr 2023 15:58:05 GMT</pubDate>
            <atom:updated>2023-05-21T07:47:31.042Z</atom:updated>
            <content:encoded><![CDATA[<p><em>In this two-part series, we’ll explore building a Zero Knowledge circuit using the Halo 2 zkSNARK proving system and subsequently how we can compile it to WebAssembly to be used in a web app.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PwGgbDV0n5LvEV97x5ESYA.png" /><figcaption>A hamster-like character (you’ll have to keep reading to see why) with zero eyes, but much knowledge.</figcaption></figure><h3>Introduction</h3><p>There’s no shortage of ways in which Zero Knowledge apps that can be built these days. The past few years have brought about a rapid advancement of proving systems, libraries, domain-specific languages (DSLs), and developer interest in the space. In this two-part series, we’ll be building a very basic web app using the Halo 2 proof system.</p><p>Halo 2 was created by the <a href="https://electriccoin.co/">Electric Coin Company</a> (who also created <a href="https://z.cash/">Zcash</a>) as a solution to some of the inefficiencies and security issues (such as trusted setup) of Zcash. The Halo 2 proof system is implemented via a set of Rust crates that enable the creation and verification of zkSNARK proofs without a trusted setup.</p><p>The functions that we’ll be creating to generate the circuit, proofs, proving/verifying keys, etc. can all be compiled down to WebAssembly, which can subsequently be used in a web app.</p><p>A fair warning that the topics covered in this series may be a big more difficult for beginners. If you’re just starting out, you might want to take a look at my previous blog posts on <a href="https://medium.com/@yujiangtham/lets-dissect-a-zksnark-part-1-a82fc092f58a">dissecting a zkSNARK</a> to get an idea of how things work.</p><h3>Background</h3><p>The original Halo was created by the Electric Coin Company as a zkSNARK construction that would not require a trusted setup and be significantly more performant than Zcash. After that, Halo 2 was created by replacing the Sonic proving system with PLONK.</p><h4>PLONK</h4><p>PLONK is a proof system for generating zkSNARKs that uses a universal and updatable trusted setup. A computation must first be converted into an <a href="https://medium.com/@yujiangtham/lets-dissect-a-zksnark-part-1-a82fc092f58a">arithmetic circuit</a>, in order for the proof system to understand it. In PLONK, all arithmetic constraints (called “gates”) are of the form:</p><pre>(Q_L)a + (Q_R)b + (Q_O)c + (Q_M)ab + Q_C = 0</pre><p>This allows us to come up with addition or multiplication of two inputs (a, b) plus some constant to equal an output c. Each of the Q’s are selectors:</p><pre>Q_L: left input selector<br>Q_R: right input selector<br>Q_O: output selector<br>Q_M: multiplication selector<br>Q_C: constant value</pre><p>Therefore, we can create an addition gate by setting the following values for the selectors:</p><pre>Q_L = 1<br>Q_R = 1<br>Q_O = -1<br>Q_M = 0<br>Q_C = 0<br><br>(1)a + (1)b + (-1)c + (0)ab + 0 = 0<br>a + b = c</pre><p>Similarly, we can create a multiplication gate:</p><pre>Q_L = 0<br>Q_R = 0<br>Q_O = -1<br>Q_M = 1<br>Q_C = 0<br><br>(0)a + (0)b + (-1)c + (1)ab + 0 = 0<br>ab = c</pre><p>Halo 2 uses PLONK<em>ish </em>arithmetization in which there’s more flexibility in the gates.</p><h4>PLONKish</h4><p>PLONKish gates offer more flexibility than regular PLONK gates. They are laid out in a table and can have any number of columns and rows (although there are tradeoffs for speed, and number of rows must be a power of 2), with three different types of columns: advice, instance, and fixed.</p><ul><li><strong>advice</strong>: private inputs and intermediate values go here</li><li><strong>instance</strong>: generally used for public inputs</li><li><strong>fixed</strong>: constants, lookup tables, and selectors</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*71ZM_94sgnfamwzZVFj4DA.png" /><figcaption>Illustration of the different columns of a PLONKish table</figcaption></figure><p>The various cells in the table are able to reference other cells, giving PLONKish gates a huge amount of flexibility.</p><h3>What will we be building?</h3><p>We’ll be building a <a href="https://en.wikipedia.org/wiki/Hamming_distance">Hamming distance</a> web app called Hammster. The Hamming distance of two same-length strings is the number of places at which the symbols are different. Our app takes two 8-length binary inputs, calculates their Hamming distance, and outputs a ZK proof that can be verified in a separate part of the web app.</p><p>In the first part of the series, we cover how to build the circuit in Halo 2. The second part of the series explains how to generate the Wasm files and interface with them in a Next.js app.</p><p>This app is loosely based off of the the <a href="https://zcash.github.io/halo2/user/simple-example.html">“Simple Example”</a> (but not really that simple) in the Halo 2 book.</p><p>A demo of the web app is available here: <a href="https://hammster.vercel.app/">https://hammster.vercel.app/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t7gRjCvATvF4CggLptMonQ.png" /><figcaption>The Hammster web app!</figcaption></figure><p>Github repo: <a href="https://github.com/ytham/hammster">https://github.com/ytham/hammster</a></p><h3>Prerequisites</h3><ul><li><a href="https://www.rust-lang.org/tools/install">Rust</a></li><li><a href="https://rustup.rs/">rustup</a></li><li><a href="https://nodejs.org/en/download">Node.js</a></li><li><a href="https://classic.yarnpkg.com/lang/en/docs/install/">yarn</a></li><li><a href="https://developer.mozilla.org/en-US/docs/WebAssembly/Rust_to_wasm#rust_environment_setup">wasm-pack</a></li></ul><p>Note that the current example runs on Apple M architectures (stable-aarch64-apple-darwin) but I have not tested with any other architecture, and some modifications will be required if you’re not running an Apple M computer.</p><h3>Getting started</h3><p>Let’s get started! We’ll first create a new next.js project, which we’ll use to hold the rest of our project. You can run the following command in your terminal to create a new next.js app</p><blockquote><em>yarn create next-app</em></blockquote><p>Call it <em>hammster</em> and hit enter to select all of the default settings until it starts downloading the packages. This will take a minute or two.</p><p>Once that’s done, we’ll go ahead and use cargo to create a new Rust project within our new next.js project. We’ll enter our newly-generated generated hammster folder and generate a new Rust project called circuits using the following commands:</p><blockquote><em>cd hammster</em></blockquote><blockquote><em>cargo new circuits</em></blockquote><p>This will create a new folder called circuits within our hammster next.js project. We’ll be using a variety of packages, so we’ll need to update our Cargo.toml file to make it look like the following:</p><pre>// file: circuits/Cargo.toml<br><br>[package]<br>name = &quot;halo2_hammster&quot;<br>version = &quot;0.1.0&quot;<br>edition = &quot;2021&quot;<br><br>[lib]<br>name = &quot;hammster&quot;<br>path = &quot;src/lib.rs&quot;<br>crate-type = [&quot;cdylib&quot;, &quot;rlib&quot;]<br><br>[dependencies]<br>extend = &quot;1.2.0&quot;<br>halo2_proofs = { version = &quot;0.3.0&quot;, features = [&quot;dev-graph&quot;] }<br>plotters = &quot;0.3.4&quot;<br>rand_core = &quot;0.6.4&quot;<br>serde = { version = &quot;1.0.156&quot;, features = [&quot;derive&quot;] }<br>serde_json = &quot;1.0.94&quot;<br>getrandom = { version = &quot;0.2&quot;, features = [&quot;js&quot;] }<br>wasm-bindgen = &quot;0.2.84&quot;<br>js-sys = &quot;0.3.61&quot;</pre><p>We’ll first create a file called hammster.rs in the path circuits/src. We’ll add all of our imports and constants first, as seen below:</p><pre>// file: circuits/src/hammster.rs<br><br>use std::{<br>    marker::PhantomData,<br>};<br>use halo2_proofs::{<br>    arithmetic::Field, <br>    dev::MockProver,<br>    circuit::{Layouter, Chip, Value, AssignedCell, Region, SimpleFloorPlanner}, <br>    plonk::{Column, Advice, Instance, Error, Selector, ConstraintSystem, Circuit, Expression, create_proof, keygen_vk, keygen_pk, ProvingKey, VerifyingKey, verify_proof, SingleVerifier}, <br>    poly::{Rotation, commitment::Params}, <br>    pasta::{Fp, EqAffine}, transcript::{Blake2bWrite, Challenge255, Blake2bRead}, <br>};<br>use rand_core::OsRng;<br><br>// The length of our binary inputs<br>const BINARY_LENGTH: usize = 8;</pre><h3>Define instructions for our Chip</h3><p>We need to create a set of function signatures in the trait definition of our Chip that will do the things that we need to do. In this case, our Hammster circuit needs functions to load private inputs and check that they’re binary values, apply an XOR to two numbers, add those XORed values together (to find the Hamming distance), and then expose a result as a public output.</p><pre>// file: circuits/src/hammster.rs<br><br>// Traits for the chip<br>trait Instructions&lt;F: Field&gt;: Chip&lt;F&gt; {<br>    type Num;<br><br>    fn load_private_and_check_binary(&amp;self, layouter: impl Layouter&lt;F&gt;, column: usize, value: [Value&lt;F&gt;; BINARY_LENGTH]) -&gt; Result&lt;Vec&lt;Self::Num&gt;, Error&gt;;<br><br>    fn xor(&amp;self, layouter: impl Layouter&lt;F&gt;, a: Self::Num, b: Self::Num) -&gt; Result&lt;Self::Num, Error&gt;;<br><br>    fn accumulator(&amp;self, layouter: impl Layouter&lt;F&gt;, values: [Self::Num; BINARY_LENGTH]) -&gt; Result&lt;Self::Num, Error&gt;;<br><br>    fn expose_public(&amp;self, layouter: impl Layouter&lt;F&gt;, num: Self::Num) -&gt; Result&lt;(), Error&gt;;<br>}</pre><p>Great, now we have a set of function signatures for a generic Chip, of which we’ll write implementations for our HammsterChip later.</p><pre>// file: circuits/src/hammster.rs<br><br>// The chip which holds the circuit config<br>pub struct HammsterChip&lt;F: Field&gt; {<br>    config: HammsterConfig,<br>    _marker: PhantomData&lt;F&gt;,<br>}<br><br>// Set what happens when config and loaded eq<br>impl&lt;F: Field&gt; Chip&lt;F&gt; for HammsterChip&lt;F&gt; {<br>    type Config = HammsterConfig;<br>    type Loaded = ();<br><br>    fn config(&amp;self) -&gt; &amp;Self::Config {<br>        &amp;self.config<br>    }<br><br>    fn loaded(&amp;self) -&gt; &amp;Self::Loaded {<br>        &amp;()<br>    }<br>}<br><br>// The configuration of the circuit<br>#[derive(Debug, Clone)]<br>pub struct HammsterConfig {<br>    advice: [Column&lt;Advice&gt;; 3],<br>    instance: Column&lt;Instance&gt;,<br>    s_binary_l: Selector,<br>    s_binary_r: Selector,<br>    s_xor: Selector,<br>    s_accumulator: Selector,<br>}</pre><h3>Configuring the Chip</h3><p>A <a href="https://zcash.github.io/halo2/concepts/chips.html">chip</a> in Halo 2 is a way to organize some logic into a reusable component. For example, some chips may implement some sort of hashing function or scalar multiplication.</p><p>We now need to build out the Chip configuration. This is where we will create various types of gates that will be turned on with our selectors that we similarly define. For each of the gates that we create, the output vec! contains the polynomial expressions that constrain that gate.</p><p>The gates defined in PLONKish circuits also refer to cells via relative offsets via the Rotation input, with Rotation::cur() being the current cell, and Rotation::prev() and Rotation::next() pointing to the cell that is in the current column in the previous and next rows, respectively.</p><p>For each of the gates in our example, we only need one constraint. Inside the vec!, if the selector is nonzero, then whatever it multiplies must equal zero. For example, in the case of vec![s_accumulator * (inputs_sum — sum)], if s_accumulator is enabled (set to 1), then there is a constraint such that inputs_sum — sum = 0.</p><pre>// file: circuits/src/hammster.rs<br><br>impl&lt;F: Field&gt; HammsterChip&lt;F&gt; {<br>    fn construct(config: &lt;Self as Chip&lt;F&gt;&gt;::Config) -&gt; Self {<br>        Self { <br>            config, <br>            _marker: PhantomData, <br>        }<br>    }<br><br>    fn configure(<br>        meta: &amp;mut ConstraintSystem&lt;F&gt;,<br>        advice: [Column&lt;Advice&gt;; 3],<br>        instance: Column&lt;Instance&gt;,<br>    ) -&gt; &lt;Self as Chip&lt;F&gt;&gt;::Config {<br>        // Enable checking of equality for each of the columns<br>        meta.enable_equality(instance);<br>        for column in &amp;advice {<br>            meta.enable_equality(*column);<br>        }<br><br>        // The selectors we&#39;ll be using in the circuit<br>        let s_binary_l = meta.selector();<br>        let s_binary_r = meta.selector();<br>        let s_xor = meta.selector();<br>        let s_accumulator = meta.selector();<br><br>        // Gate that checks that the value in the first column&#39;s cell is 0 or 1<br>        meta.create_gate(&quot;is binary left&quot;, |meta| {<br>            let value = meta.query_advice(advice[0], Rotation::cur());<br>            let s_binary_l = meta.query_selector(s_binary_l);<br><br>            vec![s_binary_l * (value.clone() * (Expression::Constant(F::ONE) - value))]<br>        });<br><br>        // Gate that checks that the value in the second column&#39;s cell is 0 or 1<br>        meta.create_gate(&quot;is binary right&quot;, |meta| {<br>            let value = meta.query_advice(advice[1], Rotation::cur());<br>            let s_binary_r = meta.query_selector(s_binary_r);<br><br>            vec![s_binary_r * (value.clone() * (Expression::Constant(F::ONE) - value))]<br>        });<br><br>        // This gate performs and XOR operation between two cells and outputs the the result to a third cell<br>        meta.create_gate(&quot;xor&quot;, |meta| {<br>            let lhs = meta.query_advice(advice[0], Rotation::cur());<br>            let rhs = meta.query_advice(advice[1], Rotation::cur());<br>            let out = meta.query_advice(advice[2], Rotation::cur());<br>            let s_xor = meta.query_selector(s_xor);<br><br>            // The XOR constraint is defined as (a + b - 2ab - out) == 0<br>            vec![s_xor * (lhs.clone() + rhs.clone() - Expression::Constant(F::ONE.double()) * lhs * rhs - out)]<br>        });<br><br>        // This gate accumulates all of the values from the column of results of the XOR gate above it<br>        meta.create_gate(&quot;accumulator&quot;, |meta| {<br>            let inputs_sum = (0..BINARY_LENGTH)<br>                .map(|i| meta.query_advice(advice[2], Rotation((i as i32) - (BINARY_LENGTH as i32))))<br>                .fold(Expression::Constant(F::ZERO), |acc, e| acc + e);<br>            let sum = meta.query_advice(advice[2], Rotation::cur());<br>            let s_accumulator = meta.query_selector(s_accumulator);<br><br>            vec![s_accumulator * (inputs_sum - sum)]<br>        });<br><br>        HammsterConfig {<br>            advice,<br>            instance,<br>            s_binary_l,<br>            s_binary_r,<br>            s_xor,<br>            s_accumulator,<br>        }<br>    }<br>}</pre><h3>Describing the Layout</h3><p>We implement the chip traits for our HammsterChip in this section. Utilizing a tool in Halo 2 called the Layouter, we write the logic to determine how each gate will function and assign the cells based on that logic.</p><pre>// file: circuits/src/hammster.rs<br><br>// This struct represents a number in the circuit, which wraps a cell<br>#[derive(Clone, Debug)]<br>struct Number&lt;F: Field&gt;(AssignedCell&lt;F, F&gt;);<br><br>// Implement all of the chip traits. In this section, we&#39;ll be describing how Layouter will assign values to <br>// various cells in the circuit.<br>impl&lt;F: Field&gt; Instructions&lt;F&gt; for HammsterChip&lt;F&gt; {<br>    type Num = Number&lt;F&gt;;<br><br>    // Loads private inputs into two advice columns and checks if the digits are binary values<br>    fn load_private_and_check_binary(<br>        &amp;self, <br>        mut layouter: impl Layouter&lt;F&gt;, <br>        column: usize, <br>        values: [Value&lt;F&gt;; BINARY_LENGTH]<br>    ) -&gt; Result&lt;Vec&lt;Self::Num&gt;, Error&gt; {<br>        let config = self.config();<br><br>        layouter.assign_region(<br>            || &quot;assign private values&quot;, <br>            |mut region| {<br>                values<br>                    .iter()<br>                    .enumerate()<br>                    .map(|(i, value)| {<br>                        // Check that each cell of the input is a binary value<br>                        if column == 0 {<br>                            config.s_binary_l.enable(&amp;mut region, i)?;<br>                        } else {<br>                            config.s_binary_r.enable(&amp;mut region, i)?;<br>                        }<br>                        // Assign the private input value to an advice cell<br>                        region<br>                            .assign_advice(|| &quot;assign private input&quot;, config.advice[column], i, || *value)<br>                            .map(Number)<br>                        }<br>                    )<br>                    .collect()<br>            }<br>        )<br>    }<br><br>    // Performs and XOR operation between two field elements<br>    fn xor(<br>        &amp;self, <br>        mut layouter: impl Layouter&lt;F&gt;, <br>        a: Self::Num, <br>        b: Self::Num<br>    ) -&gt; Result&lt;Self::Num, Error&gt; {<br>        let config = self.config();<br><br>        layouter.assign_region(<br>            || &quot;assign xor region&quot;, <br>            |mut region: Region&lt;&#39;_, F&gt;| {<br>                config.s_xor.enable(&amp;mut region, 0)?;<br><br>                // Copy the left and right advice cell values <br>                let a_val = a.0.copy_advice(|| &quot;lhs&quot;, &amp;mut region, config.advice[0], 0)?;<br>                let b_val = b.0.copy_advice(|| &quot;rhs&quot;, &amp;mut region, config.advice[1], 0)?;<br><br>                // Calculate the XOR result<br>                let xor_result = a_val.value()<br>                    .zip(b_val.value())<br>                    .map(|(a, b)| if *a == *b { F::ZERO } else { F::ONE });<br><br>                // Assign the result to the third advice cell<br>                region<br>                    .assign_advice(|| &quot;a xor b&quot;, config.advice[2], 0, || xor_result)<br>                    .map(Number)<br>            },<br>        )<br>    }<br><br>    // Accumulates the column of XOR results into a single number<br>    fn accumulator(<br>        &amp;self, <br>        mut layouter: impl Layouter&lt;F&gt;, <br>        values: [Self::Num; BINARY_LENGTH]<br>    ) -&gt; Result&lt;Self::Num, Error&gt; {<br>        let config = self.config();<br><br>        layouter.assign_region(<br>            || &quot;assign accumulator region&quot;, <br>            |mut region: Region&lt;&#39;_, F&gt;| {<br>                config.s_accumulator.enable(&amp;mut region, BINARY_LENGTH)?;<br><br>                // Copy the result of the XOR values to the advice cells in the third column<br>                for (i, value) in values.iter().enumerate() {<br>                    (*value).0.copy_advice(|| format!(&quot;output[{}]&quot;, i), &amp;mut region, config.advice[2], i)?;<br>                }<br><br>                // Calculate the accumulation of the XOR column results<br>                let accumulation = values<br>                    .iter()<br>                    .map(|n| n.0.value().copied())<br>                    .fold(Value::known(F::ZERO), |acc, e| acc + e);<br><br>                // Assign the accumulation result to an advice cell<br>                region<br>                    .assign_advice(|| &quot;accumulation result&quot;, config.advice[2], BINARY_LENGTH, || accumulation)<br>                    .map(Number)<br>            }<br>        )<br>    }<br><br>    // Expose output of accumulated XORs as a public value. Constrain the accumulation value from <br>    // (column advice[2], row BINARY_LENGTH) to equal instance column value in row 0 which is the <br>    // public input of the Hamming distance calculated outside the circuit <br>    fn expose_public(<br>        &amp;self, <br>        mut layouter: impl Layouter&lt;F&gt;, <br>        num: Self::Num<br>    ) -&gt; Result&lt;(), Error&gt; {<br>        let config = self.config();<br>        layouter.constrain_instance(num.0.cell(), config.instance, 0)<br>    }<br>}</pre><h3>Write the Circuit</h3><p>Now, we can write the circuit using what we’ve built in the previous sections! We first define the circuit as a struct that takes in two field element slices of length BINARY_LENGTH (8 in this case).</p><pre>// file: circuits/src/hammster.rs<br><br>#[derive(Default)]<br>pub struct HammsterCircuit&lt;F: Field&gt; {<br>    a: [Value&lt;F&gt;; BINARY_LENGTH],<br>    b: [Value&lt;F&gt;; BINARY_LENGTH],<br>}</pre><p>We then need to write out the functions in the Circuit implementation for our HammsterCircuit. The main functions that are written here are the configure and synthesize functions, which perform as named.</p><pre>// file: circuits/src/hammster.rs<br><br>impl&lt;F: Field&gt; Circuit&lt;F&gt; for HammsterCircuit&lt;F&gt; {<br>    type Config = HammsterConfig;<br>    type FloorPlanner = SimpleFloorPlanner;<br><br>    fn without_witnesses(&amp;self) -&gt; Self {<br>        // Just outputs the default circuit if calling without witnesses<br>        Self::default()<br>    }<br><br>    fn configure(meta: &amp;mut ConstraintSystem&lt;F&gt;) -&gt; Self::Config {<br>        // Our configuration will include 3 advice columns (two for inputs, one for the output of the XOR operation)<br>        let advice = [meta.advice_column(), meta.advice_column(), meta.advice_column()];<br><br>        // We&#39;ll also have one instance column for the public input (calculated Hamming distance)<br>        let instance = meta.instance_column();<br><br>        HammsterChip::configure(meta, advice, instance)<br>    }<br><br>    fn synthesize(&amp;self, config: Self::Config, mut layouter: impl Layouter&lt;F&gt;) -&gt; Result&lt;(), Error&gt; {<br>        let hammster_chip = HammsterChip::&lt;F&gt;::construct(config);<br><br>        // Load private variable vectors &amp; check if each digit is binary<br>        let a = hammster_chip.load_private_and_check_binary(layouter.namespace(|| &quot;load a&quot;), 0, self.a)?;<br>        let b = hammster_chip.load_private_and_check_binary(layouter.namespace(|| &quot;load b&quot;), 1, self.b)?;<br><br>        // Perform XOR on each row<br>        let xor_results: Vec&lt;Number&lt;F&gt;&gt; = (0..BINARY_LENGTH)<br>            .map(|i| {<br>                hammster_chip.xor(layouter.namespace(|| format!(&quot;xor[{}]&quot;, i)), a[i].clone(), b[i].clone()).unwrap()<br>            })<br>            .collect();<br>        let xor_slice: [Number&lt;F&gt;; 8] = xor_results.clone().try_into().unwrap();<br><br>        // Accumulate the results of the XOR output column<br>        let accumulate = hammster_chip.accumulator(layouter.namespace(|| &quot;accumulate xor results&quot;), xor_slice)?;<br><br>        // Ensure the accumulated value equals the public input (of the precalculated accumulation value)<br>        hammster_chip.expose_public(layouter.namespace(|| &quot;expose accumulate&quot;), accumulate)<br>    }<br>}</pre><h3>Writing some helper functions</h3><p>It’s pretty useful to have some helper functions that we can call externally to keep the code neater. Let’s write some of those here.</p><pre>// file: circuits/src/hammster.rs<br><br>// Draws the layout of the circuit. Super useful for debugging.<br>#[cfg(not(target_family = &quot;wasm&quot;))]<br>pub fn draw_circuit&lt;F: Field&gt;(k: u32, circuit: &amp;HammsterCircuit&lt;F&gt;) {<br>    use plotters::prelude::*;<br>    let base = BitMapBackend::new(&quot;layout.png&quot;, (1600,1600)).into_drawing_area();<br>    base.fill(&amp;WHITE).unwrap();<br>    let base = base.titled(&quot;Hammster Circuit&quot;, (&quot;sans-serif&quot;, 24)).unwrap();<br><br>    halo2_proofs::dev::CircuitLayout::default()<br>        .show_equality_constraints(true)<br>        .render(k, circuit, &amp;base)<br>        .unwrap();<br>}</pre><p>The follow two functions generate circuits. One outputs an empty circuit, the other outputs a circuit from two input vectors.</p><pre>// file: circuits/src/hammster.rs<br><br>// Generates an empty circuit. Useful for generating the proving/verifying keys.<br>pub fn empty_circuit() -&gt; HammsterCircuit&lt;Fp&gt; {<br>    HammsterCircuit {<br>        a: [Value::unknown(); BINARY_LENGTH],<br>        b: [Value::unknown(); BINARY_LENGTH],<br>    }<br>}<br><br>// Creates a circuit from two vector inputs<br>pub fn create_circuit(a: Vec&lt;u64&gt;, b: Vec&lt;u64&gt;) -&gt; HammsterCircuit&lt;Fp&gt; {<br>    // Put inputs into circuit-friendly form<br>    let a_vec: [Value&lt;Fp&gt;; BINARY_LENGTH] = a<br>        .clone()<br>        .iter()<br>        .map(|f| Value::known(Fp::from(*f)))<br>        .collect::&lt;Vec&lt;Value&lt;Fp&gt;&gt;&gt;()<br>        .try_into()<br>        .unwrap();<br><br>    let b_vec: [Value&lt;Fp&gt;; BINARY_LENGTH] = b<br>        .clone()<br>        .iter()<br>        .map(|f| Value::known(Fp::from(*f)))<br>        .collect::&lt;Vec&lt;Value&lt;Fp&gt;&gt;&gt;()<br>        .try_into()<br>        .unwrap();<br><br>    // Create circuit from inputs<br>    HammsterCircuit {<br>        a: a_vec,<br>        b: b_vec,<br>    }<br>}</pre><p>It’s also useful to have a few functions that generate setup params and proving/verifying keys. For generating the proving and verifying keys, you can just pass in an empty circuit (thanks to Jonathan Wang from Axiom for help with this!):</p><pre>// file: circuits/src/hammster.rs<br><br>// Generates setup parameters using k, which is the number of rows of the circuit<br>// can fit in and must be a power of two<br>pub fn generate_setup_params(<br>    k: u32,<br>) -&gt; Params&lt;EqAffine&gt; {<br>    Params::&lt;EqAffine&gt;::new(k)<br>}<br><br>// Generates the verifying and proving keys. We can pass in an empty circuit to generate these<br>pub fn generate_keys(<br>    params: &amp;Params&lt;EqAffine&gt;,<br>    circuit: &amp;HammsterCircuit&lt;Fp&gt;,<br>) -&gt; (ProvingKey&lt;EqAffine&gt;, VerifyingKey&lt;EqAffine&gt;) {<br>    // just to emphasize that for vk, pk we don&#39;t need to know the value of `x`<br>    let vk = keygen_vk(params, circuit).expect(&quot;vk should not fail&quot;);<br>    let pk = keygen_pk(params, vk.clone(), circuit).expect(&quot;pk should not fail&quot;);<br>    (pk, vk)<br>}</pre><p>This function simply takes our two input vectors and calculates the Hamming distance, outputting a vector containing a single field element, which is a nicer format for using in our proving and verifying functions later.</p><pre>// file: circuits/src/hammster.rs<br><br>// Calculates the hamming distance between two vectors<br>pub fn calculate_hamming_distance(a: Vec&lt;u64&gt;, b: Vec&lt;u64&gt;) -&gt; Vec&lt;Fp&gt; {<br>    let hamming_dist = a<br>        .clone()<br>        .iter()<br>        .enumerate()<br>        .map(|(i, x)| (x + b[i]) % 2)<br>        .fold(0, |acc, x| acc + x);<br>    vec![Fp::from(hamming_dist)]<br>}</pre><p>The mock prover is a very useful tool that can help you identify issues in the circuit. Our run_mock_prover function will pretty-print any errors found in the circuit.</p><pre>// file: circuits/src/hammster.rs<br><br>// Runs the mock prover and prints any errors<br>pub fn run_mock_prover(<br>    k: u32,<br>    circuit: &amp;HammsterCircuit&lt;Fp&gt;,<br>    pub_input: &amp;Vec&lt;Fp&gt;,<br>) {<br>    let prover = MockProver::run(k, circuit, vec![pub_input.clone()]).expect(&quot;Mock prover should run&quot;);<br>    let res = prover.verify();<br>    match res {<br>        Ok(()) =&gt; println!(&quot;MockProver OK&quot;),<br>        Err(e) =&gt; println!(&quot;err {:#?}&quot;, e),<br>    }<br>}</pre><p>In our generate_proof function, the create_proof function takes in a mutable transcript and writes the proof to the transcript, which we then finalize and output as the proof.</p><pre>// file: circuits/src/hammster.rs<br><br>// Generates a proof <br>pub fn generate_proof(<br>    params: &amp;Params&lt;EqAffine&gt;,<br>    pk: &amp;ProvingKey&lt;EqAffine&gt;,<br>    circuit: HammsterCircuit&lt;Fp&gt;,<br>    pub_input: &amp;Vec&lt;Fp&gt;,<br>) -&gt; Vec&lt;u8&gt; {<br>    println!(&quot;Generating proof...&quot;);<br>    let mut transcript = Blake2bWrite::&lt;_, _, Challenge255&lt;_&gt;&gt;::init(vec![]);<br>    create_proof(<br>        params, <br>        pk, <br>        &amp;[circuit],<br>        &amp;[&amp;[pub_input]], <br>        OsRng, <br>        &amp;mut transcript<br>    ).expect(&quot;Prover should not fail&quot;);<br>    transcript.finalize()<br>}</pre><p>In our verify function, the output will just be the result of verify_proof.</p><pre>// file: circuits/src/hammster.rs<br><br>// Verifies the proof <br>pub fn verify(<br>    params: &amp;Params&lt;EqAffine&gt;,<br>    vk: &amp;VerifyingKey&lt;EqAffine&gt;,<br>    pub_input: &amp;Vec&lt;Fp&gt;,<br>    proof: Vec&lt;u8&gt;,<br>) -&gt; Result&lt;(), Error&gt; {<br>    println!(&quot;Verifying proof...&quot;);<br>    let strategy = SingleVerifier::new(&amp;params);<br>    let mut transcript = Blake2bRead::&lt;_, _, Challenge255&lt;_&gt;&gt;::init(&amp;proof[..]);<br>    verify_proof(<br>        params, <br>        vk, <br>        strategy, <br>        &amp;[&amp;[pub_input]], <br>        &amp;mut transcript,<br>    )<br>}</pre><h3>Putting it all together</h3><p>Alright, now we have a ton of useful functions that we can use to generate a proof and verify a proof of our Hamming distance app. We’ll go ahead and create one more file named circuits/src/lib.rs and add the following to it:</p><pre>// file: circuits/src/lib.rs<br><br>pub mod hammster;</pre><p>Then, we’ll go to circuits/src/main.rs and delete all of the boilerplate code and replace it with the code below. We add a cfg attribute to ensure that this doesn’t compile when we’re building our Wasm module, which we will do in part 2. We then call our helper functions to take us through the steps of doing the setup, generating the proof, and verifying it.</p><pre>// file: circuits/src/main.rs<br><br>#[cfg(not(target_family = &quot;wasm&quot;))]<br>fn main() {<br>    use hammster::hammster::{calculate_hamming_distance, create_circuit, empty_circuit, draw_circuit, generate_setup_params, generate_keys, generate_proof, verify, run_mock_prover};<br><br>    // Size of the circuit. Circuit must fit within 2^k rows.<br>    let k = 6;<br><br>    // Input values to generate a proof with<br>    let a_vec = vec![1, 1, 0, 1, 0, 1, 0, 0];<br>    let b_vec: Vec&lt;u64&gt; = vec![0, 1, 0, 0, 0, 1, 1, 0];<br>    let hamming_dist = calculate_hamming_distance(a_vec.clone(), b_vec.clone());<br><br>    // Create circuit<br>    let hammster_circuit = create_circuit(a_vec, b_vec);<br>    <br>    // Items that are useful for debugging issues<br>    draw_circuit(k, &amp;hammster_circuit);<br>    run_mock_prover(k, &amp;hammster_circuit, &amp;hamming_dist);<br><br>    // Generate setup params<br>    let params = generate_setup_params(k);<br><br>    // Generate proving and verifying keys<br>    let empty_circuit = empty_circuit();<br>    let (pk, vk) = generate_keys(&amp;params, &amp;empty_circuit);<br><br>    // Generate proof<br>    let proof = generate_proof(&amp;params, &amp;pk, hammster_circuit, &amp;hamming_dist);<br>    <br>    // Verify proof<br>    let verify = verify(&amp;params, &amp;vk, &amp;hamming_dist, proof);<br>    println!(&quot;Verify result: {:?}&quot;, verify);<br>}</pre><h3>Running the program</h3><p>From the circuits folder, we can run the program using the following command:</p><blockquote><em>cargo run</em></blockquote><p><strong><em>Note</em></strong><em>: if you’re following along using the Github repository and are not using an Apple M architecture machine, you will need to modify </em>target = &quot;aarch64-apple-darwin&quot; <em>in </em>circuits/.cargo/config<em> to whatever matches your machine.</em></p><p>We should see the following output in the terminal:</p><pre>   Compiling halo2_hammster v0.1.0 (/Users/yujiangtham/zk/hammster/circuits)<br>    Finished dev [unoptimized + debuginfo] target(s) in 3.32s<br>     Running `target/aarch64-apple-darwin/debug/halo2_hammster`<br>MockProver OK<br>Generating proof...<br>Verifying proof...<br>Verify result: Ok(())</pre><p>Additionally, our draw_circuit function also outputs a nice diagram of the circuit layout:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8WmN6Tb_egJjRQ1oEOhZow.png" /><figcaption>Circuit layout showing instance (white), advice (red), and fixed (purple) columns.</figcaption></figure><p>This circuit layout is also super useful for debugging. The layout shows instance column in white, advice columns in red, and fixed (selector) columns in purple. The red lines between different cells also show equality constraints, which was an option that we enabled.</p><h3>Conclusion</h3><p>Well, that’s it for today! We were able to build a Zero Knowledge circuit that generates a proof and verifies it using the Halo 2 proof system. If you enjoyed this content, don’t forget to add a clap and follow me on here and <a href="https://twitter.com/DarkForestHam">Twitter</a>. In part 2, we then compile our circuit to Wasm and build out a Next.js app around it!</p><p><a href="https://medium.com/@yujiangtham/building-a-zero-knowledge-web-app-with-halo-2-and-wasm-part-2-379477444dc3">Continue to part 2</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=80858c8d16ee" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Writing a Zero Knowledge dApp]]></title>
            <link>https://medium.com/@yujiangtham/writing-a-zero-knowledge-dapp-fd7f936e2d43?source=rss-999ab4bada2c------2</link>
            <guid isPermaLink="false">https://medium.com/p/fd7f936e2d43</guid>
            <category><![CDATA[cryptocurrency]]></category>
            <category><![CDATA[zero-knowledge-proofs]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[zksnark]]></category>
            <category><![CDATA[zero-knowledge]]></category>
            <dc:creator><![CDATA[Yu Jiang Tham]]></dc:creator>
            <pubDate>Thu, 16 Mar 2023 16:30:28 GMT</pubDate>
            <atom:updated>2023-03-29T02:38:33.483Z</atom:updated>
            <content:encoded><![CDATA[<p><em>We shed some light on integrating zero knowledge circuits into your smart contracts and subsequently into a dApp.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H8XmcYG8UdKPRi0z28PrRg.png" /><figcaption>Welcome to the world of Zero Knowledge</figcaption></figure><h3>Introduction</h3><p>The world of Zero Knowledge (ZK) cryptography has been all the rage in the past few months. As new zkRollups and zkEVMs are announced, the crypto world has turned its attention the ability of zero knowledge proofs to provide elegant solutions to the problems of privacy and scalability (see my <a href="https://medium.com/@yujiangtham/what-are-zero-knowledge-proofs-and-why-do-they-matter-b580e8de71e0">previous post</a> for details) on blockchains.</p><p>This two-part series of posts assumes knowledge of Solidity and Typescript (react/next.js) and is here to help fill in the gaps of how to write a ZK circuit (in <a href="https://iden3.io/circom">Circom</a>) as well as how to integrate that into a next.js app. <a href="https://medium.com/@yujiangtham/lets-dissect-a-zksnark-part-1-a82fc092f58a">Basic knowledge of finite fields</a> is also useful.</p><p>The main goal of this post is not to explain how to write in circuits in Circom, but to outline the series of steps from getting code written in Circom to something that someone can use in their dApp.</p><h3>What we’ll be building</h3><p>We’ll be building a simple dApp that checks if a two numbers that you submit are between 0 and 5, and that they are not equal to each other. You’ll generate a ZK proof in the browser and submit only the proof in the transaction, so no one on the internet or even the contract itself will know the two numbers that were submitted, only that they matched the constraints above.</p><p>Before we start building, let’s review a few things so that we are standing on a solid foundation…</p><h3>What is a ZK circuit?</h3><p>A ZK circuit is a program that, given some set of inputs, outputs a proof, which can be easily verified, that every step of computation that was run inside the circuit were done correctly.</p><h3>How do you write a ZK circuit?</h3><p>There are a number of ways to create a ZK circuit, with some higher-level domain-specific languages such as <a href="https://aztec.network/noir/">Noir</a> and <a href="https://iden3.io/circom">Circom</a> that allow you to write a program that will be compiled down to a circuit. Alternatively, there are also low-level packages like <a href="https://halo2.dev/en-US">Halo2</a> in which you will specify exactly where values will fall in your table that represents your circuit.</p><p>Today, we’ll be using Circom with SnarkJS because they are both relatively widely-used and currently work with generating proofs in the browser.</p><h3>Stuff that’s good to know</h3><p>Writing in Circom and most other domain-specific languages means that you will need to get familiar with dealing with field elements and writing constraints.</p><h4>Field elements</h4><p>In Circom, there is only one data type, the field element. For the purposes of this tutorial, you can think of field elements as basically any number modulo a large prime number, which is based on the elliptic curve that is used. The default curve in Circom is BN128.</p><h4>Constraints</h4><p>Circuits can accept arbitrary inputs from the entity that is generating the proof, so these inputs must be constrained within the circuit so that the inputs, outputs, and intermediate values fall within some acceptable set of values or hold some relationship to another variable. Two example of constraints could be ensuring that one input is the square of another input, or that the input is not equal to the output. We’ll discuss how to write these in the code example.</p><h4>General flow</h4><p>The general flow of the process that we’ll be covering can be visualized in this diagram:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/1*PtnM_QNNug9RwF1yrs7Lsw.png" /><figcaption>Overall flow for creating a zero knowledge dApp. Highlighted boxes are developer or user inputs.</figcaption></figure><h3>Let’s dive in</h3><p>I’m sure you’ve had enough of the intro and background, so let’s dive right in. I’ll break this down into three sections, based on the general flow diagram above in order to make it easier to follow. The Circuit section discusses everything about writing the ZK circuit in Circom, which we then export to the Contract section, which interacts with the Frontend section.</p><p>The proving system we’ll use is Plonk, which allows us to have a universal trusted setup instead of having to generate additional randomness for each circuit. It’s slower than the Groth16 proving system, but is good enough for what we want right now.</p><p>Here’s a link to the repo:</p><blockquote><a href="https://github.com/ytham/zk_example_dapp"><em>https://github.com/ytham/zk_example_dapp</em></a></blockquote><h3>Setup</h3><p>We’ll require the following to be installed before continuing:</p><ul><li><a href="https://nodejs.org/en/download/">Node.js</a></li><li><a href="https://classic.yarnpkg.com/lang/en/docs/install/">Yarn</a></li><li><a href="https://github.com/foundry-rs/foundry">Foundry</a></li><li><a href="https://docs.circom.io/getting-started/installation/">Circom</a></li><li><a href="https://www.npmjs.com/package/snarkjs">SnarkJS</a></li><li><a href="https://metamask.io/">Metamask</a></li></ul><p>Let’s first create the project folder. We’ll create a next.js app using the command with the following settings:</p><blockquote>yarn create next-app</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TsSia5mjv5NLWAf6Fy3dwg.png" /><figcaption>Settings for our new next.js repo</figcaption></figure><p>Once that’s all done, cd into the folder and then run the command to add the following packages:</p><blockquote>yarn add circomlib snarkjs wagmi ethers@^5 axios @mantine/core @mantine/hooks @mantine/notifications @emotion/react</blockquote><h3>Circuit</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/1*7ahnJQoKTTk62l7QaQqm4g.png" /><figcaption>Circuit section highlighted</figcaption></figure><h4>Setup</h4><p>Ensure that you’re in the project folder and create a folder called circuits, and then a folder inside circuits named build. We’ll be working inside the circuits folder in this section.</p><h4>Write circuit</h4><p>As explained above, the circuit that we’ll be writing today that takes two inputs, ensures that they’re both between 0 and 5, and also ensures that they’re both not equal to each other. It will then multiply and output the two values. I’ve added inline comments to the circom file below:</p><p><strong><em>Note:</em></strong><em> the line that says </em><em>// file: &lt;filename&gt;at the top is not actually part of the file, it’s only telling you where the file is located with respect to the project root.</em></p><pre>// file: /circuits/simple_multiplier.circom<br><br>pragma circom 2.1.3;<br><br>include &quot;../node_modules/circomlib/circuits/comparators.circom&quot;;<br><br>template SimpleMultiplier() {<br>    // Private input signals<br>    signal input in[2];<br><br>    // Output signal (public)<br>    signal output out;<br><br>    // Create a constraint here saying that our two input signals cannot<br>    // equal each other.<br>    component isz = IsZero();<br>    isz.in &lt;== in[0] - in[1];<br><br>    // The IsZero component returns 1 if the input is 0, or 0 otherwise.<br>    isz.out === 0;<br><br>    // Define the greater than and less than components that we&#39;ll define <br>    // inside the for loop below.<br>    component gte[2];<br>    component lte[2];<br>    <br>    // We loop through the two signals to compare them.<br>    for (var i = 0; i &lt; 2; i++) {<br>        // Both the LessEqThan and GreaterEqThan components take number of <br>        // bits as an input. In this case, we want to ensure our inputs are <br>        // [0,5], which requires 3 bits (101).<br>        lte[i] = LessEqThan(3);<br><br>        // We put our circuit&#39;s input signal as the input signal to the <br>        // LessEqThan component and compare it against 5.<br>        lte[i].in[0] &lt;== in[i];<br>        lte[i].in[1] &lt;== 5;<br><br>        // The LessEqThan component outputs a 1 if the evaluation is true, <br>        // 0 otherwise, so we create this equality constraint.<br>        lte[i].out === 1;<br><br>        // We do the same with GreaterEqThan, and also require 3 bits since<br>        // the range of inputs is still [0,5].<br>        gte[i] = GreaterEqThan(3);<br><br>        // Compare our input with 0 <br>        gte[i].in[0] &lt;== in[i];<br>        gte[i].in[1] &lt;== 0;<br><br>        // The GreaterEqThan component outputs a 1 if the evaluation is true, <br>        // 0 otherwise, so we create this equality constraint.<br>        gte[i].out === 1;<br>    }<br><br>    // Write a * b into c and then constrain c to be equal to a * b.<br>    out &lt;== in[0] * in[1];<br>}<br><br>component main = SimpleMultiplier();</pre><h4>Compile to intermediate representation</h4><p>Once the circuit has been completed, we’ll compile it down to an intermediate representation called R1CS (Rank-1 Constraint System). Additional info on R1CS can be found in a <a href="https://medium.com/@yujiangtham/lets-dissect-a-zksnark-part-2-5f92f1d7d2e9">previous post</a>. Run the following command in the circuits folder:</p><blockquote>circom simple_multiplier.circom --r1cs --wasm --sym -o build</blockquote><p>Which will output the R1CS, WASM, and symbols into the circuits/build folder and display the circuit data, including number of constraints.</p><h4>Powers of Tau trusted setup file</h4><p>There are a number of Powers of Tau trusted setups that have been generated that we can use, based on the size of our circuit (number of constraints). To reduce proving times, you’ll want to use the Powers of Tau that is closest to the size of your circuit. You can find the trusted setup files in this repository:</p><blockquote><a href="https://github.com/iden3/snarkjs#7-prepare-phase-2"><em>https://github.com/iden3/snarkjs#7-prepare-phase-2</em></a></blockquote><p>Let’s go ahead and use the smallest one (<a href="https://hermez.s3-eu-west-1.amazonaws.com/powersOfTau28_hez_final_08.ptau">powersOfTau28_hez_final_08.ptau</a>), which supports up to 256 constraints, since our circuit has ~14 constraints.</p><h4>Generate proving key</h4><p>Now, from the circuits directory, we’ll run the command to generate the proving key that we will use to generate the proof using the R1CS and ptau files:</p><blockquote>snarkjs plonk setup build/simple_multiplier.r1cs ptau/powersOfTau28_hez_final_08.ptau build/proving_key.zkey</blockquote><h3>Contract</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/1*lqw-qJl8izeSK1kYQ6EKbQ.png" /><figcaption>Contract section highlighted</figcaption></figure><h4>Setup</h4><p>Create a new directory in the project root directory called contracts. cd contracts and then use the following Foundry command to create a new project inside the contracts folder:</p><blockquote>forge init --no-commit</blockquote><p>Delete the generated starter files inside the script, src, and test folders.</p><p>Add a .env file inside the contracts folder as well, in which you’ll add your private key for the wallet you want to deploy from (ensure that this wallet has some GoerliETH, which you can get from the <a href="https://goerli-faucet.pk910.de/">Goerli PoW faucet</a>). You’ll also need to have an account with Alchemy (or whichever other RPC provider of choice) and input your RPC url from the Alchemy dashboard:</p><pre>// file: /contracts/.env<br><br>GOERLI_RPC_URL=https://eth-goerli.g.alchemy.com/v2/&lt;YOUR_GOERLI_API_KEY&gt;<br>PRIVATE_KEY=&lt;YOUR_PRIVATE_KEY&gt;</pre><p>Also add the following to your foundry.toml file:</p><pre>// file: /contracts/foundry.toml<br><br>[profile.default]<br>src = &#39;src&#39;<br>out = &#39;out&#39;<br>libs = [&#39;lib&#39;]<br><br># Add this <br>[rpc_endpoints]<br>goerli = &quot;${GOERLI_RPC_URL}&quot;</pre><h4>Export smart contract verifier</h4><p>We can generate the verifier smart contract using the following SnarkJS command from the project root:</p><blockquote>snarkjs zkey export solidityverifier circuits/build/proving_key.zkey contracts/src/PlonkVerifier.sol</blockquote><h4>Write smart contract</h4><p>We’ll write the following contract that utilizes the PlonkVerifier.sol file that we exported above. The contract merely outputs a boolean true or false based on the result of the PlonkVerifier, but you can imagine writing something that mints an NFT, transfers tokens, deploys another contract, or anything else you can think of. For brevity, I’ve excluded tests.</p><pre>// file: /contracts/src/SimpleMultiplier.sol<br><br>// SPDX-License-Identifier: UNLICENSED<br>pragma solidity ^0.8.13;<br><br>// Interface to PlonkVerifier.sol<br>interface IPlonkVerifier {<br>    function verifyProof(bytes memory proof, uint[] memory pubSignals) external view returns (bool);<br>}<br><br>contract SimpleMultiplier {<br>    address public s_plonkVerifierAddress;<br><br>    event ProofResult(bool result);<br><br>    constructor(address plonkVerifierAddress) {<br>        s_plonkVerifierAddress = plonkVerifierAddress;<br>    }<br><br>    // ZK proof is generated in the browser and submitted as a transaction w/ the proof as bytes.<br>    function submitProof(bytes memory proof, uint256[] memory pubSignals) public returns (bool) {<br>        bool result = IPlonkVerifier(s_plonkVerifierAddress).verifyProof(proof, pubSignals);<br>        emit ProofResult(result);<br>        return result;<br>    }<br>}</pre><p>Build the contract by running the following command in the contracts folder:</p><blockquote>forge build</blockquote><p>Then, go back into the project root directory and then create a folder called abi in the src/lib folder and copy the json output into that folder:</p><blockquote>mkdir -p src/lib/abi</blockquote><blockquote>cp contracts/out/SimpleMultiplier.sol/SimpleMultiplier.json src/lib/abi/.</blockquote><h4>Deploy contracts</h4><p>We then deploy the contracts with the deploy script:</p><pre>// file: /contracts/scripts/SimpleMultiplier.s.sol<br><br>// SPDX-License-Identifier: UNLICENSED<br>pragma solidity ^0.8.13;<br><br>import &quot;forge-std/Script.sol&quot;;<br>import &quot;../src/PlonkVerifier.sol&quot;;<br>import &quot;../src/SimpleMultiplier.sol&quot;;<br><br>contract SimpleMultiplierScript is Script {<br>    function setUp() public {}<br><br>    function run() public {<br>        uint256 deployerPrivateKey = vm.envUint(&quot;PRIVATE_KEY&quot;);<br>        vm.startBroadcast(deployerPrivateKey);<br><br>        PlonkVerifier pv = new PlonkVerifier();<br>        SimpleMultiplier sm = new SimpleMultiplier(address(pv));<br><br>        vm.stopBroadcast();<br>    }<br>}</pre><p>And run the deploy script with the following command:</p><blockquote>forge script script/SimpleMultiplier.s.sol SimpleMultiplierScript --broadcast --verify --rpc-url goerli</blockquote><p>You’ll see two contracts deployed. The first one is the PlonkVerifier contract, and the second is the SimpleMultiplier contract. We only need the address of the SimpleMultiplier contract. Let’s save this address to be used later in the frontend:</p><pre>// file: /src/shared/addresses.ts<br><br>export const Addresses = {<br>  SIMPLE_MULTIPLIER_ADDR: &quot;&lt;YOUR_DEPLOYED_CONTRACT_ADDR&gt;&quot; as `0x${string}`,<br>}</pre><p>Great! Now we’ve deployed our verifier and contract and are ready to move onto building out the user interface in the browser!</p><h3>Frontend</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/1*WKQLqVi_TAA6nru5q9HL3A.png" /><figcaption>Frontend section highlighted</figcaption></figure><h4>Setup</h4><p>We’ll be deploying our dApp to <a href="https://vercel.com/">Vercel</a> via <a href="https://github.com/">Github</a>, so please ensure that you have an account at both places before proceeding.</p><h4>Creating the frontend</h4><p>We’ll build out the frontend interface by creating or modifying the following files. For the sake of brevity, I’ve globed a number of items in various pages instead of creating separate components for them. I’ve also not included every case for error handling. This is not a next.js/react tutorial, so I’ll assume the reader has cursory understanding already.</p><p>We utilize the Wagmi package to connect to the blockchain and wrap our entire app in the WagmiConfig:</p><pre>// file: /src/pages/_app.tsx<br><br>import &#39;@/styles/globals.css&#39;<br>import { WagmiConfig, createClient, configureChains, goerli } from &#39;wagmi&#39;<br>import { publicProvider } from &#39;wagmi/providers/public&#39;<br>import type { AppProps } from &#39;next/app&#39;<br>import { MantineProvider } from &#39;@mantine/core&#39;<br>import { Notifications } from &#39;@mantine/notifications&#39;;<br><br>// We&#39;ll just be using Goerli testnet for now<br>const { chains, provider, webSocketProvider } = configureChains(<br>  [goerli],<br>  [publicProvider()],<br>)<br> <br>const client = createClient({<br>  autoConnect: true,<br>  provider,<br>  webSocketProvider,<br>})<br><br>export default function App({ Component, pageProps }: AppProps) {<br>  // We&#39;ll be using Wagmi sending our transaction and Mantine for CSS <br>  // and notifications<br>  return (<br>    &lt;WagmiConfig client={client}&gt;<br>      &lt;MantineProvider withNormalizeCSS&gt;<br>        &lt;Notifications /&gt;<br>        &lt;Component {...pageProps} /&gt;<br>      &lt;/MantineProvider&gt;<br>    &lt;/WagmiConfig&gt;<br>  )<br>}</pre><p>Our index.tsx file contains a ConnectWalletButton and two input fields where a user can input their numbers [0,5]. When the user presses the Submit button for the two input fields, it sends a POST request to the backend with the inputs to generate the proof. Once the proof is generated, it takes that proof data and submits it as a transaction on the blockchain.</p><p>Ideally we’d like to separate this into a lot of different component files, but for the sake of simplicity, it’s all in one file:</p><pre>// file: /src/pages/index.tsx<br><br>import Head from &#39;next/head&#39;<br>import Link from &#39;next/link&#39;;<br>import { useState } from &#39;react&#39;;<br>import { Stack, Text, Title, Grid, Input, Button, Group, Space } from &#39;@mantine/core&#39;<br>import axios, { AxiosRequestConfig } from &#39;axios&#39;;<br>import { useAccount } from &#39;wagmi&#39;;<br>import { notifications } from &quot;@mantine/notifications&quot;;<br>import { ConnectWalletButton } from &#39;@/components/ConnectWalletButton&#39;;<br>import { executeTransaction } from &#39;@/lib/executeTransaction&#39;;<br><br>export default function Home() {<br>  const [input0, setInput0] = useState(&quot;&quot;);<br>  const [input1, setInput1] = useState(&quot;&quot;);<br>  const { isConnected } = useAccount();<br>  <br>  const handleGenerateProofSendTransaction = async (e: any) =&gt; {<br>    e.preventDefault();<br>    <br>    // We will send an HTTP request with our inputs to our next.js backend to <br>    // request a proof to be generated.<br>    const data = {<br>      input0,<br>      input1,<br>    }<br>    const config: AxiosRequestConfig = {<br>      headers: {<br>        &quot;Content-Type&quot;: &quot;application/json&quot;,<br>      }<br>    }<br><br>    // Send the HTTP request<br>    try {<br>      const res = await axios.post(&quot;/api/generate_proof&quot;, data, config);<br>      notifications.show({<br>        message: &quot;Proof generated successfully! Submitting transaction...&quot;,<br>        color: &quot;green&quot;,<br>      });<br><br>      // Split out the proof and public signals from the response data<br>      const { proof, publicSignals } = res.data;<br><br>      // Write the transaction<br>      const txResult = await executeTransaction(proof, publicSignals);<br>      const txHash = txResult.transactionHash;<br><br>      notifications.show({<br>        message: `Transaction succeeded! Tx Hash: ${txHash}`,<br>        color: &quot;green&quot;,<br>        autoClose: false,<br>      });<br>    } catch (err: any) {<br>      const statusCode = err?.response?.status;<br>      const errorMsg = err?.response?.data?.error;<br>      notifications.show({<br>        message: `Error ${statusCode}: ${errorMsg}`,<br>        color: &quot;red&quot;,<br>      });<br>    }<br>  }<br><br>  // Only allow submit if the user first connects their wallet<br>  const renderSubmitButton = () =&gt; {<br>    if (!isConnected) {<br>      return &lt;ConnectWalletButton /&gt;<br>    }<br>    return (<br>      &lt;Button type=&quot;submit&quot;&gt;Generate Proof &amp; Send Transaction&lt;/Button&gt;<br>    )<br>  }<br><br>  return (<br>    &lt;&gt;<br>      &lt;Head&gt;<br>        &lt;title&gt;ZK Simple Multiplier&lt;/title&gt;<br>        &lt;link rel=&quot;icon&quot; href=&quot;/favicon.ico&quot; /&gt;<br>      &lt;/Head&gt;<br>      &lt;Stack justify=&quot;center&quot; align=&quot;center&quot; w=&quot;100vw&quot; h=&quot;100vh&quot; spacing={0}&gt;<br>        &lt;Stack align=&quot;center&quot; spacing={0}&gt;<br>          &lt;Group w=&quot;96vw&quot; h=&quot;10vh&quot; position=&quot;apart&quot; align=&quot;center&quot;&gt;<br>            &lt;Title order={3}&gt;<br>              ZK Simple Multiplier<br>            &lt;/Title&gt;<br>            &lt;ConnectWalletButton /&gt;<br>          &lt;/Group&gt;<br>          &lt;Grid align=&quot;center&quot; justify=&quot;center&quot; mih=&quot;80vh&quot;&gt;<br>            &lt;Grid.Col sm={8} md={6} lg={4}&gt;<br>              &lt;Text&gt;<br>                {&quot;Input two numbers between 0 and 5, inclusive. The two numbers must \<br>                not be equal. We&#39;ll generate a ZK proof locally in the browser, and \<br>                only the proof will be sent to the blockchain so that no one \<br>                watching the blockchain will know the two numbers.&quot;}<br>              &lt;/Text&gt;<br>              &lt;Space h={20} /&gt;<br>              &lt;form onSubmit={handleGenerateProofSendTransaction}&gt;<br>                &lt;Stack spacing=&quot;sm&quot;&gt;<br>                  &lt;Input.Wrapper label=&quot;Input 0&quot;&gt;<br>                    &lt;Input <br>                      placeholder=&quot;Number between 0 and 5&quot; <br>                      value={input0} <br>                      onChange={(e) =&gt; setInput0(e.currentTarget.value)}<br>                    /&gt;<br>                  &lt;/Input.Wrapper&gt;<br>                  &lt;Input.Wrapper label=&quot;Input 1&quot;&gt;<br>                  &lt;Input <br>                      placeholder=&quot;Number between 0 and 5&quot; <br>                      value={input1} <br>                      onChange={(e) =&gt; setInput1(e.currentTarget.value)}<br>                    /&gt;<br>                  &lt;/Input.Wrapper&gt;<br>                  &lt;Space h={10} /&gt;<br>                  { renderSubmitButton() }<br>                &lt;/Stack&gt;<br>              &lt;/form&gt;<br>            &lt;/Grid.Col&gt;<br>          &lt;/Grid&gt;<br>          &lt;Group w=&quot;96vw&quot; h=&quot;10vh&quot; position=&quot;center&quot; align=&quot;center&quot;&gt;<br>            &lt;Link href=&quot;https://medium.com/@yujiangtham/writing-a-zero-knowledge-dapp-fd7f936e2d43&quot;&gt;<br>              &lt;Text&gt;<br>                Created using this tutorial!<br>              &lt;/Text&gt;<br>            &lt;/Link&gt;<br>          &lt;/Group&gt;<br>        &lt;/Stack&gt;<br>      &lt;/Stack&gt;<br>    &lt;/&gt;<br>  )<br>}</pre><p>For the ConnectWalletButton, we’ll be building it for Metamask since it’s the most popular, but you can use any other wallet that you’d like and utilize the appropriate <a href="https://wagmi.sh/react/connectors/injected">Wagmi connector(s)</a>.</p><pre>// file: /src/components/ConnectWalletButton.tsx<br><br>import { Button } from &quot;@mantine/core&quot;<br>import { disconnect } from &quot;@wagmi/core&quot;;<br>import { useAccount, useConnect, useEnsName } from &#39;wagmi&#39;<br>import { InjectedConnector } from &#39;wagmi/connectors/injected&#39;<br><br>export const ConnectWalletButton = () =&gt; {<br>  const { address, isConnected } = useAccount();<br>  const { data: ensName } = useEnsName({ address });<br>  const { connect } = useConnect({<br>    connector: new InjectedConnector(),<br>  });<br><br>  const handleClick = () =&gt; {<br>    if (isConnected) {<br>      disconnect();<br>    } else {<br>      connect();<br>    }<br>  }<br><br>  const renderConnectText = () =&gt; {<br>    if (isConnected) {<br>      const start = address?.slice(0,6);<br>      const end = address?.slice(address.length-4, address.length);<br>      return `${start}...${end}`;<br>    } else {<br>      return &quot;Connect Wallet&quot;;<br>    }<br>  }<br>  <br>  return (<br>    &lt;Button onClick={handleClick}&gt;<br>      { renderConnectText() }<br>    &lt;/Button&gt;<br>  )<br>}</pre><p>Once we receive the inputs from the backend, we parse the inputs and then call our generateProof library function (which we’ll implement in the next section):</p><pre>// file: /src/pages/api/generate_proof.ts<br><br>import { generateProof } from &#39;@/lib/generateProof&#39;;<br>import type { NextApiRequest, NextApiResponse } from &#39;next&#39;<br><br>export default async function handler(<br>  req: NextApiRequest,<br>  res: NextApiResponse,<br>) {<br>  const body = req?.body;<br>  if (body === undefined) {<br>    return res.status(403).json({error: &quot;Request has no body&quot;});<br>  }<br>  console.log(body);<br><br>  const input0 = parseInt(body.input0);<br>  const input1 = parseInt(body.input1);<br><br>  if (input0 === undefined || Number.isNaN(input0) <br>    || input1 === undefined || Number.isNaN(input1)) {<br>    return res.status(403).json({error: &quot;Invalid inputs&quot;});<br>  }<br>  const proof = await generateProof(input0, input1);<br><br>  if (proof.proof === &quot;&quot;) {<br>    return res.status(403).json({error: &quot;Proving failed&quot;});<br>  }<br><br>  res.setHeader(&quot;Content-Type&quot;, &quot;text/json&quot;);<br>  res.status(200).json(proof);<br>}</pre><h4>Calculating the witness and generating the proof</h4><p>Witness calculation and proof generation is done in a single step using snarkjs.plonk.fullProve in the the following file. The data is then converted into a Solidity calldata blob, which is further split into the proof and publicSignals.</p><pre>// file: /src/lib/generateProof.ts<br><br>import path from &quot;path&quot;;<br>// @ts-ignore<br>import * as snarkjs from &#39;snarkjs&#39;;<br><br>export const generateProof = async (input0: number, input1: number): Promise&lt;any&gt; =&gt; {<br>  console.log(`Generating vote proof with inputs: ${input0}, ${input1}`);<br>  <br>  // We need to have the naming scheme and shape of the inputs match the .circom file<br>  const inputs = {<br>    in: [input0, input1],<br>  }<br><br>  // Paths to the .wasm file and proving key<br>  const wasmPath = path.join(process.cwd(), &#39;circuits/build/simple_multiplier_js/simple_multiplier.wasm&#39;);<br>  const provingKeyPath = path.join(process.cwd(), &#39;circuits/build/proving_key.zkey&#39;)<br><br>  try {<br>    // Generate a proof of the circuit and create a structure for the output signals<br>    const { proof, publicSignals } = await snarkjs.plonk.fullProve(inputs, wasmPath, provingKeyPath);<br><br>    // Convert the data into Solidity calldata that can be sent as a transaction<br>    const calldataBlob = await snarkjs.plonk.exportSolidityCallData(proof, publicSignals);<br>    const calldata = calldataBlob.split(&#39;,&#39;);<br><br>    console.log(calldata);<br><br>    return {<br>      proof: calldata[0], <br>      publicSignals: JSON.parse(calldata[1]),<br>    }<br>  } catch (err) {<br>    console.log(`Error:`, err)<br>    return {<br>      proof: &quot;&quot;, <br>      publicSignals: [],<br>    }<br>  }<br>}</pre><h4>Submitting the transaction</h4><p>The transaction is submitted in this file:</p><pre>// file: /src/lib/executeTransaction.ts<br><br>import { Addresses } from &#39;@/shared/addresses&#39;;<br>import { TransactionReceipt } from &#39;@ethersproject/abstract-provider&#39;;<br>import { prepareWriteContract, writeContract } from &#39;@wagmi/core&#39;;<br><br>export const executeTransaction = async (proof: any, publicSignals: Array&lt;string&gt;): Promise&lt;TransactionReceipt&gt; =&gt; {<br>  const abiPath = require(&#39;./abi/SimpleMultiplier.json&#39;);<br><br>  // Prepare the transaction data<br>  const config = await prepareWriteContract({<br>    address: Addresses.SIMPLE_MULTIPLIER_ADDR,<br>    abi: abiPath.abi,<br>    functionName: &#39;submitProof&#39;,<br>    args: [proof, publicSignals]<br>  });<br><br>  // Execute the transaction<br>  const writeResult = await writeContract(config);<br><br>  // Wait for the transaction block to be mined<br>  const txResult = await writeResult.wait();<br>  return txResult;<br>}</pre><h4>Updating the UI with the result</h4><p>The transaction result is given to us at the output of await txResult.wait(). Here, we’ve just sent a notification to the user on the frontend, but you can update the UI with the information in the manner you best see fit.</p><h4>Interacting with your app</h4><p>You can run a local server by running yarn dev in the project root directory to try it out.</p><p>Additionally, you can also deploy to <a href="https://vercel.com/">Vercel</a> to have your dApp on the web for anyone to play with. First, create a new Github repository and commit all of the changes and push your files to it. Go to Vercel, then add a new Project:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/984/1*tAJ6VN6vfLli6gC6_JC4Lg.png" /><figcaption>Add a new Project in Vercel</figcaption></figure><p>Select the git repository that you’d like to import:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8xjm6a07Ii3oeWPu-bm_rg.png" /><figcaption>Git repository to import</figcaption></figure><p>Ensure that the framework preset is Next.js and then hit deploy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6rdDk7ektAQluTi1utnD0w.png" /></figure><p>Wait a couple of minutes for the project to build, and then you should have a link that you can use or send to your friends. My deployment is here:</p><blockquote><a href="https://zk-example-dapp.vercel.app/"><em>https://zk-example-dapp.vercel.app/</em></a></blockquote><h3>Try it out!</h3><p>Navigate to the page you’ve deployed on Vercel and give it a go!</p><h3>Summary</h3><h4>Circuit</h4><ol><li>Write circom circuit</li><li>Compile the circuit:<br> circom circuit.circom --r1cs --wasm --sym</li><li>Download a powers of tau trusted setup file</li><li>Run Plonk setup to get the proving key:<br>snarkjs plonk setup circuit.r1cs ptau_file.ptau proving_key.zkey</li></ol><h4>Contract</h4><ol><li>Export verifier smart contract<br>snarkjs zkey export solidityverifier proving_key.zkey verifier.sol</li><li>Integrate verifier into your Solidity project</li></ol><h4>Frontend</h4><ol><li>Take user inputs</li><li>Calculate witness &amp; generate proof in one step<br>await snarkjs.plonk.fullProve({ inputs }, wasmPath, provingKeyPath);</li><li>Submit transaction with proof to Verifier contract</li></ol><h3>Conclusion</h3><p>Hopefully, this post has been helpful on your zk dApp development journey. If you have any questions or need any clarification, please be sure in the comments. For more on ZK, follow me here on Medium and on <a href="https://twitter.com/DarkForestHam">Twitter</a> as well! Cheers!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fd7f936e2d43" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Let’s dissect a zkSNARK! (part 3)]]></title>
            <link>https://medium.com/@yujiangtham/lets-dissect-a-zksnark-part-3-a53350f93417?source=rss-999ab4bada2c------2</link>
            <guid isPermaLink="false">https://medium.com/p/a53350f93417</guid>
            <category><![CDATA[zkp]]></category>
            <category><![CDATA[zero-knowledge-proofs]]></category>
            <category><![CDATA[crytocurrency]]></category>
            <category><![CDATA[zksnark]]></category>
            <category><![CDATA[zero-knowledge]]></category>
            <dc:creator><![CDATA[Yu Jiang Tham]]></dc:creator>
            <pubDate>Tue, 28 Feb 2023 18:00:52 GMT</pubDate>
            <atom:updated>2023-02-28T19:14:35.168Z</atom:updated>
            <content:encoded><![CDATA[<p>Continuing from <a href="https://medium.com/@yujiangtham/lets-dissect-a-zksnark-part-2-5f92f1d7d2e9">part 2</a>, where we discussed building circuits and arithmetization. Now, we conclude our series by discussing how we go from constraint satisfaction through to a proof system and finally end up with a zkSNARK.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fGIEeaPchgv_NAi9jM3wfw.png" /><figcaption>Rabbit in a rabbit hole</figcaption></figure><h3>Zooming out again</h3><p>Back to this diagram from last time, we went from an execution trace, cranked it through an arithmetization method (R1CS), and turned it into a constraint satisfaction problem. Now, we’ll be discussing the right half of the diagram:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/721/1*z4qi06PDOHxp6dthKh7Emg.png" /><figcaption>Components of a proof system</figcaption></figure><h3>Commitment schemes</h3><p>Before diving in, we should back up a bit and ensure that we have an understanding of cryptographic commitment schemes, which are fundamental building blocks of the ZK ecosystem. When you write a message on an envelope and send it via your local post office to your friend, you can’t change that message once it’s been sent. In essence, you’ve effectively committed to the contents of the message.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*PHKxEwJOo7k6V3NYMttyMA.png" /><figcaption>A message in a locked box</figcaption></figure><p>Cryptographic commitment schemes do something similar. A committer is able to take a message and run it through some function to get a value that they can publish publicly. Once that value is published, the committer has <em>committed</em> to that value, and a verifier can, at some future point, be able to verify that the committer did indeed commit that message. The committed message should not be able to be read by anyone without the key (hiding) and there should be no way for some other version of the message to evaluate to the same commitment (binding).</p><p>Commitment schemes happen in two phases: <em>commit</em> and <em>reveal</em>. In the <em>commit</em> phase, the committer calculates c = Comm(u,m) where u is a key, and m is the message. In the r<em>eveal</em> phase, the committer sends u and m to the receiver, who can then calculate c&#39; = Comm(u,m) and check that c&#39; = c.</p><h4>Polynomial Commitment Schemes (PCS)</h4><p>Polynomials are used in a variety of applied mathematical contexts. Reed-Soloman codes utilizes polynomials to enable a class of techniques called Error Correcting Codes, which automatically correct transmission errors over a potentially noisy channel. These are used in a number of places from hard disk drives to cellular networks to ensure that the data is read or transmitted correctly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*CU3WuwDaKwcBH1bou7PWTQ.png" /><figcaption>Part of a hard disk drive chilling on a table</figcaption></figure><p>A Polynomial Commitment Scheme allows a committer to generate a polynomial to commit to that is easily verified by the recipient. They are used extensively in zkSNARKs. Polynomials have a very useful property in which a receiver can query one part of the polynomial without having to reveal the entire polynomial (side note: this is called <em>oracle access</em>, which we’ll discuss later).</p><p>In other words, we are able to prove that we know a some number of points i on the polynomial p(x) where p(a_i) = b_i without revealing our polynomial p(x). Unlike in a regular cryptographic commitment scheme, (c = Comm(u,m), where u and m must be revealed to the verifier), polynomial commitments allow a verifier to prove evaluations of the polynomial at various points without revealing the entire polynomial.</p><p>They can be used to take a large amount of information (such as a very long execution trace of an arithmetic circuit) and fit it into a small amount of information (a polynomial). There are a number of different types of commitment schemes, each with various properties.</p><h4>KZG Commitments</h4><p>The KZG polynomial commitment scheme is one of the most common forms of polynomial commitments used in zkSNARKs today. The name KZG comes from the authors of the <a href="https://www.iacr.org/archive/asiacrypt2010/6477178/6477178.pdf">original paper</a>: Kate, Zaverucha, Goldberg. A KZG commitment is a commitment to a vector of n polynomial evaluations of the polynomial p(x) that is of degree n-1 (called a <em>witness polynomial</em>). Essentially, the verifier is able to discern with very high probability that the committed polynomial is correct.</p><h3>Interactive Oracle Proofs (IOP)</h3><p>Interactive Oracle Proofs are an information theoretic model that operate on a number of idealized assumptions such as unbounded computation ability of the prover/verifier or that the prover/verifier must operate on without communicating with other parties during the execution of the protocol.</p><p>IOPs are a type of Interactive Proof (IP) that utilizes o<em>racle access</em> to the proof. Interactive Proofs are a class of proofs that require a number of rounds of interaction between a prover and a verifier, wherein the verifier will query the prover and receive responses. O<em>racle access</em> means that the prover has sent the entire proof P(x) to an oracle, which the verifier can then query random values (i.e. the verifier will choose a random number, say x = 5, and ask P(5) = ?, and will get the answer P(5) = 10 back) without having the entire proof P(x)revealed.</p><h3>Proof systems</h3><p>We get a proof system after putting an IOP (which, if you remember, is just an idealized model) through a cryptographic compiler. Cryptographic compilers remove idealized assumptions of communication and utilize cryptographic primitives such as hash functions or elliptic curves to move an IOP into a real-world proof system that can generate a zkSNARK.</p><p>We’ll briefly touch on two proof systems that are older but have a wide amount of adoption:</p><h4>Groth16</h4><p>Groth16 is an older, well-used proof system. One thing that a lot of people see as a turn off is that that requires a per-circuit trusted setup, which makes it much more difficult to use, but is more secure. Groth16 also has the smallest proof size.</p><h4>Plonk</h4><p>Plonk, on the other hand, uses a universal trusted setup and so it’s a lot easier to use. Proofs that are generated by using Plonk are bigger than Groth16 proofs.</p><h4>Newer proving systems</h4><p>Newer proving systems such as <a href="https://zcash.github.io/halo2/index.html">halo2</a> and <a href="https://github.com/mir-protocol/plonky2">Plonky2</a> combine the best of other proof systems and other new concepts to allow for orders-of-magnitude faster proving/verifying times, recursion, and more. In this fast-moving field, the is always something new and interesting on the horizon!</p><h3>zkSNARK</h3><p>So, we’ve gone through all of this to come up with a zkSNARK! So you might be wondering what a zkSNARK proof even looks like. It can come in a number of different formats, but here’s one that’s generated by <a href="https://iden3.io/circom">Circom/SnarkJS</a> with Plonk:</p><pre>{<br> &quot;A&quot;: [<br>  &quot;6908956559376137340171196334631977634711358419710404769689125968088654624644&quot;,<br>  &quot;16932989149179303110306042962567858437672652090915736000213210179928213052205&quot;,<br>  &quot;1&quot;<br> ],<br> &quot;B&quot;: [<br>  &quot;10588840689520264771936066469568807327119382366634392323966486988467407001638&quot;,<br>  &quot;10229316063452690801507259777947935670857074599961348945620381561034515164406&quot;,<br>  &quot;1&quot;<br> ],<br> &quot;C&quot;: [<br>  &quot;16084899085204675689132108134083605933751081775503786540495196599722848162338&quot;,<br>  &quot;21356787944490833330652242243111424190095383591299924564125418627026991789158&quot;,<br>  &quot;1&quot;<br> ],<br> &quot;Z&quot;: [<br>  &quot;17765107575899672040993541878831073381023263680467188595309317410911854244771&quot;,<br>  &quot;6313343890583290837650965624272827660438348800173375236989766452773637648713&quot;,<br>  &quot;1&quot;<br> ],<br> &quot;T1&quot;: [<br>  &quot;9554996580112652857081087006710106006873579191557920158338510670114836358531&quot;,<br>  &quot;10692777877219430516985193994926553868926808589724390039483447860423047846932&quot;,<br>  &quot;1&quot;<br> ],<br> &quot;T2&quot;: [<br>  &quot;676790424696889453973167662648988910434711585806269850335472050317445000801&quot;,<br>  &quot;19046102729811438225780142024141399492680515098326829586767383998198297849113&quot;,<br>  &quot;1&quot;<br> ],<br> &quot;T3&quot;: [<br>  &quot;4605880236713526737003637609771442419611615015020516846461894965226380068331&quot;,<br>  &quot;19331673596656480838213028785359744521984113367516263088749444124059486171827&quot;,<br>  &quot;1&quot;<br> ],<br> &quot;eval_a&quot;: &quot;15485933003077165236672451528127828232974110105382592967191331423684824757418&quot;,<br> &quot;eval_b&quot;: &quot;16629977471156978182828773382438576062157680070473413146331064655197104175954&quot;,<br> &quot;eval_c&quot;: &quot;19887998895846667152935870867467200995858182358449502995901961038310475312715&quot;,<br> &quot;eval_s1&quot;: &quot;2861053678782603869717695335350019077968004966013839132807493210057313857498&quot;,<br> &quot;eval_s2&quot;: &quot;12045841120468746488230522035590421057538184460262526104889604898312099136113&quot;,<br> &quot;eval_zw&quot;: &quot;4030229530359541063568939638832079137472854642425576803825418801503661461483&quot;,<br> &quot;eval_r&quot;: &quot;4007002272841740548667739607769563075966899148986525117512093975687169758932&quot;,<br> &quot;Wxi&quot;: [<br>  &quot;2604076815338219820969818933185487042665467863796932384089487859508714979834&quot;,<br>  &quot;14726021541798728844627399835533201742658584651576597396311585628406002751083&quot;,<br>  &quot;1&quot;<br> ],<br> &quot;Wxiw&quot;: [<br>  &quot;4486542282232103671498159945862056575371277318055006380926533302403456544125&quot;,<br>  &quot;6939810882697630067565408176534942709703777425287032514579101958507243736198&quot;,<br>  &quot;1&quot;<br> ],<br> &quot;protocol&quot;: &quot;plonk&quot;,<br> &quot;curve&quot;: &quot;bn128&quot;<br>}</pre><h3>Wrapping up</h3><p>The journey to learning ZK is definitely not easy or straightforward, but every new piece of the puzzle makes the image that much more clear. I encourage you to continue learning on your own as there are many resources out there, no matter where you are in your ZK journey.</p><p>The next few posts will likely focus on more practical approaches to implementing zkApps using available toolchains, so stay tuned!</p><p>Hopefully you’ve been able to learn something through all of this. If so, please share with a friend and follow me here on Medium and on <a href="https://twitter.com/DarkForestHam">Twitter</a>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a53350f93417" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Let’s dissect a zkSNARK! (part 2)]]></title>
            <link>https://medium.com/@yujiangtham/lets-dissect-a-zksnark-part-2-5f92f1d7d2e9?source=rss-999ab4bada2c------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f92f1d7d2e9</guid>
            <category><![CDATA[zksnark]]></category>
            <category><![CDATA[zkp]]></category>
            <category><![CDATA[zero-knowledge-proofs]]></category>
            <category><![CDATA[cryptocurrency]]></category>
            <category><![CDATA[zero-knowledge]]></category>
            <dc:creator><![CDATA[Yu Jiang Tham]]></dc:creator>
            <pubDate>Wed, 15 Feb 2023 18:40:14 GMT</pubDate>
            <atom:updated>2023-04-24T00:28:52.768Z</atom:updated>
            <content:encoded><![CDATA[<p>This post continues from <a href="https://medium.com/@yujiangtham/lets-dissect-a-zksnark-part-1-a82fc092f58a">part 1</a>, which reviewed what a zkSNARK is, as well as some of the math required to understand it. Now, we head deeper into the rabbit hole and take a look at going from a computer program to decomposing it into the elements required for a zkSNARK proof.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*o8OGYEA6TjxpHC-CiPJQ-w.png" /><figcaption>A rabbit on a journey.</figcaption></figure><h3>30,000-ft picture</h3><p>Before we go too far off the deep end, it pays to zoom out a bit and get a sense of what we’re looking at today. I’ve redrawn a diagram of the components of a proof system from Ying Tong Lai a ZK engineer and researcher who was at the Ethereum Foundation for a number of years:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/721/1*yqlh_xb7ztuxXSQVU8A86w.png" /><figcaption>Components of a proof system</figcaption></figure><p>Today’s focus will be on the left half, going through how we get correctness of computation through arithmetization and constraint satisfaction.</p><h3>Zero Knowledge Circuits</h3><p>In order to create a zkSNARK, we first must generate a arithmetic circuit. Unlike a hardware circuit board that you might be imagining, arithmetic circuits are software constructions that are essentially arithmetic circuits on finite fields (see <a href="https://medium.com/@yujiangtham/lets-dissect-a-zksnark-part-1-a82fc092f58a">the previous post</a> for details) of a prime order (prime number of elements in the field), of which the prime number is chosen because it works especially well for elliptic curve cryptography.</p><p>Circuit constructions are utilized because they can easily be used for probabilistic checks by a verifier to ensure that the computations were correctly run. Because circuits can be defined as a series of polynomials, which are required for probabilistic checks, they have become the standard way to construct ZK proofs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*_blAYUQG96gjPRZcWaCVjw.png" /><figcaption>A hardware circuit board that is NOT like the circuits that we’re discussing</figcaption></figure><p>In order to visualize how a program could be turned into a circuit, we can take the following example. Imagine we have a variable in and want to check if in is equal to either 10, 15, or 25 and if so, return 1, otherwise return 0. Some pseudocode for this would look like:</p><pre>if (in == 10 || in == 15 || in == 25) {<br>  return 1;<br>} else {<br>  return 0;<br>}</pre><p>In order to do the same thing in an arithmetic circuit, we can express this as an equation (in-10)(in-15)(in-25) ?= 0. Here’s an equivalent circuit diagram:</p><p>Essentially, what’s happening here is that the left hand side of the equation will evaluate to 0 if in is 10, 15, or 25, and nonzero otherwise. The isZero component is a circuit that returns 1 if its input is equal to 0, and 0 otherwise.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/591/1*P2lJEUn1C84dRPfl0vtghg.png" /><figcaption>(in - 10)(in - 15)(in - 25) ?= 0</figcaption></figure><h3>Writing a Circuit</h3><p>The natural question that arises from all of this is how does one go about writing a circuit for a zkSNARK? There are a number of domain-specific languages that are being used to accomplish this task.</p><h4>Circom</h4><p><a href="https://iden3.io/circom">Circom</a> is a language and compiler that lets people write and compile arithmetic circuits for ZK proofs. It’s often used in conjunction with <a href="https://github.com/iden3/snarkjs">SnarkJS</a> to generate keys with trusted setup parameters and to prove and verify with the compiled circuit output from Circom. Since Circom has been around for a while, it’s the gold standard for writing circuits for ZK proofs.</p><p>With that said, writing in Circom can take a little bit of getting used to. Circom is a constraint-based language and requires the programmer to constrain the inputs, intermediate signals, and outputs of the circuit to valid values. I’ll have another post that goes more in-depth on this another day.</p><p>Circom compiles down to R1CS (which we’ll discuss further down in this post), WASM, and JSON.</p><h4>Noir</h4><p>New on the scene from Aztec, a pioneer in the ZK space, is <a href="https://aztec.network/noir/">Noir</a>. Noir is a Rust-like language that allows for programmers to pick up the language more naturally. For example, conditional branching is supported in Noir.</p><p>Another benefit touted by the Aztec team is that Noir compiles down to what they call an Abstract Circuit Intermediate Representation (ACIR), which will eventually allow you to utilize any SNARK-based proving system in the future.</p><p>Unfortunately, as of February 2023, there’s still a number of inconsistencies in their compiler and JS prover that make it difficult to deploy this in production. Hopefully the issues will be resolved soon.</p><h4>Lurk</h4><p><a href="https://github.com/lurk-lang">Lurk</a> is a language from Protocol Labs/Filecoin that supports recursive zkSNARKs via Lisp-like expression. I haven’t dug too deeply into Lurk but it’s definitely been gaining adoption because Filecoin is such a large entity that <a href="https://filecoin.io/blog/posts/filecoin-zk-snarks-zero-knowledge-but-a-lot-of-zero-knowledge/">has already been using zkSNARKs for a long time</a>.</p><h3>Arithmetization</h3><p>Arithmetization is the process of taking a circuit description via a programming language and turning it into a system of mathematical constraints that enable fast verification. With this set of mathematical constraints, which we’ll dive further into below, a verifier can run a small number of algebraic checks to show with high probability that the prover is not lying. In this section we go from circuit -&gt; R1CS -&gt; QAP, which we’ll describe below.</p><h4>Rank-1 Constraint System (R1CS)</h4><p>One way of displaying arithmetic circuits is the Rank-1 Constraint System, or R1CS. By taking a circuit and transforming it into a series of matrices and vectors, we can eventually feed this into any proof system that supports R1CS to generate a zkSNARK.</p><p>To get an R1CS, we have to “flatten” our circuit into a series of mathematical constraints of the form left * right = output, or equivalently left * right — output = 0, where left is the left wire of an arithmetic circuit gate, right is the right wire, and output is the output wire.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/276/1*X7GA-nlTgZdk-xIFOoWNWA.png" /><figcaption>left, right, and output wires for an arithmetic circuit gate</figcaption></figure><p>If we take our arithmetic circuit for (in-10)(in-15)(in-25) above, and simplify it so that we will only check if (in-10)(in-15)(in-25)=0, we can label our wires (excluding constants) and gates as such:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/1*9SW20FWUOnYNM8R0PHsCGA.png" /><figcaption>wires and gates labeled for our circuit (in-10)(in-15)(in-25)=0</figcaption></figure><p>Which gives us the following system of equations:</p><pre>g0: w1 - 10 = w4<br>g1: w2 - 15 = w5<br>g2: w3 - 25 = w7<br>g3: w4 * w5 = w6<br>g4: w6 * w7 = w8</pre><p>Now, a prover can come along and claim that they know a value of in that satisfies the circuit wherein w8 = 0 (put another way, the prover wants to show that they know an input value that causes the equation to equal to 0).</p><p>The prover will then set the in value to 15 and substitute this into the system of equations:</p><pre>g0: w4 = 15 - 10,   w4 = 5<br>g1: w5 = 15 - 15,   w5 = 0<br>g2: w7 = 15 - 25,   w7 = -10<br>g3: w6 = 5 * 0,     w6 = 0<br>g4: w8 = 0 * (-10), w8 = 0</pre><p>The R1CS representation works because if we are able to show that these set of equations is correct, we then know that the original equation is correct. The prover can create a vector that contains all of the wire values, called a <em>witness</em>. The <em>witness</em> is the set of inputs, outputs, and all intermediate values of the arithmetic circuit. The witness vector also includes a w0 = 1 value by default (notice how we started counting from w1 in the diagram).</p><pre>wires:     w0  w1  w2  w3  w4  w5  w6   w7  w8<br>witness = { 1, 15, 15, 15,  5,  0,  0, -10,  0}</pre><p>Using the witness vector w, we can create a series of equations of the form (w . left) * (w . right) — (w . output) = 0 where . is the dot product operation (multiply each corresponding element in two vectors of the same size and sum the results to equal a scalar) which allows us to eventually generate vectors for the left, right, and output for each gate. Here’s how it will look for g0:</p><pre>g0:<br>w      [  1,15,15,15, 5, 0, 0,-10, 0]<br>left   [  0, 1, 0, 0, 0, 0, 0,  0, 0]<br><br>w      [  1,15,15,15, 5, 0, 0,-10, 0]<br>right  [-10, 0, 0, 0, 0, 0, 0,  0, 0]<br><br>w      [  1,15,15,15, 5, 0, 0,-10, 0]<br>output [  0, 0, 0, 0, 1, 0, 0,  0, 0]<br><br>     left * right - output = 0<br>(15 - 10) *     1 -      5 = 0</pre><p>Note that in the case of an addition or subtraction gate in the above example, the addition/subtraction of the right wire gets combined in the left wire and the right wire is set to 1 to ensure the left * right — output equation holds. Also, note that w0 is used for constants, so the first element of right is equal to -10 in this case.</p><p>Now, here are the rest of the gates g1 to g4:</p><pre>g1:<br>w      [  1,15,15,15, 5, 0, 0,-10, 0]<br>left   [  0, 0, 1, 0, 0, 0, 0,  0, 0]<br><br>w      [  1,15,15,15, 5, 0, 0,-10, 0]<br>right  [-15, 0, 0, 0, 0, 0, 0,  0, 0]<br><br>w      [  1,15,15,15, 5, 0, 0,-10, 0]<br>output [  0, 0, 0, 0, 0, 1, 0,  0, 0]<br><br>     left * right - output = 0<br>(15 - 15) *     1 -      0 = 0</pre><pre>g2:<br>w      [  1,15,15,15, 5, 0, 0,-10, 0]<br>left   [  0, 0, 0, 1, 0, 0, 0,  0, 0]<br><br>w      [  1,15,15,15, 5, 0, 0,-10, 0]<br>right  [-25, 0, 0, 0, 0, 0, 0,  0, 0]<br><br>w      [  1,15,15,15, 5, 0, 0,-10, 0]<br>output [  0, 0, 0, 0, 0, 0, 0,  1, 0]<br><br>     left * right - output = 0<br>(15 - 25) *     1 -    -10 = 0</pre><pre>g3:<br>w      [  1,15,15,15, 5, 0, 0,-10, 0]<br>left   [  0, 0, 0, 0, 1, 0, 0,  0, 0]<br><br>w      [  1,15,15,15, 5, 0, 0,-10, 0]<br>right  [  0, 0, 0, 0, 0, 1, 0,  0, 0]<br><br>w      [  1,15,15,15, 5, 0, 0,-10, 0]<br>output [  0, 0, 0, 0, 0, 0, 1,  0, 0]<br><br>left * right - output = 0<br>   5 *     0 -      0 = 0</pre><pre>g4:<br>w      [  1,15,15,15, 5, 0, 0,-10, 0]<br>left   [  0, 0, 0, 0, 0, 0, 1,  0, 0]<br><br>w      [  1,15,15,15, 5, 0, 0,-10, 0]<br>right  [  0, 0, 0, 0, 0, 0, 0,  1, 0]<br><br>w      [  1,15,15,15, 5, 0, 0,-10, 0]<br>output [  0, 0, 0, 0, 0, 0, 0,  0, 1]<br><br>left * right - output = 0<br>   0 *   -10 -      0 = 0</pre><p>We then collect the left, right, and output vectors to get 2D matrices for each:</p><pre>left:<br>[[  0, 1, 0, 0, 0, 0, 0, 0, 0],<br> [  0, 0, 1, 0, 0, 0, 0, 0, 0],<br> [  0, 0, 0, 1, 0, 0, 0, 0, 0],<br> [  0, 0, 0, 0, 1, 0, 0, 0, 0],<br> [  0, 0, 0, 0, 0, 0, 1, 0, 0]]<br><br>right:<br>[[-10, 0, 0, 0, 0, 0, 0, 0, 0],<br> [-15, 0, 0, 0, 0, 0, 0, 0, 0],<br> [-25, 0, 0, 0, 0, 0, 0, 0, 0],<br> [  0, 0, 0, 0, 0, 1, 0, 0, 0],<br> [  0, 0, 0, 0, 0, 0, 0, 1, 0]]<br><br>output:<br>[[  0, 0, 0, 0, 1, 0, 0, 0, 0],<br> [  0, 0, 0, 0, 0, 1, 0, 0, 0],<br> [  0, 0, 0, 0, 0, 0, 0, 1, 0],<br> [  0, 0, 0, 0, 0, 0, 1, 0, 0],<br> [  0, 0, 0, 0, 0, 0, 0, 0, 1]]</pre><p>Essentially, with these vectors and the witness w, we’re able to express that the original computation was performed with an in value of 10 and pass this data into a proving system that can generate a zkSNARK proof that is easily verifiable by a verifier.</p><h4>Quadratic Arithmetic Program (QAP)</h4><p>Once the R1CS process is complete, the output is a series of vectors, which is then handed to the Quadratic Arithmetic Program (QAP), turning the output vectors into a system of quadratic polynomials. Once the data is in this polynomial form, it can easily be checked by any number of interactive and non-interactive proof systems.</p><h4>Other arithmetizations: AIR</h4><p>As an aside, another popular type of arithmetization (amongst many others) is the Algebraic Intermediate Representation (AIR), used in both SNARKs and STARKs. AIR has three main components:</p><ol><li>a 2D matrix of the execution trace, with the columns representing intermediate field elements of the execution, and rows representing the computation steps over time, from start to end.</li><li>A set of constraint equations that define algebraic relationships between the columns and rows of the matrix.</li><li>A set of boundary constraints that enforce constraints on inputs, outputs, and constants.</li></ol><p>I won’t go into too much detail on AIR today, but we can revisit the topic at a later date.</p><h3>Summary</h3><p>Today, we discussed how to get from a program to a circuit, subsequently converting that circuit into a form that can allow Stay tuned!</p><p><a href="https://medium.com/@yujiangtham/lets-dissect-a-zksnark-part-3-a53350f93417">Continue to Part 3</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f92f1d7d2e9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Let’s dissect a zkSNARK! (part 1)]]></title>
            <link>https://medium.com/@yujiangtham/lets-dissect-a-zksnark-part-1-a82fc092f58a?source=rss-999ab4bada2c------2</link>
            <guid isPermaLink="false">https://medium.com/p/a82fc092f58a</guid>
            <category><![CDATA[zero-knowledge]]></category>
            <category><![CDATA[zero-knowledge-proofs]]></category>
            <category><![CDATA[snark]]></category>
            <category><![CDATA[zksnark]]></category>
            <category><![CDATA[cryptocurrency]]></category>
            <dc:creator><![CDATA[Yu Jiang Tham]]></dc:creator>
            <pubDate>Mon, 06 Feb 2023 16:14:57 GMT</pubDate>
            <atom:updated>2023-04-24T00:28:28.978Z</atom:updated>
            <content:encoded><![CDATA[<p>What exactly is a zkSNARK, you ask? Well, today we’re going to answer that question by peeking into the rabbit hole.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*FpPODJ0vMMwPgOxYPuLClQ.png" /><figcaption>Follow the rabbit…</figcaption></figure><h3>First of all, what exactly is a zkSNARK?</h3><p>zkSNARKs stand for zero-knowledge Succinct Non-interactive ARguments of Knowledge. They are essentially a proof that some computation (with potentially private inputs) has been run. Every step of the computation is encoded into a polynomial equation (yes, the same ones you had to do back in high school) and a small proof consisting of a few tens to hundreds of numbers is created.</p><h4>A powerful use case for SNARKs</h4><p>Like I alluded to <a href="https://medium.com/@yujiangtham/what-are-zero-knowledge-proofs-and-why-do-they-matter-b580e8de71e0">in my previous post</a>, Zero Knowledge Proofs (and those of the SNARK or STARK variety) are extremely tantalizing to people who want to scale blockchain computation because they can offload computation to more powerful computers in a trustless manner, while allowing parties with lower compute power to easily verify that the computation was done correctly. They don’t even necessarily need to use the Zero Knowledge property of a zkSNARK! In fact, Zero Knowledge Rollups are currently built on top of Ethereum using this verifiable computation model.</p><p>Taking a step back, what exactly does a “computation” mean, anyway? Simply put, every transaction on a blockchain is a computation or series of computations. For example, every full node on Ethereum must replay every single transaction on the blockchain to ensure that it leads to a valid state change. This leads to Ethereum’s security, but also prevents the network from increased throughput and causes network usage to be expensive, especially during high load times.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*NypepIVfofmUOIkFrHLl0g.png" /><figcaption>Magnifying glass looking at part of a circuit board</figcaption></figure><p>However, instead of requiring every single full node to replay every single transaction, zkRollups are able to utilize much more powerful computers to build blocks of transactions, create a proof that the block was computed correctly, and allow anyone to quickly and easily verify that this was the case. Without this succinct proof of computational integrity (or naïvely replaying transactions) , the nodes in the ecosystem that build blocks of transactions could potentially alter or remove any transactions they want.</p><p>You might be wondering how this is different than just hashing the computation or data. With hashing, you won’t be able to check in a succinct way that every step of the computation was done correctly, you’d just have the final hash at the end. The big difference is that creating a SNARK proof means turning every step of the computation into a mathematical system of equations in a process called arithmetization. The way the proof is created and its structure is small enough for any third party (called a Verifier) to check with a high degree of certainty that all steps of the computation were run correctly.</p><h3>A little zkSNARK math primer</h3><p>Now, with all of that out of the way, let’s get back to it. In order to understand SNARKs, we’ll need to build a little bit of understanding of some of the mathematical concepts behind them. We’ll assume knowledge of hash functions, but if not there’s many <a href="https://blockgeeks.com/guides/what-is-hashing/">resources available online</a>. The following sections will focus more on some of the more mathematical concepts required to understand SNARKs.</p><h4>Finite Fields</h4><p>zkSNARKs work on finite fields with a prime order. A finite field is a finite set of elements (positive integers, in this case) in which the operations of addition, subtraction, multiplication, and division are <em>closed</em> on them. Being <em>closed</em> means that any operation on two elements of the field results in another element in the field.</p><p>The order of a finite field is the number of elements in the field. Finite fields of a prime order have a number of elements that are a prime number. A finite field with order 7 contains the numbers {0, 1, 2, 3, 4, 5, 6}. Every finite field has a prime order or an order of a prime raised to some power.</p><h4>Modular Arithmetic</h4><p>When doing mathematical operations on the field elements, they will wrap around in either direction (the <em>closed</em> property described above). This is called modular arithmetic, and is denoted by the operator <em>mod</em>. Therefore, 3 + 6 = 9 mod 7 = 2 (since 9 is outside of the field {0, …, 6}, we wrap around to 9 - 7 = 2).</p><p>One way to think of it You can think of it like operations on a clock (but instead of 12 o’clock, we’ll use 0 instead, so we’ll have a finite field with elements {0, 1, 2, …, 11}. If you count past 11, you get back to 0.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/242/1*eitr3xjd6ZCsmHhH4gv_Fg.png" /><figcaption>A finite field of order 12, containing elements {0, 1, 2, …, 11}</figcaption></figure><p>So, if you we are to start at 9 o’clock and to add 6 hours, we land at 3 o’clock (and not 15 o’clock, unless you’re in one of those 24-hour countries).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/242/1*EYeZSvfvH7uzwC7xKnhTnA.png" /><figcaption>9 o’clock + 6 hours = 3 o’clock</figcaption></figure><p>Similarly, for multiplication on this clock, we can do the same: 5 * 5 = 25 mod 12 = 1 (25 / 12 = 2, remainder 1).</p><h4>Arithmetic Circuits</h4><p>In order for a zkSNARK proof to be created, it must first be turned into an arithmetic circuit through a process called arithmetization. You can think of an arithmetic circuit as a way of showing a mathematical equation in a visual form, in which two inputs go into a mathematical operation and give an output. For example, 2 + 3 = 5 can be modeled like so:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/202/1*pI9Qu0mUy1fgw4rJQru4og.png" /><figcaption>Arithmetic circuit showing 2 + 3 = 5</figcaption></figure><p>Each operator, such as the (+) above is called a gate. In order to model more complex circuits, more gates are used. For example, we can model the equation (2 + 3) * (2 + 1) as a circuit as well:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/422/1*tMe7LHOqh0ri6RWe2wyGGQ.png" /><figcaption>(2 + 3) * (2 + 1) = 15</figcaption></figure><p>Much larger circuits can represent much larger systems. The logic for a zkSNARK proof is written in a programming language (such as <a href="https://iden3.io/circom">Circom</a> or <a href="https://aztec.network/noir/">Noir</a>) that specifies what inputs, outputs, and intermediate signals are valid. That program is then turned is then turned into an arithmetic circuit, which allows a prover to provide some public and private inputs, run the computation against the circuit, and get a succinct proof, which can be easily verified by a verifier. These calculations are all done within a prime field, so if we are operating on the finite field with order 7, (2 + 3) * (2 + 1) = 15 mod 7 = 1.</p><h3>Summary</h3><p>That’s a good place to stop for today. This time, we reviewed some of the basic mathematical principles that are the foundation for how zkSNARKs work. In the next session, we’ll cover a bit more about how you actually go from a computation to a SNARK. Stay tuned!</p><p><a href="https://medium.com/@yujiangtham/lets-dissect-a-zksnark-part-2-5f92f1d7d2e9">Continue to Part 2</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a82fc092f58a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What are Zero Knowledge Proofs and why do they matter?]]></title>
            <link>https://medium.com/@yujiangtham/what-are-zero-knowledge-proofs-and-why-do-they-matter-b580e8de71e0?source=rss-999ab4bada2c------2</link>
            <guid isPermaLink="false">https://medium.com/p/b580e8de71e0</guid>
            <category><![CDATA[cryptocurrency]]></category>
            <category><![CDATA[web3]]></category>
            <category><![CDATA[zero-knowledge-proofs]]></category>
            <category><![CDATA[crypto]]></category>
            <category><![CDATA[zero-knowledge]]></category>
            <dc:creator><![CDATA[Yu Jiang Tham]]></dc:creator>
            <pubDate>Fri, 06 Jan 2023 16:03:42 GMT</pubDate>
            <atom:updated>2023-01-06T16:03:42.632Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/509/1*de47oEdfCx12ovVwMWwHYw.jpeg" /></figure><h3>Introduction</h3><p>This article is meant to be an overview and will skim over a large number of technical details so that the reader can get a better understanding of Zero Knowledge Proofs and how they fit in the blockchain landscape.</p><p>Zero Knowledge Proofs (ZKPs) are a large and ever-expanding class of proofs that allow a computer program (prover) to construct a proof that a computation has been done correctly. With that proof, any other computer running software that can read the proof (verifier) can check that this computation was done without needing to know all of the inputs of the computation and without needing to re-do the entire computation. This is a lot to ingest, so we’ll break down what all of this means further down.</p><p>Although they’ve been around since the mid-80’s, it wasn’t until the past few years that the field of Zero Knowledge Cryptography has really started to pick up steam due to finding product-market fit in blockchains. To see why, we have to take a small detour to understand what a modern blockchain does.</p><h3>Replicated State Machines</h3><p>A blockchain can be thought of as a replicated state machine across a number of nodes. A state machine is a computer science abstraction that allows a system to be thought of as a set of valid states, with valid inputs transitioning the system to a another set of valid states.</p><p>To gain a better intuition of how this applies to blockchains, let’s go through a quick example on the Ethereum blockchain. If you have 1 ETH and your drinking buddy Jimmy has 2 ETH at the beginning of the night, this is the starting state of the system. At the end of the night, you send 0.1 ETH to Jimmy since he bought a few rounds and you didn’t have your credit card with you (the input in this case is the 0.1 ETH transaction from you to Jimmy). Since this was a valid transaction, the new state of the system is that you have 0.9 ETH (minus gas fees), and Jimmy has 2.1 ETH. Now, scale this up a bunch and you have a blockchain. Kind of.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/481/1*Yr8A9Q6XTqYHEsg1T9nDRA.png" /><figcaption>Sending ETH to Jimmy</figcaption></figure><p>The other part is that the state machine is replicated across some number of computers (called nodes). The network of nodes must come to agreement on the state of the system via a process called consensus. There are numerous ways that the network can achieve consensus, which is beyond the scope of this article, but two examples are the Bitcoin network, which uses <a href="https://en.wikipedia.org/wiki/Proof_of_work">proof-of-work</a>, and the Ethereum network, which uses <a href="https://en.wikipedia.org/wiki/Proof_of_stake">proof-of-stake</a>.</p><p>In order for the state of the system to be replicated across all of the nodes, every node must replay each transaction to validate that the transaction leads to a valid state. For a large number of transactions in a large replicated system, this requires ever-increasing storage and compute requirements. The current requirements for running a full Ethereum node are not insignificant, and are as follows:</p><ul><li>A fast CPU with 4+ cores</li><li>16 GB+ of RAM</li><li>A fast SSD drive with at least 1 TB of space (storage capacity will grow over time)</li><li>25 MBit/s bandwidth</li></ul><h3>Zero Knowledge Proofs and Blockchains</h3><p>Zero Knowledge Proofs have gotten so much hype in the crypto world in the past few years because they really are a perfect fit for blockchains. Due to how they are constructed, ZKPs can be used to do two things that blockchains builders have desired for a long time:</p><ol><li>Private Data</li><li>Verifiable Computing</li></ol><h4>Private Data</h4><p>Because of the way ZKPs are constructed, a blockchain can advance the state of its system by receiving inputs that do not need to be revealed to anyone viewing or validating the chain. Data about an account or transaction can be trustlessly verified without the counterparty knowing anything about the actual content of the data.</p><p>One example that is thrown around a lot is that it’s like being able to prove that you are over the legal drinking age without having to show the bouncer at a bar your ID (which contains a lot of information other than your age).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ww-XClYnefqiO-zTGjOlQw.jpeg" /><figcaption>This bouncer wants to read everything on your ID</figcaption></figure><p>The private data property of Zero Knowledge Proofs also allows for private transactions, which makes blockchains act more like current payment rails in which you’re not showing every transaction you make to the whole world.</p><p>Institutions also require private transactions for compliance purposes, so this may open up the crypto world to a whole new class of participants who were previously unable to utilize blockchains.</p><h4>Verifiable Computing</h4><p>Due to the fact that Zero Knowledge Proofs tend to imply privacy in their name, this subject gets less attention, but it is as — if not more — important than the ability for private transactions.</p><p>Verifiable Computing (VC) refers to the ability for a computation to be run on a different (usually significantly more powerful) computer and have the output be easily verifiable that it’s been done correctly. In this case, a computation could refer to one million blockchain transactions in a short period of time.</p><p>Because of the replicated state machine property of current blockchains that we discussed earlier, having each node in the network replay each of the one million transactions to verify that they are valid within the required timeframe would mean that the requirements for running a full node would be significantly higher, leading to less decentralization in the network.</p><p>Instead, with ZKPs, there could be a few extremely powerful computers in the network that process transactions, build blocks, and create proofs that all of these computations were done correctly. Then, the rest of the nodes in the network can quickly and easily verify that the computation was done correctly without having to replay all of the transactions.</p><p>The benefit of this is that the verification cost could be low enough that mobile phones could be verification nodes in the blockchain.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/931/1*77dxes0_fgjBPhcCrZjIKA.jpeg" /><figcaption>A mobile phone verifying the blockchain (in the background)</figcaption></figure><h3>Conclusion</h3><p>Hopefully this helps you understand why Zero Knowledge Proofs are so powerful and why they’ve been getting increasing amounts of attention. There’s a huge amount of very complex math behind why these proofs work, and I’ll be touching on some of this in future articles. For now, if you found this helpful, share it with a friend!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b580e8de71e0" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>