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
32bb::fr from_buffer_with_bound_checks(const std::vector<uint8_t>& buffer)
33{
34 BB_ASSERT_EQ(buffer.size(), 32U, "acir_format::from_buffer_with_bound_checks: buffer size must be 32 bytes.");
35 return fr::serialize_from_buffer(buffer.data());
36}
37
39{
40 WitnessOrConstant<bb::fr> result = std::visit(
41 [&](auto&& e) {
42 using T = std::decay_t<decltype(e)>;
45 .index = e.value.value,
46 .value = bb::fr::zero(),
47 .is_constant = false,
48 };
51 .index = bb::stdlib::IS_CONSTANT,
52 .value = from_buffer_with_bound_checks(e.value),
53 .is_constant = true,
54 };
55 } else {
56 bb::assert_failure("acir_format::parse_input: unrecognized Acir::FunctionInput variant. An error here "
57 "means there was a serialization error.");
58 }
59 },
60 input.value);
61 return result;
62}
63
65{
67 "acir_format::get_witness_from_function_input: input must be a Witness variant. An error here means "
68 "there was a serialization error.");
69
70 return std::get<Acir::FunctionInput::Witness>(input.value).value.value;
71}
72
73void update_max_witness_index(const uint32_t witness_idx, AcirFormat& af)
74{
75 if (witness_idx != stdlib::IS_CONSTANT) {
76 af.max_witness_index = std::max(af.max_witness_index, witness_idx);
77 }
78}
79
81{
82 // Process multiplication terms: each term has two witness indices
83 for (const auto& mul_term : expr.mul_terms) {
86 }
87
88 // Process linear combinations: each term has one witness index
89 for (const auto& linear_term : expr.linear_combinations) {
91 }
92}
93
95{
96 auto update_max_witness_index_from_function_input = [&](const Acir::FunctionInput& input) {
99 }
100 };
101
102 auto update_max_witness_index_from_witness = [&](const Acir::Witness& witness) {
103 update_max_witness_index(witness.value, af);
104 };
105
106 std::visit(
107 [&](auto&& arg) {
108 using T = std::decay_t<decltype(arg)>;
112 std::visit(
113 [&](auto&& bb_arg) {
114 using BBT = std::decay_t<decltype(bb_arg)>;
117 update_max_witness_index_from_function_input(bb_arg.lhs);
118 update_max_witness_index_from_function_input(bb_arg.rhs);
119 update_max_witness_index_from_witness(bb_arg.output);
121 update_max_witness_index_from_function_input(bb_arg.input);
123 for (const auto& input : bb_arg.inputs) {
124 update_max_witness_index_from_function_input(input);
125 }
126 for (const auto& input : *bb_arg.iv) {
127 update_max_witness_index_from_function_input(input);
128 }
129 for (const auto& input : *bb_arg.key) {
130 update_max_witness_index_from_function_input(input);
131 }
132 for (const auto& output : bb_arg.outputs) {
133 update_max_witness_index_from_witness(output);
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 }
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 }
155 for (const auto& input : *bb_arg.public_key_x) {
156 update_max_witness_index_from_function_input(input);
157 }
158 for (const auto& input : *bb_arg.public_key_y) {
159 update_max_witness_index_from_function_input(input);
160 }
161 for (const auto& input : *bb_arg.signature) {
162 update_max_witness_index_from_function_input(input);
163 }
164 for (const auto& input : *bb_arg.hashed_message) {
165 update_max_witness_index_from_function_input(input);
166 }
167 update_max_witness_index_from_function_input(bb_arg.predicate);
168 update_max_witness_index_from_witness(bb_arg.output);
170 for (const auto& input : bb_arg.points) {
171 update_max_witness_index_from_function_input(input);
172 }
173 for (const auto& input : bb_arg.scalars) {
174 update_max_witness_index_from_function_input(input);
175 }
176 update_max_witness_index_from_function_input(bb_arg.predicate);
177 for (const auto& output : *bb_arg.outputs) {
178 update_max_witness_index_from_witness(output);
179 }
181 for (const auto& input : *bb_arg.input1) {
182 update_max_witness_index_from_function_input(input);
183 }
184 for (const auto& input : *bb_arg.input2) {
185 update_max_witness_index_from_function_input(input);
186 }
187 update_max_witness_index_from_function_input(bb_arg.predicate);
188 for (const auto& output : *bb_arg.outputs) {
189 update_max_witness_index_from_witness(output);
190 }
192 for (const auto& input : *bb_arg.inputs) {
193 update_max_witness_index_from_function_input(input);
194 }
195 for (const auto& output : *bb_arg.outputs) {
196 update_max_witness_index_from_witness(output);
197 }
199 for (const auto& input : bb_arg.verification_key) {
200 update_max_witness_index_from_function_input(input);
201 }
202 for (const auto& input : bb_arg.proof) {
203 update_max_witness_index_from_function_input(input);
204 }
205 for (const auto& input : bb_arg.public_inputs) {
206 update_max_witness_index_from_function_input(input);
207 }
208 update_max_witness_index_from_function_input(bb_arg.key_hash);
209 update_max_witness_index_from_function_input(bb_arg.predicate);
211 for (const auto& input : bb_arg.inputs) {
212 update_max_witness_index_from_function_input(input);
213 }
214 for (const auto& output : bb_arg.outputs) {
215 update_max_witness_index_from_witness(output);
216 }
217 }
218 },
219 arg.value.value);
220 } else if constexpr (std::is_same_v<T, Acir::Opcode::MemoryInit>) {
221 for (const auto& init : arg.init) {
222 update_max_witness_index_from_witness(init);
223 }
224 } else if constexpr (std::is_same_v<T, Acir::Opcode::MemoryOp>) {
227 update_max_witness_index_from_expression(arg.op.operation, af);
229 // Process inputs
230 for (const auto& input : arg.inputs) {
231 std::visit(
232 [&](auto&& e) {
233 using IT = std::decay_t<decltype(e)>;
237 for (const auto& expr : e.value) {
239 }
240 }
241 // MemoryArray contains a BlockId, no direct witnesses to track
242 },
243 input.value);
244 }
245 // Process outputs
246 for (const auto& output : arg.outputs) {
247 std::visit(
248 [&](auto&& e) {
249 using OT = std::decay_t<decltype(e)>;
251 update_max_witness_index_from_witness(e.value);
253 for (const auto& witness : e.value) {
254 update_max_witness_index_from_witness(witness);
255 }
256 }
257 },
258 output.value);
259 }
260 // Process optional predicate
261 if (arg.predicate.has_value()) {
262 update_max_witness_index_from_expression(arg.predicate.value(), af);
263 }
264 } else {
265 bb::assert_failure("acir_format::update_max_witness_index_from_opcode: Unrecognized opcode.");
266 }
267 },
268 opcode.value);
269}
270
272
273template <typename T>
274T deserialize_any_format(std::vector<uint8_t>&& buf,
275 std::function<T(msgpack::object const&)> decode_msgpack,
276 std::function<T(std::vector<uint8_t>)> decode_bincode)
277{
278 // We can't rely on exceptions to try to deserialize binpack, falling back to
279 // msgpack if it fails, because exceptions are (or were) not supported in Wasm
280 // and they are turned off in arch.cmake.
281 //
282 // For now our other option is to check if the data is valid msgpack,
283 // which slows things down, but we can't tell if the first byte of
284 // the data accidentally matches one of our format values.
285 //
286 // Unfortunately this doesn't seem to work either: `msgpack::parse`
287 // returns true for a `bincode` encoded program, and we have to check
288 // whether the value parsed is plausible.
289
290 if (!buf.empty()) {
291 // Once we remove support for legacy bincode format, we should expect to always
292 // have a format marker corresponding to acir::serialization::Format::Msgpack,
293 // but until then a match could be pure coincidence.
294 const uint8_t FORMAT_MSGPACK = 2;
295 const uint8_t FORMAT_MSGPACK_COMPACT = 3;
296 uint8_t format = buf[0];
297 if (format == FORMAT_MSGPACK || format == FORMAT_MSGPACK_COMPACT) {
298 // Skip the format marker to get the data.
299 const char* buffer = &reinterpret_cast<const char*>(buf.data())[1];
300 size_t size = buf.size() - 1;
301 msgpack::null_visitor probe;
302 if (msgpack::parse(buffer, size, probe)) {
303 auto oh = msgpack::unpack(buffer, size);
304 // This has to be on a separate line, see
305 // https://github.com/msgpack/msgpack-c/issues/695#issuecomment-393035172
306 auto o = oh.get();
307 // In experiments bincode data was parsed as 0, so a successful parse is not a guarnatee that it's
308 // msgpack. All the top level formats we look for are MAP or ARRAY types (depending on the format).
309 if (o.type == msgpack::type::MAP || o.type == msgpack::type::ARRAY) {
310 return decode_msgpack(o);
311 }
312 }
313 }
314 // `buf[0] == 1` would indicate bincode starting with a format byte,
315 // but if it's a coincidence and it fails to parse then we can't recover
316 // from it, so let's just acknowledge that for now we don't want to
317 // exercise this code path and treat the whole data as bincode.
318 }
319 return decode_bincode(std::move(buf));
320}
321
323{
325 circuit.opcodes.size(), UINT32_MAX, "acir_format::circuit_serde_to_acir_format: too many opcodes in circuit.");
326
327 AcirFormat af;
328 af.num_acir_opcodes = static_cast<uint32_t>(circuit.opcodes.size());
329 af.public_inputs = join({
331 [&](const Acir::Witness& e) {
332 update_max_witness_index(e.value, af);
333 return e.value;
334 }),
336 [&](const Acir::Witness& e) {
337 update_max_witness_index(e.value, af);
338 return e.value;
339 }),
340 });
341 // Map to a pair of: BlockConstraint, and list of opcodes associated with that BlockConstraint
342 // Block constraints are built as we process the opcodes, so we store them in this map and we add them to the
343 // AcirFormat struct at the end
344 // NOTE: We want to deterministically visit this map, so unordered_map should not be used.
346
347 for (size_t i = 0; i < circuit.opcodes.size(); ++i) {
348 const auto& gate = circuit.opcodes[i];
350 std::visit(
351 [&](auto&& arg) {
352 using T = std::decay_t<decltype(arg)>;
357 } else if constexpr (std::is_same_v<T, Acir::Opcode::MemoryInit>) {
358 auto block = memory_init_to_block_constraint(arg);
359 uint32_t block_id = arg.block_id.value;
360 block_id_to_block_constraint[block_id] = { block, /*opcode_indices=*/{ i } };
361 } else if constexpr (std::is_same_v<T, Acir::Opcode::MemoryOp>) {
362 auto block = block_id_to_block_constraint.find(arg.block_id.value);
363 if (block == block_id_to_block_constraint.end()) {
364 bb::assert_failure("acir_format::circuit_serder_to_acir_format: unitialized MemoryOp.");
365 }
366 add_memory_op_to_block_constraint(arg, block->second.first);
367 block->second.second.push_back(i);
369 // This is a no-op in barretenberg
370 } else {
371 bb::assert_failure("acir_format::circuit_serde_to_acir_format: Unrecognized Acir Opcode. An error "
372 "here means there was a serialization error.");
373 }
374 },
375 gate.value);
376 }
377 // Add the block constraints to the AcirFormat struct
378 for (const auto& [_, block] : block_id_to_block_constraint) {
379 af.block_constraints.push_back(block.first);
380 af.original_opcode_indices.block_constraints.push_back(block.second);
381 }
382
383 return af;
384}
385
387{
388 // We need to deserialize into Acir::Program first because the buffer returned by Noir has this structure
389 auto program = deserialize_any_format<Acir::Program>(
390 std::move(buf),
391 [](auto o) -> Acir::Program {
392 Acir::Program program;
393 try {
394 // Deserialize into a partial structure that ignores the Brillig parts,
395 // so that new opcodes can be added without breaking Barretenberg.
396 Acir::ProgramWithoutBrillig program_wob;
397 o.convert(program_wob);
398 program.functions = program_wob.functions;
399 } catch (const msgpack::type_error&) {
400 std::cerr << o << std::endl;
402 "acir_format::circuit_buf_to_acir_format: failed to convert msgpack data to Program");
403 }
404 return program;
405 },
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_any_format<Witnesses::WitnessStack>(
416 std::move(buf),
417 [](auto o) {
418 Witnesses::WitnessStack witness_stack;
419 try {
420 o.convert(witness_stack);
421 } catch (const msgpack::type_error&) {
422 std::cerr << o << std::endl;
424 "acir_format::witness_buf_to_witness_vector: failed to convert msgpack data to WitnessStack");
425 }
426 return witness_stack;
427 },
429 BB_ASSERT_EQ(witness_stack.stack.size(),
430 1U,
431 "acir_format::witness_buf_to_witness_vector: expected single WitnessMap in WitnessStack");
432
433 return witness_map_to_witness_vector(witness_stack.stack[0].witness);
434}
435
437{
438 // Note that the WitnessMap is in increasing order of witness indices because the comparator for the Acir::Witness
439 // is defined in terms of the witness index.
440
441 WitnessVector witness_vector;
442 for (size_t index = 0; const auto& e : witness_map.value) {
443 // ACIR uses a sparse format for WitnessMap where unused witness indices may be left unassigned.
444 // To ensure that witnesses sit at the correct indices in the `WitnessVector`, we fill any indices
445 // which do not exist within the `WitnessMap` with the random values. We use random values instead of zero
446 // because unassigned witnesses indices are not supposed to be used in any constraint, so filling them with a
447 // random value helps catching bugs.
448 while (index < e.first.value) {
449 witness_vector.emplace_back(fr::random_element());
450 index++;
451 }
452 witness_vector.emplace_back(from_buffer_with_bound_checks(e.second));
453 index++;
454 }
455
456 return witness_vector;
457}
458
460
462 std::map<uint32_t, bb::fr>& linear_terms)
463{
464 // Lambda to add next linear term from linear_terms to the mul_quad_ gate and erase it from linear_terms
465 auto add_linear_term_and_erase = [](uint32_t& idx, fr& scaling, std::map<uint32_t, fr>& linear_terms) {
467 idx, bb::stdlib::IS_CONSTANT, "Attempting to override a non-constant witness index in mul_quad_ gate");
468 idx = linear_terms.begin()->first;
469 scaling += linear_terms.begin()->second;
470 linear_terms.erase(idx);
471 };
472
474 // We cannot precompute the exact number of gates that will result from the expression. Therefore, we reserve the
475 // maximum number of gates that could ever be needed: one per multiplication term plus one per linear term. The real
476 // number of gates will in general be lower than this.
477 BB_ASSERT_LTE(arg.mul_terms.size(),
478 SIZE_MAX - linear_terms.size(),
479 "split_into_mul_quad_gates: overflow when reserving space for mul_quad_ gates.");
480 result.reserve(arg.mul_terms.size() + linear_terms.size());
481
482 // Step 1. Add multiplication terms and linear terms with the same witness index
483 for (const auto& mul_term : arg.mul_terms) {
484 result.emplace_back(mul_quad_<fr>{
485 .a = std::get<1>(mul_term).value,
486 .b = std::get<2>(mul_term).value,
487 .c = bb::stdlib::IS_CONSTANT,
488 .d = bb::stdlib::IS_CONSTANT,
489 .mul_scaling = from_buffer_with_bound_checks(std::get<0>(mul_term)),
490 .a_scaling = fr::zero(),
491 .b_scaling = fr::zero(),
492 .c_scaling = fr::zero(),
493 .d_scaling = fr::zero(),
494 .const_scaling = fr::zero(),
495 });
496
497 // Add linear terms corresponding to the witnesses involved in the multiplication term
498 auto& mul_quad = result.back();
499 if (linear_terms.contains(mul_quad.a)) {
500 mul_quad.a_scaling += linear_terms.at(mul_quad.a);
501 linear_terms.erase(mul_quad.a); // Remove it as the linear term for a has been processed
502 }
503 if (linear_terms.contains(mul_quad.b)) {
504 // Note that we enter here only if b is different from a
505 mul_quad.b_scaling += linear_terms.at(mul_quad.b);
506 linear_terms.erase(mul_quad.b); // Remove it as the linear term for b has been processed
507 }
508 }
509
510 // Step 2. Add linear terms to existing gates
511 bool is_first_gate = true;
512 for (auto& mul_quad : result) {
513 if (!linear_terms.empty()) {
514 add_linear_term_and_erase(mul_quad.c, mul_quad.c_scaling, linear_terms);
515 }
516
517 if (is_first_gate) {
518 // First gate contains the constant term and uses all four wires
519 mul_quad.const_scaling = from_buffer_with_bound_checks(arg.q_c);
520 if (!linear_terms.empty()) {
521 add_linear_term_and_erase(mul_quad.d, mul_quad.d_scaling, linear_terms);
522 }
523 is_first_gate = false;
524 }
525 }
526
527 // Step 3. Add remaining linear terms
528 while (!linear_terms.empty()) {
529 // We need to create new mul_quad_ gates to accomodate the remaining linear terms
530 mul_quad_<fr> mul_quad = {
531 .a = bb::stdlib::IS_CONSTANT,
532 .b = bb::stdlib::IS_CONSTANT,
533 .c = bb::stdlib::IS_CONSTANT,
534 .d = bb::stdlib::IS_CONSTANT,
535 .mul_scaling = fr::zero(),
536 .a_scaling = fr::zero(),
537 .b_scaling = fr::zero(),
538 .c_scaling = fr::zero(),
539 .d_scaling = fr::zero(),
540 .const_scaling = fr::zero(),
541 };
542 if (!linear_terms.empty()) {
543 add_linear_term_and_erase(mul_quad.a, mul_quad.a_scaling, linear_terms);
544 }
545 if (!linear_terms.empty()) {
546 add_linear_term_and_erase(mul_quad.b, mul_quad.b_scaling, linear_terms);
547 }
548 if (!linear_terms.empty()) {
549 add_linear_term_and_erase(mul_quad.c, mul_quad.c_scaling, linear_terms);
550 }
551 if (is_first_gate) {
552 // First gate contains the constant term and uses all four wires
554 if (!linear_terms.empty()) {
555 add_linear_term_and_erase(mul_quad.d, mul_quad.d_scaling, linear_terms);
556 }
557 is_first_gate = false;
558 }
559
560 result.emplace_back(mul_quad);
561 }
562
563 BB_ASSERT(!result.empty(),
564 "split_into_mul_quad_gates: resulted in zero gates. This means that there is an expression with no "
565 "multiplication terms and no linear terms.");
566 result.shrink_to_fit();
567
568 return result;
569}
570
572{
573 // Lambda to detect zero gates
574 auto is_zero_gate = [](const mul_quad_<fr>& gate) {
575 return ((gate.mul_scaling == fr(0)) && (gate.a_scaling == fr(0)) && (gate.b_scaling == fr(0)) &&
576 (gate.c_scaling == fr(0)) && (gate.d_scaling == fr(0)) && (gate.const_scaling == fr(0)));
577 };
578
579 auto linear_terms = process_linear_terms(arg.value);
580 bool is_single_gate = is_single_arithmetic_gate(arg.value, linear_terms);
581 std::vector<mul_quad_<fr>> mul_quads = split_into_mul_quad_gates(arg.value, linear_terms);
582
583 if (is_single_gate) {
584 BB_ASSERT_EQ(mul_quads.size(), 1U, "acir_format::assert_zero_to_quad_constraints: expected a single gate.");
585 auto mul_quad = mul_quads[0];
586
587 af.quad_constraints.push_back(mul_quad);
588 af.original_opcode_indices.quad_constraints.push_back(opcode_index);
589 } else {
590 BB_ASSERT_GT(mul_quads.size(),
591 1U,
592 "acir_format::assert_zero_to_quad_constraints: expected multiple gates but found one.");
593 af.big_quad_constraints.push_back(BigQuadConstraint(mul_quads));
594 af.original_opcode_indices.big_quad_constraints.push_back(opcode_index);
595 }
596
597 for (auto const& mul_quad : mul_quads) {
598 BB_ASSERT(!is_zero_gate(mul_quad),
599 "acir_format::assert_zero_to_quad_constraints: produced an arithmetic zero gate.");
600 }
601}
602
604 AcirFormat& af,
605 size_t opcode_index)
606{
607 auto to_witness_or_constant = [&](const Acir::FunctionInput& e) { return parse_input(e); };
608 auto to_witness = [&](const Acir::Witness& e) { return e.value; };
609 auto to_witness_from_input = [&](const Acir::FunctionInput& e) { return get_witness_from_function_input(e); };
610
611 std::visit(
612 [&](auto&& arg) {
613 using T = std::decay_t<decltype(arg)>;
616 .a = parse_input(arg.lhs),
617 .b = parse_input(arg.rhs),
618 .result = to_witness(arg.output),
619 .num_bits = arg.num_bits,
620 .is_xor_gate = false,
621 });
622 af.original_opcode_indices.logic_constraints.push_back(opcode_index);
625 .a = parse_input(arg.lhs),
626 .b = parse_input(arg.rhs),
627 .result = to_witness(arg.output),
628 .num_bits = arg.num_bits,
629 .is_xor_gate = true,
630 });
631 af.original_opcode_indices.logic_constraints.push_back(opcode_index);
635 .num_bits = arg.num_bits,
636 });
637 af.original_opcode_indices.range_constraints.push_back(opcode_index);
640 .inputs = transform::map(arg.inputs, to_witness_or_constant),
641 .iv = transform::map(*arg.iv, to_witness_or_constant),
642 .key = transform::map(*arg.key, to_witness_or_constant),
643 .outputs = transform::map(arg.outputs, to_witness),
644 });
645 af.original_opcode_indices.aes128_constraints.push_back(opcode_index);
648 .inputs = transform::map(*arg.inputs, to_witness_or_constant),
649 .hash_values = transform::map(*arg.hash_values, to_witness_or_constant),
650 .result = transform::map(*arg.outputs, to_witness),
651 });
652 af.original_opcode_indices.sha256_compression.push_back(opcode_index);
655 .inputs = transform::map(arg.inputs,
656 [&](auto& e) {
657 return Blake2sInput{
658 .blackbox_input = parse_input(e),
659 .num_bits = 8,
660 };
661 }),
662 .result = transform::map(*arg.outputs, to_witness),
663 });
664 af.original_opcode_indices.blake2s_constraints.push_back(opcode_index);
668 arg.inputs,
669 [&](auto& e) { return Blake3Input{ .blackbox_input = parse_input(e), .num_bits = 8 }; }),
670 .result = transform::map(*arg.outputs, to_witness),
671 });
672 af.original_opcode_indices.blake3_constraints.push_back(opcode_index);
674 af.ecdsa_k1_constraints.push_back(EcdsaConstraint{
676 .hashed_message = transform::map(*arg.hashed_message, to_witness_from_input),
677 .signature = transform::map(*arg.signature, to_witness_from_input),
678 .pub_x_indices = transform::map(*arg.public_key_x, to_witness_from_input),
679 .pub_y_indices = transform::map(*arg.public_key_y, to_witness_from_input),
680 .predicate = parse_input(arg.predicate),
681 .result = to_witness(arg.output),
682 });
683 af.original_opcode_indices.ecdsa_k1_constraints.push_back(opcode_index);
685 af.ecdsa_r1_constraints.push_back(EcdsaConstraint{
687 .hashed_message = transform::map(*arg.hashed_message, to_witness_from_input),
688 .signature = transform::map(*arg.signature, to_witness_from_input),
689 .pub_x_indices = transform::map(*arg.public_key_x, to_witness_from_input),
690 .pub_y_indices = transform::map(*arg.public_key_y, to_witness_from_input),
691 .predicate = parse_input(arg.predicate),
692 .result = to_witness(arg.output),
693 });
694 af.original_opcode_indices.ecdsa_r1_constraints.push_back(opcode_index);
696 af.multi_scalar_mul_constraints.push_back(MultiScalarMul{
697 .points = transform::map(arg.points, to_witness_or_constant),
698 .scalars = transform::map(arg.scalars, to_witness_or_constant),
699 .predicate = parse_input(arg.predicate),
700 .out_point_x = to_witness((*arg.outputs)[0]),
701 .out_point_y = to_witness((*arg.outputs)[1]),
702 .out_point_is_infinite = to_witness((*arg.outputs)[2]),
703 });
704 af.original_opcode_indices.multi_scalar_mul_constraints.push_back(opcode_index);
706 af.ec_add_constraints.push_back(EcAdd{
707 .input1_x = parse_input((*arg.input1)[0]),
708 .input1_y = parse_input((*arg.input1)[1]),
709 .input1_infinite = parse_input((*arg.input1)[2]),
710 .input2_x = parse_input((*arg.input2)[0]),
711 .input2_y = parse_input((*arg.input2)[1]),
712 .input2_infinite = parse_input((*arg.input2)[2]),
713 .predicate = parse_input(arg.predicate),
714 .result_x = to_witness((*arg.outputs)[0]),
715 .result_y = to_witness((*arg.outputs)[1]),
716 .result_infinite = to_witness((*arg.outputs)[2]),
717 });
718 af.original_opcode_indices.ec_add_constraints.push_back(opcode_index);
720 af.keccak_permutations.push_back(Keccakf1600{
721 .state = transform::map(*arg.inputs, to_witness_or_constant),
722 .result = transform::map(*arg.outputs, to_witness),
723 });
724 af.original_opcode_indices.keccak_permutations.push_back(opcode_index);
726 auto predicate = parse_input(arg.predicate);
727 if (predicate.is_constant && predicate.value.is_zero()) {
728 // No constraint if the recursion is disabled
729 return;
730 }
731 auto c = RecursionConstraint{
732 .key = transform::map(arg.verification_key, to_witness_from_input),
733 .proof = transform::map(arg.proof, to_witness_from_input),
734 .public_inputs = transform::map(arg.public_inputs, to_witness_from_input),
735 .key_hash = get_witness_from_function_input(arg.key_hash),
736 .proof_type = arg.proof_type,
737 .predicate = predicate,
738 };
739
740 // Add the recursion constraint to the appropriate container based on proof type
741 switch (c.proof_type) {
742 case HONK_ZK:
743 case HONK:
744 case ROLLUP_HONK:
745 case ROOT_ROLLUP_HONK:
746 af.honk_recursion_constraints.push_back(c);
747 af.original_opcode_indices.honk_recursion_constraints.push_back(opcode_index);
748 break;
749 case OINK:
750 case HN:
751 case HN_TAIL:
752 case HN_FINAL:
753 af.hn_recursion_constraints.push_back(c);
754 af.original_opcode_indices.hn_recursion_constraints.push_back(opcode_index);
755 break;
756 case AVM:
757 af.avm_recursion_constraints.push_back(c);
758 af.original_opcode_indices.avm_recursion_constraints.push_back(opcode_index);
759 break;
760 case CHONK:
761 af.chonk_recursion_constraints.push_back(c);
762 af.original_opcode_indices.chonk_recursion_constraints.push_back(opcode_index);
763 break;
764 default:
766 "acir_format::handle_black_box_fun_call: Invalid PROOF_TYPE in RecursionConstraint.");
767 }
769 af.poseidon2_constraints.push_back(Poseidon2Constraint{
770 .state = transform::map(arg.inputs, to_witness_or_constant),
771 .result = transform::map(arg.outputs, to_witness),
772 });
773 af.original_opcode_indices.poseidon2_constraints.push_back(opcode_index);
774 } else {
775 bb::assert_failure("acir_format::handle_blackbox_func_call: Unrecognized BlackBoxFuncCall variant. An "
776 "error here means there was a serialization error.");
777 }
778 },
779 arg.value.value);
780}
781
783{
784 // Noir doesn't distinguish between ROM and RAM table. Therefore, we initialize every table as a ROM table, and
785 // then we make it a RAM table if there is at least one write operation
786 BlockConstraint block{
787 .init = {},
788 .trace = {},
789 .type = BlockType::ROM,
790 .calldata_id = CallDataType::None,
791 };
792
793 for (const auto& init : mem_init.init) {
794 block.init.push_back(init.value);
795 }
796
797 // Databus is only supported for Goblin, non Goblin builders will treat call_data and return_data as normal
798 // array.
800 uint32_t calldata_id = std::get<Acir::BlockType::CallData>(mem_init.block_type.value).value;
801 BB_ASSERT(calldata_id == 0 || calldata_id == 1, "acir_format::handle_memory_init: Unsupported calldata id");
802
803 block.type = BlockType::CallData;
804 block.calldata_id = calldata_id == 0 ? CallDataType::Primary : CallDataType::Secondary;
806 block.type = BlockType::ReturnData;
807 }
808
809 return block;
810}
811
813{
814 // Lambda to convert an Acir::Expression to a witness index
815 auto acir_expression_to_witness_or_constant = [&](const Acir::Expression& expr) {
816 // Noir gives us witnesses or constants for read/write operations. We use the following assertions to ensure
817 // that the data coming from Noir is in the correct form.
818 BB_ASSERT(expr.mul_terms.empty(), "MemoryOp should not have multiplication terms");
819 BB_ASSERT_LTE(expr.linear_combinations.size(), 1U, "MemoryOp should have at most one linear term");
820
821 const fr a_scaling = expr.linear_combinations.size() == 1
822 ? from_buffer_with_bound_checks(std::get<0>(expr.linear_combinations[0]))
823 : fr::zero();
824 const fr constant_term = from_buffer_with_bound_checks(expr.q_c);
825
826 bool is_witness = a_scaling == fr::one() && constant_term == fr::zero();
827 bool is_constant = a_scaling == fr::zero();
828 BB_ASSERT(is_witness || is_constant, "MemoryOp expression must be a witness or a constant");
829
831 .index = is_witness ? std::get<1>(expr.linear_combinations[0]).value : bb::stdlib::IS_CONSTANT,
832 .value = is_constant ? constant_term : fr::zero(),
833 .is_constant = is_constant,
834 };
835 };
836
837 // Lambda to determine whether a memory operation is a read or write operation
838 auto is_read_operation = [&](const Acir::Expression& expr) {
839 BB_ASSERT(expr.mul_terms.empty(), "MemoryOp expression should not have multiplication terms");
840 BB_ASSERT(expr.linear_combinations.empty(), "MemoryOp expression should not have linear terms");
841
842 const fr const_term = from_buffer_with_bound_checks(expr.q_c);
843
844 BB_ASSERT((const_term == fr::one()) || (const_term == fr::zero()),
845 "MemoryOp expression should be either zero or one");
846
847 // A read operation is given by a zero Expression
848 return const_term == fr::zero();
849 };
850
851 AccessType access_type = is_read_operation(mem_op.op.operation) ? AccessType::Read : AccessType::Write;
852 if (access_type == AccessType::Write) {
853 // We are not allowed to write on the databus
854 BB_ASSERT((block.type != BlockType::CallData) && (block.type != BlockType::ReturnData));
855 // Mark the table as a RAM table
856 block.type = BlockType::RAM;
857 }
858
859 // Update the ranges of the index using the array length
860 WitnessOrConstant<bb::fr> index = acir_expression_to_witness_or_constant(mem_op.op.index);
861 WitnessOrConstant<bb::fr> value = acir_expression_to_witness_or_constant(mem_op.op.value);
862
863 MemOp acir_mem_op = MemOp{ .access_type = access_type, .index = index, .value = value };
864 block.trace.push_back(acir_mem_op);
865}
866
868{
869 static constexpr size_t NUM_WIRES = 4; // Equal to the number of wires in the arithmetization
870
871 // If there are more than 4 distinct witnesses in the linear terms, then we need multiple arithmetic gates
872 if (linear_terms.size() > NUM_WIRES) {
873 return false;
874 }
875
876 if (arg.mul_terms.size() > 1) {
877 // If there is more than one multiplication gate, then we need multiple arithmetic gates
878 return false;
879 }
880
881 if (arg.mul_terms.size() == 1) {
882 // In this case we have two witnesses coming from the multiplication term plus the linear terms.
883 // We proceed as follows:
884 // 0. Start from the assumption that all witnesses (from linear terms and multiplication) are distinct
885 // 1. Check if the lhs and rhs witness in the multiplication are already contained in the linear terms
886 // 2. Check if the lhs witness and the rhs witness are equal
887 // 2.a If they are distinct, update the total number of witnesses to be added to wires according to result
888 // of the check at step 1: each distinct witness already in the linear terms subtracts one from the
889 // total
890 // 2.b If they are equal, update the total number of witnesses to be added to wires according to result of
891 // the check at step 1: if the witness is already in the linear terms, it removes one from the total
892
893 // Number of witnesses to be put in wires if the witnesses from the linear terms and the multiplication term are
894 // all different
895 size_t num_witnesses_to_be_put_in_wires = 2 + linear_terms.size();
896
897 uint32_t witness_idx_lhs = std::get<1>(arg.mul_terms[0]).value;
898 uint32_t witness_idx_rhs = std::get<2>(arg.mul_terms[0]).value;
899
900 bool lhs_is_distinct_from_linear_terms = !linear_terms.contains(witness_idx_lhs);
901 bool rhs_is_distinct_from_linear_terms = !linear_terms.contains(witness_idx_rhs);
902
903 if (witness_idx_lhs != witness_idx_rhs) {
904 num_witnesses_to_be_put_in_wires -= lhs_is_distinct_from_linear_terms ? 0U : 1U;
905 num_witnesses_to_be_put_in_wires -= rhs_is_distinct_from_linear_terms ? 0U : 1U;
906 } else {
907 num_witnesses_to_be_put_in_wires -= lhs_is_distinct_from_linear_terms ? 0U : 1U;
908 }
909
910 return num_witnesses_to_be_put_in_wires <= NUM_WIRES;
911 }
912
913 return linear_terms.size() <= NUM_WIRES;
914}
915
917{
918 std::map<uint32_t, bb::fr> linear_terms;
919 for (const auto& linear_term : expr.linear_combinations) {
920 fr selector_value = from_buffer_with_bound_checks(std::get<0>(linear_term));
921 uint32_t witness_idx = std::get<1>(linear_term).value;
922 if (linear_terms.contains(witness_idx)) {
923 linear_terms[witness_idx] += selector_value; // Accumulate coefficients for duplicate witnesses
924 } else {
925 linear_terms[witness_idx] = selector_value;
926 }
927 }
928 return linear_terms;
929}
930
931} // namespace acir_format
#define BB_ASSERT(expression,...)
Definition assert.hpp:80
#define BB_ASSERT_GT(left, right,...)
Definition assert.hpp:123
#define BB_ASSERT_EQ(actual, expected,...)
Definition assert.hpp:93
#define BB_ASSERT_LTE(left, right,...)
Definition assert.hpp:168
#define BB_ASSERT_LT(left, right,...)
Definition assert.hpp:153
Constraint representing a polynomial of degree 1 or 2 that does not fit into a standard UltraHonk ari...
std::string format(Args... args)
Definition log.hpp:24
uint8_t const * buf
Definition data_store.hpp:9
uint8_t buffer[RANDOM_BUFFER_SIZE]
Definition engine.cpp:34
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.
T deserialize_any_format(std::vector< uint8_t > &&buf, std::function< T(msgpack::object const &)> decode_msgpack, std::function< T(std::vector< uint8_t >)> decode_bincode)
========= BYTES TO BARRETENBERG'S REPRESENTATION ========= ///
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.
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:174
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::variant< Memory, CallData, ReturnData > value
Definition acir.hpp:3914
Acir::PublicInputs return_values
Definition acir.hpp:5008
std::vector< Acir::Opcode > opcodes
Definition acir.hpp:5005
Acir::PublicInputs public_parameters
Definition acir.hpp:5007
std::vector< std::tuple< std::vector< uint8_t >, Acir::Witness > > linear_combinations
Definition acir.hpp:4000
std::vector< uint8_t > q_c
Definition acir.hpp:4001
std::vector< std::tuple< std::vector< uint8_t >, Acir::Witness, Acir::Witness > > mul_terms
Definition acir.hpp:3999
std::variant< Constant, Witness > value
Definition acir.hpp:2962
Acir::Expression value
Definition acir.hpp:4323
Acir::Expression operation
Definition acir.hpp:4321
Acir::Expression index
Definition acir.hpp:4322
Acir::Expression value
Definition acir.hpp:4359
std::vector< Acir::Witness > init
Definition acir.hpp:4432
Acir::BlockType block_type
Definition acir.hpp:4433
std::variant< AssertZero, BlackBoxFuncCall, MemoryOp, MemoryInit, BrilligCall, Call > value
Definition acir.hpp:4546
std::vector< Acir::Circuit > functions
Definition acir.hpp:5087
static Program bincodeDeserialize(std::vector< uint8_t >)
Definition acir.hpp:11509
std::vector< Acir::Circuit > functions
Definition acir.hpp:5119
std::vector< Acir::Witness > value
Definition acir.hpp:4983
std::map< Witnesses::Witness, std::vector< uint8_t > > value
static WitnessStack bincodeDeserialize(std::vector< uint8_t >)
std::vector< WitnessOrConstant< bb::fr > > inputs
Barretenberg's representation of ACIR constraints.
std::vector< Blake2sConstraint > blake2s_constraints
std::vector< Sha256Compression > sha256_compression
std::vector< LogicConstraint > logic_constraints
std::vector< QuadConstraint > quad_constraints
std::vector< Blake3Constraint > blake3_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< uint32_t > public_inputs
std::vector< std::vector< size_t > > block_constraints
std::vector< Blake2sInput > inputs
std::vector< Blake3Input > inputs
Struct holding the data required to add memory constraints to a circuit.
std::vector< uint32_t > init
Logic constraint representation in ACIR format.
WitnessOrConstant< fr > a
Memory operation. Index and value store the index of the memory location, and value is the value to b...
std::array< WitnessOrConstant< bb::fr >, 16 > inputs
static constexpr field one()
static field random_element(numeric::RNG *engine=nullptr) noexcept
static field serialize_from_buffer(const uint8_t *buffer)
static constexpr field zero()