Barretenberg
The ZK-SNARK library at the core of Aztec
Loading...
Searching...
No Matches
ultra_circuit_builder.cpp
Go to the documentation of this file.
1// === AUDIT STATUS ===
2// internal: { status: Complete, auditors: [Luke, Raju], commit: }
3// external_1: { status: not started, auditors: [], commit: }
4// external_2: { status: not started, auditors: [], commit: }
5// =====================
6
16#include "rom_ram_logic.hpp"
17
20#include <execution>
21#include <unordered_map>
22#include <unordered_set>
23
24namespace bb {
25
26template <typename ExecutionTrace> void UltraCircuitBuilder_<ExecutionTrace>::finalize_circuit()
27{
53 if (!this->circuit_finalized) {
54 process_non_native_field_multiplications();
55#ifndef ULTRA_FUZZ
56 this->rom_ram_logic.process_ROM_arrays(this);
57 this->rom_ram_logic.process_RAM_arrays(this);
58 process_range_lists();
59#endif
60 populate_public_inputs_block();
61 this->circuit_finalized = true;
62 } else {
63 // Gates added after first call to finalize will not be processed since finalization is only performed once
64 info("WARNING: Redundant call to finalize_circuit(). Is this intentional?");
65 }
66}
67
72{
73 BB_BENCH_NAME("populate_public_inputs_block");
74
75 // Update the public inputs block
76 for (const auto& idx : this->public_inputs()) {
77 // first two wires get a copy of the public inputs
78 blocks.pub_inputs.populate_wires(idx, idx, this->zero_idx(), this->zero_idx());
79 for (auto& selector : this->blocks.pub_inputs.get_selectors()) {
80 selector.emplace_back(0);
81 }
82 }
83}
84
93template <typename ExecutionTrace> void UltraCircuitBuilder_<ExecutionTrace>::create_add_gate(const add_triple_<FF>& in)
94{
95 // Delegate to create_big_add_gate with 4th wire set to zero
96 create_big_add_gate({ .a = in.a,
97 .b = in.b,
98 .c = in.c,
99 .d = this->zero_idx(),
100 .a_scaling = in.a_scaling,
101 .b_scaling = in.b_scaling,
102 .c_scaling = in.c_scaling,
103 .d_scaling = 0,
104 .const_scaling = in.const_scaling });
105}
106
115template <typename ExecutionTrace>
117 const bool include_next_gate_w_4)
118{
119 this->assert_valid_variables({ in.a, in.b, in.c, in.d });
120 blocks.arithmetic.populate_wires(in.a, in.b, in.c, in.d);
121 // If include_next_gate_w_4 is true then we set q_arith = 2. In this case, the linear term in the ArithmeticRelation
122 // is scaled by a factor of 2. We compensate here by scaling the quadratic term by 2 to achieve the constraint:
123 // 2 * [q_m * w_1 * w_2 + \sum_{i=1..4} q_i * w_i + q_c + w_4_shift] = 0
124 const FF mul_scaling = include_next_gate_w_4 ? in.mul_scaling * FF(2) : in.mul_scaling;
125 blocks.arithmetic.q_m().emplace_back(mul_scaling);
126 blocks.arithmetic.q_1().emplace_back(in.a_scaling);
127 blocks.arithmetic.q_2().emplace_back(in.b_scaling);
128 blocks.arithmetic.q_3().emplace_back(in.c_scaling);
129 blocks.arithmetic.q_c().emplace_back(in.const_scaling);
130 blocks.arithmetic.q_4().emplace_back(in.d_scaling);
131 blocks.arithmetic.set_gate_selector(include_next_gate_w_4 ? 2 : 1);
132 check_selector_length_consistency();
133 this->increment_num_gates();
134}
135
144template <typename ExecutionTrace>
146 const bool include_next_gate_w_4)
147{
148 this->assert_valid_variables({ in.a, in.b, in.c, in.d });
149 blocks.arithmetic.populate_wires(in.a, in.b, in.c, in.d);
150 blocks.arithmetic.q_m().emplace_back(0);
151 blocks.arithmetic.q_1().emplace_back(in.a_scaling);
152 blocks.arithmetic.q_2().emplace_back(in.b_scaling);
153 blocks.arithmetic.q_3().emplace_back(in.c_scaling);
154 blocks.arithmetic.q_c().emplace_back(in.const_scaling);
155 blocks.arithmetic.q_4().emplace_back(in.d_scaling);
156 blocks.arithmetic.set_gate_selector(include_next_gate_w_4 ? 2 : 1);
157 check_selector_length_consistency();
158 this->increment_num_gates();
159}
160
166template <typename ExecutionTrace>
168{
169 this->assert_valid_variables({ variable_index });
170
171 blocks.arithmetic.populate_wires(variable_index, variable_index, this->zero_idx(), this->zero_idx());
172 blocks.arithmetic.q_m().emplace_back(1);
173 blocks.arithmetic.q_1().emplace_back(-1);
174 blocks.arithmetic.q_2().emplace_back(0);
175 blocks.arithmetic.q_3().emplace_back(0);
176 blocks.arithmetic.q_c().emplace_back(0);
177 blocks.arithmetic.q_4().emplace_back(0);
178 blocks.arithmetic.set_gate_selector(1);
179 check_selector_length_consistency();
180 this->increment_num_gates();
181}
182
189template <typename ExecutionTrace>
191{
192 this->assert_valid_variables({ in.a, in.b, in.c });
193
194 blocks.arithmetic.populate_wires(in.a, in.b, in.c, this->zero_idx());
195 blocks.arithmetic.q_m().emplace_back(in.q_m);
196 blocks.arithmetic.q_1().emplace_back(in.q_l);
197 blocks.arithmetic.q_2().emplace_back(in.q_r);
198 blocks.arithmetic.q_3().emplace_back(in.q_o);
199 blocks.arithmetic.q_c().emplace_back(in.q_c);
200 blocks.arithmetic.q_4().emplace_back(0);
201 blocks.arithmetic.set_gate_selector(1);
202 check_selector_length_consistency();
203 this->increment_num_gates();
204}
205
222template <typename ExecutionTrace>
224{
225 this->assert_valid_variables({ in.x1, in.x2, in.x3, in.y1, in.y2, in.y3 });
226
227 auto& block = blocks.elliptic;
228
229 // Convert bool to field element for the relation: +1 for addition, -1 for subtraction
230 // The elliptic curve relation assumes q_sign² = 1 (see elliptic_relation.hpp)
231 const FF q_sign = in.is_addition ? FF(1) : FF(-1);
232
233 // Determine whether we can fuse this addition operation into the previous gate in the block
234 bool can_fuse_into_previous_gate =
235 block.size() > 0 && /* a previous gate exists in the block */
236 block.w_r()[block.size() - 1] == in.x1 && /* output x coord of previous gate is input of this one */
237 block.w_o()[block.size() - 1] == in.y1; /* output y coord of previous gate is input of this one */
238
239 if (can_fuse_into_previous_gate) {
240 block.q_1().set(block.size() - 1, q_sign); // set q_sign of previous gate
241 block.q_elliptic().set(block.size() - 1, 1); // set q_ecc of previous gate to 1
242 } else {
243 block.populate_wires(this->zero_idx(), in.x1, in.y1, this->zero_idx());
244 block.q_3().emplace_back(0);
245 block.q_4().emplace_back(0);
246 block.q_1().emplace_back(q_sign);
247
248 block.q_2().emplace_back(0);
249 block.q_m().emplace_back(0);
250 block.q_c().emplace_back(0);
251 block.set_gate_selector(1);
252 check_selector_length_consistency();
253 this->increment_num_gates();
254 }
255 // Create the unconstrained gate with the output of the doubling to be read into by the previous gate via shifts
256 create_unconstrained_gate(block, in.x2, in.x3, in.y3, in.y2);
257}
258
275template <typename ExecutionTrace>
277{
278 this->assert_valid_variables({ in.x1, in.x3, in.y1, in.y3 });
279
280 auto& block = blocks.elliptic;
281
282 // Determine whether we can fuse this doubling operation into the previous gate in the block
283 bool can_fuse_into_previous_gate =
284 block.size() > 0 && /* a previous gate exists in the block */
285 block.w_r()[block.size() - 1] == in.x1 && /* output x coord of previous gate is input of this one */
286 block.w_o()[block.size() - 1] == in.y1; /* output y coord of previous gate is input of this one */
287
288 // If possible, update the previous gate to be the first gate in the pair, otherwise create a new gate
289 if (can_fuse_into_previous_gate) {
290 block.q_elliptic().set(block.size() - 1, 1); // set q_ecc of previous gate to 1
291 block.q_m().set(block.size() - 1, 1); // set q_m (q_is_double) of previous gate to 1
292 } else {
293 block.populate_wires(this->zero_idx(), in.x1, in.y1, this->zero_idx());
294 block.q_m().emplace_back(1);
295 block.q_1().emplace_back(0);
296 block.q_2().emplace_back(0);
297 block.q_3().emplace_back(0);
298 block.q_c().emplace_back(0);
299 block.q_4().emplace_back(0);
300 block.set_gate_selector(1);
301 check_selector_length_consistency();
302 this->increment_num_gates();
303 }
304 // Create the unconstrained gate with the output of the doubling to be read into by the previous gate via shifts
305 create_unconstrained_gate(block, this->zero_idx(), in.x3, in.y3, this->zero_idx());
306}
307
314template <typename ExecutionTrace>
315void UltraCircuitBuilder_<ExecutionTrace>::fix_witness(const uint32_t witness_index, const FF& witness_value)
316{
317 this->assert_valid_variables({ witness_index });
318
319 // Mark as intentionally single-gate for boomerang detection
320 update_used_witnesses(witness_index);
321
322 blocks.arithmetic.populate_wires(witness_index, this->zero_idx(), this->zero_idx(), this->zero_idx());
323 blocks.arithmetic.q_m().emplace_back(0);
324 blocks.arithmetic.q_1().emplace_back(1);
325 blocks.arithmetic.q_2().emplace_back(0);
326 blocks.arithmetic.q_3().emplace_back(0);
327 blocks.arithmetic.q_c().emplace_back(-witness_value);
328 blocks.arithmetic.q_4().emplace_back(0);
329 blocks.arithmetic.set_gate_selector(1);
330 check_selector_length_consistency();
331 this->increment_num_gates();
332}
333
334template <typename ExecutionTrace>
336{
337 if (constant_variable_indices.contains(variable)) {
338 return constant_variable_indices.at(variable);
339 } else {
340 uint32_t variable_index = this->add_variable(variable);
341 fix_witness(variable_index, variable);
342 constant_variable_indices.insert({ variable, variable_index });
343 return variable_index;
344 }
345}
346
355template <typename ExecutionTrace>
357{
358 for (plookup::BasicTable& table : lookup_tables) {
359 if (table.id == id) {
360 return table;
361 }
362 }
363 // Table doesn't exist! So try to create it.
364 lookup_tables.emplace_back(plookup::create_basic_table(id, lookup_tables.size()));
365 return lookup_tables.back();
366}
367
369template <typename ExecutionTrace>
371{
372 table.table_index = lookup_tables.size();
373 lookup_tables.emplace_back(std::move(table));
374 return &lookup_tables.back();
375}
376
378template <typename ExecutionTrace>
380 const uint32_t val1_idx,
381 const uint32_t val2_idx,
382 plookup::BasicTable& table,
384 const FF column_1_step_size,
385 const FF column_2_step_size,
386 const FF column_3_step_size)
387{
388 this->assert_valid_variables({ key_idx, val1_idx, val2_idx });
389
390 table.lookup_gates.emplace_back(entry);
391
392 blocks.lookup.populate_wires(key_idx, val1_idx, val2_idx, this->zero_idx());
393 blocks.lookup.set_gate_selector(1);
394 blocks.lookup.q_3().emplace_back(FF(table.table_index));
395 blocks.lookup.q_2().emplace_back(column_1_step_size);
396 blocks.lookup.q_m().emplace_back(column_2_step_size);
397 blocks.lookup.q_c().emplace_back(column_3_step_size);
398 blocks.lookup.q_1().emplace_back(0);
399 blocks.lookup.q_4().emplace_back(0);
400
401 check_selector_length_consistency();
402 this->increment_num_gates();
403}
404
432template <typename ExecutionTrace>
434 const plookup::MultiTableId& id,
435 const plookup::ReadData<FF>& read_values,
436 const uint32_t key_a_index,
438{
439 using plookup::ColumnIdx;
440
441 const auto& multi_table = plookup::get_multitable(id);
442 const size_t num_lookups = read_values[ColumnIdx::C1].size();
445 for (size_t i = 0; i < num_lookups; ++i) {
446 const bool is_first_lookup = (i == 0);
447 const bool is_last_lookup = (i == num_lookups - 1);
448
449 // Get basic lookup table; construct and add to builder.lookup_tables if not already present
450 plookup::BasicTable& table = get_table(multi_table.basic_table_ids[i]);
451
452 // Create witness variables: first lookup reuses user's input indices, subsequent create new variables
453 const auto first_idx = is_first_lookup ? key_a_index : this->add_variable(read_values[ColumnIdx::C1][i]);
454 const auto second_idx = (is_first_lookup && key_b_index.has_value())
455 ? *key_b_index
456 : this->add_variable(read_values[ColumnIdx::C2][i]);
457 const auto third_idx = this->add_variable(read_values[ColumnIdx::C3][i]);
458
459 read_data[ColumnIdx::C1].push_back(first_idx);
460 read_data[ColumnIdx::C2].push_back(second_idx);
461 read_data[ColumnIdx::C3].push_back(third_idx);
462
463 // Step size coefficients: zero for last lookup (no next accumulator), negative step sizes otherwise
464 const FF col1_step = is_last_lookup ? FF(0) : -multi_table.column_1_step_sizes[i + 1];
465 const FF col2_step = is_last_lookup ? FF(0) : -multi_table.column_2_step_sizes[i + 1];
466 const FF col3_step = is_last_lookup ? FF(0) : -multi_table.column_3_step_sizes[i + 1];
468 create_lookup_gate(
469 first_idx, second_idx, third_idx, table, read_values.lookup_entries[i], col1_step, col2_step, col3_step);
470 }
471 return read_data;
472}
473
477template <typename ExecutionTrace>
479 const uint64_t target_range)
480{
481 RangeList result;
482 const auto range_tag = get_new_tag();
483 const auto tau_tag = get_new_tag();
484 set_tau_transposition(range_tag, tau_tag);
485 result.target_range = target_range;
486 result.range_tag = range_tag;
487 result.tau_tag = tau_tag;
488
489 uint64_t num_multiples_of_three = (target_range / DEFAULT_PLOOKUP_RANGE_STEP_SIZE);
490 // allocate the minimum number of variable indices required for the range constraint. this function is only called
491 // when we are creating a range constraint on a witness index, which is responsible for the extra + 1. (note that
492 // the below loop goes from 0 to `num_multiples_of_three` inclusive.)
493 result.variable_indices.reserve(static_cast<uint32_t>(num_multiples_of_three + 3));
494 for (uint64_t i = 0; i <= num_multiples_of_three; ++i) {
495 const uint32_t index = this->add_variable(fr(i * DEFAULT_PLOOKUP_RANGE_STEP_SIZE));
496 result.variable_indices.emplace_back(index);
497 assign_tag(index, result.range_tag);
498 }
499 // `target_range` may not be divisible by 3, so we explicitly add it also.
500 {
501 const uint32_t index = this->add_variable(fr(target_range));
502 result.variable_indices.emplace_back(index);
503 assign_tag(index, result.range_tag);
505 // Need this because these variables will not appear in the witness otherwise
506 create_unconstrained_gates(result.variable_indices);
507
508 return result;
509}
510
511template <typename ExecutionTrace>
513 const uint32_t variable_index, const uint64_t num_bits, const uint64_t target_range_bitnum, std::string const& msg)
514{
515 this->assert_valid_variables({ variable_index });
516 // make sure `num_bits` satisfies the correct bounds
517 BB_ASSERT_GT(num_bits, 0U);
518 BB_ASSERT_GTE(MAX_NUM_BITS_RANGE_CONSTRAINT, num_bits);
519
520 uint256_t val = (uint256_t)(this->get_variable(variable_index));
522 // If the value is out of range, set the CircuitBuilder error to the given msg.
523 if (val.get_msb() >= num_bits && !this->failed()) {
524 this->failure(msg);
525 }
526
527 // compute limb structure
528 const uint64_t sublimb_mask = (1ULL << target_range_bitnum) - 1;
529
530 std::vector<uint64_t> sublimbs;
531 std::vector<uint32_t> sublimb_indices;
532
533 const bool has_remainder_bits = (num_bits % target_range_bitnum != 0);
534 const uint64_t num_limbs = (num_bits / target_range_bitnum) + has_remainder_bits;
535 const uint64_t last_limb_size = num_bits - ((num_bits / target_range_bitnum) * target_range_bitnum);
536 const uint64_t last_limb_range = ((uint64_t)1 << last_limb_size) - 1;
537
538 // extract limbs from the value
539 uint256_t accumulator = val;
540 for (size_t i = 0; i < num_limbs; ++i) {
541 sublimbs.push_back(accumulator.data[0] & sublimb_mask);
542 accumulator = accumulator >> target_range_bitnum;
543 }
544 // set the correct range constraint on each limb. note that when there are remainder bits, the last limb must be
545 // constrained to a smaller range.
546 const size_t num_full_limbs = has_remainder_bits ? sublimbs.size() - 1 : sublimbs.size();
547 for (size_t i = 0; i < num_full_limbs; ++i) {
548 const auto limb_idx = this->add_variable(bb::fr(sublimbs[i]));
549 sublimb_indices.emplace_back(limb_idx);
550 create_small_range_constraint(limb_idx, sublimb_mask);
551 }
552 if (has_remainder_bits) {
553 const auto limb_idx = this->add_variable(bb::fr(sublimbs.back()));
554 sublimb_indices.emplace_back(limb_idx);
555 create_small_range_constraint(limb_idx, last_limb_range);
556 }
557
558 // Prove that the limbs reconstruct the original value by processing limbs in groups of 3.
559 // We constrain: value = sum_{j=0}^{num_limbs-1} limb[j] * 2^(j * target_range_bitnum)
560 //
561 // Each iteration subtracts 3 limbs' contributions from an accumulator (starting at `val`),
562 // and constrains that the accumulator updates correctly via an arithmetic gate.
563 const uint64_t num_limb_triples = (num_limbs / 3) + ((num_limbs % 3) != 0);
564 // `leftovers` is the number of real limbs in the final triple (1, 2, or 3).
565 const uint64_t leftovers = (num_limbs % 3) == 0 ? 3 : (num_limbs % 3);
566
567 accumulator = val;
568 uint32_t accumulator_idx = variable_index;
569 // loop goes from `i = 0` to `num_limb_triples`, but some special case must be taken for the last triple (`i ==
570 // num_limb_triples - 1`), hence some conditional logic.
571 for (size_t i = 0; i < num_limb_triples; ++i) {
572 // `real_limbs` which limb positions in this triple contain actual limbs vs zero-padding.
573 // When `i == num_limb_triples - 1`, some positions may be unused if `num_limbs` isn't divisible by 3.
574 const bool real_limbs[3]{
575 !(i == (num_limb_triples - 1) && (leftovers < 1)),
576 !(i == (num_limb_triples - 1) && (leftovers < 2)),
577 !(i == (num_limb_triples - 1) && (leftovers < 3)),
578 };
579
580 // The witness values of the 3 limbs in this triple (0 for padding positions).
581 const uint64_t round_sublimbs[3]{
582 real_limbs[0] ? sublimbs[3 * i] : 0,
583 real_limbs[1] ? sublimbs[3 * i + 1] : 0,
584 real_limbs[2] ? sublimbs[3 * i + 2] : 0,
585 };
586 // The witnesss indices of the current 3 limbs (zero_idx for padding positions).
587 const uint32_t new_limbs[3]{
588 real_limbs[0] ? sublimb_indices[3 * i] : this->zero_idx(),
589 real_limbs[1] ? sublimb_indices[3 * i + 1] : this->zero_idx(),
590 real_limbs[2] ? sublimb_indices[3 * i + 2] : this->zero_idx(),
591 };
592 // Bit-shifts for each limb: limb[3*i+k] contributes at bit position (3*i+k) * target_range_bitnum.
593 const uint64_t shifts[3]{
594 target_range_bitnum * (3 * i),
595 target_range_bitnum * (3 * i + 1),
596 target_range_bitnum * (3 * i + 2),
597 };
598 // Compute the new accumulator after subtracting this triple's contribution.
599 // After the final iteration, accumulator should be 0.
600 uint256_t new_accumulator = accumulator - (uint256_t(round_sublimbs[0]) << shifts[0]) -
601 (uint256_t(round_sublimbs[1]) << shifts[1]) -
602 (uint256_t(round_sublimbs[2]) << shifts[2]);
604 // This `big_add_gate` has differing behavior depending on whether or not `i == num_limb_triples - 1`.
605 // If `i != num_limb_triples - 1`, then the constraint will be limb[0]*2^shift[0] + limb[1]*2^shift[1] +
606 // limb[2]*2^shift[2] - acc = new_accumulator (the last argument to `create_big_add_gate` is `true`, means the
607 // sum is w_4-shift, which will be the witness corresponding to what is currently `new_accumulator`.).
608 // If `i == num_limb_triples - 1`, then the last argument to `create_big_add_gate` is false, so the constraint
609 // is limb[0]*2^shift[0] + limb[1]*2^shift[1] + limb[2]*2^shift[2] - acc = 0.
610 //
611 // N.B. When `num_bits` is small, we only have remainder bits. This last constraint, checking the correctness of
612 // the limb-decomposition, ensures that the variable is not orphaned. (See the warning in
613 // `create_small_range_constraint`.)
614 create_big_add_gate(
615 {
616 new_limbs[0],
617 new_limbs[1],
618 new_limbs[2],
619 accumulator_idx,
620 uint256_t(1) << shifts[0],
621 uint256_t(1) << shifts[1],
622 uint256_t(1) << shifts[2],
623 -1,
624 0,
625 },
626 (i != num_limb_triples - 1));
627 if (i != num_limb_triples - 1) {
628 accumulator_idx = this->add_variable(fr(new_accumulator));
629 accumulator = new_accumulator;
630 }
631 }
632 return sublimb_indices;
633}
634
635template <typename ExecutionTrace>
637 const uint64_t target_range,
638 std::string const msg)
639{
640 // make sure `target_range` is not too big.
641 BB_ASSERT_GTE(MAX_SMALL_RANGE_CONSTRAINT_VAL, target_range);
642 const bool is_out_of_range = (uint256_t(this->get_variable(variable_index)).data[0] > target_range);
643 if (is_out_of_range && !this->failed()) {
644 this->failure(msg);
645 }
646 if (range_lists.count(target_range) == 0) {
647 range_lists.insert({ target_range, create_range_list(target_range) });
648 }
649 // The tag of `variable_index` is `DEFAULT_TAG` if it has never been range-constrained and a non-trivial value
650 // otherwise.
651 const auto existing_tag = this->real_variable_tags[this->real_variable_index[variable_index]];
652 auto& list = range_lists[target_range];
653
654 // If the variable's tag matches the target range list's tag, do nothing; the variable has _already_ been
655 // constrained to this exact range (i.e., `create_new_range_constraint(variable_index, target_range)` has already
656 // been called).
657 if (existing_tag == list.range_tag) {
658 return;
659 }
660 // If the variable is 'untagged' (i.e., it has the dummy tag), assign it the appropriate tag, which amounts to
661 // setting the range-constraint.
662 if (existing_tag == DEFAULT_TAG) {
663 assign_tag(variable_index, list.range_tag);
664 list.variable_indices.emplace_back(variable_index);
665 return;
666 }
667 // Otherwise, find the range for which the variable has already been tagged.
668 bool found_tag = false;
669 for (const auto& r : range_lists) {
670 if (r.second.range_tag == existing_tag) {
671 found_tag = true;
672 if (r.first < target_range) {
673 // The variable already has a more restrictive range check, so do nothing.
674 return;
675 }
676 // The range constraint we are trying to impose is more restrictive than the existing range
677 // constraint. It would be difficult to remove an existing range check. Instead, arithmetically copy the
678 // variable and apply a range check to new variable. We do _not_ simply create a
679 // copy-constraint, because that would copy the tag, which exactly corresponds to the old (less
680 // restrictive) range constraint. Instead, we use an arithmetic gate to constrain the value of
681 // the new variable and set the tag (a.k.a. range-constraint) via a new call to
682 // `create_new_range_constraint`.
683 const uint32_t copied_witness = this->add_variable(this->get_variable(variable_index));
684 create_add_gate({ .a = variable_index,
685 .b = copied_witness,
686 .c = this->zero_idx(),
687 .a_scaling = 1,
688 .b_scaling = -1,
689 .c_scaling = 0,
690 .const_scaling = 0 });
691 // Recurse with new witness that has no tag attached.
692 create_small_range_constraint(copied_witness, target_range, msg);
693 return;
694 }
695 }
696 // should never occur
697 BB_ASSERT(found_tag);
699
700template <typename ExecutionTrace> void UltraCircuitBuilder_<ExecutionTrace>::process_range_list(RangeList& list)
701{
702 this->assert_valid_variables(list.variable_indices);
703
704 BB_ASSERT_GT(list.variable_indices.size(), 0U);
705
706 // replace witness-index in variable_indices with the corresponding real-variable-index i.e., if a copy constraint
707 // has been applied on a variable after it was range constrained, this makes sure the indices in list point to the
708 // updated index in the range list so the set equivalence does not fail
709 for (uint32_t& x : list.variable_indices) {
710 x = this->real_variable_index[x];
711 }
712 // Sort `variable_indices` and remove duplicate witness indices to prevent the sorted list set size being wrong!
713 std::sort(list.variable_indices.begin(), list.variable_indices.end());
714 auto back_iterator = std::unique(list.variable_indices.begin(), list.variable_indices.end());
715 list.variable_indices.erase(back_iterator, list.variable_indices.end());
716
717 // Extract the values of each (real) variable into a list to be sorted (in the sense of the range/plookup-style
718 // argument).
719 std::vector<uint32_t> sorted_list;
720 sorted_list.reserve(list.variable_indices.size());
721 for (const auto variable_index : list.variable_indices) {
722 // note that `field_element` is < 32 bits as the corresponding witness has a non-trivial range-constraint.
723 const auto& field_element = this->get_variable(variable_index);
724 const uint32_t shrinked_value = static_cast<uint32_t>(field_element);
725 sorted_list.emplace_back(shrinked_value);
726 }
727
728#ifdef NO_PAR_ALGOS
729 std::sort(sorted_list.begin(), sorted_list.end());
730#else
731 std::sort(std::execution::par_unseq, sorted_list.begin(), sorted_list.end());
732#endif
733 // list must be padded to a multipe of 4 and larger than 4 (gate_width)
734 constexpr size_t gate_width = NUM_WIRES;
735 size_t padding = (gate_width - (list.variable_indices.size() % gate_width)) % gate_width;
736
737 std::vector<uint32_t> indices;
738 indices.reserve(padding + sorted_list.size());
739
740 if (list.variable_indices.size() <= gate_width) {
741 padding += gate_width;
742 }
743 for (size_t i = 0; i < padding; ++i) {
744 indices.emplace_back(this->zero_idx());
745 }
746 // tag the elements in the sorted_list to apply the multiset-equality check implicit in range-constraints.
747 for (const auto sorted_value : sorted_list) {
748 const uint32_t index = this->add_variable(fr(sorted_value));
749 assign_tag(index, list.tau_tag);
750 indices.emplace_back(index);
751 }
752 // constrain the _sorted_ list: starts at 0, ends at `target_range`, consecutive differences in {0, 1, 2, 3}.
753 create_sort_constraint_with_edges(indices, 0, list.target_range);
754}
755
756template <typename ExecutionTrace> void UltraCircuitBuilder_<ExecutionTrace>::process_range_lists()
757{
758 for (auto& i : range_lists) {
759 process_range_list(i.second);
760 }
761}
762
763template <typename ExecutionTrace>
764void UltraCircuitBuilder_<ExecutionTrace>::enforce_small_deltas(const std::vector<uint32_t>& variable_indices)
765{
766 constexpr size_t gate_width = NUM_WIRES;
767 BB_ASSERT_EQ(variable_indices.size() % gate_width, 0U);
768 this->assert_valid_variables(variable_indices);
769
770 for (size_t i = 0; i < variable_indices.size(); i += gate_width) {
771 blocks.delta_range.populate_wires(
772 variable_indices[i], variable_indices[i + 1], variable_indices[i + 2], variable_indices[i + 3]);
773
774 this->increment_num_gates();
775 blocks.delta_range.q_m().emplace_back(0);
776 blocks.delta_range.q_1().emplace_back(0);
777 blocks.delta_range.q_2().emplace_back(0);
778 blocks.delta_range.q_3().emplace_back(0);
779 blocks.delta_range.q_c().emplace_back(0);
780 blocks.delta_range.q_4().emplace_back(0);
781 blocks.delta_range.set_gate_selector(1);
782 check_selector_length_consistency();
783 }
784 // dummy gate needed because of widget's check of next row
785 create_unconstrained_gate(blocks.delta_range,
786 variable_indices[variable_indices.size() - 1],
787 this->zero_idx(),
788 this->zero_idx(),
789 this->zero_idx());
790}
791
792// useful to put variables in the witness that aren't already used - e.g. the dummy variables of the range constraint in
793// multiples of four
794template <typename ExecutionTrace>
795void UltraCircuitBuilder_<ExecutionTrace>::create_unconstrained_gates(const std::vector<uint32_t>& variable_index)
796{
797 std::vector<uint32_t> padded_list = variable_index;
798 constexpr size_t gate_width = NUM_WIRES;
799 const uint64_t padding = (gate_width - (padded_list.size() % gate_width)) % gate_width;
800 for (uint64_t i = 0; i < padding; ++i) {
801 padded_list.emplace_back(this->zero_idx());
802 }
803 this->assert_valid_variables(variable_index);
804 this->assert_valid_variables(padded_list);
805
806 for (size_t i = 0; i < padded_list.size(); i += gate_width) {
807 create_unconstrained_gate(
808 blocks.arithmetic, padded_list[i], padded_list[i + 1], padded_list[i + 2], padded_list[i + 3]);
809 }
810}
811
812template <typename ExecutionTrace>
814 const std::vector<uint32_t>& variable_indices, const FF& start, const FF& end)
815{
816 // Convenient to assume size is at least 8 (gate_width = 4) for separate gates for start and end conditions
817 constexpr size_t gate_width = NUM_WIRES;
818 BB_ASSERT_EQ(variable_indices.size() % gate_width, 0U);
819 BB_ASSERT_GT(variable_indices.size(), gate_width);
820 this->assert_valid_variables(variable_indices);
821 // only work with the delta_range block. this forces: `w_2 - w_1`, `w_3 - w_2`, `w_4 - w_3`, and `w_1_shift - w_4`
822 // to be in {0, 1, 2, 3}.
823 auto& block = blocks.delta_range;
824
825 // Add an arithmetic gate to ensure the first input is equal to the start value of the range being checked
826 create_add_gate({ variable_indices[0], this->zero_idx(), this->zero_idx(), 1, 0, 0, -start });
827
828 // enforce delta range relation for all rows (there are `variabe_indices.size() / gate_width`). note that there are
829 // at least two rows.
830 for (size_t i = 0; i < variable_indices.size(); i += gate_width) {
831
832 block.populate_wires(
833 variable_indices[i], variable_indices[i + 1], variable_indices[i + 2], variable_indices[i + 3]);
834 this->increment_num_gates();
835 block.q_m().emplace_back(0);
836 block.q_1().emplace_back(0);
837 block.q_2().emplace_back(0);
838 block.q_3().emplace_back(0);
839 block.q_c().emplace_back(0);
840 block.q_4().emplace_back(0);
841 block.set_gate_selector(1);
842 check_selector_length_consistency();
843 }
844
845 // the delta_range constraint has to have access to w_1-shift (it checks that w_1-shift - w_4 is in {0, 1, 2, 3}).
846 // Therefore, we repeat the last element in an unconstrained gate.
847 create_unconstrained_gate(
848 block, variable_indices[variable_indices.size() - 1], this->zero_idx(), this->zero_idx(), this->zero_idx());
849 // arithmetic gate to constrain that `variable_indices[last] == end`, i.e., verify the boundary condition.
850 create_add_gate(
851 { variable_indices[variable_indices.size() - 1], this->zero_idx(), this->zero_idx(), 1, 0, 0, -end });
852}
853
876template <typename ExecutionTrace>
878{
879 auto& block = blocks.memory;
880 block.set_gate_selector(type == MEMORY_SELECTORS::MEM_NONE ? 0 : 1);
881 switch (type) {
882 case MEMORY_SELECTORS::ROM_CONSISTENCY_CHECK: {
883 // Memory read gate used with the sorted list of memory reads.
884 // Apply sorted memory read checks with the following additional check:
885 // 1. Assert that if index field across two gates does not change, the value field does not change.
886 // Used for ROM reads and RAM reads across write/read boundaries
887 block.q_1().emplace_back(1);
888 block.q_2().emplace_back(1);
889 block.q_3().emplace_back(0);
890 block.q_4().emplace_back(0);
891 block.q_m().emplace_back(0);
892 block.q_c().emplace_back(0);
893 check_selector_length_consistency();
894 break;
895 }
896 case MEMORY_SELECTORS::RAM_CONSISTENCY_CHECK: {
897 // Memory read gate used with the sorted list of memory reads.
898 // 1. Validate adjacent index values across 2 gates increases by 0 or 1
899 // 2. Validate record computation (r = read_write_flag + index * \eta + \timestamp * \eta^2 + value * \eta^3)
900 // 3. If adjacent index values across 2 gates does not change, and the next gate's read_write_flag is set to
901 // 'read', validate adjacent values do not change Used for ROM reads and RAM reads across read/write boundaries
902 block.q_1().emplace_back(0);
903 block.q_2().emplace_back(0);
904 block.q_3().emplace_back(1);
905 block.q_4().emplace_back(0);
906 block.q_m().emplace_back(0);
907 block.q_c().emplace_back(0);
908 check_selector_length_consistency();
909 break;
910 }
911 case MEMORY_SELECTORS::RAM_TIMESTAMP_CHECK: {
912 // For two adjacent RAM entries that share the same index, validate the timestamp value is monotonically
913 // increasing
914 block.q_1().emplace_back(1);
915 block.q_2().emplace_back(0);
916 block.q_3().emplace_back(0);
917 block.q_4().emplace_back(1);
918 block.q_m().emplace_back(0);
919 block.q_c().emplace_back(0);
920 check_selector_length_consistency();
921 break;
922 }
923 case MEMORY_SELECTORS::ROM_READ: {
924 // Memory read gate for reading memory cells. Also used for the _initialization_ of ROM memory cells.
925 // Validates record witness computation (r = read_write_flag + index * \eta + timestamp * \eta^2 + value *
926 // \eta^3)
927 block.q_1().emplace_back(1);
928 block.q_2().emplace_back(0);
929 block.q_3().emplace_back(0);
930 block.q_4().emplace_back(0);
931 block.q_m().emplace_back(1); // validate record witness is correctly computed
932 block.q_c().emplace_back(0); // read/write flag stored in q_c
933 check_selector_length_consistency();
934 break;
935 }
936 case MEMORY_SELECTORS::RAM_READ: {
937 // Memory read gate for reading memory cells.
938 // Validates record witness computation (r = read_write_flag + index * \eta + timestamp * \eta^2 + value *
939 // \eta^3)
940 block.q_1().emplace_back(1);
941 block.q_2().emplace_back(0);
942 block.q_3().emplace_back(0);
943 block.q_4().emplace_back(0);
944 block.q_m().emplace_back(1); // validate record witness is correctly computed
945 block.q_c().emplace_back(0); // read/write flag stored in q_c
946 check_selector_length_consistency();
947 break;
948 }
949 case MEMORY_SELECTORS::RAM_WRITE: {
950 // Memory read gate for writing memory cells.
951 // Validates record witness computation (r = read_write_flag + index * \eta + timestamp * \eta^2 + value *
952 // \eta^3)
953 block.q_1().emplace_back(1);
954 block.q_2().emplace_back(0);
955 block.q_3().emplace_back(0);
956 block.q_4().emplace_back(0);
957 block.q_m().emplace_back(1); // validate record witness is correctly computed
958 block.q_c().emplace_back(1); // read/write flag stored in q_c
959 check_selector_length_consistency();
960 break;
961 }
962 default: {
963 block.q_1().emplace_back(0);
964 block.q_2().emplace_back(0);
965 block.q_3().emplace_back(0);
966 block.q_4().emplace_back(0);
967 block.q_m().emplace_back(0);
968 block.q_c().emplace_back(0);
969 check_selector_length_consistency();
970 break;
971 }
972 }
973}
974
998template <typename ExecutionTrace>
1000{
1001 auto& block = blocks.nnf;
1002 block.set_gate_selector(type == NNF_SELECTORS::NNF_NONE ? 0 : 1);
1003 switch (type) {
1004 case NNF_SELECTORS::LIMB_ACCUMULATE_1: {
1005 block.q_1().emplace_back(0);
1006 block.q_2().emplace_back(0);
1007 block.q_3().emplace_back(1);
1008 block.q_4().emplace_back(1);
1009 block.q_m().emplace_back(0);
1010 block.q_c().emplace_back(0);
1011 check_selector_length_consistency();
1012 break;
1013 }
1014 case NNF_SELECTORS::LIMB_ACCUMULATE_2: {
1015 block.q_1().emplace_back(0);
1016 block.q_2().emplace_back(0);
1017 block.q_3().emplace_back(1);
1018 block.q_4().emplace_back(0);
1019 block.q_m().emplace_back(1);
1020 block.q_c().emplace_back(0);
1021 check_selector_length_consistency();
1022 break;
1023 }
1024 case NNF_SELECTORS::NON_NATIVE_FIELD_1: {
1025 block.q_1().emplace_back(0);
1026 block.q_2().emplace_back(1);
1027 block.q_3().emplace_back(1);
1028 block.q_4().emplace_back(0);
1029 block.q_m().emplace_back(0);
1030 block.q_c().emplace_back(0);
1031 check_selector_length_consistency();
1032 break;
1033 }
1034 case NNF_SELECTORS::NON_NATIVE_FIELD_2: {
1035 block.q_1().emplace_back(0);
1036 block.q_2().emplace_back(1);
1037 block.q_3().emplace_back(0);
1038 block.q_4().emplace_back(1);
1039 block.q_m().emplace_back(0);
1040 block.q_c().emplace_back(0);
1041 check_selector_length_consistency();
1042 break;
1043 }
1044 case NNF_SELECTORS::NON_NATIVE_FIELD_3: {
1045 block.q_1().emplace_back(0);
1046 block.q_2().emplace_back(1);
1047 block.q_3().emplace_back(0);
1048 block.q_4().emplace_back(0);
1049 block.q_m().emplace_back(1);
1050 block.q_c().emplace_back(0);
1051 check_selector_length_consistency();
1052 break;
1053 }
1054 default: {
1055 block.q_1().emplace_back(0);
1056 block.q_2().emplace_back(0);
1057 block.q_3().emplace_back(0);
1058 block.q_4().emplace_back(0);
1059 block.q_m().emplace_back(0);
1060 block.q_c().emplace_back(0);
1061 check_selector_length_consistency();
1062 break;
1063 }
1064 }
1065}
1066
1077template <typename ExecutionTrace>
1079 const uint32_t hi_idx,
1080 const size_t lo_limb_bits,
1081 const size_t hi_limb_bits,
1082 std::string const& msg)
1083{
1084 // Validate limbs are <= 70 bits. If limbs are larger we require more witnesses and cannot use our limb accumulation
1085 // custom gate
1086 BB_ASSERT_LTE(lo_limb_bits, 14U * 5U);
1087 BB_ASSERT_LTE(hi_limb_bits, 14U * 5U);
1088
1089 // If the value is larger than the range, we log the error in builder
1090 const bool is_lo_out_of_range = (uint256_t(this->get_variable(lo_idx)) >= (uint256_t(1) << lo_limb_bits));
1091 if (is_lo_out_of_range && !this->failed()) {
1092 this->failure(msg + ": lo limb.");
1093 }
1094 const bool is_hi_out_of_range = (uint256_t(this->get_variable(hi_idx)) >= (uint256_t(1) << hi_limb_bits));
1095 if (is_hi_out_of_range && !this->failed()) {
1096 this->failure(msg + ": hi limb.");
1097 }
1098
1099 // Sometimes we try to use limbs that are too large. It's easier to catch this issue here
1100 const auto get_sublimbs = [&](const uint32_t& limb_idx, const std::array<uint64_t, 5>& sublimb_masks) {
1101 const uint256_t limb = this->get_variable(limb_idx);
1102 // we can use constant 2^14 - 1 mask here. If the sublimb value exceeds the expected value then witness will
1103 // fail the range check below
1104 // We also use zero_idx to substitute variables that should be zero
1105 constexpr uint256_t MAX_SUBLIMB_MASK = (uint256_t(1) << 14) - 1;
1106 std::array<uint32_t, 5> sublimb_indices;
1107 sublimb_indices[0] = sublimb_masks[0] != 0 ? this->add_variable(fr(limb & MAX_SUBLIMB_MASK)) : this->zero_idx();
1108 sublimb_indices[1] =
1109 sublimb_masks[1] != 0 ? this->add_variable(fr((limb >> 14) & MAX_SUBLIMB_MASK)) : this->zero_idx();
1110 sublimb_indices[2] =
1111 sublimb_masks[2] != 0 ? this->add_variable(fr((limb >> 28) & MAX_SUBLIMB_MASK)) : this->zero_idx();
1112 sublimb_indices[3] =
1113 sublimb_masks[3] != 0 ? this->add_variable(fr((limb >> 42) & MAX_SUBLIMB_MASK)) : this->zero_idx();
1114 sublimb_indices[4] =
1115 sublimb_masks[4] != 0 ? this->add_variable(fr((limb >> 56) & MAX_SUBLIMB_MASK)) : this->zero_idx();
1116 return sublimb_indices;
1117 };
1118
1119 const auto get_limb_masks = [](size_t limb_bits) {
1120 std::array<uint64_t, 5> sublimb_masks;
1121 sublimb_masks[0] = limb_bits >= 14 ? 14 : limb_bits;
1122 sublimb_masks[1] = limb_bits >= 28 ? 14 : (limb_bits > 14 ? limb_bits - 14 : 0);
1123 sublimb_masks[2] = limb_bits >= 42 ? 14 : (limb_bits > 28 ? limb_bits - 28 : 0);
1124 sublimb_masks[3] = limb_bits >= 56 ? 14 : (limb_bits > 42 ? limb_bits - 42 : 0);
1125 sublimb_masks[4] = (limb_bits > 56 ? limb_bits - 56 : 0);
1126
1127 for (auto& mask : sublimb_masks) {
1128 mask = (1ULL << mask) - 1ULL;
1129 }
1130 return sublimb_masks;
1131 };
1132
1133 const auto lo_masks = get_limb_masks(lo_limb_bits);
1134 const auto hi_masks = get_limb_masks(hi_limb_bits);
1135 const std::array<uint32_t, 5> lo_sublimbs = get_sublimbs(lo_idx, lo_masks);
1136 const std::array<uint32_t, 5> hi_sublimbs = get_sublimbs(hi_idx, hi_masks);
1137
1138 blocks.nnf.populate_wires(lo_sublimbs[0], lo_sublimbs[1], lo_sublimbs[2], lo_idx);
1139 blocks.nnf.populate_wires(lo_sublimbs[3], lo_sublimbs[4], hi_sublimbs[0], hi_sublimbs[1]);
1140 blocks.nnf.populate_wires(hi_sublimbs[2], hi_sublimbs[3], hi_sublimbs[4], hi_idx);
1141
1142 apply_nnf_selectors(NNF_SELECTORS::LIMB_ACCUMULATE_1);
1143 apply_nnf_selectors(NNF_SELECTORS::LIMB_ACCUMULATE_2);
1144 apply_nnf_selectors(NNF_SELECTORS::NNF_NONE);
1145 this->increment_num_gates(3);
1146
1147 for (size_t i = 0; i < 5; i++) {
1148 if (lo_masks[i] != 0) {
1149 create_small_range_constraint(
1150 lo_sublimbs[i], lo_masks[i], "ultra_circuit_builder: sublimb of low too large");
1151 }
1152 if (hi_masks[i] != 0) {
1153 create_small_range_constraint(
1154 hi_sublimbs[i], hi_masks[i], "ultra_circuit_builder: sublimb of hi too large");
1155 }
1156 }
1157};
1158
1174template <typename ExecutionTrace>
1177{
1178 const auto [a0, a1, a2, a3] = std::array{ this->get_variable(input.a[0]),
1179 this->get_variable(input.a[1]),
1180 this->get_variable(input.a[2]),
1181 this->get_variable(input.a[3]) };
1182 const auto [b0, b1, b2, b3] = std::array{ this->get_variable(input.b[0]),
1183 this->get_variable(input.b[1]),
1184 this->get_variable(input.b[2]),
1185 this->get_variable(input.b[3]) };
1186 const auto [q0, q1, q2, q3] = std::array{ this->get_variable(input.q[0]),
1187 this->get_variable(input.q[1]),
1188 this->get_variable(input.q[2]),
1189 this->get_variable(input.q[3]) };
1190 const auto [r0, r1, r2, r3] = std::array{ this->get_variable(input.r[0]),
1191 this->get_variable(input.r[1]),
1192 this->get_variable(input.r[2]),
1193 this->get_variable(input.r[3]) };
1194 const auto& p_neg = input.neg_modulus;
1195
1196 constexpr FF LIMB_SHIFT = uint256_t(1) << DEFAULT_NON_NATIVE_FIELD_LIMB_BITS;
1197 constexpr FF LIMB_RSHIFT = FF(1) / FF(uint256_t(1) << DEFAULT_NON_NATIVE_FIELD_LIMB_BITS);
1198 constexpr FF LIMB_RSHIFT_2 = FF(1) / FF(uint256_t(1) << (2 * DEFAULT_NON_NATIVE_FIELD_LIMB_BITS));
1199
1200 // lo_0 = (a0·b0 - r0) + (a1·b0 + a0·b1)·2^L
1201 FF lo_0 = (a0 * b0 - r0) + (a1 * b0 + a0 * b1) * LIMB_SHIFT;
1202 // lo_1 = (lo_0 + q0·p0' + (q1·p0' + q0·p1' - r1)·2^L) / 2^2L
1203 FF lo_1 = (lo_0 + q0 * p_neg[0] + (q1 * p_neg[0] + q0 * p_neg[1] - r1) * LIMB_SHIFT) * LIMB_RSHIFT_2;
1204
1205 // hi_0 = (a2·b0 + a0·b2) + (a0·b3 + a3·b0 - r3)·2^L
1206 FF hi_0 = (a2 * b0 + a0 * b2) + (a0 * b3 + a3 * b0 - r3) * LIMB_SHIFT;
1207 // hi_1 = hi_0 + (a1·b1 - r2) + (a1·b2 + a2·b1)·2^L
1208 FF hi_1 = hi_0 + (a1 * b1 - r2) + (a1 * b2 + a2 * b1) * LIMB_SHIFT;
1209 // hi_2 = hi_1 + lo_1 + q2·p0' + (q3·p0' + q2·p1')·2^L
1210 FF hi_2 = hi_1 + lo_1 + q2 * p_neg[0] + (q3 * p_neg[0] + q2 * p_neg[1]) * LIMB_SHIFT;
1211 // hi_3 = (hi_2 + q0·p2' + q1·p1' + (q0·p3' + q1·p2')·2^L) / 2^2L
1212 FF hi_3 = (hi_2 + q0 * p_neg[2] + q1 * p_neg[1] + (q0 * p_neg[3] + q1 * p_neg[2]) * LIMB_SHIFT) * LIMB_RSHIFT_2;
1213
1214 const uint32_t lo_0_idx = this->add_variable(lo_0);
1215 const uint32_t lo_1_idx = this->add_variable(lo_1);
1216 const uint32_t hi_0_idx = this->add_variable(hi_0);
1217 const uint32_t hi_1_idx = this->add_variable(hi_1);
1218 const uint32_t hi_2_idx = this->add_variable(hi_2);
1219 const uint32_t hi_3_idx = this->add_variable(hi_3);
1220
1221 // Gate 1: big_add_gate to validate lo_1
1222 // (lo_0 + q_0(p_0 + p_1*2^b) + q_1(p_0*2^b) - (r_1)2^b)2^-2b - lo_1 = 0
1223 // This constraint requires two rows in the trace: an arithmetic gate plus an unconstrained arithmetic gate
1224 // containing lo_0 in wire 4 so that the previous gate can access it via shifts. (We cannot use the next nnf gate
1225 // for this purpose since our trace is sorted by gate type).
1226 create_big_add_gate({ input.q[0],
1227 input.q[1],
1228 input.r[1],
1229 lo_1_idx,
1230 input.neg_modulus[0] + input.neg_modulus[1] * LIMB_SHIFT,
1231 input.neg_modulus[0] * LIMB_SHIFT,
1232 -LIMB_SHIFT,
1233 -LIMB_SHIFT.sqr(),
1234 0 },
1235 /*include_next_gate_w_4*/ true);
1236 // Gate 2: unconstrained gate to provide lo_0 via w_4_shift for gate 1
1237 create_unconstrained_gate(blocks.arithmetic, this->zero_idx(), this->zero_idx(), this->zero_idx(), lo_0_idx);
1238
1239 //
1240 // a = (a3 || a2 || a1 || a0) = (a3 * 2^b + a2) * 2^b + (a1 * 2^b + a0)
1241 // b = (b3 || b2 || b1 || b0) = (b3 * 2^b + b2) * 2^b + (b1 * 2^b + b0)
1242 //
1243 // Gate 3: NNF gate to check if lo_0 was computed correctly
1244 // The gate structure for the nnf gates is as follows:
1245 //
1246 // | a1 | b1 | r0 | lo_0 | <-- Gate 3: check lo_0
1247 // | a0 | b0 | a3 | b3 |
1248 // | a2 | b2 | r3 | hi_0 |
1249 // | a1 | b1 | r2 | hi_1 |
1250 //
1251 // Constraint: lo_0 = (a1 * b0 + a0 * b1) * 2^b + (a0 * b0) - r0
1252 // w4 = (w1 * w'2 + w'1 * w2) * 2^b + (w'1 * w'2) - w3
1253 //
1254 blocks.nnf.populate_wires(input.a[1], input.b[1], input.r[0], lo_0_idx);
1255 apply_nnf_selectors(NNF_SELECTORS::NON_NATIVE_FIELD_1);
1256 this->increment_num_gates();
1257
1258 //
1259 // Gate 4: NNF gate to check if hi_0 was computed correctly
1260 //
1261 // | a1 | b1 | r0 | lo_0 |
1262 // | a0 | b0 | a3 | b3 | <-- Gate 4: check hi_0
1263 // | a2 | b2 | r3 | hi_0 |
1264 // | a1 | b1 | r2 | hi_1 |
1265 //
1266 // Constraint: hi_0 = (a0 * b3 + a3 * b0 - r3) * 2^b + (a0 * b2 + a2 * b0)
1267 // w'4 = (w1 * w4 + w2 * w3 - w'3) * 2^b + (w1 * w'2 + w'1 * w2)
1268 //
1269 blocks.nnf.populate_wires(input.a[0], input.b[0], input.a[3], input.b[3]);
1270 apply_nnf_selectors(NNF_SELECTORS::NON_NATIVE_FIELD_2);
1271 this->increment_num_gates();
1272
1273 //
1274 // Gate 5: NNF gate to check if hi_1 was computed correctly
1275 //
1276 // | a1 | b1 | r0 | lo_0 |
1277 // | a0 | b0 | a3 | b3 |
1278 // | a2 | b2 | r3 | hi_0 | <-- Gate 5: check hi_1
1279 // | a1 | b1 | r2 | hi_1 |
1280 //
1281 // Constraint: hi_1 = hi_0 + (a2 * b1 + a1 * b2) * 2^b + (a1 * b1) - r2
1282 // w'4 = w4 + (w1 * w'2 + w'1 * w2) * 2^b + (w'1 * w'2) - w'3
1283 //
1284 blocks.nnf.populate_wires(input.a[2], input.b[2], input.r[3], hi_0_idx);
1285 apply_nnf_selectors(NNF_SELECTORS::NON_NATIVE_FIELD_3);
1286 this->increment_num_gates();
1287
1288 //
1289 // Gate 6: NNF gate with no constraints (q_nnf=0, truly unconstrained)
1290 // Provides values a[1], b[1], r[2], hi_1 to Gate 5 via shifts (w'1, w'2, w'3, w'4)
1291 //
1292 blocks.nnf.populate_wires(input.a[1], input.b[1], input.r[2], hi_1_idx);
1293 apply_nnf_selectors(NNF_SELECTORS::NNF_NONE);
1294 this->increment_num_gates();
1295
1296 //
1297 // Gate 7: big_add_gate to validate hi_2
1298 //
1299 // hi_2 - hi_1 - lo_1 - q[2](p[1].2^b + p[0]) - q[3](p[0].2^b) = 0
1300 //
1301 create_big_add_gate(
1302 {
1303 input.q[2],
1304 input.q[3],
1305 lo_1_idx,
1306 hi_1_idx,
1307 -input.neg_modulus[1] * LIMB_SHIFT - input.neg_modulus[0],
1308 -input.neg_modulus[0] * LIMB_SHIFT,
1309 -1,
1310 -1,
1311 0,
1312 },
1313 /*include_next_gate_w_4*/ true);
1314
1315 //
1316 // Gate 8: big_add_gate to validate hi_3 (provides hi_2 in w_4 for gate 7)
1317 //
1318 // hi_3 - (hi_2 - q[0](p[3].2^b + p[2]) - q[1](p[2].2^b + p[1])).2^-2b = 0
1319 //
1320 create_big_add_gate({
1321 hi_3_idx,
1322 input.q[0],
1323 input.q[1],
1324 hi_2_idx,
1325 -1,
1326 input.neg_modulus[3] * LIMB_RSHIFT + input.neg_modulus[2] * LIMB_RSHIFT_2,
1327 input.neg_modulus[2] * LIMB_RSHIFT + input.neg_modulus[1] * LIMB_RSHIFT_2,
1328 LIMB_RSHIFT_2,
1329 0,
1330 });
1331
1332 return std::array<uint32_t, 2>{ lo_1_idx, hi_3_idx };
1333}
1334
1342{
1343 for (size_t i = 0; i < cached_partial_non_native_field_multiplications.size(); ++i) {
1344 auto& c = cached_partial_non_native_field_multiplications[i];
1345 for (size_t j = 0; j < c.a.size(); ++j) {
1346 c.a[j] = this->real_variable_index[c.a[j]];
1347 c.b[j] = this->real_variable_index[c.b[j]];
1348 }
1349 }
1350 cached_partial_non_native_field_multiplication::deduplicate(cached_partial_non_native_field_multiplications, this);
1351
1352 // iterate over the cached items and create constraints
1353 for (const auto& input : cached_partial_non_native_field_multiplications) {
1354
1355 blocks.nnf.populate_wires(input.a[1], input.b[1], this->zero_idx(), input.lo_0);
1356 apply_nnf_selectors(NNF_SELECTORS::NON_NATIVE_FIELD_1);
1357 this->increment_num_gates();
1358
1359 blocks.nnf.populate_wires(input.a[0], input.b[0], input.a[3], input.b[3]);
1360 apply_nnf_selectors(NNF_SELECTORS::NON_NATIVE_FIELD_2);
1361 this->increment_num_gates();
1362
1363 blocks.nnf.populate_wires(input.a[2], input.b[2], this->zero_idx(), input.hi_0);
1364 apply_nnf_selectors(NNF_SELECTORS::NON_NATIVE_FIELD_3);
1365 this->increment_num_gates();
1366
1367 blocks.nnf.populate_wires(input.a[1], input.b[1], this->zero_idx(), input.hi_1);
1368 apply_nnf_selectors(NNF_SELECTORS::NNF_NONE);
1369 this->increment_num_gates();
1370 }
1371}
1372
1379template <typename ExecutionTrace>
1382{
1384 this->get_variable(input.a[0]),
1385 this->get_variable(input.a[1]),
1386 this->get_variable(input.a[2]),
1387 this->get_variable(input.a[3]),
1388 };
1390 this->get_variable(input.b[0]),
1391 this->get_variable(input.b[1]),
1392 this->get_variable(input.b[2]),
1393 this->get_variable(input.b[3]),
1394 };
1395
1396 constexpr FF LIMB_SHIFT = uint256_t(1) << DEFAULT_NON_NATIVE_FIELD_LIMB_BITS;
1397
1398 FF lo_0 = a[0] * b[0] + ((a[1] * b[0] + a[0] * b[1]) * LIMB_SHIFT);
1399 FF hi_0 = a[2] * b[0] + a[0] * b[2] + ((a[0] * b[3] + a[3] * b[0]) * LIMB_SHIFT);
1400 FF hi_1 = hi_0 + a[1] * b[1] + ((a[1] * b[2] + a[2] * b[1]) * LIMB_SHIFT);
1401
1402 const uint32_t lo_0_idx = this->add_variable(lo_0);
1403 const uint32_t hi_0_idx = this->add_variable(hi_0);
1404 const uint32_t hi_1_idx = this->add_variable(hi_1);
1405
1406 // Add witnesses into the multiplication cache (duplicates removed during circuit finalization)
1408 .a = input.a,
1409 .b = input.b,
1410 .lo_0 = lo_0_idx,
1411 .hi_0 = hi_0_idx,
1412 .hi_1 = hi_1_idx,
1413 };
1414 cached_partial_non_native_field_multiplications.emplace_back(cache_entry);
1415 return std::array<uint32_t, 2>{ lo_0_idx, hi_1_idx };
1416}
1417
1423template <typename ExecutionTrace>
1426{
1427 const uint32_t& x_0 = std::get<0>(limb0).first;
1428 const uint32_t& x_1 = std::get<0>(limb1).first;
1429 const uint32_t& x_2 = std::get<0>(limb2).first;
1430 const uint32_t& x_3 = std::get<0>(limb3).first;
1431 const uint32_t& x_p = std::get<0>(limbp);
1432
1433 const FF& x_mulconst0 = std::get<0>(limb0).second;
1434 const FF& x_mulconst1 = std::get<0>(limb1).second;
1435 const FF& x_mulconst2 = std::get<0>(limb2).second;
1436 const FF& x_mulconst3 = std::get<0>(limb3).second;
1437
1438 const uint32_t& y_0 = std::get<1>(limb0).first;
1439 const uint32_t& y_1 = std::get<1>(limb1).first;
1440 const uint32_t& y_2 = std::get<1>(limb2).first;
1441 const uint32_t& y_3 = std::get<1>(limb3).first;
1442 const uint32_t& y_p = std::get<1>(limbp);
1443
1444 const FF& y_mulconst0 = std::get<1>(limb0).second;
1445 const FF& y_mulconst1 = std::get<1>(limb1).second;
1446 const FF& y_mulconst2 = std::get<1>(limb2).second;
1447 const FF& y_mulconst3 = std::get<1>(limb3).second;
1448
1449 // constant additive terms
1450 const FF& addconst0 = std::get<2>(limb0);
1451 const FF& addconst1 = std::get<2>(limb1);
1452 const FF& addconst2 = std::get<2>(limb2);
1453 const FF& addconst3 = std::get<2>(limb3);
1454 const FF& addconstp = std::get<2>(limbp);
1455
1456 // get value of result limbs
1457 const FF z_0value = (this->get_variable(x_0) * x_mulconst0) + (this->get_variable(y_0) * y_mulconst0) + addconst0;
1458 const FF z_1value = (this->get_variable(x_1) * x_mulconst1) + (this->get_variable(y_1) * y_mulconst1) + addconst1;
1459 const FF z_2value = (this->get_variable(x_2) * x_mulconst2) + (this->get_variable(y_2) * y_mulconst2) + addconst2;
1460 const FF z_3value = (this->get_variable(x_3) * x_mulconst3) + (this->get_variable(y_3) * y_mulconst3) + addconst3;
1461 const FF z_pvalue = this->get_variable(x_p) + this->get_variable(y_p) + addconstp;
1462
1463 const uint32_t z_0 = this->add_variable(z_0value);
1464 const uint32_t z_1 = this->add_variable(z_1value);
1465 const uint32_t z_2 = this->add_variable(z_2value);
1466 const uint32_t z_3 = this->add_variable(z_3value);
1467 const uint32_t z_p = this->add_variable(z_pvalue);
1468
1490 auto& block = blocks.arithmetic;
1491 block.populate_wires(y_p, x_0, y_0, x_p);
1492 block.populate_wires(z_p, x_1, y_1, z_0);
1493 block.populate_wires(x_2, y_2, z_2, z_1);
1494 block.populate_wires(x_3, y_3, z_3, this->zero_idx());
1495
1496 // When q_arith == 3, w_4_shift is scaled by 2 (see ArithmeticRelation for details). Therefore, for consistency we
1497 // also scale each linear term by this factor of 2 so that the constraint is effectively:
1498 // (q_l * w_1) + (q_r * w_2) + (q_o * w_3) + (q_4 * w_4) + q_c + w_4_shift = 0
1499 const FF linear_term_scale_factor = 2;
1500 block.q_m().emplace_back(addconstp);
1501 block.q_1().emplace_back(0);
1502 block.q_2().emplace_back(-x_mulconst0 * linear_term_scale_factor);
1503 block.q_3().emplace_back(-y_mulconst0 * linear_term_scale_factor);
1504 block.q_4().emplace_back(0);
1505 block.q_c().emplace_back(-addconst0 * linear_term_scale_factor);
1506 block.set_gate_selector(3);
1507
1508 block.q_m().emplace_back(0);
1509 block.q_1().emplace_back(0);
1510 block.q_2().emplace_back(-x_mulconst1);
1511 block.q_3().emplace_back(-y_mulconst1);
1512 block.q_4().emplace_back(0);
1513 block.q_c().emplace_back(-addconst1);
1514 block.set_gate_selector(2);
1515
1516 block.q_m().emplace_back(0);
1517 block.q_1().emplace_back(-x_mulconst2);
1518 block.q_2().emplace_back(-y_mulconst2);
1519 block.q_3().emplace_back(1);
1520 block.q_4().emplace_back(0);
1521 block.q_c().emplace_back(-addconst2);
1522 block.set_gate_selector(1);
1523
1524 block.q_m().emplace_back(0);
1525 block.q_1().emplace_back(-x_mulconst3);
1526 block.q_2().emplace_back(-y_mulconst3);
1527 block.q_3().emplace_back(1);
1528 block.q_4().emplace_back(0);
1529 block.q_c().emplace_back(-addconst3);
1530 block.set_gate_selector(1);
1531
1532 check_selector_length_consistency();
1533
1534 this->increment_num_gates(4);
1536 z_0, z_1, z_2, z_3, z_p,
1537 };
1538}
1539
1545template <typename ExecutionTrace>
1548{
1549 const uint32_t& x_0 = std::get<0>(limb0).first;
1550 const uint32_t& x_1 = std::get<0>(limb1).first;
1551 const uint32_t& x_2 = std::get<0>(limb2).first;
1552 const uint32_t& x_3 = std::get<0>(limb3).first;
1553 const uint32_t& x_p = std::get<0>(limbp);
1554
1555 const FF& x_mulconst0 = std::get<0>(limb0).second;
1556 const FF& x_mulconst1 = std::get<0>(limb1).second;
1557 const FF& x_mulconst2 = std::get<0>(limb2).second;
1558 const FF& x_mulconst3 = std::get<0>(limb3).second;
1559
1560 const uint32_t& y_0 = std::get<1>(limb0).first;
1561 const uint32_t& y_1 = std::get<1>(limb1).first;
1562 const uint32_t& y_2 = std::get<1>(limb2).first;
1563 const uint32_t& y_3 = std::get<1>(limb3).first;
1564 const uint32_t& y_p = std::get<1>(limbp);
1565
1566 const FF& y_mulconst0 = std::get<1>(limb0).second;
1567 const FF& y_mulconst1 = std::get<1>(limb1).second;
1568 const FF& y_mulconst2 = std::get<1>(limb2).second;
1569 const FF& y_mulconst3 = std::get<1>(limb3).second;
1570
1571 // constant additive terms
1572 const FF& addconst0 = std::get<2>(limb0);
1573 const FF& addconst1 = std::get<2>(limb1);
1574 const FF& addconst2 = std::get<2>(limb2);
1575 const FF& addconst3 = std::get<2>(limb3);
1576 const FF& addconstp = std::get<2>(limbp);
1577
1578 // get value of result limbs
1579 const FF z_0value = (this->get_variable(x_0) * x_mulconst0) - (this->get_variable(y_0) * y_mulconst0) + addconst0;
1580 const FF z_1value = (this->get_variable(x_1) * x_mulconst1) - (this->get_variable(y_1) * y_mulconst1) + addconst1;
1581 const FF z_2value = (this->get_variable(x_2) * x_mulconst2) - (this->get_variable(y_2) * y_mulconst2) + addconst2;
1582 const FF z_3value = (this->get_variable(x_3) * x_mulconst3) - (this->get_variable(y_3) * y_mulconst3) + addconst3;
1583 const FF z_pvalue = this->get_variable(x_p) - this->get_variable(y_p) + addconstp;
1584
1585 const uint32_t z_0 = this->add_variable(z_0value);
1586 const uint32_t z_1 = this->add_variable(z_1value);
1587 const uint32_t z_2 = this->add_variable(z_2value);
1588 const uint32_t z_3 = this->add_variable(z_3value);
1589 const uint32_t z_p = this->add_variable(z_pvalue);
1590
1615 auto& block = blocks.arithmetic;
1616 block.populate_wires(y_p, x_0, y_0, z_p);
1617 block.populate_wires(x_p, x_1, y_1, z_0);
1618 block.populate_wires(x_2, y_2, z_2, z_1);
1619 block.populate_wires(x_3, y_3, z_3, this->zero_idx());
1620
1621 // When q_arith == 3, w_4_shift is scaled by 2 (see ArithmeticRelation for details). Therefore, for consistency we
1622 // also scale each linear term by this factor of 2 so that the constraint is effectively:
1623 // (q_l * w_1) + (q_r * w_2) + (q_o * w_3) + (q_4 * w_4) + q_c + w_4_shift = 0
1624 const FF linear_term_scale_factor = 2;
1625 block.q_m().emplace_back(-addconstp);
1626 block.q_1().emplace_back(0);
1627 block.q_2().emplace_back(-x_mulconst0 * linear_term_scale_factor);
1628 block.q_3().emplace_back(y_mulconst0 * linear_term_scale_factor);
1629 block.q_4().emplace_back(0);
1630 block.q_c().emplace_back(-addconst0 * linear_term_scale_factor);
1631 block.set_gate_selector(3);
1632
1633 block.q_m().emplace_back(0);
1634 block.q_1().emplace_back(0);
1635 block.q_2().emplace_back(-x_mulconst1);
1636 block.q_3().emplace_back(y_mulconst1);
1637 block.q_4().emplace_back(0);
1638 block.q_c().emplace_back(-addconst1);
1639 block.set_gate_selector(2);
1640
1641 block.q_m().emplace_back(0);
1642 block.q_1().emplace_back(-x_mulconst2);
1643 block.q_2().emplace_back(y_mulconst2);
1644 block.q_3().emplace_back(1);
1645 block.q_4().emplace_back(0);
1646 block.q_c().emplace_back(-addconst2);
1647 block.set_gate_selector(1);
1648
1649 block.q_m().emplace_back(0);
1650 block.q_1().emplace_back(-x_mulconst3);
1651 block.q_2().emplace_back(y_mulconst3);
1652 block.q_3().emplace_back(1);
1653 block.q_4().emplace_back(0);
1654 block.q_c().emplace_back(-addconst3);
1655 block.set_gate_selector(1);
1656
1657 check_selector_length_consistency();
1658
1659 this->increment_num_gates(4);
1661 z_0, z_1, z_2, z_3, z_p,
1662 };
1663}
1664
1674template <typename ExecutionTrace>
1676{
1677 return this->rom_ram_logic.create_ROM_array(array_size);
1678}
1679
1689template <typename ExecutionTrace>
1691{
1692 return this->rom_ram_logic.create_RAM_array(array_size);
1693}
1694
1702template <typename ExecutionTrace>
1704 const size_t index_value,
1705 const uint32_t value_witness)
1706{
1707 this->rom_ram_logic.init_RAM_element(this, ram_id, index_value, value_witness);
1708}
1709
1710template <typename ExecutionTrace>
1711uint32_t UltraCircuitBuilder_<ExecutionTrace>::read_RAM_array(const size_t ram_id, const uint32_t index_witness)
1712{
1713 return this->rom_ram_logic.read_RAM_array(this, ram_id, index_witness);
1714}
1715
1716template <typename ExecutionTrace>
1718 const uint32_t index_witness,
1719 const uint32_t value_witness)
1720{
1721 this->rom_ram_logic.write_RAM_array(this, ram_id, index_witness, value_witness);
1722}
1723
1739template <typename ExecutionTrace>
1741 const size_t index_value,
1742 const uint32_t value_witness)
1743{
1744 this->rom_ram_logic.set_ROM_element(this, rom_id, index_value, value_witness);
1745}
1746
1754template <typename ExecutionTrace>
1756 const size_t index_value,
1757 const std::array<uint32_t, 2>& value_witnesses)
1758{
1759 this->rom_ram_logic.set_ROM_element_pair(this, rom_id, index_value, value_witnesses);
1760}
1761
1769template <typename ExecutionTrace>
1770uint32_t UltraCircuitBuilder_<ExecutionTrace>::read_ROM_array(const size_t rom_id, const uint32_t index_witness)
1771{
1772 return this->rom_ram_logic.read_ROM_array(this, rom_id, index_witness);
1773}
1774
1782template <typename ExecutionTrace>
1783std::array<uint32_t, 2> UltraCircuitBuilder_<ExecutionTrace>::read_ROM_array_pair(const size_t rom_id,
1784 const uint32_t index_witness)
1785{
1786 return this->rom_ram_logic.read_ROM_array_pair(this, rom_id, index_witness);
1787}
1788
1792template <typename FF>
1794{
1795 auto& block = this->blocks.poseidon2_external;
1796 block.populate_wires(in.a, in.b, in.c, in.d);
1797 block.q_m().emplace_back(0);
1801 block.q_c().emplace_back(0);
1803 block.set_gate_selector(1);
1804 this->check_selector_length_consistency();
1805 this->increment_num_gates();
1806}
1807
1811template <typename FF>
1813{
1814 auto& block = this->blocks.poseidon2_internal;
1815 block.populate_wires(in.a, in.b, in.c, in.d);
1816 block.q_m().emplace_back(0);
1818 block.q_2().emplace_back(0);
1819 block.q_3().emplace_back(0);
1820 block.q_c().emplace_back(0);
1821 block.q_4().emplace_back(0);
1822 block.set_gate_selector(1);
1823 this->check_selector_length_consistency();
1824 this->increment_num_gates();
1825}
1826
1833template <typename ExecutionTrace> msgpack::sbuffer UltraCircuitBuilder_<ExecutionTrace>::export_circuit()
1834{
1835 // You should not name `zero` by yourself
1836 // but it will be rewritten anyway
1837 auto first_zero_idx = this->get_first_variable_in_class(this->zero_idx());
1838 if (!this->variable_names.contains(first_zero_idx)) {
1839 this->set_variable_name(this->zero_idx(), "zero");
1840 } else {
1841 this->variable_names[first_zero_idx] = "zero";
1842 }
1843 using base = CircuitBuilderBase<FF>;
1845
1846 std::array<uint64_t, 4> modulus = {
1847 FF::Params::modulus_0, FF::Params::modulus_1, FF::Params::modulus_2, FF::Params::modulus_3
1848 };
1849 std::stringstream buf;
1850 buf << std::hex << std::setfill('0') << std::setw(16) << modulus[3] << std::setw(16) << modulus[2] << std::setw(16)
1851 << modulus[1] << std::setw(16) << modulus[0];
1852
1853 cir.modulus = buf.str();
1854
1855 for (uint32_t i = 0; i < this->num_public_inputs(); i++) {
1856 cir.public_inps.push_back(this->real_variable_index[this->public_inputs()[i]]);
1857 }
1858
1859 for (auto& tup : base::variable_names) {
1860 cir.vars_of_interest.insert({ this->real_variable_index[tup.first], tup.second });
1861 }
1862
1863 for (const auto& var : this->get_variables()) {
1864 cir.variables.push_back(var);
1865 }
1866
1867 FF curve_b;
1868 if constexpr (FF::modulus == bb::fq::modulus) {
1869 curve_b = bb::g1::curve_b;
1870 } else if constexpr (FF::modulus == grumpkin::fq::modulus) {
1871 curve_b = grumpkin::g1::curve_b;
1872 } else {
1873 curve_b = 0;
1874 }
1875
1876 for (auto& block : blocks.get()) {
1877 std::vector<std::vector<FF>> block_selectors;
1879 for (size_t idx = 0; idx < block.size(); ++idx) {
1880 std::vector<FF> tmp_sel = { block.q_m()[idx],
1881 block.q_1()[idx],
1882 block.q_2()[idx],
1883 block.q_3()[idx],
1884 block.q_4()[idx],
1885 block.q_c()[idx],
1886 block.q_arith()[idx],
1887 block.q_delta_range()[idx],
1888 block.q_elliptic()[idx],
1889 block.q_memory()[idx],
1890 block.q_nnf()[idx],
1891 block.q_lookup()[idx],
1892 curve_b };
1893
1894 std::vector<uint32_t> tmp_w = {
1895 this->real_variable_index[block.w_l()[idx]],
1896 this->real_variable_index[block.w_r()[idx]],
1897 this->real_variable_index[block.w_o()[idx]],
1898 this->real_variable_index[block.w_4()[idx]],
1899 };
1900
1901 if (idx < block.size() - 1) {
1902 tmp_w.push_back(block.w_l()[idx + 1]);
1903 tmp_w.push_back(block.w_r()[idx + 1]);
1904 tmp_w.push_back(block.w_o()[idx + 1]);
1905 tmp_w.push_back(block.w_4()[idx + 1]);
1906 } else {
1907 tmp_w.push_back(0);
1908 tmp_w.push_back(0);
1909 tmp_w.push_back(0);
1910 tmp_w.push_back(0);
1911 }
1912
1913 block_selectors.push_back(tmp_sel);
1914 block_wires.push_back(tmp_w);
1915 }
1916 cir.selectors.push_back(block_selectors);
1917 cir.wires.push_back(block_wires);
1918 }
1919
1920 cir.real_variable_index = this->real_variable_index;
1921
1922 for (const auto& table : this->lookup_tables) {
1923 const FF table_index(table.table_index);
1924 info("Table no: ", table.table_index);
1925 std::vector<std::vector<FF>> tmp_table;
1926 for (size_t i = 0; i < table.size(); ++i) {
1927 tmp_table.push_back({ table.column_1[i], table.column_2[i], table.column_3[i] });
1928 }
1929 cir.lookup_tables.push_back(tmp_table);
1930 }
1931
1932 cir.real_variable_tags = this->real_variable_tags;
1933
1934 for (const auto& list : range_lists) {
1935 cir.range_tags[list.second.range_tag] = list.first;
1936 }
1937
1938 for (auto& rom_table : this->rom_ram_logic.rom_arrays) {
1939 std::sort(rom_table.records.begin(), rom_table.records.end());
1940
1942 table.reserve(rom_table.records.size());
1943 for (const auto& rom_entry : rom_table.records) {
1944 table.push_back({
1945 this->real_variable_index[rom_entry.index_witness],
1946 this->real_variable_index[rom_entry.value_column1_witness],
1947 this->real_variable_index[rom_entry.value_column2_witness],
1948 });
1949 }
1950 cir.rom_records.push_back(table);
1951 cir.rom_states.push_back(rom_table.state);
1952 }
1953
1954 for (auto& ram_table : this->rom_ram_logic.ram_arrays) {
1955 std::sort(ram_table.records.begin(), ram_table.records.end());
1956
1958 table.reserve(ram_table.records.size());
1959 for (const auto& ram_entry : ram_table.records) {
1960 table.push_back({ this->real_variable_index[ram_entry.index_witness],
1961 this->real_variable_index[ram_entry.value_witness],
1962 this->real_variable_index[ram_entry.timestamp_witness],
1963 ram_entry.access_type });
1964 }
1965 cir.ram_records.push_back(table);
1966 cir.ram_states.push_back(ram_table.state);
1967 }
1968
1969 cir.circuit_finalized = this->circuit_finalized;
1970
1971 msgpack::sbuffer buffer;
1972 msgpack::pack(buffer, cir);
1973 return buffer;
1974}
1975
1978
1979} // namespace bb
#define BB_ASSERT(expression,...)
Definition assert.hpp:70
#define BB_ASSERT_GTE(left, right,...)
Definition assert.hpp:128
#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
bb::field< bb::Bn254FrParams > FF
Definition field.cpp:24
#define BB_BENCH_NAME(name)
Definition bb_bench.hpp:264
void fix_witness(const uint32_t witness_index, const FF &witness_value)
Add a gate equating a particular witness to a constant, fixing its value.
void init_RAM_element(const size_t ram_id, const size_t index_value, const uint32_t value_witness)
Initialize a RAM cell to equal value_witness
void create_ecc_dbl_gate(const ecc_dbl_gate_< FF > &in)
Create an elliptic curve doubling gate.
void create_sort_constraint_with_edges(const std::vector< uint32_t > &variable_indices, const FF &start, const FF &end)
Constrain consecutive variable differences to be in {0, 1, 2, 3}, with boundary checks.
void process_range_list(RangeList &list)
void create_poseidon2_internal_gate(const poseidon2_internal_gate_< FF > &in)
Poseidon2 internal round gate, activates the q_poseidon2_internal selector and relation.
size_t create_RAM_array(const size_t array_size)
Create a new updatable memory region.
void create_big_mul_add_gate(const mul_quad_< FF > &in, const bool use_next_gate_w_4=false)
Create a big multiplication-addition gate, where in.a * in.b * in.mul_scaling + in....
void create_small_range_constraint(const uint32_t variable_index, const uint64_t target_range, std::string const msg="create_small_range_constraint")
Range-constraints for small ranges, where the upper bound (target_range) need not be dyadic....
std::tuple< scaled_witness, scaled_witness, FF > add_simple
uint32_t read_RAM_array(const size_t ram_id, const uint32_t index_witness)
void create_unconstrained_gates(const std::vector< uint32_t > &variable_index)
void create_add_gate(const add_triple_< FF > &in)
Create an addition gate, where in.a * in.a_scaling + in.b * in.b_scaling + in.c * in....
void create_big_add_gate(const add_quad_< FF > &in, const bool use_next_gate_w_4=false)
Create a big addition gate, where in.a * in.a_scaling + in.b * in.b_scaling + in.c * in....
void create_ecc_add_gate(const ecc_add_gate_ &in)
Create an elliptic curve addition gate.
plookup::BasicTable * register_basic_lookup_table(plookup::BasicTable &&table)
Register a BasicTable with the builder, assigning it a unique table_index.
typename ExecutionTrace::FF FF
std::array< uint32_t, 5 > evaluate_non_native_field_addition(add_simple limb0, add_simple limb1, add_simple limb2, add_simple limb3, std::tuple< uint32_t, uint32_t, FF > limbp)
Construct gates for non-native field addition.
std::vector< uint32_t > create_limbed_range_constraint(const uint32_t variable_index, const uint64_t num_bits, const uint64_t target_range_bitnum=DEFAULT_PLOOKUP_RANGE_BITNUM, std::string const &msg="create_limbed_range_constraint")
Range-constrain a variable to [0, 2^num_bits - 1] by decomposing into smaller limbs.
size_t create_ROM_array(const size_t array_size)
Create a new read-only memory region (a.k.a. ROM table)
plookup::ReadData< uint32_t > create_gates_from_plookup_accumulators(const plookup::MultiTableId &id, const plookup::ReadData< FF > &read_values, const uint32_t key_a_index, std::optional< uint32_t > key_b_index=std::nullopt)
Create gates from pre-computed accumulator values which simultaneously establish individual basic-tab...
plookup::BasicTable & get_table(const plookup::BasicTableId id)
Get the basic table with provided ID from the set of tables for the present circuit; create it if it ...
void apply_nnf_selectors(const NNF_SELECTORS type)
Enable the nnf gate of particular type.
void create_poseidon2_external_gate(const poseidon2_external_gate_< FF > &in)
Poseidon2 external round gate, activates the q_poseidon2_external selector and relation.
std::array< uint32_t, 2 > evaluate_non_native_field_multiplication(const non_native_multiplication_witnesses< FF > &input)
Create gates for a full non-native field multiplication identity a * b = q * p + r.
void populate_public_inputs_block()
Copy the public input idx data into the public inputs trace block.
uint32_t read_ROM_array(const size_t rom_id, const uint32_t index_witness)
Read a single element from ROM.
RangeList create_range_list(const uint64_t target_range)
uint32_t put_constant_variable(const FF &variable)
void set_ROM_element(const size_t rom_id, const size_t index_value, const uint32_t value_witness)
Initialize a rom cell to equal value_witness
void enforce_small_deltas(const std::vector< uint32_t > &variable_indices)
Check for a sequence of variables that the neighboring differences are in {0, 1, 2,...
void create_bool_gate(const uint32_t a)
Generate an arithmetic gate equivalent to x^2 - x = 0, which forces x to be 0 or 1.
void write_RAM_array(const size_t ram_id, const uint32_t index_witness, const uint32_t value_witness)
void set_ROM_element_pair(const size_t rom_id, const size_t index_value, const std::array< uint32_t, 2 > &value_witnesses)
Initialize a ROM array element with a pair of witness values.
std::array< uint32_t, 2 > read_ROM_array_pair(const size_t rom_id, const uint32_t index_witness)
Read a pair of elements from ROM.
void range_constrain_two_limbs(const uint32_t lo_idx, const uint32_t hi_idx, const size_t lo_limb_bits=DEFAULT_NON_NATIVE_FIELD_LIMB_BITS, const size_t hi_limb_bits=DEFAULT_NON_NATIVE_FIELD_LIMB_BITS, std::string const &msg="range_constrain_two_limbs")
std::array< uint32_t, 2 > queue_partial_non_native_field_multiplication(const non_native_partial_multiplication_witnesses< FF > &input)
Queue the addition of gates constraining the limb-multiplication part of a non native field mul.
std::array< uint32_t, 5 > evaluate_non_native_field_subtraction(add_simple limb0, add_simple limb1, add_simple limb2, add_simple limb3, std::tuple< uint32_t, uint32_t, FF > limbp)
Construct gates for non-native field subtraction.
void apply_memory_selectors(const MEMORY_SELECTORS type)
Enable the memory gate of particular type.
void process_non_native_field_multiplications()
Iterates over the cached_non_native_field_multiplication objects, removes duplicates,...
void create_arithmetic_gate(const arithmetic_triple_< FF > &in)
A plonk gate with disabled (set to zero) fourth wire. q_m * a * b + q_1 * a + q_2 * b + q_3.
void create_lookup_gate(uint32_t key_idx, uint32_t val1_idx, uint32_t val2_idx, plookup::BasicTable &table, const plookup::BasicTable::LookupEntry &entry, FF column_1_step_size=0, FF column_2_step_size=0, FF column_3_step_size=0)
Create a single plookup lookup gate.
static constexpr Fq curve_b
Definition group.hpp:53
constexpr uint64_t get_msb() const
Container for lookup accumulator values and table reads.
Definition types.hpp:360
std::vector< BasicTable::LookupEntry > lookup_entries
Definition types.hpp:366
#define info(...)
Definition log.hpp:93
FF a
FF b
std::unique_ptr< uint8_t[]> buffer
Definition engine.cpp:60
BasicTable create_basic_table(const BasicTableId id, const size_t index)
const MultiTable & get_multitable(const MultiTableId id)
Return the multitable with the provided ID; construct all MultiTables if not constructed already.
Entry point for Barretenberg command-line interface.
Definition api.hpp:5
field< Bn254FrParams > fr
Definition fr.hpp:155
constexpr decltype(auto) get(::tuplet::tuple< T... > &&t) noexcept
Definition tuple.hpp:13
Serialized state of a circuit.
std::vector< std::vector< std::vector< FF > > > selectors
std::vector< uint32_t > real_variable_index
std::unordered_map< uint32_t, uint64_t > range_tags
std::unordered_map< uint32_t, std::string > vars_of_interest
std::vector< std::vector< uint32_t > > ram_states
std::vector< std::vector< std::array< uint32_t, 2 > > > rom_states
std::vector< std::vector< std::vector< uint32_t > > > ram_records
std::vector< std::vector< std::vector< uint32_t > > > rom_records
std::vector< std::vector< std::vector< FF > > > lookup_tables
std::vector< uint32_t > real_variable_tags
std::vector< uint32_t > public_inps
std::vector< std::vector< std::vector< uint32_t > > > wires
Used to store instructions to create partial_non_native_field_multiplication gates.
static constexpr std::array< std::array< FF, t >, rounds_f+rounds_p > round_constants
static constexpr uint256_t modulus
Definition types.hpp:289
A basic table from which we can perform lookups (for example, an xor table)
Definition types.hpp:288
std::vector< LookupEntry > lookup_gates
Definition types.hpp:324
size_t size() const
Definition types.hpp:335
std::vector< bb::fr > column_3
Definition types.hpp:323
std::vector< bb::fr > column_2
Definition types.hpp:322
std::vector< bb::fr > column_1
Definition types.hpp:321