Barretenberg
The ZK-SNARK library at the core of Aztec
Loading...
Searching...
No Matches
acir_to_constraint_buf.cpp
Go to the documentation of this file.
1// === AUDIT STATUS ===
2// internal: { status: Complete, auditors: [Federico], commit: 2094fd1467dd9a94803b2c5007cf60ac357aa7d2 }
3// external_1: { status: not started, auditors: [], commit: }
4// external_2: { status: not started, auditors: [], commit: }
5// =====================
6
8
9#include <cstddef>
10#include <cstdint>
11#include <map>
12#include <tuple>
13#include <utility>
14
25
26namespace acir_format {
27
28using namespace bb;
29
31
32template <class... Ts> struct overloaded : Ts... {
33 using Ts::operator()...;
34};
35
36bb::fr from_buffer_with_bound_checks(const std::vector<uint8_t>& buffer)
37{
38 BB_ASSERT_EQ(buffer.size(), 32U, "acir_format::from_buffer_with_bound_checks: buffer size must be 32 bytes.");
39 return fr::serialize_from_buffer(buffer.data());
40}
41
43{
44 WitnessOrConstant<bb::fr> result = std::visit(overloaded{ [](const Acir::FunctionInput::Witness& e) {
46 .index = e.value.value,
47 .value = bb::fr::zero(),
48 .is_constant = false,
49 };
50 },
53 .index = bb::stdlib::IS_CONSTANT,
54 .value = from_buffer_with_bound_checks(e.value),
55 .is_constant = true,
56 };
57 } },
58 input.value);
59 return result;
60}
61
63{
65 "acir_format::get_witness_from_function_input: input must be a Witness variant. An error here means "
66 "there was a serialization error.");
67
68 return std::get<Acir::FunctionInput::Witness>(input.value).value.value;
69}
70
71void update_max_witness_index(const uint32_t witness_idx, AcirFormat& af)
72{
73 if (witness_idx != stdlib::IS_CONSTANT) {
74 af.max_witness_index = std::max(af.max_witness_index, witness_idx);
75 }
76}
77
79{
80 // Process multiplication terms: each term has two witness indices
81 for (const auto& mul_term : expr.mul_terms) {
84 }
85
86 // Process linear combinations: each term has one witness index
87 for (const auto& linear_term : expr.linear_combinations) {
89 }
90}
91
93{
94 auto update_max_witness_index_from_function_input = [&](const Acir::FunctionInput& input) {
97 }
98 };
99
100 auto update_max_witness_index_from_witness = [&](const Acir::Witness& witness) {
101 update_max_witness_index(witness.value, af);
102 };
103
104 std::visit(
106 [&](const Acir::Opcode::AssertZero& arg) { update_max_witness_index_from_expression(arg.value, af); },
107 [&](const Acir::Opcode::BlackBoxFuncCall& arg) {
108 std::visit(overloaded{ [&](const Acir::BlackBoxFuncCall::AND& bb_arg) {
109 update_max_witness_index_from_function_input(bb_arg.lhs);
110 update_max_witness_index_from_function_input(bb_arg.rhs);
111 update_max_witness_index_from_witness(bb_arg.output);
112 },
113 [&](const Acir::BlackBoxFuncCall::XOR& bb_arg) {
114 update_max_witness_index_from_function_input(bb_arg.lhs);
115 update_max_witness_index_from_function_input(bb_arg.rhs);
116 update_max_witness_index_from_witness(bb_arg.output);
117 },
118 [&](const Acir::BlackBoxFuncCall::RANGE& bb_arg) {
119 update_max_witness_index_from_function_input(bb_arg.input);
120 },
121 [&](const Acir::BlackBoxFuncCall::AES128Encrypt& bb_arg) {
122 for (const auto& input : bb_arg.inputs) {
123 update_max_witness_index_from_function_input(input);
124 }
125 for (const auto& input : *bb_arg.iv) {
126 update_max_witness_index_from_function_input(input);
127 }
128 for (const auto& input : *bb_arg.key) {
129 update_max_witness_index_from_function_input(input);
130 }
131 for (const auto& output : bb_arg.outputs) {
132 update_max_witness_index_from_witness(output);
133 }
134 },
136 for (const auto& input : *bb_arg.inputs) {
137 update_max_witness_index_from_function_input(input);
138 }
139 for (const auto& input : *bb_arg.hash_values) {
140 update_max_witness_index_from_function_input(input);
141 }
142 for (const auto& output : *bb_arg.outputs) {
143 update_max_witness_index_from_witness(output);
144 }
145 },
146 [&](const Acir::BlackBoxFuncCall::Blake2s& bb_arg) {
147 for (const auto& input : bb_arg.inputs) {
148 update_max_witness_index_from_function_input(input);
149 }
150 for (const auto& output : *bb_arg.outputs) {
151 update_max_witness_index_from_witness(output);
152 }
153 },
154 [&](const Acir::BlackBoxFuncCall::Blake3& bb_arg) {
155 for (const auto& input : bb_arg.inputs) {
156 update_max_witness_index_from_function_input(input);
157 }
158 for (const auto& output : *bb_arg.outputs) {
159 update_max_witness_index_from_witness(output);
160 }
161 },
162 [&](const Acir::BlackBoxFuncCall::EcdsaSecp256k1& bb_arg) {
163 for (const auto& input : *bb_arg.public_key_x) {
164 update_max_witness_index_from_function_input(input);
165 }
166 for (const auto& input : *bb_arg.public_key_y) {
167 update_max_witness_index_from_function_input(input);
168 }
169 for (const auto& input : *bb_arg.signature) {
170 update_max_witness_index_from_function_input(input);
171 }
172 for (const auto& input : *bb_arg.hashed_message) {
173 update_max_witness_index_from_function_input(input);
174 }
175 update_max_witness_index_from_function_input(bb_arg.predicate);
176 update_max_witness_index_from_witness(bb_arg.output);
177 },
178 [&](const Acir::BlackBoxFuncCall::EcdsaSecp256r1& bb_arg) {
179 for (const auto& input : *bb_arg.public_key_x) {
180 update_max_witness_index_from_function_input(input);
181 }
182 for (const auto& input : *bb_arg.public_key_y) {
183 update_max_witness_index_from_function_input(input);
184 }
185 for (const auto& input : *bb_arg.signature) {
186 update_max_witness_index_from_function_input(input);
187 }
188 for (const auto& input : *bb_arg.hashed_message) {
189 update_max_witness_index_from_function_input(input);
190 }
191 update_max_witness_index_from_function_input(bb_arg.predicate);
192 update_max_witness_index_from_witness(bb_arg.output);
193 },
194 [&](const Acir::BlackBoxFuncCall::MultiScalarMul& bb_arg) {
195 for (const auto& input : bb_arg.points) {
196 update_max_witness_index_from_function_input(input);
197 }
198 for (const auto& input : bb_arg.scalars) {
199 update_max_witness_index_from_function_input(input);
200 }
201 update_max_witness_index_from_function_input(bb_arg.predicate);
202 for (const auto& output : *bb_arg.outputs) {
203 update_max_witness_index_from_witness(output);
204 }
205 },
207 for (const auto& input : *bb_arg.input1) {
208 update_max_witness_index_from_function_input(input);
209 }
210 for (const auto& input : *bb_arg.input2) {
211 update_max_witness_index_from_function_input(input);
212 }
213 update_max_witness_index_from_function_input(bb_arg.predicate);
214 for (const auto& output : *bb_arg.outputs) {
215 update_max_witness_index_from_witness(output);
216 }
217 },
218 [&](const Acir::BlackBoxFuncCall::Keccakf1600& bb_arg) {
219 for (const auto& input : *bb_arg.inputs) {
220 update_max_witness_index_from_function_input(input);
221 }
222 for (const auto& output : *bb_arg.outputs) {
223 update_max_witness_index_from_witness(output);
224 }
225 },
227 for (const auto& input : bb_arg.verification_key) {
228 update_max_witness_index_from_function_input(input);
229 }
230 for (const auto& input : bb_arg.proof) {
231 update_max_witness_index_from_function_input(input);
232 }
233 for (const auto& input : bb_arg.public_inputs) {
234 update_max_witness_index_from_function_input(input);
235 }
236 update_max_witness_index_from_function_input(bb_arg.key_hash);
237 update_max_witness_index_from_function_input(bb_arg.predicate);
238 },
240 for (const auto& input : bb_arg.inputs) {
241 update_max_witness_index_from_function_input(input);
242 }
243 for (const auto& output : bb_arg.outputs) {
244 update_max_witness_index_from_witness(output);
245 }
246 } },
247 arg.value.value);
248 },
249 [&](const Acir::Opcode::MemoryInit& arg) {
250 for (const auto& init : arg.init) {
251 update_max_witness_index_from_witness(init);
252 }
253 },
254 [&](const Acir::Opcode::MemoryOp& arg) {
255 update_max_witness_index_from_witness(arg.op.index);
256 update_max_witness_index_from_witness(arg.op.value);
257 },
258 [&](const Acir::Opcode::BrilligCall& arg) {
259 for (const auto& input : arg.inputs) {
260 std::visit(overloaded{
261 [&](const Acir::BrilligInputs::Single& e) {
263 },
264 [&](const Acir::BrilligInputs::Array& e) {
265 for (const auto& expr : e.value) {
267 }
268 },
270 // MemoryArray does not contain witnesses directly, so nothing to do here.
271 },
272 },
273 input.value);
274 }
275 for (const auto& output : arg.outputs) {
276 std::visit(overloaded{
277 [&](const Acir::BrilligOutputs::Simple& e) {
278 update_max_witness_index_from_witness(e.value);
279 },
280 [&](const Acir::BrilligOutputs::Array& e) {
281 for (const auto& witness : e.value) {
282 update_max_witness_index_from_witness(witness);
283 }
284 },
285 },
286 output.value);
287 }
289 },
290 [&](const Acir::Opcode::Call&) {
291 bb::assert_failure("acir_format::update_max_witness_index_from_opcode: Call opcode is not supported.");
292 },
293 },
294 opcode.value);
295}
296
298
299template <typename T>
300T deserialize_msgpack_compact(std::vector<uint8_t>&& buf, std::function<T(msgpack::object const&)> decode_msgpack)
301{
302 BB_ASSERT(!buf.empty(), "deserialize_msgpack_compact: buffer is empty");
303
304 // Expect format marker for msgpack, msgpack-compact or msgpack-tagged
305 const uint8_t FORMAT_MSGPACK = 2;
306 const uint8_t FORMAT_MSGPACK_COMPACT = 3;
307 const uint8_t FORMAT_MSGPACK_TAGGED = 4;
308 uint8_t format_u8 = buf[0];
309 BB_ASSERT(format_u8 == FORMAT_MSGPACK || format_u8 == FORMAT_MSGPACK_COMPACT || format_u8 == FORMAT_MSGPACK_TAGGED,
310 "deserialize_msgpack_compact: expected msgpack format marker (2, 3 or 4), got " +
311 std::to_string(format_u8));
312
313 // Skip the format marker to get the data.
314 const char* buffer = &reinterpret_cast<const char*>(buf.data())[1];
315 size_t size = buf.size() - 1;
316
317 auto oh = msgpack::unpack(buffer, size);
318 auto o = oh.get();
319
320 // Expect ARRAY type for msgpack-compact format
321 if (format_u8 == FORMAT_MSGPACK_COMPACT) {
322 BB_ASSERT(o.type == msgpack::type::ARRAY,
323 "deserialize_msgpack_compact: expected ARRAY type, got " + std::to_string(o.type));
324 }
325
326 return decode_msgpack(o);
327}
328
330{
332 circuit.opcodes.size(), UINT32_MAX, "acir_format::circuit_serde_to_acir_format: too many opcodes in circuit.");
333
334 AcirFormat af;
335 af.num_acir_opcodes = static_cast<uint32_t>(circuit.opcodes.size());
336 af.public_inputs = join({
338 [&](const Acir::Witness& e) {
339 update_max_witness_index(e.value, af);
340 return e.value;
341 }),
343 [&](const Acir::Witness& e) {
344 update_max_witness_index(e.value, af);
345 return e.value;
346 }),
347 });
348 // Map to a pair of: BlockConstraint, and list of opcodes associated with that BlockConstraint
349 // Block constraints are built as we process the opcodes, so we store them in this map and we add them to the
350 // AcirFormat struct at the end
351 // NOTE: We want to deterministically visit this map, so unordered_map should not be used.
353
354 for (size_t i = 0; i < circuit.opcodes.size(); ++i) {
355 const auto& gate = circuit.opcodes[i];
357 std::visit(
359 [&](const Acir::Opcode::AssertZero& arg) { assert_zero_to_quad_constraints(arg, af, i); },
361 [&](const Acir::Opcode::MemoryInit& arg) {
362 auto block = memory_init_to_block_constraint(arg);
363 uint32_t block_id = arg.block_id.value;
364 block_id_to_block_constraint[block_id] = { block, /*opcode_indices=*/{ i } };
365 },
366 [&](const Acir::Opcode::MemoryOp& arg) {
367 auto block = block_id_to_block_constraint.find(arg.block_id.value);
368 if (block == block_id_to_block_constraint.end()) {
369 bb::assert_failure("acir_format::circuit_serde_to_acir_format: unitialized MemoryOp.");
370 }
371 add_memory_op_to_block_constraint(arg, block->second.first);
372 block->second.second.push_back(i);
373 },
374 [&](const Acir::Opcode::BrilligCall&) {},
375 [&](const Acir::Opcode::Call&) {
376 bb::assert_failure("acir_format::circuit_serde_to_acir_format: Call opcode is not supported.");
377 },
378 },
379 gate.value);
380 }
381 // Add the block constraints to the AcirFormat struct
382 for (const auto& [_, block] : block_id_to_block_constraint) {
383 af.block_constraints.push_back(block.first);
384 af.original_opcode_indices.block_constraints.push_back(block.second);
385 }
386
387 return af;
388}
389
390AcirFormat circuit_buf_to_acir_format(std::vector<uint8_t>&& buf)
391{
392 // We need to deserialize into Acir::Program first because the buffer returned by Noir has this structure
393 auto program = deserialize_msgpack_compact<Acir::ProgramWithoutBrillig>(
394 std::move(buf), [](auto o) -> Acir::ProgramWithoutBrillig {
395 Acir::ProgramWithoutBrillig program_wob;
396 try {
397 // Deserialize into a partial structure that ignores the Brillig parts,
398 // so that new opcodes can be added without breaking Barretenberg.
399 o.convert(program_wob);
400 } catch (const msgpack::type_error&) {
401 std::cerr << o << std::endl;
403 "acir_format::circuit_buf_to_acir_format: failed to convert msgpack data to Program");
404 }
405 return program_wob;
406 });
407 BB_ASSERT_EQ(program.functions.size(), 1U, "circuit_buf_to_acir_format: expected single function in ACIR program");
408
409 return circuit_serde_to_acir_format(program.functions[0]);
410}
411
413{
414 // We need to deserialize into WitnessStack first because the buffer returned by Noir has this structure
415 auto witness_stack = deserialize_msgpack_compact<Witnesses::WitnessStack>(std::move(buf), [](auto o) {
416 Witnesses::WitnessStack witness_stack;
417 try {
418 o.convert(witness_stack);
419 } catch (const msgpack::type_error&) {
420 std::cerr << o << std::endl;
422 "acir_format::witness_buf_to_witness_vector: failed to convert msgpack data to WitnessStack");
423 }
424 return witness_stack;
425 });
426 BB_ASSERT_EQ(witness_stack.stack.size(),
427 1U,
428 "acir_format::witness_buf_to_witness_vector: expected single WitnessMap in WitnessStack");
429
430 return witness_map_to_witness_vector(witness_stack.stack[0].witness);
431}
432
434{
435 // Note that the WitnessMap is in increasing order of witness indices because the comparator for the Acir::Witness
436 // is defined in terms of the witness index.
437
438 WitnessVector witness_vector;
439 for (size_t index = 0; const auto& e : witness_map.value) {
440 // ACIR uses a sparse format for WitnessMap where unused witness indices may be left unassigned.
441 // To ensure that witnesses sit at the correct indices in the `WitnessVector`, we fill any indices
442 // which do not exist within the `WitnessMap` with the random values. We use random values instead of zero
443 // because unassigned witnesses indices are not supposed to be used in any constraint, so filling them with a
444 // random value helps catching bugs.
445 while (index < e.first.value) {
446 witness_vector.emplace_back(fr::random_element());
447 index++;
448 }
449 witness_vector.emplace_back(from_buffer_with_bound_checks(e.second));
450 index++;
451 }
452
453 return witness_vector;
454}
455
457
459 std::map<uint32_t, bb::fr>& linear_terms)
460{
461 // Lambda to add next linear term from linear_terms to the mul_quad_ gate and erase it from linear_terms
462 auto add_linear_term_and_erase = [](uint32_t& idx, fr& scaling, std::map<uint32_t, fr>& linear_terms) {
464 idx, bb::stdlib::IS_CONSTANT, "Attempting to override a non-constant witness index in mul_quad_ gate");
465 idx = linear_terms.begin()->first;
466 scaling += linear_terms.begin()->second;
467 linear_terms.erase(idx);
468 };
469
471 // We cannot precompute the exact number of gates that will result from the expression. Therefore, we reserve the
472 // maximum number of gates that could ever be needed: one per multiplication term plus one per linear term. The real
473 // number of gates will in general be lower than this.
474 BB_ASSERT_LTE(arg.mul_terms.size(),
475 SIZE_MAX - linear_terms.size(),
476 "split_into_mul_quad_gates: overflow when reserving space for mul_quad_ gates.");
477 result.reserve(arg.mul_terms.size() + linear_terms.size());
478
479 // Step 1. Add multiplication terms and linear terms with the same witness index
480 for (const auto& mul_term : arg.mul_terms) {
481 result.emplace_back(mul_quad_<fr>{
482 .a = std::get<1>(mul_term).value,
483 .b = std::get<2>(mul_term).value,
484 .c = bb::stdlib::IS_CONSTANT,
485 .d = bb::stdlib::IS_CONSTANT,
486 .mul_scaling = from_buffer_with_bound_checks(std::get<0>(mul_term)),
487 .a_scaling = fr::zero(),
488 .b_scaling = fr::zero(),
489 .c_scaling = fr::zero(),
490 .d_scaling = fr::zero(),
491 .const_scaling = fr::zero(),
492 });
493
494 // Add linear terms corresponding to the witnesses involved in the multiplication term
495 auto& mul_quad = result.back();
496 if (linear_terms.contains(mul_quad.a)) {
497 mul_quad.a_scaling += linear_terms.at(mul_quad.a);
498 linear_terms.erase(mul_quad.a); // Remove it as the linear term for a has been processed
499 }
500 if (linear_terms.contains(mul_quad.b)) {
501 // Note that we enter here only if b is different from a
502 mul_quad.b_scaling += linear_terms.at(mul_quad.b);
503 linear_terms.erase(mul_quad.b); // Remove it as the linear term for b has been processed
504 }
505 }
506
507 // Step 2. Add linear terms to existing gates
508 bool is_first_gate = true;
509 for (auto& mul_quad : result) {
510 if (!linear_terms.empty()) {
511 add_linear_term_and_erase(mul_quad.c, mul_quad.c_scaling, linear_terms);
512 }
513
514 if (is_first_gate) {
515 // First gate contains the constant term and uses all four wires
516 mul_quad.const_scaling = from_buffer_with_bound_checks(arg.q_c);
517 if (!linear_terms.empty()) {
518 add_linear_term_and_erase(mul_quad.d, mul_quad.d_scaling, linear_terms);
519 }
520 is_first_gate = false;
521 }
522 }
523
524 // Step 3. Add remaining linear terms
525 while (!linear_terms.empty()) {
526 // We need to create new mul_quad_ gates to accomodate the remaining linear terms
527 mul_quad_<fr> mul_quad = {
528 .a = bb::stdlib::IS_CONSTANT,
529 .b = bb::stdlib::IS_CONSTANT,
530 .c = bb::stdlib::IS_CONSTANT,
531 .d = bb::stdlib::IS_CONSTANT,
532 .mul_scaling = fr::zero(),
533 .a_scaling = fr::zero(),
534 .b_scaling = fr::zero(),
535 .c_scaling = fr::zero(),
536 .d_scaling = fr::zero(),
537 .const_scaling = fr::zero(),
538 };
539 if (!linear_terms.empty()) {
540 add_linear_term_and_erase(mul_quad.a, mul_quad.a_scaling, linear_terms);
541 }
542 if (!linear_terms.empty()) {
543 add_linear_term_and_erase(mul_quad.b, mul_quad.b_scaling, linear_terms);
544 }
545 if (!linear_terms.empty()) {
546 add_linear_term_and_erase(mul_quad.c, mul_quad.c_scaling, linear_terms);
547 }
548 if (is_first_gate) {
549 // First gate contains the constant term and uses all four wires
551 if (!linear_terms.empty()) {
552 add_linear_term_and_erase(mul_quad.d, mul_quad.d_scaling, linear_terms);
553 }
554 is_first_gate = false;
555 }
556
557 result.emplace_back(mul_quad);
558 }
559
560 BB_ASSERT(!result.empty(),
561 "split_into_mul_quad_gates: resulted in zero gates. This means that there is an expression with no "
562 "multiplication terms and no linear terms.");
563 result.shrink_to_fit();
564
565 return result;
566}
567
569{
570 // Lambda to detect zero gates
571 auto is_zero_gate = [](const mul_quad_<fr>& gate) {
572 return ((gate.mul_scaling == fr(0)) && (gate.a_scaling == fr(0)) && (gate.b_scaling == fr(0)) &&
573 (gate.c_scaling == fr(0)) && (gate.d_scaling == fr(0)) && (gate.const_scaling == fr(0)));
574 };
575
576 auto linear_terms = process_linear_terms(arg.value);
577
578 // Check for unsatisfiable constraint: no variables but a non-zero constant means the circuit requires
579 // `constant == 0` which can never be satisfied.
580 if (arg.value.mul_terms.empty() && linear_terms.empty()) {
582 BB_ASSERT_EQ(constant,
583 fr::zero(),
584 "circuit is unsatisfiable. An AssertZero opcode contains no variables but has a non-zero "
585 "constant, which can never equal zero.");
586 }
587
588 bool is_single_gate = is_single_arithmetic_gate(arg.value, linear_terms);
589 std::vector<mul_quad_<fr>> mul_quads = split_into_mul_quad_gates(arg.value, linear_terms);
590
591 if (is_single_gate) {
592 BB_ASSERT_EQ(mul_quads.size(), 1U, "acir_format::assert_zero_to_quad_constraints: expected a single gate.");
593 auto mul_quad = mul_quads[0];
594
595 af.quad_constraints.push_back(mul_quad);
596 af.original_opcode_indices.quad_constraints.push_back(opcode_index);
597 } else {
598 BB_ASSERT_GT(mul_quads.size(),
599 1U,
600 "acir_format::assert_zero_to_quad_constraints: expected multiple gates but found one.");
601 af.big_quad_constraints.push_back(BigQuadConstraint(mul_quads));
602 af.original_opcode_indices.big_quad_constraints.push_back(opcode_index);
603 }
604
605 for (auto const& mul_quad : mul_quads) {
606 BB_ASSERT(!is_zero_gate(mul_quad),
607 "acir_format::assert_zero_to_quad_constraints: produced an arithmetic zero gate.");
608 }
609}
610
612 AcirFormat& af,
613 size_t opcode_index)
614{
615 auto to_witness_or_constant = [](const Acir::FunctionInput& e) { return parse_input(e); };
616 auto to_witness = [](const Acir::Witness& e) { return e.value; };
617 auto to_witness_from_input = [](const Acir::FunctionInput& e) { return get_witness_from_function_input(e); };
618
619 std::visit(
620 overloaded{ [&](const Acir::BlackBoxFuncCall::AND& arg) {
622 .a = parse_input(arg.lhs),
623 .b = parse_input(arg.rhs),
624 .result = to_witness(arg.output),
625 .num_bits = arg.num_bits,
626 .is_xor_gate = false,
627 });
628 af.original_opcode_indices.logic_constraints.push_back(opcode_index);
629 },
630 [&](const Acir::BlackBoxFuncCall::XOR& arg) {
632 .a = parse_input(arg.lhs),
633 .b = parse_input(arg.rhs),
634 .result = to_witness(arg.output),
635 .num_bits = arg.num_bits,
636 .is_xor_gate = true,
637 });
638 af.original_opcode_indices.logic_constraints.push_back(opcode_index);
639 },
640 [&](const Acir::BlackBoxFuncCall::RANGE& arg) {
643 .num_bits = arg.num_bits,
644 });
645 af.original_opcode_indices.range_constraints.push_back(opcode_index);
646 },
649 .inputs = transform::map(arg.inputs, to_witness_or_constant),
650 .iv = transform::map(*arg.iv, to_witness_or_constant),
651 .key = transform::map(*arg.key, to_witness_or_constant),
652 .outputs = transform::map(arg.outputs, to_witness),
653 });
654 af.original_opcode_indices.aes128_constraints.push_back(opcode_index);
655 },
658 .inputs = transform::map(*arg.inputs, to_witness_or_constant),
659 .hash_values = transform::map(*arg.hash_values, to_witness_or_constant),
660 .result = transform::map(*arg.outputs, to_witness),
661 });
662 af.original_opcode_indices.sha256_compression.push_back(opcode_index);
663 },
664 [&](const Acir::BlackBoxFuncCall::Blake2s& arg) {
666 .inputs = transform::map(arg.inputs, to_witness_or_constant),
667 .result = transform::map(*arg.outputs, to_witness),
668 });
669 af.original_opcode_indices.blake2s_constraints.push_back(opcode_index);
670 },
671 [&](const Acir::BlackBoxFuncCall::Blake3& arg) {
673 .inputs = transform::map(arg.inputs, to_witness_or_constant),
674 .result = transform::map(*arg.outputs, to_witness),
675 });
676 af.original_opcode_indices.blake3_constraints.push_back(opcode_index);
677 },
681 .hashed_message = transform::map(*arg.hashed_message, to_witness_from_input),
682 .signature = transform::map(*arg.signature, to_witness_from_input),
683 .pub_x_indices = transform::map(*arg.public_key_x, to_witness_from_input),
684 .pub_y_indices = transform::map(*arg.public_key_y, to_witness_from_input),
685 .predicate = parse_input(arg.predicate),
686 .result = to_witness(arg.output),
687 });
688 af.original_opcode_indices.ecdsa_k1_constraints.push_back(opcode_index);
689 },
693 .hashed_message = transform::map(*arg.hashed_message, to_witness_from_input),
694 .signature = transform::map(*arg.signature, to_witness_from_input),
695 .pub_x_indices = transform::map(*arg.public_key_x, to_witness_from_input),
696 .pub_y_indices = transform::map(*arg.public_key_y, to_witness_from_input),
697 .predicate = parse_input(arg.predicate),
698 .result = to_witness(arg.output),
699 });
700 af.original_opcode_indices.ecdsa_r1_constraints.push_back(opcode_index);
701 },
704 .points = transform::map(arg.points, to_witness_or_constant),
705 .scalars = transform::map(arg.scalars, to_witness_or_constant),
706 .predicate = parse_input(arg.predicate),
707 .out_point_x = to_witness((*arg.outputs)[0]),
708 .out_point_y = to_witness((*arg.outputs)[1]),
709 });
710 af.original_opcode_indices.multi_scalar_mul_constraints.push_back(opcode_index);
711 },
713 af.ec_add_constraints.push_back(EcAdd{
714 .input1_x = parse_input((*arg.input1)[0]),
715 .input1_y = parse_input((*arg.input1)[1]),
716 .input2_x = parse_input((*arg.input2)[0]),
717 .input2_y = parse_input((*arg.input2)[1]),
718 .predicate = parse_input(arg.predicate),
719 .result_x = to_witness((*arg.outputs)[0]),
720 .result_y = to_witness((*arg.outputs)[1]),
721 });
722 af.original_opcode_indices.ec_add_constraints.push_back(opcode_index);
723 },
725 af.keccak_permutations.push_back(Keccakf1600{
726 .state = transform::map(*arg.inputs, to_witness_or_constant),
727 .result = transform::map(*arg.outputs, to_witness),
728 });
729 af.original_opcode_indices.keccak_permutations.push_back(opcode_index);
730 },
732 auto predicate = parse_input(arg.predicate);
733 if (predicate.is_constant && predicate.value.is_zero()) {
734 // No constraint if the recursion is disabled
735 return;
736 }
737 auto c = RecursionConstraint{
738 .key = transform::map(arg.verification_key, to_witness_from_input),
739 .proof = transform::map(arg.proof, to_witness_from_input),
740 .public_inputs = transform::map(arg.public_inputs, to_witness_from_input),
741 .key_hash = get_witness_from_function_input(arg.key_hash),
742 .proof_type = arg.proof_type,
743 .predicate = predicate,
744 };
745
746 // Add the recursion constraint to the appropriate container based on proof type
747 switch (c.proof_type) {
748 case HONK_ZK:
749 case HONK:
750 case ROLLUP_HONK:
751 case ROOT_ROLLUP_HONK:
752 af.honk_recursion_constraints.push_back(c);
753 af.original_opcode_indices.honk_recursion_constraints.push_back(opcode_index);
754 break;
755 case OINK:
756 case HN:
757 case HN_TAIL:
758 case HN_FINAL:
759 af.hn_recursion_constraints.push_back(c);
760 af.original_opcode_indices.hn_recursion_constraints.push_back(opcode_index);
761 break;
762 case AVM:
763 af.avm_recursion_constraints.push_back(c);
764 af.original_opcode_indices.avm_recursion_constraints.push_back(opcode_index);
765 break;
766 case CHONK:
767 af.chonk_recursion_constraints.push_back(c);
768 af.original_opcode_indices.chonk_recursion_constraints.push_back(opcode_index);
769 break;
770 default:
772 "acir_format::handle_black_box_fun_call: Invalid PROOF_TYPE in RecursionConstraint.");
773 }
774 },
777 .state = transform::map(arg.inputs, to_witness_or_constant),
778 .result = transform::map(arg.outputs, to_witness),
779 });
780 af.original_opcode_indices.poseidon2_constraints.push_back(opcode_index);
781 } },
782 arg.value.value);
783}
784
786{
787 // Noir doesn't distinguish between ROM and RAM table. Therefore, we initialize every table as a ROM table, and
788 // then we make it a RAM table if there is at least one write operation
789 BlockConstraint block{
790 .init = {},
791 .trace = {},
792 .type = BlockType::ROM,
793 .calldata_id = CallDataType::None,
794 };
795
796 for (const auto& init : mem_init.init) {
797 block.init.push_back(init.value);
798 }
799
800 // Databus is only supported for Goblin, non Goblin builders will treat call_data and return_data as normal
801 // array.
803 uint32_t calldata_id = std::get<Acir::BlockType::CallData>(mem_init.block_type.value).value;
804 BB_ASSERT_LTE(calldata_id,
805 MAX_APPS_PER_KERNEL,
806 "acir_format::handle_memory_init: calldata id exceeds kernel + MAX_APPS_PER_KERNEL app columns");
807
808 block.type = BlockType::CallData;
809 block.calldata_id = static_cast<CallDataType>(calldata_id);
811 block.type = BlockType::ReturnData;
812 }
813
814 return block;
815}
816
818{
819 // Acir::MemOp::read is the serialized MemOpKind bool: false = Read, true = Write.
820 AccessType access_type = mem_op.op.read ? AccessType::Write : AccessType::Read;
821 if (access_type == AccessType::Write) {
822 // We are not allowed to write on the databus
824 // Mark the table as a RAM table
825 block.type = BlockType::RAM;
826 }
827
828 MemOp acir_mem_op = MemOp{
829 .access_type = access_type,
830 .index = mem_op.op.index.value,
831 .value = mem_op.op.value.value,
832 };
833 block.trace.push_back(acir_mem_op);
834}
835
837{
838 static constexpr size_t NUM_WIRES = 4; // Equal to the number of wires in the arithmetization
839
840 // If there are more than 4 distinct witnesses in the linear terms, then we need multiple arithmetic gates
841 if (linear_terms.size() > NUM_WIRES) {
842 return false;
843 }
844
845 if (arg.mul_terms.size() > 1) {
846 // If there is more than one multiplication gate, then we need multiple arithmetic gates
847 return false;
848 }
849
850 if (arg.mul_terms.size() == 1) {
851 // In this case we have two witnesses coming from the multiplication term plus the linear terms.
852 // We proceed as follows:
853 // 0. Start from the assumption that all witnesses (from linear terms and multiplication) are distinct
854 // 1. Check if the lhs and rhs witness in the multiplication are already contained in the linear terms
855 // 2. Check if the lhs witness and the rhs witness are equal
856 // 2.a If they are distinct, update the total number of witnesses to be added to wires according to result
857 // of the check at step 1: each distinct witness already in the linear terms subtracts one from the
858 // total
859 // 2.b If they are equal, update the total number of witnesses to be added to wires according to result of
860 // the check at step 1: if the witness is already in the linear terms, it removes one from the total
861
862 // Number of witnesses to be put in wires if the witnesses from the linear terms and the multiplication term are
863 // all different
864 size_t num_witnesses_to_be_put_in_wires = 2 + linear_terms.size();
865
866 uint32_t witness_idx_lhs = std::get<1>(arg.mul_terms[0]).value;
867 uint32_t witness_idx_rhs = std::get<2>(arg.mul_terms[0]).value;
868
869 bool lhs_is_distinct_from_linear_terms = !linear_terms.contains(witness_idx_lhs);
870 bool rhs_is_distinct_from_linear_terms = !linear_terms.contains(witness_idx_rhs);
871
872 if (witness_idx_lhs != witness_idx_rhs) {
873 num_witnesses_to_be_put_in_wires -= lhs_is_distinct_from_linear_terms ? 0U : 1U;
874 num_witnesses_to_be_put_in_wires -= rhs_is_distinct_from_linear_terms ? 0U : 1U;
875 } else {
876 num_witnesses_to_be_put_in_wires -= lhs_is_distinct_from_linear_terms ? 0U : 1U;
877 }
878
879 return num_witnesses_to_be_put_in_wires <= NUM_WIRES;
880 }
881
882 return linear_terms.size() <= NUM_WIRES;
883}
884
886{
887 std::map<uint32_t, bb::fr> linear_terms;
888 for (const auto& linear_term : expr.linear_combinations) {
889 fr selector_value = from_buffer_with_bound_checks(std::get<0>(linear_term));
890 uint32_t witness_idx = std::get<1>(linear_term).value;
891 if (linear_terms.contains(witness_idx)) {
892 linear_terms[witness_idx] += selector_value; // Accumulate coefficients for duplicate witnesses
893 } else {
894 linear_terms[witness_idx] = selector_value;
895 }
896 }
897 return linear_terms;
898}
899
900} // namespace acir_format
#define BB_ASSERT(expression,...)
Definition assert.hpp:70
#define BB_ASSERT_GT(left, right,...)
Definition assert.hpp:113
#define BB_ASSERT_EQ(actual, expected,...)
Definition assert.hpp:83
#define BB_ASSERT_LTE(left, right,...)
Definition assert.hpp:158
#define BB_ASSERT_LT(left, right,...)
Definition assert.hpp:143
Constraint representing a polynomial of degree 1 or 2 that does not fit into a standard UltraHonk ari...
std::unique_ptr< uint8_t[]> buffer
Definition engine.cpp:60
const auto init
Definition fr.bench.cpp:135
void add_memory_op_to_block_constraint(Acir::Opcode::MemoryOp const &mem_op, BlockConstraint &block)
Process memory operation, either read or write, and update the BlockConstraint type accordingly.
AcirFormat circuit_serde_to_acir_format(Acir::Circuit const &circuit)
Convert an Acir::Circuit into an AcirFormat by processing all the opcodes.
WitnessOrConstant< bb::fr > parse_input(const Acir::FunctionInput &input)
Parse an Acir::FunctionInput (which can either be a witness or a constant) into a WitnessOrConstant.
void update_max_witness_index_from_opcode(Acir::Opcode const &opcode, AcirFormat &af)
Update the max witness index by processing all the witness indices contained in the Acir::Opcode.
uint32_t get_witness_from_function_input(const Acir::FunctionInput &input)
Extract the witness index from an Acir::FunctionInput representing a witness.
void update_max_witness_index_from_expression(Acir::Expression const &expr, AcirFormat &af)
Update max_witness_index by processing all witnesses in an Acir::Expression.
WitnessVector witness_buf_to_witness_vector(std::vector< uint8_t > &&buf)
Convert a buffer representing a witness vector into Barretenberg's internal WitnessVector format.
std::vector< mul_quad_< fr > > split_into_mul_quad_gates(Acir::Expression const &arg, std::map< uint32_t, bb::fr > &linear_terms)
========= ACIR OPCODE HANDLERS ========= ///
void update_max_witness_index(const uint32_t witness_idx, AcirFormat &af)
Update the max_witness_index.
WitnessVector witness_map_to_witness_vector(Witnesses::WitnessMap const &witness_map)
Convert from the ACIR-native WitnessMap format to Barretenberg's internal WitnessVector format.
T deserialize_msgpack_compact(std::vector< uint8_t > &&buf, std::function< T(msgpack::object const &)> decode_msgpack)
========= BYTES TO BARRETENBERG'S REPRESENTATION ========= ///
std::vector< bb::fr > WitnessVector
bool is_single_arithmetic_gate(Acir::Expression const &arg, const std::map< uint32_t, bb::fr > &linear_terms)
Given an Acir::Expression and its processed linear terms, determine whether it can be represented by ...
BlockConstraint memory_init_to_block_constraint(Acir::Opcode::MemoryInit const &mem_init)
========= MEMORY OPERATIONS ========== ///
AcirFormat circuit_buf_to_acir_format(std::vector< uint8_t > &&buf)
Convert a buffer representing a circuit into Barretenberg's internal AcirFormat representation.
bb::fr from_buffer_with_bound_checks(const std::vector< uint8_t > &buffer)
========= HELPERS ========= ///
void assert_zero_to_quad_constraints(Acir::Opcode::AssertZero const &arg, AcirFormat &af, size_t opcode_index)
Single entrypoint for processing arithmetic (AssertZero) opcodes.
void add_blackbox_func_call_to_acir_format(Acir::Opcode::BlackBoxFuncCall const &arg, AcirFormat &af, size_t opcode_index)
std::map< uint32_t, bb::fr > process_linear_terms(Acir::Expression const &expr)
========= ACIR OPCODE HANDLERS ========= ///
Cont< OutElem > map(Cont< InElem, Args... > const &in, F &&op)
Definition map.hpp:15
Entry point for Barretenberg command-line interface.
Definition api.hpp:5
field< Bn254FrParams > fr
Definition fr.hpp:155
void assert_failure(std::string const &err)
Definition assert.cpp:11
C join(std::initializer_list< C > to_join)
Definition container.hpp:26
@ SECP256K1
Definition types.hpp:10
@ SECP256R1
Definition types.hpp:10
constexpr decltype(auto) get(::tuplet::tuple< T... > &&t) noexcept
Definition tuple.hpp:13
std::string to_string(bb::avm2::ValueTag tag)
std::variant< AES128Encrypt, AND, XOR, RANGE, Blake2s, Blake3, EcdsaSecp256k1, EcdsaSecp256r1, MultiScalarMul, EmbeddedCurveAdd, Keccakf1600, RecursiveAggregation, Poseidon2Permutation, Sha256Compression > value
Definition acir.hpp:5259
std::variant< Memory, CallData, ReturnData > value
Definition acir.hpp:5733
Acir::PublicInputs return_values
Definition acir.hpp:7235
std::vector< Acir::Opcode > opcodes
Definition acir.hpp:7232
Acir::PublicInputs public_parameters
Definition acir.hpp:7234
std::vector< std::tuple< std::vector< uint8_t >, Acir::Witness > > linear_combinations
Definition acir.hpp:5856
std::vector< uint8_t > q_c
Definition acir.hpp:5857
std::vector< std::tuple< std::vector< uint8_t >, Acir::Witness, Acir::Witness > > mul_terms
Definition acir.hpp:5855
std::variant< Constant, Witness > value
Definition acir.hpp:4288
bool read
Definition acir.hpp:6273
Acir::Witness index
Definition acir.hpp:6274
Acir::Witness value
Definition acir.hpp:6275
Acir::Expression value
Definition acir.hpp:6330
Acir::BlackBoxFuncCall value
Definition acir.hpp:6348
std::vector< Acir::Witness > init
Definition acir.hpp:6415
Acir::BlockType block_type
Definition acir.hpp:6416
std::variant< AssertZero, BlackBoxFuncCall, MemoryOp, MemoryInit, BrilligCall, Call > value
Definition acir.hpp:6592
std::vector< Acir::Witness > value
Definition acir.hpp:7213
uint32_t value
Definition acir.hpp:4233
std::map< Witnesses::Witness, std::vector< uint8_t > > value
std::vector< WitnessOrConstant< bb::fr > > inputs
Barretenberg's representation of ACIR constraints.
std::vector< MultiScalarMul > multi_scalar_mul_constraints
std::vector< Blake2sConstraint > blake2s_constraints
std::vector< Sha256Compression > sha256_compression
std::vector< Poseidon2Constraint > poseidon2_constraints
std::vector< LogicConstraint > logic_constraints
std::vector< EcAdd > ec_add_constraints
std::vector< QuadConstraint > quad_constraints
std::vector< Keccakf1600 > keccak_permutations
std::vector< RecursionConstraint > honk_recursion_constraints
std::vector< Blake3Constraint > blake3_constraints
std::vector< EcdsaConstraint > ecdsa_r1_constraints
std::vector< RangeConstraint > range_constraints
std::vector< BigQuadConstraint > big_quad_constraints
std::vector< AES128Constraint > aes128_constraints
AcirFormatOriginalOpcodeIndices original_opcode_indices
std::vector< BlockConstraint > block_constraints
std::vector< EcdsaConstraint > ecdsa_k1_constraints
std::vector< RecursionConstraint > hn_recursion_constraints
std::vector< uint32_t > public_inputs
std::vector< RecursionConstraint > avm_recursion_constraints
std::vector< RecursionConstraint > chonk_recursion_constraints
std::vector< std::vector< size_t > > block_constraints
std::vector< WitnessOrConstant< bb::fr > > inputs
std::vector< WitnessOrConstant< bb::fr > > inputs
Struct holding the data required to add memory constraints to a circuit.
std::vector< uint32_t > init
Constraints for addition of two points on the Grumpkin curve.
WitnessOrConstant< bb::fr > input1_x
std::array< WitnessOrConstant< bb::fr >, 25 > state
Logic constraint representation in ACIR format.
WitnessOrConstant< fr > a
Memory operation. index is the witness index of the memory location, and value is the witness index o...
std::vector< WitnessOrConstant< bb::fr > > points
std::vector< WitnessOrConstant< bb::fr > > state
RecursionConstraint struct contains information required to recursively verify a proof.
std::array< WitnessOrConstant< bb::fr >, 16 > inputs
========= HELPERS ========= ///
static field random_element(numeric::RNG *engine=nullptr) noexcept
static field serialize_from_buffer(const uint8_t *buffer)
static constexpr field zero()