|
| 1 | +//! Heavily commented example of creating IR representing a circuit for a division gadget. |
| 2 | +//! |
| 3 | +//! The gadget performs the division and constrains the dividend to be equal to the quotient times |
| 4 | +//! the divisor. |
| 5 | +//! |
| 6 | +//! Creates a single struct with two inputs and one output. |
| 7 | +
|
| 8 | +use std::error::Error as StdError; |
| 9 | +use std::result::Result as StdResult; |
| 10 | + |
| 11 | +// Commonly used types are re-exported in the prelude. |
| 12 | +use llzk::{builder::OpBuilder, prelude::*}; |
| 13 | + |
| 14 | +type Result<T> = StdResult<T, Box<dyn StdError>>; |
| 15 | + |
| 16 | +fn main() -> Result<()> { |
| 17 | + // The context preloads the LLZK dialects for convenience. |
| 18 | + let context = LlzkContext::new(); |
| 19 | + // IR objects have a location associated to them. Usually a source location |
| 20 | + // but we won't bother with that in this case. |
| 21 | + let location = Location::unknown(&context); |
| 22 | + // LLZK top-level modules require some additional attributes. |
| 23 | + // This function creates a module preconfigured with these attributes. |
| 24 | + let module = llzk_module(location); |
| 25 | + |
| 26 | + // The entry point of the circuit is always a struct named `@Main`. |
| 27 | + // Operations can be created with factory methods with the same name as the op they create, |
| 28 | + // mimicking its mnemonic (struct.def in this case). |
| 29 | + let main_st = r#struct::def(location, "Main", &[], [])?; |
| 30 | + |
| 31 | + // The inputs of `@Main` must be of type !struct.type<@Signal>. |
| 32 | + // We need to create this struct to generate properly constructed IR. |
| 33 | + let signal_st: StructDefOpRef = module |
| 34 | + .body() |
| 35 | + .insert_operation(0, r#struct::helpers::define_signal_struct(&context)?.into()) |
| 36 | + .try_into()?; |
| 37 | + |
| 38 | + // We store the output of the division in a data field. |
| 39 | + // Fields can have two extra annotations; column and public. |
| 40 | + // The public annotation makes the field an output of the circuit. |
| 41 | + let out_field = { |
| 42 | + let is_column = false; |
| 43 | + let is_public = true; |
| 44 | + r#struct::field(location, "c", FeltType::new(&context), is_column, is_public)? |
| 45 | + }; |
| 46 | + let compute_fn = witness(&context, location, signal_st.r#type().into(), &out_field)?; |
| 47 | + let constrain_fn = constraints(&context, location, signal_st.r#type().into(), &out_field)?; |
| 48 | + |
| 49 | + main_st.body().append_operation(out_field.into()); |
| 50 | + main_st.body().append_operation(compute_fn.into()); |
| 51 | + main_st.body().append_operation(constrain_fn.into()); |
| 52 | + |
| 53 | + // Now that we have filled out the struct we can add it to the module, verify it, and print it. |
| 54 | + module.body().append_operation(main_st.into()); |
| 55 | + // For verifying and printing we need get a reference to the `builtin.module` op representing |
| 56 | + // the module. |
| 57 | + let module_op = module.as_operation(); |
| 58 | + |
| 59 | + if module_op.verify() { |
| 60 | + println!("{module_op}") |
| 61 | + } else { |
| 62 | + eprintln!("Module failed to verify"); |
| 63 | + } |
| 64 | + |
| 65 | + Ok(()) |
| 66 | +} |
| 67 | + |
| 68 | +fn witness<'c>( |
| 69 | + // Context is the type used in melior to represent the MLIRContext. |
| 70 | + // A reference to a LlzkContext can be used as a reference to a Context. |
| 71 | + context: &'c Context, |
| 72 | + location: Location<'c>, |
| 73 | + signal_ty: Type<'c>, |
| 74 | + out_field: &FieldDefOp<'c>, |
| 75 | +) -> Result<Operation<'c>> { |
| 76 | + // The inputs to the functions are public circuit inputs. |
| 77 | + let inputs = vec![(signal_ty, location); 2]; |
| 78 | + let pub_attr = [PublicAttribute::named_attr_pair(context)]; |
| 79 | + let main_ty = StructType::from_str(context, "Main"); |
| 80 | + |
| 81 | + // The functions inside a struct need to have a particular structure. This helper creates the |
| 82 | + // `@compute` function with its proper structure. |
| 83 | + let compute_fn = |
| 84 | + r#struct::helpers::compute_fn(location, main_ty, &inputs, Some(&[&pub_attr, &pub_attr]))?; |
| 85 | + |
| 86 | + // Witness generation is represented by creating an instance of the containing struct, filling |
| 87 | + // its fields, and returning the value of the struct. The `compute_fn` helper |
| 88 | + // inserts a `struct.new` operation followed by a `function.return` operation to represent this. |
| 89 | + // The specific IR for our circuit needs to go in between these two operations. |
| 90 | + // We will insert it using the return op as reference so we need to get ahold of it and the |
| 91 | + // block that contains it. |
| 92 | + let (block, ret_op) = compute_fn |
| 93 | + .region(0)? |
| 94 | + .first_block() |
| 95 | + .and_then(|b| Some((b, b.terminator()?))) |
| 96 | + .unwrap(); |
| 97 | + |
| 98 | + let builder = OpBuilder::new(context); |
| 99 | + |
| 100 | + // To get the inputs we get the arguments and then read the inner value of the signal struct |
| 101 | + // for performing the arithmetic. |
| 102 | + let a = block |
| 103 | + .insert_operation_before( |
| 104 | + ret_op, |
| 105 | + r#struct::readf( |
| 106 | + &builder, |
| 107 | + location, |
| 108 | + FeltType::new(context).into(), |
| 109 | + block.argument(0)?.into(), |
| 110 | + "reg", |
| 111 | + )?, |
| 112 | + ) |
| 113 | + .result(0)?; |
| 114 | + let b = block |
| 115 | + .insert_operation_before( |
| 116 | + ret_op, |
| 117 | + r#struct::readf( |
| 118 | + &builder, |
| 119 | + location, |
| 120 | + FeltType::new(context).into(), |
| 121 | + block.argument(1)?.into(), |
| 122 | + "reg", |
| 123 | + )?, |
| 124 | + ) |
| 125 | + .result(0)?; |
| 126 | + |
| 127 | + // The witness computes c = a / b |
| 128 | + let c = block |
| 129 | + .insert_operation_before(ret_op, felt::div(location, a.into(), b.into())?) |
| 130 | + .result(0)?; |
| 131 | + // The result needs to be written into the output field. For that we need to get the value |
| 132 | + // created by `struct.new` first. |
| 133 | + let self_value = block.first_operation().unwrap().result(0)?; |
| 134 | + // Then use the `struct.writef` operation to commit the value into the signal. |
| 135 | + block.insert_operation_before( |
| 136 | + ret_op, |
| 137 | + r#struct::writef( |
| 138 | + location, |
| 139 | + self_value.into(), |
| 140 | + out_field.field_name(), |
| 141 | + c.into(), |
| 142 | + )?, |
| 143 | + ); |
| 144 | + |
| 145 | + Ok(compute_fn.into()) |
| 146 | +} |
| 147 | + |
| 148 | +fn constraints<'c>( |
| 149 | + context: &'c Context, |
| 150 | + location: Location<'c>, |
| 151 | + signal_ty: Type<'c>, |
| 152 | + out_field: &FieldDefOp<'c>, |
| 153 | +) -> Result<Operation<'c>> { |
| 154 | + // The inputs to the functions are public circuit inputs. |
| 155 | + let inputs = vec![(signal_ty, location); 2]; |
| 156 | + let pub_attr = [PublicAttribute::named_attr_pair(context)]; |
| 157 | + let main_ty = StructType::from_str(context, "Main"); |
| 158 | + |
| 159 | + // The functions inside a struct need to have a particular structure. This helper creates the |
| 160 | + // `@constrain` function with its proper structure. |
| 161 | + let constrain_fn = |
| 162 | + r#struct::helpers::constrain_fn(location, main_ty, &inputs, Some(&[&pub_attr, &pub_attr]))?; |
| 163 | + |
| 164 | + // The constraint system is represented by a function that takes as argument an instance of |
| 165 | + // the parent struct as well as the same inputs the `@compute` function takes. |
| 166 | + // This function returns no values. |
| 167 | + // The `constrain_fn` helper inserts an empty `function.return` operation. |
| 168 | + // |
| 169 | + // Similar to how we generated the IR for `@compute` we need to put the IR before the |
| 170 | + // `function.return` operation. |
| 171 | + let (block, ret_op) = constrain_fn |
| 172 | + .region(0)? |
| 173 | + .first_block() |
| 174 | + .and_then(|b| Some((b, b.terminator()?))) |
| 175 | + .unwrap(); |
| 176 | + |
| 177 | + let builder = OpBuilder::new(context); |
| 178 | + |
| 179 | + // We follow the same steps for obtaining the inputs but with the offsets increased by 1. |
| 180 | + let a = block |
| 181 | + .insert_operation_before( |
| 182 | + ret_op, |
| 183 | + r#struct::readf( |
| 184 | + &builder, |
| 185 | + location, |
| 186 | + FeltType::new(context).into(), |
| 187 | + block.argument(1)?.into(), |
| 188 | + "reg", |
| 189 | + )?, |
| 190 | + ) |
| 191 | + .result(0)?; |
| 192 | + let b = block |
| 193 | + .insert_operation_before( |
| 194 | + ret_op, |
| 195 | + r#struct::readf( |
| 196 | + &builder, |
| 197 | + location, |
| 198 | + FeltType::new(context).into(), |
| 199 | + block.argument(2)?.into(), |
| 200 | + "reg", |
| 201 | + )?, |
| 202 | + ) |
| 203 | + .result(0)?; |
| 204 | + // The instance that we are constraining is passed as the first argument. |
| 205 | + let self_value = block.argument(0)?; |
| 206 | + // And then read the witness output from the instance. |
| 207 | + let c = block |
| 208 | + .insert_operation_before( |
| 209 | + ret_op, |
| 210 | + r#struct::readf( |
| 211 | + &builder, |
| 212 | + location, |
| 213 | + FeltType::new(context).into(), |
| 214 | + self_value.into(), |
| 215 | + out_field.field_name(), |
| 216 | + )?, |
| 217 | + ) |
| 218 | + .result(0)?; |
| 219 | + |
| 220 | + // The constraint is c * b = a |
| 221 | + // We can use the `constrain.eq` operation for emitting equality constraints. |
| 222 | + let t = block |
| 223 | + .insert_operation_before(ret_op, felt::mul(location, c.into(), b.into())?) |
| 224 | + .result(0)?; |
| 225 | + block.insert_operation_before(ret_op, constrain::eq(location, t.into(), a.into())); |
| 226 | + |
| 227 | + Ok(constrain_fn.into()) |
| 228 | +} |
0 commit comments