halo2/user/simple-example.html

592 lines
32 KiB
HTML
Raw Normal View History

<!DOCTYPE HTML>
<html lang="en" class="sidebar-visible no-js light">
<head>
<!-- Book generated using mdBook -->
<meta charset="UTF-8">
<title>A simple example - The halo2 Book</title>
<!-- Custom HTML head -->
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="theme-color" content="#ffffff" />
<link rel="icon" href="../favicon.svg">
<link rel="shortcut icon" href="../favicon.png">
<link rel="stylesheet" href="../css/variables.css">
<link rel="stylesheet" href="../css/general.css">
<link rel="stylesheet" href="../css/chrome.css">
<link rel="stylesheet" href="../css/print.css" media="print">
<!-- Fonts -->
<link rel="stylesheet" href="../FontAwesome/css/font-awesome.css">
<link rel="stylesheet" href="../fonts/fonts.css">
<!-- Highlight.js Stylesheets -->
<link rel="stylesheet" href="../highlight.css">
<link rel="stylesheet" href="../tomorrow-night.css">
<link rel="stylesheet" href="../ayu-highlight.css">
<!-- Custom theme stylesheets -->
</head>
<body>
<!-- Provide site root to javascript -->
<script type="text/javascript">
var path_to_root = "../";
var default_theme = window.matchMedia("(prefers-color-scheme: dark)").matches ? "navy" : "light";
</script>
<!-- Work around some values being stored in localStorage wrapped in quotes -->
<script type="text/javascript">
try {
var theme = localStorage.getItem('mdbook-theme');
var sidebar = localStorage.getItem('mdbook-sidebar');
if (theme.startsWith('"') && theme.endsWith('"')) {
localStorage.setItem('mdbook-theme', theme.slice(1, theme.length - 1));
}
if (sidebar.startsWith('"') && sidebar.endsWith('"')) {
localStorage.setItem('mdbook-sidebar', sidebar.slice(1, sidebar.length - 1));
}
} catch (e) { }
</script>
<!-- Set the theme before any content is loaded, prevents flash -->
<script type="text/javascript">
var theme;
try { theme = localStorage.getItem('mdbook-theme'); } catch(e) { }
if (theme === null || theme === undefined) { theme = default_theme; }
var html = document.querySelector('html');
html.classList.remove('no-js')
html.classList.remove('light')
html.classList.add(theme);
html.classList.add('js');
</script>
<!-- Hide / unhide sidebar before it is displayed -->
<script type="text/javascript">
var html = document.querySelector('html');
var sidebar = 'hidden';
if (document.body.clientWidth >= 1080) {
try { sidebar = localStorage.getItem('mdbook-sidebar'); } catch(e) { }
sidebar = sidebar || 'visible';
}
html.classList.remove('sidebar-visible');
html.classList.add("sidebar-" + sidebar);
</script>
<nav id="sidebar" class="sidebar" aria-label="Table of contents">
<div class="sidebar-scrollbox">
<ol class="chapter"><li class="chapter-item expanded affix "><a href="../index.html">halo2</a></li><li class="chapter-item expanded "><a href="../concepts.html"><strong aria-hidden="true">1.</strong> Concepts</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="../concepts/proofs.html"><strong aria-hidden="true">1.1.</strong> Proof systems</a></li><li class="chapter-item expanded "><a href="../concepts/arithmetization.html"><strong aria-hidden="true">1.2.</strong> UltraPLONK Arithmetization</a></li><li class="chapter-item expanded "><a href="../concepts/cores.html"><strong aria-hidden="true">1.3.</strong> Cores</a></li><li class="chapter-item expanded "><a href="../concepts/chips.html"><strong aria-hidden="true">1.4.</strong> Chips</a></li><li class="chapter-item expanded "><a href="../concepts/gadgets.html"><strong aria-hidden="true">1.5.</strong> Gadgets</a></li></ol></li><li class="chapter-item expanded "><a href="../user.html"><strong aria-hidden="true">2.</strong> User Documentation</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="../user/simple-example.html" class="active"><strong aria-hidden="true">2.1.</strong> A simple example</a></li><li class="chapter-item expanded "><a href="../user/lookup-tables.html"><strong aria-hidden="true">2.2.</strong> Lookup tables</a></li><li class="chapter-item expanded "><a href="../user/gadgets.html"><strong aria-hidden="true">2.3.</strong> Gadgets</a></li><li class="chapter-item expanded "><a href="../user/tips-and-tricks.html"><strong aria-hidden="true">2.4.</strong> Tips and tricks</a></li></ol></li><li class="chapter-item expanded "><a href="../design.html"><strong aria-hidden="true">3.</strong> Design</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="../design/proving-system.html"><strong aria-hidden="true">3.1.</strong> Proving system</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="../design/proving-system/multipoint-opening.html"><strong aria-hidden="true">3.1.1.</strong> Multipoint opening argument</a></li><li class="chapter-item expanded "><a href="../design/proving-system/permutation.html"><strong aria-hidden="true">3.1.2.</strong> Permutation argument</a></li><li class="chapter-item expanded "><a href="../design/proving-system/lookup-argument.html"><strong aria-hidden="true">3.1.3.</strong> Lookup argument</a></li><li class="chapter-item expanded "><a href="../design/proving-system/comparison.html"><strong aria-hidden="true">3.1.4.</strong> Comparison to other work</a></li></ol></li><li class="chapter-item expanded "><a href="../design/implementation.html"><strong aria-hidden="true">3.2.</strong> Implementation</a></li><li class="chapter-item expanded "><a href="../design/gadgets.html"><strong aria-hidden="true">3.3.</strong> Gadgets</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="../design/gadgets/sha256.html"><strong aria-hidden="true">3.3.1.</strong> SHA-256</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="../design/gadgets/sha256/table16.html"><strong aria-hidden="true">3.3.1.1.</strong> 16-bit table chip</a></li></ol></li></ol></li></ol></li><li class="chapter-item expanded "><a href="../background.html"><strong aria-hidden="true">4.</strong> Background Material</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="../background/fields.html"><strong aria-hidden="true">4.1.</strong> Fields</a></li><li class="chapter-item expanded "><a href="../background/polynomials.html"><strong aria-hidden="true">4.2.</strong> Polynomials</a></li><li class="chapter-item expanded "><a href="../background/groups.html"><strong aria-hidden="true">4.3.</strong> Cryptographic groups</a></li><li class="chapter-item expanded "><a href="../background/curves.html"><strong aria-hidden="true">4.4.</strong> Elliptic curves</a></li><li class="chapter-item expanded "><a href="../background/upa.html"><strong aria-hidden="true">4.5.</strong> UltraPLONK arithmetisation</a></li><li class="chapter-item exp
</div>
<div id="sidebar-resize-handle" class="sidebar-resize-handle"></div>
</nav>
<div id="page-wrapper" class="page-wrapper">
<div class="page">
<div id="menu-bar-hover-placeholder"></div>
<div id="menu-bar" class="menu-bar sticky bordered">
<div class="left-buttons">
<button id="sidebar-toggle" class="icon-button" type="button" title="Toggle Table of Contents" aria-label="Toggle Table of Contents" aria-controls="sidebar">
<i class="fa fa-bars"></i>
</button>
<button id="theme-toggle" class="icon-button" type="button" title="Change theme" aria-label="Change theme" aria-haspopup="true" aria-expanded="false" aria-controls="theme-list">
<i class="fa fa-paint-brush"></i>
</button>
<ul id="theme-list" class="theme-popup" aria-label="Themes" role="menu">
<li role="none"><button role="menuitem" class="theme" id="light">Light (default)</button></li>
<li role="none"><button role="menuitem" class="theme" id="rust">Rust</button></li>
<li role="none"><button role="menuitem" class="theme" id="coal">Coal</button></li>
<li role="none"><button role="menuitem" class="theme" id="navy">Navy</button></li>
<li role="none"><button role="menuitem" class="theme" id="ayu">Ayu</button></li>
</ul>
<button id="search-toggle" class="icon-button" type="button" title="Search. (Shortkey: s)" aria-label="Toggle Searchbar" aria-expanded="false" aria-keyshortcuts="S" aria-controls="searchbar">
<i class="fa fa-search"></i>
</button>
</div>
<h1 class="menu-title">The halo2 Book</h1>
<div class="right-buttons">
<a href="../print.html" title="Print this book" aria-label="Print this book">
<i id="print-button" class="fa fa-print"></i>
</a>
</div>
</div>
<div id="search-wrapper" class="hidden">
<form id="searchbar-outer" class="searchbar-outer">
<input type="search" name="search" id="searchbar" name="searchbar" placeholder="Search this book ..." aria-controls="searchresults-outer" aria-describedby="searchresults-header">
</form>
<div id="searchresults-outer" class="searchresults-outer hidden">
<div id="searchresults-header" class="searchresults-header"></div>
<ul id="searchresults">
</ul>
</div>
</div>
<!-- Apply ARIA attributes after the sidebar and the sidebar toggle button are added to the DOM -->
<script type="text/javascript">
document.getElementById('sidebar-toggle').setAttribute('aria-expanded', sidebar === 'visible');
document.getElementById('sidebar').setAttribute('aria-hidden', sidebar !== 'visible');
Array.from(document.querySelectorAll('#sidebar a')).forEach(function(link) {
link.setAttribute('tabIndex', sidebar === 'visible' ? 0 : -1);
});
</script>
<div id="content" class="content">
<main>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.12.0/dist/katex.min.css" integrity="sha384-AfEj0r4/OFrOo5t7NnNe46zW/tFgW6x/bCJG8FqQCEo3+Aro6EYUG4+cU+KJWu/X" crossorigin="anonymous">
<h1><a class="header" href="#a-simple-example" id="a-simple-example">A simple example</a></h1>
<p>Let's start with a simple circuit, to introduce you to the common APIs and how they are
used. The circuit will take a public input <span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.43056em;vertical-align:0em;"></span><span class="mord mathnormal">c</span></span></span></span>, and will prove knowledge of two private
inputs <span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.43056em;vertical-align:0em;"></span><span class="mord mathnormal">a</span></span></span></span> and <span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.69444em;vertical-align:0em;"></span><span class="mord mathnormal">b</span></span></span></span> such that</p>
<p><span class="katex-display"><span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.8641079999999999em;vertical-align:0em;"></span><span class="mord"><span class="mord mathnormal">a</span><span class="msupsub"><span class="vlist-t"><span class="vlist-r"><span class="vlist" style="height:0.8641079999999999em;"><span style="top:-3.113em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mtight">2</span></span></span></span></span></span></span></span><span class="mspace" style="margin-right:0.2222222222222222em;"></span><span class="mbin"></span><span class="mspace" style="margin-right:0.2222222222222222em;"></span></span><span class="base"><span class="strut" style="height:0.8641079999999999em;vertical-align:0em;"></span><span class="mord"><span class="mord mathnormal">b</span><span class="msupsub"><span class="vlist-t"><span class="vlist-r"><span class="vlist" style="height:0.8641079999999999em;"><span style="top:-3.113em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mtight">2</span></span></span></span></span></span></span></span><span class="mspace" style="margin-right:0.2777777777777778em;"></span><span class="mrel">=</span><span class="mspace" style="margin-right:0.2777777777777778em;"></span></span><span class="base"><span class="strut" style="height:0.43056em;vertical-align:0em;"></span><span class="mord mathnormal">c</span><span class="mord">.</span></span></span></span></span></p>
<h2><a class="header" href="#define-instructions" id="define-instructions">Define instructions</a></h2>
<p>Firstly, we need to define the instructions that our circuit will rely on. Instructions
are the boundary between high-level <a href="../concepts/gadgets.html">gadgets</a> and the low-level
circuit operations. Instructions may be as coarse or as granular as desired, but in
practice you want to strike a balance between an instruction being large enough to
effectively optimize its implementation, and small enough that it is meaningfully
reusable.</p>
<p>For our circuit, we will use three instructions:</p>
<ul>
<li>Load a private number into the circuit.</li>
<li>Multiply two numbers.</li>
<li>Expose a number as a public input to the circuit.</li>
</ul>
<p>We also need a type for a variable representing a number. Instruction interfaces provide
associated types for their inputs and outputs, to allow the implementations to represent
these in a way that makes the most sense for their optimization goals.</p>
<pre><code class="language-rust ignore no_run">trait NumericInstructions: Chip {
/// Variable representing a number.
type Num;
/// Loads a number into the circuit as a private input.
fn load_private(
layouter: &amp;mut impl Layouter&lt;Self&gt;,
a: Option&lt;Self::Field&gt;,
) -&gt; Result&lt;Self::Num, Error&gt;;
/// Returns `c = a * b`.
fn mul(
layouter: &amp;mut impl Layouter&lt;Self&gt;,
a: Self::Num,
b: Self::Num,
) -&gt; Result&lt;Self::Num, Error&gt;;
/// Exposes a number as a public input to the circuit.
fn expose_public(layouter: &amp;mut impl Layouter&lt;Self&gt;, num: Self::Num) -&gt; Result&lt;(), Error&gt;;
}
</code></pre>
<h2><a class="header" href="#define-a-chip-implementation" id="define-a-chip-implementation">Define a chip implementation</a></h2>
<p>For our circuit, we will build a <a href="../concepts/chips.html">chip</a> that provides the above
numeric instructions for a finite field.</p>
<pre><code class="language-rust ignore no_run">/// The chip that will implement our instructions! Chips do not store any persistent state
/// themselves, and usually only contain type markers if necessary.
struct FieldChip&lt;F: FieldExt&gt; {
_marker: PhantomData&lt;F&gt;,
}
</code></pre>
<p>Every chip needs to implement the <code>Chip</code> trait. This defines the properties of the chip
that a <code>Layouter</code> may rely on when synthesizing a circuit, as well as enabling any initial
state that the chip requires to be loaded into the circuit.</p>
<pre><code class="language-rust ignore no_run">impl&lt;F: FieldExt&gt; Chip for FieldChip&lt;F&gt; {
type Config = FieldConfig;
type Field = F;
fn load(_layouter: &amp;mut impl Layouter&lt;Self&gt;) -&gt; Result&lt;(), halo2::plonk::Error&gt; {
// None of the instructions implemented by this chip have any fixed state. But if
// we required e.g. a lookup table, this is where we would load it.
Ok(())
}
}
</code></pre>
<h2><a class="header" href="#configure-the-chip" id="configure-the-chip">Configure the chip</a></h2>
<p>The chip needs to be configured with the columns, permutations, and gates that will be
required to implement all of the desired instructions.</p>
<pre><code class="language-rust ignore no_run">/// Chip state is stored in a separate config struct. This is generated by the chip during
/// configuration, and then handed to the `Layouter`, which makes it available to the chip
/// when it needs to implement its instructions.
#[derive(Clone, Debug)]
struct FieldConfig {
/// For this chip, we will use two advice columns to implement our instructions. These
/// are also the columns through which we communicate with other parts of the circuit.
advice: [Column&lt;Advice&gt;; 2],
// We need to create a permutation between our advice columns. This allows us to
// copy numbers within these columns from arbitrary rows, which we can use to load
// inputs into our instruction regions.
perm: Permutation,
// We need a selector to enable the multiplication gate, so that we aren't placing
// any constraints on cells where `NumericInstructions::mul` is not being used.
// This is important when building larger circuits, where columns are used by
// multiple sets of instructions.
s_mul: Column&lt;Fixed&gt;,
// The selector for the public-input gate, which uses one of the advice columns.
s_pub: Column&lt;Fixed&gt;,
}
impl&lt;F: FieldExt&gt; FieldChip&lt;F&gt; {
fn configure(
meta: &amp;mut ConstraintSystem&lt;F&gt;,
advice: [Column&lt;Advice&gt;; 2],
aux: Column&lt;Aux&gt;,
) -&gt; FieldConfig {
let perm = Permutation::new(meta, &amp;advice);
let s_mul = meta.fixed_column();
let s_pub = meta.fixed_column();
// Define our multiplication gate!
meta.create_gate(&quot;mul&quot;, |meta| {
// To implement multiplication, we need three advice cells and a selector
// cell. We arrange them like so:
//
// | a0 | a1 | s_mul |
// |-----|-----|-------|
// | lhs | rhs | s_mul |
// | out | | |
//
// Gates may refer to any relative offsets we want, but each distinct offset
// adds a cost to the proof. The most common offsets are 0 (the current row),
// 1 (the next row), and -1 (the previous row), for which `Rotation` has
// specific constructors.
let lhs = meta.query_advice(advice[0], Rotation::cur());
let rhs = meta.query_advice(advice[1], Rotation::cur());
let out = meta.query_advice(advice[0], Rotation::next());
let s_mul = meta.query_fixed(s_mul, Rotation::cur());
// The polynomial expression returned from `create_gate` will be constrained
// by the proving system to equal zero. Our expression has the following
// properties:
// - When s_mul = 0, any value is allowed in lhs, rhs, and out.
// - When s_mul != 0, this constrains lhs * rhs = out.
s_mul * (lhs * rhs + out * -F::one())
});
// Define our public-input gate!
meta.create_gate(&quot;public input&quot;, |meta| {
// We choose somewhat-arbitrarily that we will use the second advice column
// for exposing numbers as public inputs.
let a = meta.query_advice(advice[1], Rotation::cur());
let p = meta.query_aux(aux, Rotation::cur());
let s = meta.query_fixed(s_pub, Rotation::cur());
// We simply constrain the advice cell to be equal to the aux cell, when the
// selector is enabled.
s * (p + a * -F::one())
});
FieldConfig {
advice,
perm,
s_mul,
s_pub,
}
}
}
</code></pre>
<h2><a class="header" href="#implement-chip-traits" id="implement-chip-traits">Implement chip traits</a></h2>
<pre><code class="language-rust ignore no_run">/// A variable representing a number.
#[derive(Clone)]
struct Number&lt;F: FieldExt&gt; {
cell: Cell,
value: Option&lt;F&gt;,
}
impl&lt;F: FieldExt&gt; NumericInstructions for FieldChip&lt;F&gt; {
type Num = Number&lt;F&gt;;
fn load_private(
layouter: &amp;mut impl Layouter&lt;Self&gt;,
value: Option&lt;Self::Field&gt;,
) -&gt; Result&lt;Self::Num, Error&gt; {
let config = layouter.config().clone();
let mut num = None;
layouter.assign_region(
|| &quot;load private&quot;,
|mut region| {
let cell = region.assign_advice(
|| &quot;private input&quot;,
config.advice[0],
0,
|| value.ok_or(Error::SynthesisError),
)?;
num = Some(Number { cell, value });
Ok(())
},
)?;
Ok(num.unwrap())
}
fn mul(
layouter: &amp;mut impl Layouter&lt;Self&gt;,
a: Self::Num,
b: Self::Num,
) -&gt; Result&lt;Self::Num, Error&gt; {
let config = layouter.config().clone();
let mut out = None;
layouter.assign_region(
|| &quot;mul&quot;,
|mut region| {
// We only want to use a single multiplication gate in this region, so we
// enable it at region offset 0; this means it will constrain cells at
// offsets 0 and 1.
region.assign_fixed(|| &quot;example mul&quot;, config.s_mul, 0, || Ok(F::one()))?;
// The inputs we've been given could be located anywhere in the circuit,
// but we can only rely on relative offsets inside this region. So we
// assign new cells inside the region and constrain them to have the same
// values as the inputs.
let lhs = region.assign_advice(
|| &quot;lhs&quot;,
config.advice[0],
0,
|| a.value.ok_or(Error::SynthesisError),
)?;
let rhs = region.assign_advice(
|| &quot;rhs&quot;,
config.advice[1],
0,
|| b.value.ok_or(Error::SynthesisError),
)?;
region.constrain_equal(&amp;config.perm, a.cell, lhs)?;
region.constrain_equal(&amp;config.perm, b.cell, rhs)?;
// Now we can assign the multiplication result into the output position.
let value = a.value.and_then(|a| b.value.map(|b| a * b));
let cell = region.assign_advice(
|| &quot;lhs * rhs&quot;,
config.advice[0],
1,
|| value.ok_or(Error::SynthesisError),
)?;
// Finally, we return a variable representing the output, to be used in
// another part of the circuit.
out = Some(Number { cell, value });
Ok(())
},
)?;
Ok(out.unwrap())
}
fn expose_public(layouter: &amp;mut impl Layouter&lt;Self&gt;, num: Self::Num) -&gt; Result&lt;(), Error&gt; {
let config = layouter.config().clone();
layouter.assign_region(
|| &quot;expose public&quot;,
|mut region| {
// Enable the public-input gate.
region.assign_fixed(|| &quot;public result&quot;, config.s_pub, 0, || Ok(F::one()))?;
// Load the output into the correct advice column.
let out = region.assign_advice(
|| &quot;public advice&quot;,
config.advice[1],
0,
|| num.value.ok_or(Error::SynthesisError),
)?;
region.constrain_equal(&amp;config.perm, num.cell, out)?;
// We don't assign to the auxiliary column inside the circuit; the mapping
// of public inputs to cells is provided to the prover.
Ok(())
},
)
}
}
</code></pre>
<h2><a class="header" href="#build-the-circuit" id="build-the-circuit">Build the circuit</a></h2>
<p>Now that we have the instructions we need, and a chip that implements them, we can finally
build our circuit!</p>
<pre><code class="language-rust ignore no_run">/// The full circuit implementation.
///
/// In this struct we store the private input variables. We use `Option&lt;F&gt;` because they
/// won't have any value during key generation. During proving, if any of these were
/// `None` we would get an error.
struct MyCircuit&lt;F: FieldExt&gt; {
a: Option&lt;F&gt;,
b: Option&lt;F&gt;,
}
impl&lt;F: FieldExt&gt; Circuit&lt;F&gt; for MyCircuit&lt;F&gt; {
// Since we are using a single chip for everything, we can just reuse its config.
type Config = FieldConfig;
fn configure(meta: &amp;mut ConstraintSystem&lt;F&gt;) -&gt; Self::Config {
// We create the two advice columns that FieldChip uses for I/O.
let advice = [meta.advice_column(), meta.advice_column()];
// We also need an auxiliary column to store public inputs.
let aux = meta.aux_column();
FieldChip::configure(meta, advice, aux)
}
fn synthesize(&amp;self, cs: &amp;mut impl Assignment&lt;F&gt;, config: Self::Config) -&gt; Result&lt;(), Error&gt; {
let mut layouter = SingleChip::new(cs, config);
// Load our private values into the circuit.
let a = FieldChip::load_private(&amp;mut layouter, self.a)?;
let b = FieldChip::load_private(&amp;mut layouter, self.b)?;
// We only have access to plain multiplication. We could implement our circuit as:
// asq = a*a
// bsq = b*b
// c = asq*bsq
//
// but it's more efficient to implement it as:
// ab = a*b
// c = ab^2
let ab = FieldChip::mul(&amp;mut layouter, a, b)?;
let c = FieldChip::mul(&amp;mut layouter, ab.clone(), ab)?;
// Expose the result as a public input to the circuit.
FieldChip::expose_public(&amp;mut layouter, c)
}
}
</code></pre>
<h2><a class="header" href="#testing-the-circuit" id="testing-the-circuit">Testing the circuit</a></h2>
<p><code>halo2::dev::MockProver</code> can be used to test that the circuit is working correctly. The
private and public inputs to the circuit are constructed as we will do to create a proof,
but by passing them to <code>MockProver::run</code> we get an object that can test every constraint
in the circuit, and tell us exactly what is failing (if anything).</p>
<pre><code class="language-rust ignore no_run"> // The number of rows in our circuit cannot exceed 2^k. Since our example circuit is
// very small, we can pick a very small value here.
let k = 3;
// Prepare the private and public inputs to the circuit!
let a = Fp::from(2);
let b = Fp::from(3);
let c = a.square() * b.square();
// Instantiate the circuit with the private inputs.
let circuit = MyCircuit {
a: Some(a),
b: Some(b),
};
// Arrange the public input. We expose the multiplication result in row 4 of the aux
// column, so we position it there in our public inputs.
let mut public_inputs = vec![Fp::zero(); 1 &lt;&lt; k];
public_inputs[6] = c;
// Given the correct public input, our circuit will verify.
let prover = MockProver::run(k, &amp;circuit, vec![public_inputs.clone()]).unwrap();
assert_eq!(prover.verify(), Ok(()));
// If we try some other public input, the proof will fail!
public_inputs[6] += Fp::one();
let prover = MockProver::run(k, &amp;circuit, vec![public_inputs]).unwrap();
assert_eq!(
prover.verify(),
Err(VerifyFailure::Gate {
gate_index: 1,
gate_name: &quot;public input&quot;,
row: 6,
})
);
</code></pre>
<h2><a class="header" href="#full-example" id="full-example">Full example</a></h2>
<p>You can find the source code for this example
<a href="https://github.com/zcash/halo2/tree/main/examples/simple-example.rs">here</a>.</p>
</main>
<nav class="nav-wrapper" aria-label="Page navigation">
<!-- Mobile navigation buttons -->
<a rel="prev" href="../user.html" class="mobile-nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
<i class="fa fa-angle-left"></i>
</a>
<a rel="next" href="../user/lookup-tables.html" class="mobile-nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
<i class="fa fa-angle-right"></i>
</a>
<div style="clear: both"></div>
</nav>
</div>
</div>
<nav class="nav-wide-wrapper" aria-label="Page navigation">
<a rel="prev" href="../user.html" class="nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
<i class="fa fa-angle-left"></i>
</a>
<a rel="next" href="../user/lookup-tables.html" class="nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
<i class="fa fa-angle-right"></i>
</a>
</nav>
</div>
<script type="text/javascript">
window.playground_copyable = true;
</script>
<script src="../elasticlunr.min.js" type="text/javascript" charset="utf-8"></script>
<script src="../mark.min.js" type="text/javascript" charset="utf-8"></script>
<script src="../searcher.js" type="text/javascript" charset="utf-8"></script>
<script src="../clipboard.min.js" type="text/javascript" charset="utf-8"></script>
<script src="../highlight.js" type="text/javascript" charset="utf-8"></script>
<script src="../book.js" type="text/javascript" charset="utf-8"></script>
<!-- Custom JS scripts -->
</body>
</html>