2020-12-13 09:44:09 -08:00
<!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 >
2021-06-11 15:55:01 -07:00
2020-12-13 09:44:09 -08:00
<!-- 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" / >
2021-06-11 15:55:01 -07:00
< link rel = "icon" href = "../favicon.svg" >
< link rel = "shortcut icon" href = "../favicon.png" >
< link rel = "stylesheet" href = "../css/variables.css" >
2020-12-13 09:44:09 -08:00
< link rel = "stylesheet" href = "../css/general.css" >
< link rel = "stylesheet" href = "../css/chrome.css" >
2021-06-11 15:55:01 -07:00
< link rel = "stylesheet" href = "../css/print.css" media = "print" >
2020-12-13 09:44:09 -08:00
<!-- Fonts -->
< link rel = "stylesheet" href = "../FontAwesome/css/font-awesome.css" >
2021-06-11 15:55:01 -07:00
< link rel = "stylesheet" href = "../fonts/fonts.css" >
2020-12-13 09:44:09 -08:00
<!-- 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 -->
2021-06-11 15:55:01 -07:00
< / head >
2020-12-13 09:44:09 -08:00
< 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" >
2021-06-11 15:55:01 -07:00
< 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/chips.html" > < strong aria-hidden = "true" > 1.3.< / strong > Chips< / a > < / li > < li class = "chapter-item expanded " > < a href = "../concepts/gadgets.html" > < strong aria-hidden = "true" > 1.4.< / 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/dev-tools.html" > < strong aria-hidden = "true" > 2.1.< / strong > Developer tools< / a > < / li > < li class = "chapter-item expanded " > < a href = "../user/simple-example.html" class = "active" > < strong aria-hidden = "true" > 2.2.< / strong > A simple example< / a > < / li > < li class = "chapter-item expanded " > < a href = "../user/lookup-tables.html" > < strong aria-hidden = "true" > 2.3.< / strong > Lookup tables< / a > < / li > < li class = "chapter-item expanded " > < a href = "../user/gadgets.html" > < strong aria-hidden = "true" > 2.4.< / strong > Gadgets< / a > < / li > < li class = "chapter-item expanded " > < a href = "../user/tips-and-tricks.html" > < strong aria-hidden = "true" > 2.5.< / 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/lookup.html" > < strong aria-hidden = "true" > 3.1.1.< / strong > Lookup 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/circuit-commitments.html" > < strong aria-hidden = "true" > 3.1.3.< / strong > Circuit commitments< / a > < / li > < li class = "chapter-item expanded " > < a href = "../design/proving-system/vanishing.html" > < strong aria-hidden = "true" > 3.1.4.< / strong > Vanishing argument< / a > < / li > < li class = "chapter-item expanded " > < a href = "../design/proving-system/multipoint-opening.html" > < strong aria-hidden = "true" > 3.1.5.< / strong > Multipoint opening argument< / a > < / li > < li class = "chapter-item expanded " > < a href = "../design/proving-system/inner-product.html" > < strong aria-hidden = "true" > 3.1.6.< / strong > Inner product argument< / a > < / li > < li class = "chapter-item expanded " > < a href = "../design/proving-system/comparison.html" > < strong aria-hidden = "true" > 3.1.7.< / 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 > < ol class = "section" > < li class = "chapter-item expanded " > < a href = "../design/implementation/proofs.html" > < strong aria-hidden = "true" > 3.2.1.< / strong > Proofs< / a > < / li > < li class = "chapter-item expanded " > < a href = "../design/implementation/fields.html" > < strong aria-hidden = "true" > 3.2.2.< / strong > Fields< / a > < / li > < / ol > < / 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" > < str
2020-12-13 09:44:09 -08:00
< 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 >
2021-06-11 15:55:01 -07:00
< 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" >
2020-12-13 09:44:09 -08:00
< i class = "fa fa-search" > < / i >
< / button >
2021-06-11 15:55:01 -07:00
< / div >
2020-12-13 09:44:09 -08:00
< h1 class = "menu-title" > The halo2 Book< / h1 >
< div class = "right-buttons" >
2021-06-11 15:55:01 -07:00
< a href = "../print.html" title = "Print this book" aria-label = "Print this book" >
2020-12-13 09:44:09 -08:00
< i id = "print-button" class = "fa fa-print" > < / i >
< / a >
2021-06-11 15:55:01 -07:00
2020-12-13 09:44:09 -08:00
< / div >
< / div >
2021-06-11 15:55:01 -07:00
< div id = "search-wrapper" class = "hidden" >
2020-12-13 09:44:09 -08:00
< form id = "searchbar-outer" class = "searchbar-outer" >
2021-06-05 03:42:23 -07:00
< input type = "search" id = "searchbar" name = "searchbar" placeholder = "Search this book ..." aria-controls = "searchresults-outer" aria-describedby = "searchresults-header" >
2020-12-13 09:44:09 -08:00
< / 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" >
2021-06-05 03:42:23 -07:00
< h1 id = "a-simple-example" > < a class = "header" href = "#a-simple-example" > A simple example< / a > < / h1 >
2020-12-13 09:44:09 -08:00
< 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 >
2021-02-09 15:08:01 -08:00
< 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 >
2021-06-05 03:42:23 -07:00
< h2 id = "define-instructions" > < a class = "header" href = "#define-instructions" > Define instructions< / a > < / h2 >
2021-02-09 15:08:01 -08:00
< 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 >
2021-05-03 20:42:25 -07:00
< pre > < code class = "language-rust ignore no_run" > trait NumericInstructions< F: FieldExt> : Chip< F> {
2021-02-09 15:08:01 -08:00
/// Variable representing a number.
type Num;
2020-12-13 09:44:09 -08:00
2021-02-09 15:08:01 -08:00
/// Loads a number into the circuit as a private input.
2021-05-03 20:42:25 -07:00
fn load_private(& self, layouter: impl Layouter< F> , a: Option< F> ) -> Result< Self::Num, Error> ;
2021-02-09 15:08:01 -08:00
/// Returns `c = a * b`.
fn mul(
2021-05-03 20:42:25 -07:00
& self,
layouter: impl Layouter< F> ,
2021-02-09 15:08:01 -08:00
a: Self::Num,
b: Self::Num,
) -> Result< Self::Num, Error> ;
/// Exposes a number as a public input to the circuit.
2021-05-03 20:42:25 -07:00
fn expose_public(& self, layouter: impl Layouter< F> , num: Self::Num) -> Result< (), Error> ;
2021-02-09 15:08:01 -08:00
}
< / code > < / pre >
2021-06-05 03:42:23 -07:00
< h2 id = "define-a-chip-implementation" > < a class = "header" href = "#define-a-chip-implementation" > Define a chip implementation< / a > < / h2 >
2021-02-09 15:08:01 -08:00
< 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 >
2021-05-03 20:42:25 -07:00
< pre > < code class = "language-rust ignore no_run" > /// The chip that will implement our instructions! Chips store their own
/// config, as well as type markers if necessary.
2021-02-09 15:08:01 -08:00
struct FieldChip< F: FieldExt> {
2021-05-03 20:42:25 -07:00
config: FieldConfig,
2021-02-09 15:08:01 -08:00
_marker: PhantomData< F> ,
}
< / 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 >
2021-05-03 20:42:25 -07:00
< pre > < code class = "language-rust ignore no_run" > impl< F: FieldExt> Chip< F> for FieldChip< F> {
2021-02-09 15:08:01 -08:00
type Config = FieldConfig;
2021-02-25 08:06:40 -08:00
type Loaded = ();
2021-02-09 15:08:01 -08:00
2021-05-03 20:42:25 -07:00
fn config(& self) -> & Self::Config {
& self.config
}
fn loaded(& self) -> & Self::Loaded {
& ()
2021-02-09 15:08:01 -08:00
}
}
< / code > < / pre >
2021-06-05 03:42:23 -07:00
< h2 id = "configure-the-chip" > < a class = "header" href = "#configure-the-chip" > Configure the chip< / a > < / h2 >
2021-02-09 15:08:01 -08:00
< 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 >
2021-05-03 20:42:25 -07:00
< pre > < code class = "language-rust ignore no_run" > /// Chip state is stored in a config struct. This is generated by the chip
/// during configuration, and then stored inside the chip.
2021-02-09 15:08:01 -08:00
#[derive(Clone, Debug)]
struct FieldConfig {
2021-02-12 08:15:11 -08:00
/// 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.
2021-02-09 15:08:01 -08:00
advice: [Column< Advice> ; 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.
2021-02-25 08:06:40 -08:00
s_mul: Selector,
2021-02-09 15:08:01 -08:00
// The selector for the public-input gate, which uses one of the advice columns.
2021-02-25 08:06:40 -08:00
s_pub: Selector,
2021-02-09 15:08:01 -08:00
}
impl< F: FieldExt> FieldChip< F> {
2021-05-03 20:42:25 -07:00
fn construct(config: < Self as Chip< F> > ::Config) -> Self {
Self {
config,
_marker: PhantomData,
}
}
2021-02-09 15:08:01 -08:00
fn configure(
meta: & mut ConstraintSystem< F> ,
advice: [Column< Advice> ; 2],
2021-02-15 07:48:26 -08:00
instance: Column< Instance> ,
2021-05-03 20:42:25 -07:00
) -> < Self as Chip< F> > ::Config {
2021-02-17 08:11:56 -08:00
let perm = Permutation::new(
meta,
& advice
.iter()
.map(|column| (*column).into())
.collect::< Vec< _> > (),
);
2021-02-25 08:06:40 -08:00
let s_mul = meta.selector();
let s_pub = meta.selector();
2021-02-09 15:08:01 -08:00
// Define our multiplication gate!
meta.create_gate(" mul" , |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 | | |
//
2021-02-12 08:15:11 -08:00
// 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.
2021-02-09 15:08:01 -08:00
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());
2021-06-11 15:55:01 -07:00
let s_mul = meta.query_selector(s_mul);
2021-02-09 15:08:01 -08:00
2021-06-01 09:25:22 -07:00
// Finally, we return the polynomial expressions that constrain this gate.
// For our multiplication gate, we only need a single polynomial constraint.
//
// The polynomial expressions returned from `create_gate` will be
2021-02-12 08:15:11 -08:00
// constrained by the proving system to equal zero. Our expression
// has the following properties:
2021-02-09 15:08:01 -08:00
// - When s_mul = 0, any value is allowed in lhs, rhs, and out.
// - When s_mul != 0, this constrains lhs * rhs = out.
2021-06-01 09:25:22 -07:00
vec![s_mul * (lhs * rhs + out * -F::one())]
2021-02-09 15:08:01 -08:00
});
// Define our public-input gate!
meta.create_gate(" public input" , |meta| {
2021-02-12 08:15:11 -08:00
// We choose somewhat-arbitrarily that we will use the second advice
// column for exposing numbers as public inputs.
2021-02-09 15:08:01 -08:00
let a = meta.query_advice(advice[1], Rotation::cur());
2021-02-15 07:48:26 -08:00
let p = meta.query_instance(instance, Rotation::cur());
2021-06-11 15:55:01 -07:00
let s = meta.query_selector(s_pub);
2021-02-09 15:08:01 -08:00
2021-02-15 07:48:26 -08:00
// We simply constrain the advice cell to be equal to the instance cell,
2021-02-12 08:15:11 -08:00
// when the selector is enabled.
2021-06-01 09:25:22 -07:00
vec![s * (p + a * -F::one())]
2021-02-09 15:08:01 -08:00
});
FieldConfig {
advice,
perm,
s_mul,
s_pub,
}
}
}
< / code > < / pre >
2021-06-05 03:42:23 -07:00
< h2 id = "implement-chip-traits" > < a class = "header" href = "#implement-chip-traits" > Implement chip traits< / a > < / h2 >
2021-02-09 15:08:01 -08:00
< pre > < code class = "language-rust ignore no_run" > /// A variable representing a number.
#[derive(Clone)]
struct Number< F: FieldExt> {
cell: Cell,
value: Option< F> ,
}
2021-05-03 20:42:25 -07:00
impl< F: FieldExt> NumericInstructions< F> for FieldChip< F> {
2021-02-09 15:08:01 -08:00
type Num = Number< F> ;
fn load_private(
2021-05-03 20:42:25 -07:00
& self,
mut layouter: impl Layouter< F> ,
value: Option< F> ,
2021-02-09 15:08:01 -08:00
) -> Result< Self::Num, Error> {
2021-05-03 20:42:25 -07:00
let config = self.config();
2021-02-09 15:08:01 -08:00
let mut num = None;
layouter.assign_region(
|| " load private" ,
|mut region| {
let cell = region.assign_advice(
|| " private input" ,
config.advice[0],
0,
|| value.ok_or(Error::SynthesisError),
)?;
num = Some(Number { cell, value });
Ok(())
},
)?;
Ok(num.unwrap())
}
fn mul(
2021-05-03 20:42:25 -07:00
& self,
mut layouter: impl Layouter< F> ,
2021-02-09 15:08:01 -08:00
a: Self::Num,
b: Self::Num,
) -> Result< Self::Num, Error> {
2021-05-03 20:42:25 -07:00
let config = self.config();
2021-02-09 15:08:01 -08:00
let mut out = None;
layouter.assign_region(
|| " mul" ,
2021-05-03 20:42:25 -07:00
|mut region: Region< '_, F> | {
2021-02-12 08:15:11 -08:00
// 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.
2021-02-25 08:06:40 -08:00
config.s_mul.enable(& mut region, 0)?;
2021-02-09 15:08:01 -08:00
// 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
2021-02-12 08:15:11 -08:00
// assign new cells inside the region and constrain them to have the
// same values as the inputs.
2021-02-09 15:08:01 -08:00
let lhs = region.assign_advice(
|| " lhs" ,
config.advice[0],
0,
|| a.value.ok_or(Error::SynthesisError),
)?;
let rhs = region.assign_advice(
|| " rhs" ,
config.advice[1],
0,
|| b.value.ok_or(Error::SynthesisError),
)?;
region.constrain_equal(& config.perm, a.cell, lhs)?;
region.constrain_equal(& 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(
|| " lhs * rhs" ,
config.advice[0],
1,
|| value.ok_or(Error::SynthesisError),
)?;
2021-02-12 08:15:11 -08:00
// Finally, we return a variable representing the output,
// to be used in another part of the circuit.
2021-02-09 15:08:01 -08:00
out = Some(Number { cell, value });
Ok(())
},
)?;
Ok(out.unwrap())
}
2021-05-03 20:42:25 -07:00
fn expose_public(& self, mut layouter: impl Layouter< F> , num: Self::Num) -> Result< (), Error> {
let config = self.config();
2021-02-09 15:08:01 -08:00
layouter.assign_region(
|| " expose public" ,
2021-05-03 20:42:25 -07:00
|mut region: Region< '_, F> | {
2021-02-09 15:08:01 -08:00
// Enable the public-input gate.
2021-02-25 08:06:40 -08:00
config.s_pub.enable(& mut region, 0)?;
2021-02-09 15:08:01 -08:00
// Load the output into the correct advice column.
let out = region.assign_advice(
|| " public advice" ,
config.advice[1],
0,
|| num.value.ok_or(Error::SynthesisError),
)?;
region.constrain_equal(& config.perm, num.cell, out)?;
2021-02-15 07:48:26 -08:00
// We don't assign to the instance column inside the circuit;
2021-02-12 08:15:11 -08:00
// the mapping of public inputs to cells is provided to the prover.
2021-02-09 15:08:01 -08:00
Ok(())
},
)
}
}
< / code > < / pre >
2021-06-05 03:42:23 -07:00
< h2 id = "build-the-circuit" > < a class = "header" href = "#build-the-circuit" > Build the circuit< / a > < / h2 >
2021-02-09 15:08:01 -08:00
< 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.
///
2021-02-12 08:15:11 -08:00
/// In this struct we store the private input variables. We use `Option< F> ` because
/// they won't have any value during key generation. During proving, if any of these
/// were `None` we would get an error.
2021-06-22 15:57:53 -07:00
#[derive(Default)]
2020-12-13 09:44:09 -08:00
struct MyCircuit< F: FieldExt> {
2021-02-09 15:08:01 -08:00
a: Option< F> ,
b: Option< F> ,
2020-12-13 09:44:09 -08:00
}
2021-02-09 15:08:01 -08:00
impl< F: FieldExt> Circuit< F> for MyCircuit< F> {
// Since we are using a single chip for everything, we can just reuse its config.
type Config = FieldConfig;
2021-06-22 15:57:53 -07:00
type FloorPlanner = SimpleFloorPlanner;
fn without_witnesses(& self) -> Self {
Self::default()
}
2021-02-09 15:08:01 -08:00
fn configure(meta: & mut ConstraintSystem< F> ) -> Self::Config {
// We create the two advice columns that FieldChip uses for I/O.
let advice = [meta.advice_column(), meta.advice_column()];
2021-02-15 07:48:26 -08:00
// We also need an instance column to store public inputs.
let instance = meta.instance_column();
2021-02-09 15:08:01 -08:00
2021-02-15 07:48:26 -08:00
FieldChip::configure(meta, advice, instance)
2021-02-09 15:08:01 -08:00
}
2021-06-22 15:57:53 -07:00
fn synthesize(
& self,
config: Self::Config,
mut layouter: impl Layouter< F> ,
) -> Result< (), Error> {
2021-05-03 20:42:25 -07:00
let field_chip = FieldChip::< F> ::construct(config);
2021-02-09 15:08:01 -08:00
// Load our private values into the circuit.
2021-05-03 20:42:25 -07:00
let a = field_chip.load_private(layouter.namespace(|| " load a" ), self.a)?;
let b = field_chip.load_private(layouter.namespace(|| " load b" ), self.b)?;
2021-02-09 15:08:01 -08:00
2021-02-12 08:15:11 -08:00
// We only have access to plain multiplication.
// We could implement our circuit as:
2021-02-09 15:08:01 -08:00
// asq = a*a
// bsq = b*b
// c = asq*bsq
//
// but it's more efficient to implement it as:
// ab = a*b
// c = ab^2
2021-05-03 20:42:25 -07:00
let ab = field_chip.mul(layouter.namespace(|| " a * b" ), a, b)?;
let c = field_chip.mul(layouter.namespace(|| " ab * ab" ), ab.clone(), ab)?;
2021-02-09 15:08:01 -08:00
// Expose the result as a public input to the circuit.
2021-05-03 20:42:25 -07:00
field_chip.expose_public(layouter.namespace(|| " expose c" ), c)
2021-02-09 15:08:01 -08:00
}
}
< / code > < / pre >
2021-06-05 03:42:23 -07:00
< h2 id = "testing-the-circuit" > < a class = "header" href = "#testing-the-circuit" > Testing the circuit< / a > < / h2 >
2021-02-09 15:08:01 -08:00
< 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 >
2021-02-12 08:15:11 -08:00
< 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.
2021-02-09 15:08:01 -08:00
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),
};
2021-02-12 08:15:11 -08:00
// Arrange the public input. We expose the multiplication result in row 6
2021-02-15 07:48:26 -08:00
// of the instance column, so we position it there in our public inputs.
2021-02-09 15:08:01 -08:00
let mut public_inputs = vec![Fp::zero(); 1 < < k];
public_inputs[6] = c;
// Given the correct public input, our circuit will verify.
let prover = MockProver::run(k, & 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, & circuit, vec![public_inputs]).unwrap();
assert_eq!(
prover.verify(),
2021-06-05 03:42:23 -07:00
Err(vec![VerifyFailure::Constraint {
2021-02-09 15:08:01 -08:00
gate_index: 1,
gate_name: " public input" ,
2021-06-05 03:42:23 -07:00
constraint_index: 0,
2021-06-05 15:42:43 -07:00
constraint_name: " " ,
2021-02-09 15:08:01 -08:00
row: 6,
2021-05-18 12:17:00 -07:00
}])
2021-02-09 15:08:01 -08:00
);
< / code > < / pre >
2021-06-05 03:42:23 -07:00
< h2 id = "full-example" > < a class = "header" href = "#full-example" > Full example< / a > < / h2 >
2021-02-09 15:08:01 -08:00
< 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 >
2020-12-13 09:44:09 -08:00
< / main >
< nav class = "nav-wrapper" aria-label = "Page navigation" >
<!-- Mobile navigation buttons -->
2021-06-11 15:55:01 -07:00
< a rel = "prev" href = "../user/dev-tools.html" class = "mobile-nav-chapters previous" title = "Previous chapter" aria-label = "Previous chapter" aria-keyshortcuts = "Left" >
2020-12-13 09:44:09 -08:00
< i class = "fa fa-angle-left" > < / i >
< / a >
2021-06-11 15:55:01 -07:00
< a rel = "next" href = "../user/lookup-tables.html" class = "mobile-nav-chapters next" title = "Next chapter" aria-label = "Next chapter" aria-keyshortcuts = "Right" >
2020-12-13 09:44:09 -08:00
< 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" >
2021-06-11 15:55:01 -07:00
< a rel = "prev" href = "../user/dev-tools.html" class = "nav-chapters previous" title = "Previous chapter" aria-label = "Previous chapter" aria-keyshortcuts = "Left" >
2020-12-13 09:44:09 -08:00
< i class = "fa fa-angle-left" > < / i >
< / a >
2021-06-11 15:55:01 -07:00
< a rel = "next" href = "../user/lookup-tables.html" class = "nav-chapters next" title = "Next chapter" aria-label = "Next chapter" aria-keyshortcuts = "Right" >
2020-12-13 09:44:09 -08:00
< i class = "fa fa-angle-right" > < / i >
< / a >
2021-06-11 15:55:01 -07:00
< / nav >
2020-12-13 09:44:09 -08:00
< / div >
2021-06-11 15:55:01 -07:00
< script type = "text/javascript" >
2020-12-13 09:44:09 -08:00
window.playground_copyable = true;
< / script >
2021-06-11 15:55:01 -07:00
< script src = "../elasticlunr.min.js" type = "text/javascript" charset = "utf-8" > < / script >
2020-12-13 09:44:09 -08:00
< 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 >