Barretenberg
The ZK-SNARK library at the core of Aztec
Loading...
Searching...
No Matches
ultra_circuit_checker.cpp
Go to the documentation of this file.
5#include <unordered_set>
6
7namespace bb {
8
9template <> auto UltraCircuitChecker::init_empty_values<UltraCircuitBuilder_<UltraExecutionTraceBlocks>>()
10{
12}
13
14template <> auto UltraCircuitChecker::init_empty_values<MegaCircuitBuilder_<bb::fr>>()
15{
16 return MegaFlavor::AllValues{};
17}
18
19template <>
22{
23 // Create a copy of the input circuit
25 if (!builder.circuit_finalized) { // avoid warnings about finalizing an already finalized circuit
27 }
28
29 return builder;
30}
31
32template <>
33MegaCircuitBuilder_<bb::fr> UltraCircuitChecker::prepare_circuit<MegaCircuitBuilder_<bb::fr>>(
34 const MegaCircuitBuilder_<bb::fr>& builder_in)
35{
36 // Create a copy of the input circuit
37 MegaCircuitBuilder_<bb::fr> builder{ builder_in };
38
39 // Deepcopy the opqueue to avoid modifying the original one
40 builder.op_queue = std::make_shared<ECCOpQueue>(*builder.op_queue);
41
42 if (!builder.circuit_finalized) { // avoid warnings about finalizing an already finalized circuit
43 builder.finalize_circuit();
44 }
45
46 return builder;
47}
48
49template <typename Builder> bool UltraCircuitChecker::check(const Builder& builder_in)
50{
51 if (builder_in.failed()) {
52 info("CircuitChecker: circuit contains invalid witnesses: ", builder_in.err());
53 }
54
56
57 // Construct a hash table for lookup table entries to efficiently determine if a lookup gate is valid
58 LookupHashTable lookup_hash_table;
59 for (const auto& table : builder.get_lookup_tables()) {
60 const FF table_index(table.table_index);
61 for (size_t i = 0; i < table.size(); ++i) {
62 lookup_hash_table.insert({ table.column_1[i], table.column_2[i], table.column_3[i], table_index });
63 }
64 }
65
66 // Instantiate structs used for checking tag and memory record correctness
67 TagCheckData tag_data;
68 MemoryCheckData memory_data{ builder };
69
70 bool result = true;
71 size_t block_idx = 0;
72 for (auto& block : builder.blocks.get()) {
73 result = result && check_block(builder, block, tag_data, memory_data, lookup_hash_table);
74 if (!result) {
75#ifndef FUZZING_DISABLE_WARNINGS
76 info("Failed at block idx = ", block_idx);
77#else
78 (void)block_idx;
79#endif
80 return false;
81 }
82 block_idx++;
83 }
84
85#ifdef ULTRA_FUZZ
86 result = result & relaxed_check_delta_range_relation(builder);
87 if (!result) {
88 return false;
89 }
90 result = result & relaxed_check_memory_relation(builder);
91 if (!result) {
92 return false;
93 }
94#endif
95#ifndef ULTRA_FUZZ
96 // Tag check is only expected to pass after entire execution trace (all blocks) have been processed
97 result = result && check_tag_data(tag_data);
98 if (!result) {
99 info("Failed tag check.");
100 return false;
101 }
102#endif
103
104 return result;
105};
106
107template <typename Builder>
109 auto& block,
110 TagCheckData& tag_data,
111 MemoryCheckData& memory_data,
112 LookupHashTable& lookup_hash_table)
113{
114 // Initialize empty AllValues of the correct Flavor based on Builder type; for input to Relation::accumulate
115 auto values = init_empty_values<Builder>();
116 Params params;
117 params.eta = memory_data.eta; // used in Memory relation for RAM/ROM consistency
118 params.eta_two = memory_data.eta_two;
119 params.eta_three = memory_data.eta_three;
120
121 auto report_fail = [&](const char* message, size_t row_idx) {
122#ifndef FUZZING_DISABLE_WARNINGS
123 info(message, row_idx);
124#else
125 (void)message;
126 (void)row_idx;
127#endif
128#ifdef CHECK_CIRCUIT_STACKTRACES
129 block.stack_traces.print(row_idx);
130#endif
131 return false;
132 };
133
134 // Perform checks on each gate defined in the builder
135 bool result = true;
136 for (size_t idx = 0; idx < block.size(); ++idx) {
137
138 populate_values(builder, block, values, tag_data, memory_data, idx);
139
140 result = result && check_relation<Arithmetic>(values, params);
141 if (!result) {
142 return report_fail("Failed Arithmetic relation at row idx = ", idx);
143 }
144 result = result && check_relation<Elliptic>(values, params);
145 if (!result) {
146 return report_fail("Failed Elliptic relation at row idx = ", idx);
147 }
148#ifndef ULTRA_FUZZ
149 result = result && check_relation<Memory>(values, params);
150 if (!result) {
151 return report_fail("Failed Memory relation at row idx = ", idx);
152 }
153 result = result && check_relation<NonNativeField>(values, params);
154 if (!result) {
155 return report_fail("Failed NonNativeField relation at row idx = ", idx);
156 }
157 result = result && check_relation<DeltaRangeConstraint>(values, params);
158 if (!result) {
159 return report_fail("Failed DeltaRangeConstraint relation at row idx = ", idx);
160 }
161#else
162 // Bigfield related nnf gates
163 if (values.q_nnf == 1) {
164 bool f0 = values.q_o == 1 && (values.q_4 == 1 || values.q_m == 1);
165 bool f1 = values.q_r == 1 && (values.q_o == 1 || values.q_4 == 1 || values.q_m == 1);
166 if (f0 && f1) {
167 result = result && check_relation<NonNativeField>(values, params);
168 if (!result) {
169 return report_fail("Failed NonNativeField relation at row idx = ", idx);
170 }
171 }
172 }
173#endif
174 result = result && check_lookup(values, lookup_hash_table);
175 if (!result) {
176 return report_fail("Failed Lookup check relation at row idx = ", idx);
177 }
178 result = result && check_relation<PoseidonInternal>(values, params);
179 if (!result) {
180 return report_fail("Failed PoseidonInternal relation at row idx = ", idx);
181 }
182 result = result && check_relation<PoseidonExternal>(values, params);
183 if (!result) {
184 return report_fail("Failed PoseidonExternal relation at row idx = ", idx);
185 }
186
187 if constexpr (IsMegaBuilder<Builder>) {
188 result = result && check_databus_read(values, builder);
189 if (!result) {
190 return report_fail("Failed databus read at row idx = ", idx);
191 }
192 // Note: EccOpQueueRelation is not checked here because it simply establishes that the ecc_op_wire
193 // polynomials contain copies of the conventional wire data in the ecc_op region (and are zero elsewhere) so
194 // there is nothing to check at the level of the builder.
195 }
196 if (!result) {
197 return report_fail("Failed at row idx = ", idx);
198 }
199 }
200
201 return result;
202};
203
204template <typename Relation> bool UltraCircuitChecker::check_relation(auto& values, auto& params)
205{
206 // Define zero initialized array to store the evaluation of each sub-relation
207 using SubrelationEvaluations = typename Relation::SumcheckArrayOfValuesOverSubrelations;
208 SubrelationEvaluations subrelation_evaluations;
209 for (auto& eval : subrelation_evaluations) {
210 eval = 0;
211 }
212
213 // Evaluate each subrelation in the relation
214 Relation::accumulate(subrelation_evaluations, values, params, /*scaling_factor=*/1);
215
216 // Ensure each subrelation evaluates to zero
217 for (auto& eval : subrelation_evaluations) {
218 if (eval != 0) {
219 return false;
220 }
221 }
222 return true;
223}
224
225bool UltraCircuitChecker::check_lookup(auto& values, auto& lookup_hash_table)
226{
227 // If this is a lookup gate, check the inputs are in the hash table containing all table entries
228 if (!values.q_lookup.is_zero()) {
229 return lookup_hash_table.contains({ values.w_l + values.q_r * values.w_l_shift,
230 values.w_r + values.q_m * values.w_r_shift,
231 values.w_o + values.q_c * values.w_o_shift,
232 values.q_o });
233 }
234 return true;
235};
236
237template <typename Builder> bool UltraCircuitChecker::check_databus_read(auto& values, Builder& builder)
238{
239 if (!values.q_busread.is_zero()) {
240 // Extract the {index, value} pair from the read gate inputs
241 auto raw_read_idx = static_cast<size_t>(uint256_t(values.w_r));
242 auto value = values.w_l;
243
244 // Map bus_idx → wire-linear selector on the values struct (mirrors BusData<i>::selector in the relation).
245 const std::array<const FF*, NUM_BUS_COLUMNS> bus_selectors{ &values.q_l, &values.q_r, &values.q_o };
246
247 // Locate the bus column being read (exactly one selector should be active on a busread row) and look up the
248 // expected value from the builder's bus vector.
249 FF bus_value{};
250 bool read_matched = false;
251 for (size_t bus_idx = 0; bus_idx < NUM_BUS_COLUMNS; ++bus_idx) {
252 if (*bus_selectors[bus_idx] == 1) {
253 const auto& bus_vec = builder.get_bus_vector(bus_idx);
254 bus_value = builder.get_variable(bus_vec[raw_read_idx]);
255 read_matched = true;
256 }
257 }
258 BB_ASSERT(read_matched);
259 return (value == bus_value);
260 }
261 return true;
262};
263
265{
266 return tag_data.left_product == tag_data.right_product;
267};
268
269template <typename Builder>
271 Builder& builder, auto& block, auto& values, TagCheckData& tag_data, MemoryCheckData& memory_data, size_t idx)
272{
273 // Function to quickly update tag products and encountered variable set by index and value
274 auto update_tag_check_data = [&](const size_t variable_index, const FF& value) {
275 size_t real_index = builder.real_variable_index[variable_index];
276 // Check to ensure that we are not including a variable twice
277 if (tag_data.encountered_variables.contains(real_index)) {
278 return;
279 }
280 uint32_t tag_in = builder.real_variable_tags[real_index];
281 if (tag_in != DEFAULT_TAG) {
282 uint32_t tag_out = builder.tau().at(tag_in);
283 tag_data.left_product *= value + tag_data.gamma * FF(tag_in);
284 tag_data.right_product *= value + tag_data.gamma * FF(tag_out);
285 tag_data.encountered_variables.insert(real_index);
286 }
287 };
288
289 // A lambda function for computing a memory record term of the form w3 * eta_three + w2 * eta_two + w1 * eta
290 auto compute_memory_record_term =
291 [](const FF& w_1, const FF& w_2, const FF& w_3, const FF& eta, const FF& eta_two, FF& eta_three) {
292 return (w_3 * eta_three + w_2 * eta_two + w_1 * eta);
293 };
294
295 // Set wire values. Wire 4 is treated specially since it may contain memory records
296 values.w_l = builder.get_variable(block.w_l()[idx]);
297 values.w_r = builder.get_variable(block.w_r()[idx]);
298 values.w_o = builder.get_variable(block.w_o()[idx]);
299 // Note: memory_data contains indices into the block to which RAM/ROM gates were added so we need to check that
300 // we are indexing into the correct block before updating the w_4 value.
301 const bool is_ram_rom_block = (&block == &builder.blocks.memory);
302 if (is_ram_rom_block && memory_data.read_record_gates.contains(idx)) {
303 values.w_4 = compute_memory_record_term(
304 values.w_l, values.w_r, values.w_o, memory_data.eta, memory_data.eta_two, memory_data.eta_three);
305 } else if (is_ram_rom_block && memory_data.write_record_gates.contains(idx)) {
306 values.w_4 =
307 compute_memory_record_term(
308 values.w_l, values.w_r, values.w_o, memory_data.eta, memory_data.eta_two, memory_data.eta_three) +
309 FF::one();
310 } else {
311 values.w_4 = builder.get_variable(block.w_4()[idx]);
312 }
313
314 // Set shifted wire values. Again, wire 4 is treated specially. On final row, set shift values to zero
315 if (idx < block.size() - 1) {
316 values.w_l_shift = builder.get_variable(block.w_l()[idx + 1]);
317 values.w_r_shift = builder.get_variable(block.w_r()[idx + 1]);
318 values.w_o_shift = builder.get_variable(block.w_o()[idx + 1]);
319 if (is_ram_rom_block && memory_data.read_record_gates.contains(idx + 1)) {
320 values.w_4_shift = compute_memory_record_term(values.w_l_shift,
321 values.w_r_shift,
322 values.w_o_shift,
323 memory_data.eta,
324 memory_data.eta_two,
325 memory_data.eta_three);
326 } else if (is_ram_rom_block && memory_data.write_record_gates.contains(idx + 1)) {
327 values.w_4_shift = compute_memory_record_term(values.w_l_shift,
328 values.w_r_shift,
329 values.w_o_shift,
330 memory_data.eta,
331 memory_data.eta_two,
332 memory_data.eta_three) +
333 FF::one();
334 } else {
335 values.w_4_shift = builder.get_variable(block.w_4()[idx + 1]);
336 }
337 } else {
338 values.w_l_shift = 0;
339 values.w_r_shift = 0;
340 values.w_o_shift = 0;
341 values.w_4_shift = 0;
342 }
343
344 // Update tag check data
345 update_tag_check_data(block.w_l()[idx], values.w_l);
346 update_tag_check_data(block.w_r()[idx], values.w_r);
347 update_tag_check_data(block.w_o()[idx], values.w_o);
348 update_tag_check_data(block.w_4()[idx], values.w_4);
349
350 // Set selector values
351 values.q_m = block.q_m()[idx];
352 values.q_c = block.q_c()[idx];
353 values.q_l = block.q_1()[idx];
354 values.q_r = block.q_2()[idx];
355 values.q_o = block.q_3()[idx];
356 values.q_4 = block.q_4()[idx];
357 values.q_arith = block.q_arith()[idx];
358 values.q_delta_range = block.q_delta_range()[idx];
359 values.q_elliptic = block.q_elliptic()[idx];
360 values.q_memory = block.q_memory()[idx];
361 values.q_nnf = block.q_nnf()[idx];
362 values.q_lookup = block.q_lookup()[idx];
363 values.q_poseidon2_internal = block.q_poseidon2_internal()[idx];
364 values.q_poseidon2_external = block.q_poseidon2_external()[idx];
365 if constexpr (IsMegaBuilder<Builder>) {
366 values.q_busread = block.q_busread()[idx];
367 }
368}
369
370#ifdef ULTRA_FUZZ
371
383template <typename Builder> bool UltraCircuitChecker::relaxed_check_delta_range_relation(Builder& builder)
384{
385 std::unordered_map<uint32_t, uint64_t> range_tags;
386 for (const auto& list : builder.range_lists) {
387 range_tags[list.second.range_tag] = list.first;
388 }
389
390 // Unprocessed blocks check
391 for (uint32_t i = 0; i < builder.real_variable_tags.size(); i++) {
392 uint32_t tag = builder.real_variable_tags[i];
393 if (tag != 0 && range_tags.contains(tag)) {
394 uint256_t range = static_cast<uint256_t>(range_tags[tag]);
395 uint256_t value = static_cast<uint256_t>(builder.get_variable(i));
396 if (value > range) {
397#ifndef FUZZING_DISABLE_WARNINGS
398 info("Failed range constraint on variable with index = ", i, ": ", value, " > ", range);
399#endif
400 return false;
401 }
402 }
403 }
404
405 // Processed blocks check
406 auto block = builder.blocks.delta_range;
407 for (size_t idx = 0; idx < block.size(); idx++) {
408 if (block.q_delta_range()[idx] == 0) {
409 continue;
410 }
411 bb::fr w1 = builder.get_variable(block.w_l()[idx]);
412 bb::fr w2 = builder.get_variable(block.w_r()[idx]);
413 bb::fr w3 = builder.get_variable(block.w_o()[idx]);
414 bb::fr w4 = builder.get_variable(block.w_4()[idx]);
415 bb::fr w5 = idx == block.size() - 1 ? builder.get_variable(0) : builder.get_variable(block.w_l()[idx + 1]);
416
417 uint256_t delta = static_cast<uint256_t>(w2 - w1);
418 if (delta > 3) {
419#ifndef FUZZING_DISABLE_WARNINGS
420 info("Failed sort constraint relation at row idx = ", idx, " with delta1 = ", delta);
421 info(w1 - w2);
422#endif
423 return false;
424 }
425 delta = static_cast<uint256_t>(w3 - w2);
426 if (delta > 3) {
427#ifndef FUZZING_DISABLE_WARNINGS
428 info("Failed sort constraint relation at row idx = ", idx, " with delta2 = ", delta);
429#endif
430 return false;
431 }
432 delta = static_cast<uint256_t>(w4 - w3);
433 if (delta > 3) {
434#ifndef FUZZING_DISABLE_WARNINGS
435 info("Failed sort constraint at row idx = ", idx, " with delta3 = ", delta);
436#endif
437 return false;
438 }
439 delta = static_cast<uint256_t>(w5 - w4);
440 if (delta > 3) {
441#ifndef FUZZING_DISABLE_WARNINGS
442 info("Failed sort constraint at row idx = ", idx, " with delta4 = ", delta);
443#endif
444 return false;
445 }
446 }
447 return true;
448}
449
463template <typename Builder> bool UltraCircuitChecker::relaxed_check_memory_relation(Builder& builder)
464{
465 for (size_t i = 0; i < builder.rom_ram_logic.rom_arrays.size(); i++) {
466 auto rom_array = builder.rom_ram_logic.rom_arrays[i];
467
468 // check set and read ROM records
469 for (auto& rr : rom_array.records) {
470 uint32_t value_witness_1 = rr.value_column1_witness;
471 uint32_t value_witness_2 = rr.value_column2_witness;
472 uint32_t index = static_cast<uint32_t>(builder.get_variable(rr.index_witness));
473
474 uint32_t table_witness_1 = rom_array.state[index][0];
475 uint32_t table_witness_2 = rom_array.state[index][1];
476
477 if (builder.get_variable(value_witness_1) != builder.get_variable(table_witness_1)) {
478#ifndef FUZZING_DISABLE_WARNINGS
479 info("Failed SET/Read ROM[0] in table = ", i, " at idx = ", index);
480#endif
481 return false;
482 }
483 if (builder.get_variable(value_witness_2) != builder.get_variable(table_witness_2)) {
484#ifndef FUZZING_DISABLE_WARNINGS
485 info("Failed SET/Read ROM[1] in table = ", i, " at idx = ", index);
486#endif
487 return false;
488 }
489 }
490 }
491
492 for (size_t i = 0; i < builder.rom_ram_logic.ram_arrays.size(); i++) {
493 auto ram_array = builder.rom_ram_logic.ram_arrays[i];
494
495 std::vector<uint32_t> tmp_state(ram_array.state.size());
496
497 // Simulate the memory call trace
498 for (auto& rr : ram_array.records) {
499 uint32_t index = static_cast<uint32_t>(builder.get_variable(rr.index_witness));
500 uint32_t value_witness = rr.value_witness;
501 auto access_type = rr.access_type;
502
503 uint32_t table_witness = tmp_state[index];
504
505 switch (access_type) {
507 if (builder.get_variable(value_witness) != builder.get_variable(table_witness)) {
508#ifndef FUZZING_DISABLE_WARNINGS
509 info("Failed RAM read in table = ", i, " at idx = ", index);
510#endif
511 return false;
512 }
513 break;
515 tmp_state[index] = value_witness;
516 break;
517 default:
518 return false;
519 }
520 }
521
522 if (tmp_state != ram_array.state) {
523#ifndef FUZZING_DISABLE_WARNINGS
524 info("Failed RAM final state check at table = ", i);
525#endif
526 return false;
527 }
528 }
529 return true;
530}
531#endif
532
533// Template method instantiations for each check method
534template bool UltraCircuitChecker::check<UltraCircuitBuilder_<UltraExecutionTraceBlocks>>(
535 const UltraCircuitBuilder_<UltraExecutionTraceBlocks>& builder_in);
536template bool UltraCircuitChecker::check<MegaCircuitBuilder_<bb::fr>>(const MegaCircuitBuilder_<bb::fr>& builder_in);
537} // namespace bb
#define BB_ASSERT(expression,...)
Definition assert.hpp:70
A base class labelling all entities (for instance, all of the polynomials used by the prover during s...
ArrayOfValues< FF, RelationImpl::SUBRELATION_PARTIAL_LENGTHS > SumcheckArrayOfValuesOverSubrelations
std::unordered_set< Key, HashFunction > LookupHashTable
static bool check_databus_read(auto &values, Builder &builder)
Check that the {index, value} pair contained in a databus read gate reflects the actual value present...
static bool check_relation(auto &values, auto &params)
Check that a given relation is satisfied for the provided inputs corresponding to a single row.
static bool check_tag_data(const TagCheckData &tag_data)
Check whether the left and right running tag products are equal.
static bool check_lookup(auto &values, auto &lookup_hash_table)
Check whether the values in a lookup gate are contained within a corresponding hash table.
static void populate_values(Builder &builder, auto &block, auto &values, TagCheckData &tag_data, MemoryCheckData &memory_data, size_t idx)
Populate the values required to check the correctness of a single "row" of the circuit.
static bool check(const Builder &builder_in)
Check the correctness of a circuit witness.
static Builder prepare_circuit(const Builder &builder_in)
Copy the builder and finalize it before checking its validity.
static bool check_block(Builder &builder, auto &block, TagCheckData &tag_data, MemoryCheckData &memory_data, LookupHashTable &lookup_hash_table)
Checks that the provided witness satisfies all gates contained in a single execution trace block.
A field element for each entity of the flavor. These entities represent the prover polynomials evalua...
#define info(...)
Definition log.hpp:93
AluTraceBuilder builder
Definition alu.test.cpp:124
Entry point for Barretenberg command-line interface.
Definition api.hpp:5
constexpr size_t NUM_BUS_COLUMNS
The DataBus; facilitates storage of public circuit input/output.
Definition databus.hpp:76
constexpr decltype(auto) get(::tuplet::tuple< T... > &&t) noexcept
Definition tuple.hpp:13
Struct for managing memory record data for ensuring RAM/ROM correctness.
Struct for managing the running tag product data for ensuring tag correctness.
std::unordered_set< size_t > encountered_variables
static constexpr field one()