diff --git a/barretenberg/.DS_Store b/barretenberg/.DS_Store new file mode 100644 index 00000000000..132e9099e2d Binary files /dev/null and b/barretenberg/.DS_Store differ diff --git a/barretenberg/.gitrepo b/barretenberg/.gitrepo index ca8c2516afd..47765c1a6ff 100644 --- a/barretenberg/.gitrepo +++ b/barretenberg/.gitrepo @@ -6,7 +6,7 @@ [subrepo] remote = https://github.com/AztecProtocol/barretenberg branch = master - commit = d041c3e8e59132328e0171fb72d61ea50936ee48 - parent = 09d0730bad4be2f4954cbb6d27538f7860d0f21f + commit = 1ec1e450ae96a9e8526b6661a81de40acb88d93a + parent = ccf9b17495ec46df6494fa93e1c848c87a05d071 method = merge cmdver = 0.4.6 diff --git a/barretenberg/bootstrap_cache.sh b/barretenberg/bootstrap_cache.sh index daa4abfc57a..71e081f77e8 100755 --- a/barretenberg/bootstrap_cache.sh +++ b/barretenberg/bootstrap_cache.sh @@ -10,4 +10,4 @@ extract_repo bb.js \ /usr/src/barretenberg/cpp/build-wasm-threads/bin ./cpp/build-wasm-threads echo -e "\033[1mBuilding ESM bb.ts...\033[0m" -(cd ts && ./bootstrap.sh esm) +(cd ts && SKIP_CPP_BUILD=1 ./scripts/build_wasm.sh && ./bootstrap.sh esm) diff --git a/barretenberg/cpp/pil/avm/avm.pil b/barretenberg/cpp/pil/avm/avm.pil new file mode 100644 index 00000000000..26268fe25cd --- /dev/null +++ b/barretenberg/cpp/pil/avm/avm.pil @@ -0,0 +1,191 @@ + +include "mem_trace.pil"; +include "alu_chip.pil"; + +namespace avmMini(256); + + //===== CONSTANT POLYNOMIALS ================================================== + pol constant clk(i) { i }; + pol constant first = [1] + [0]*; // Used mostly to toggle off the first row consisting + // only in first element of shifted polynomials. + + //===== CONTROL FLOW ========================================================== + // Program counter + pol commit pc; + // Return Pointer + pol commit internal_return_ptr; + + pol commit sel_internal_call; + pol commit sel_internal_return; + pol commit sel_jump; + + // Halt program execution + pol commit sel_halt; + + //===== TABLE SUBOP-TR ======================================================== + // Boolean selectors for (sub-)operations. Only one operation is activated at + // a time. + + // ADD + pol commit sel_op_add; + // SUB + pol commit sel_op_sub; + // MUL + pol commit sel_op_mul; + // DIV + pol commit sel_op_div; + + // Instruction memory tag (0: uninitialized, 1: u8, 2: u16, 3: u32, 4: u64, 5: u128, 6:field) + pol commit in_tag; + + // Errors + pol commit op_err; // Boolean flag pertaining to an operation error + pol commit tag_err; // Boolean flag (foreign key to memTrace.m_tag_err) + + // A helper witness being the inverse of some value + // to show a non-zero equality + pol commit inv; + + // Intermediate register values + pol commit ia; + pol commit ib; + pol commit ic; + + // Memory operation per intermediate register + pol commit mem_op_a; + pol commit mem_op_b; + pol commit mem_op_c; + + // Read-write flag per intermediate register: Read = 0, Write = 1 + pol commit rwa; + pol commit rwb; + pol commit rwc; + + // Memory index involved into a memory operation per pertaining intermediate register + // We should range constrain it to 32 bits ultimately. For first mini-AVM, + // we will assume that these columns are of the right type. + pol commit mem_idx_a; + pol commit mem_idx_b; + pol commit mem_idx_c; + + + // Track the last line of the execution trace. It does NOT correspond to the last row of the whole table + // of size N. As this depends on the supplied bytecode, this polynomial cannot be constant. + pol commit last; + + // Relations on type constraints + + sel_op_add * (1 - sel_op_add) = 0; + sel_op_sub * (1 - sel_op_sub) = 0; + sel_op_mul * (1 - sel_op_mul) = 0; + sel_op_div * (1 - sel_op_div) = 0; + + sel_internal_call * (1 - sel_internal_call) = 0; + sel_internal_return * (1 - sel_internal_return) = 0; + sel_jump * (1 - sel_jump) = 0; + sel_halt * (1 - sel_halt) = 0; + + op_err * (1 - op_err) = 0; + tag_err * (1 - tag_err) = 0; // Potential optimization (boolean constraint derivation from equivalence check to memTrace)? + + mem_op_a * (1 - mem_op_a) = 0; + mem_op_b * (1 - mem_op_b) = 0; + mem_op_c * (1 - mem_op_c) = 0; + + rwa * (1 - rwa) = 0; + rwb * (1 - rwb) = 0; + rwc * (1 - rwc) = 0; + + // TODO: Constrain rwa, rwb, rwc to u32 type and 0 <= in_tag <= 6 + + // Set intermediate registers to 0 whenever tag_err occurs + tag_err * ia = 0; + tag_err * ib = 0; + tag_err * ic = 0; + + // Relation for division over the finite field + // If tag_err == 1 in a division, then ib == 0 and op_err == 1. + #[SUBOP_DIVISION_FF] + sel_op_div * (1 - op_err) * (ic * ib - ia) = 0; + + // When sel_op_div == 1, we want ib == 0 <==> op_err == 1 + // This can be achieved with the 2 following relations. + // inv is an extra witness to show that we can invert ib, i.e., inv = ib^(-1) + // If ib == 0, we have to set inv = 1 to satisfy the second relation, + // because op_err == 1 from the first relation. + #[SUBOP_DIVISION_ZERO_ERR1] + sel_op_div * (ib * inv - 1 + op_err) = 0; + #[SUBOP_DIVISION_ZERO_ERR2] + sel_op_div * op_err * (1 - inv) = 0; + + // op_err cannot be maliciously activated for a non-relevant + // operation selector, i.e., op_err == 1 ==> sel_op_div || sel_op_XXX || ... + // op_err * (sel_op_div + sel_op_XXX + ... - 1) == 0 + // Note that the above is even a stronger constraint, as it shows + // that exactly one sel_op_XXX must be true. + // At this time, we have only division producing an error. + #[SUBOP_ERROR_RELEVANT_OP] + op_err * (sel_op_div - 1) = 0; + + // TODO: constraint that we stop execution at the first error (tag_err or op_err) + // An error can only happen at the last sub-operation row. + + // OPEN/POTENTIAL OPTIMIZATION: Dedicated error per relevant operation? + // For the division, we could lower the degree from 4 to 3 + // (sel_op_div - op_div_err) * (ic * ib - ia) = 0; + // Same for the relations related to the error activation: + // (ib * inv - 1 + op_div_err) = 0 && op_err * (1 - inv) = 0 + // This works in combination with op_div_err * (sel_op_div - 1) = 0; + // Drawback is the need to paralllelize the latter. + + //===== CONTROL FLOW ======================================================= + //===== JUMP =============================================================== + sel_jump * (pc' - ia) = 0; + + //===== INTERNAL_CALL ====================================================== + // - The program counter in the next row should be equal to the value loaded from the ia register + // - We then write the return location (pc + 1) into the call stack (in memory) + + #[RETURN_POINTER_INCREMENT] + sel_internal_call * (internal_return_ptr' - (internal_return_ptr + 1)) = 0; + sel_internal_call * (internal_return_ptr - mem_idx_b) = 0; + sel_internal_call * (pc' - ia) = 0; + sel_internal_call * ((pc + 1) - ib) = 0; + + // TODO(md): Below relations may be removed through sub-op table lookup + sel_internal_call * (rwb - 1) = 0; + sel_internal_call * (mem_op_b - 1) = 0; + + //===== INTERNAL_RETURN =================================================== + // - We load the memory pointer to be the internal_return_ptr + // - Constrain then next program counter to be the loaded value + // - decrement the internal_return_ptr + + #[RETURN_POINTER_DECREMENT] + sel_internal_return * (internal_return_ptr' - (internal_return_ptr - 1)) = 0; + sel_internal_return * ((internal_return_ptr - 1) - mem_idx_a) = 0; + sel_internal_return * (pc' - ia) = 0; + + // TODO(md): Below relations may be removed through sub-op table lookup + sel_internal_return * rwa = 0; + sel_internal_return * (mem_op_a - 1) = 0; + + //===== CONTROL_FLOW_CONSISTENCY ============================================ + pol INTERNAL_CALL_STACK_SELECTORS = (first + sel_internal_call + sel_internal_return + sel_halt); + pol OPCODE_SELECTORS = (sel_op_add + sel_op_sub + sel_op_div + sel_op_mul); + + // Program counter must increment if not jumping or returning + #[PC_INCREMENT] + (1 - first) * (1 - sel_halt) * OPCODE_SELECTORS * (pc' - (pc + 1)) = 0; + + // first == 0 && sel_internal_call == 0 && sel_internal_return == 0 && sel_halt == 0 ==> internal_return_ptr == internal_return_ptr' + #[INTERNAL_RETURN_POINTER_CONSISTENCY] + (1 - INTERNAL_CALL_STACK_SELECTORS) * (internal_return_ptr' - internal_return_ptr) = 0; + + // TODO: we want to set an initial number for the reserved memory of the jump pointer + + // Inter-table Constraints + + // TODO: tag_err {clk} IS memTrace.m_tag_err {memTrace.m_clk} + // TODO: Map memory trace with intermediate register values whenever there is no tag error, sthg like: + // mem_op_a * (1 - tag_err) {mem_idx_a, clk, ia, rwa} IS m_sub_clk == 0 && 1 - m_tag_err {m_addr, m_clk, m_val, m_rw} diff --git a/barretenberg/cpp/src/CMakeLists.txt b/barretenberg/cpp/src/CMakeLists.txt index 0ca963d4f87..65176f7c421 100644 --- a/barretenberg/cpp/src/CMakeLists.txt +++ b/barretenberg/cpp/src/CMakeLists.txt @@ -137,7 +137,8 @@ set(BARRETENBERG_TARGET_OBJECTS $ $ $ - $) + $ + $) add_library( barretenberg diff --git a/barretenberg/cpp/src/barretenberg/bb/main.cpp b/barretenberg/cpp/src/barretenberg/bb/main.cpp index b49d6f95908..fa91f8f3667 100644 --- a/barretenberg/cpp/src/barretenberg/bb/main.cpp +++ b/barretenberg/cpp/src/barretenberg/bb/main.cpp @@ -1,5 +1,9 @@ +#include "barretenberg/bb/file_io.hpp" +#include "barretenberg/common/serialize.hpp" #include "barretenberg/dsl/types.hpp" +#include "barretenberg/honk/proof_system/types/proof.hpp" #include "barretenberg/plonk/proof_system/proving_key/serialize.hpp" +#include "barretenberg/vm/avm_trace/AvmMini_execution.hpp" #include "config.hpp" #include "get_bn254_crs.hpp" #include "get_bytecode.hpp" @@ -12,6 +16,7 @@ #include #include #include +#include #include #include #include @@ -506,6 +511,7 @@ int main(int argc, char* argv[]) if (command == "prove_and_verify_goblin") { return proveAndVerifyGoblin(bytecode_path, witness_path) ? 0 : 1; } + if (command == "prove") { std::string output_path = get_option(args, "-o", "./proofs/proof"); prove(bytecode_path, witness_path, output_path); @@ -528,6 +534,23 @@ int main(int argc, char* argv[]) } else if (command == "vk_as_fields") { std::string output_path = get_option(args, "-o", vk_path + "_fields.json"); vk_as_fields(vk_path, output_path); + } else if (command == "avm_prove") { + std::string avm_bytecode_path = get_option(args, "-b", "./target/avm_bytecode.bin"); + std::string output_path = get_option(args, "-o", "./proofs/avm_proof"); + std::vector call_data_bytes{}; + + if (flag_present(args, "-d")) { + auto const call_data_path = get_option(args, "-d", "./target/call_data.bin"); + call_data_bytes = read_file(call_data_path); + } + + srs::init_crs_factory("../srs_db/ignition"); + + std::vector const call_data = many_from_buffer(call_data_bytes); + auto const avm_bytecode = read_file(avm_bytecode_path); + auto const proof = avm_trace::Execution::run_and_prove(avm_bytecode, call_data); + std::vector const proof_bytes = to_buffer(proof); + write_file(output_path, proof_bytes); } else { std::cerr << "Unknown command: " << command << "\n"; return 1; diff --git a/barretenberg/cpp/src/barretenberg/benchmark/goblin_bench/eccvm.bench.cpp b/barretenberg/cpp/src/barretenberg/benchmark/goblin_bench/eccvm.bench.cpp index 949658c5bd0..2805fde8286 100644 --- a/barretenberg/cpp/src/barretenberg/benchmark/goblin_bench/eccvm.bench.cpp +++ b/barretenberg/cpp/src/barretenberg/benchmark/goblin_bench/eccvm.bench.cpp @@ -7,9 +7,9 @@ using namespace benchmark; using namespace bb; -using Flavor = honk::flavor::ECCVM; +using Flavor = ECCVMFlavor; using Builder = ECCVMCircuitBuilder; -using Composer = honk::ECCVMComposer; +using Composer = ECCVMComposer; namespace { diff --git a/barretenberg/cpp/src/barretenberg/benchmark/ipa_bench/ipa.bench.cpp b/barretenberg/cpp/src/barretenberg/benchmark/ipa_bench/ipa.bench.cpp index 3a25ee93dfd..af594ba44e6 100644 --- a/barretenberg/cpp/src/barretenberg/benchmark/ipa_bench/ipa.bench.cpp +++ b/barretenberg/cpp/src/barretenberg/benchmark/ipa_bench/ipa.bench.cpp @@ -3,28 +3,22 @@ using namespace benchmark; using namespace bb; -using namespace bb::honk::pcs::ipa; + namespace { using Curve = curve::Grumpkin; using Fr = Curve::ScalarField; -using IPA = IPA; -using OpeningPair = honk::pcs::OpeningPair; -using OpeningClaim = honk::pcs::OpeningClaim; -using Polynomial = Polynomial; -using CommitmentKey = honk::pcs::CommitmentKey; -using VerifierCommitmentKey = honk::pcs::VerifierCommitmentKey; constexpr size_t MIN_POLYNOMIAL_DEGREE_LOG2 = 10; constexpr size_t MAX_POLYNOMIAL_DEGREE_LOG2 = 16; std::shared_ptr> crs_factory( new bb::srs::factories::FileCrsFactory("../srs_db/grumpkin", 1 << 16)); -auto ck = std::make_shared(1 << MAX_POLYNOMIAL_DEGREE_LOG2, crs_factory); -auto vk = std::make_shared(1 << MAX_POLYNOMIAL_DEGREE_LOG2, crs_factory); +auto ck = std::make_shared>(1 << MAX_POLYNOMIAL_DEGREE_LOG2, crs_factory); +auto vk = std::make_shared>(1 << MAX_POLYNOMIAL_DEGREE_LOG2, crs_factory); -std::vector> prover_transcripts(MAX_POLYNOMIAL_DEGREE_LOG2 - - MIN_POLYNOMIAL_DEGREE_LOG2 + 1); -std::vector opening_claims(MAX_POLYNOMIAL_DEGREE_LOG2 - MIN_POLYNOMIAL_DEGREE_LOG2 + 1); +std::vector> prover_transcripts(MAX_POLYNOMIAL_DEGREE_LOG2 - + MIN_POLYNOMIAL_DEGREE_LOG2 + 1); +std::vector> opening_claims(MAX_POLYNOMIAL_DEGREE_LOG2 - MIN_POLYNOMIAL_DEGREE_LOG2 + 1); void ipa_open(State& state) noexcept { @@ -33,19 +27,19 @@ void ipa_open(State& state) noexcept state.PauseTiming(); size_t n = 1 << static_cast(state.range(0)); // Construct the polynomial - Polynomial poly(n); + Polynomial poly(n); for (size_t i = 0; i < n; ++i) { poly[i] = Fr::random_element(&engine); } auto x = Fr::random_element(&engine); auto eval = poly.evaluate(x); - const OpeningPair opening_pair = { x, eval }; - const OpeningClaim opening_claim{ opening_pair, ck->commit(poly) }; + const OpeningPair opening_pair = { x, eval }; + const OpeningClaim opening_claim{ opening_pair, ck->commit(poly) }; // initialize empty prover transcript - auto prover_transcript = std::make_shared(); + auto prover_transcript = std::make_shared(); state.ResumeTiming(); // Compute proof - IPA::compute_opening_proof(ck, opening_pair, poly, prover_transcript); + IPA::compute_opening_proof(ck, opening_pair, poly, prover_transcript); // Store info for verifier prover_transcripts[static_cast(state.range(0)) - MIN_POLYNOMIAL_DEGREE_LOG2] = prover_transcript; opening_claims[static_cast(state.range(0)) - MIN_POLYNOMIAL_DEGREE_LOG2] = opening_claim; @@ -59,10 +53,10 @@ void ipa_verify(State& state) noexcept auto prover_transcript = prover_transcripts[static_cast(state.range(0)) - MIN_POLYNOMIAL_DEGREE_LOG2]; auto opening_claim = opening_claims[static_cast(state.range(0)) - MIN_POLYNOMIAL_DEGREE_LOG2]; // initialize verifier transcript from proof data - auto verifier_transcript = std::make_shared(prover_transcript->proof_data); + auto verifier_transcript = std::make_shared(prover_transcript->proof_data); state.ResumeTiming(); - auto result = IPA::verify(vk, opening_claim, verifier_transcript); + auto result = IPA::verify(vk, opening_claim, verifier_transcript); ASSERT(result); } } diff --git a/barretenberg/cpp/src/barretenberg/benchmark/protogalaxy_bench/protogalaxy.bench.cpp b/barretenberg/cpp/src/barretenberg/benchmark/protogalaxy_bench/protogalaxy.bench.cpp index 26bebca3da7..156587d5133 100644 --- a/barretenberg/cpp/src/barretenberg/benchmark/protogalaxy_bench/protogalaxy.bench.cpp +++ b/barretenberg/cpp/src/barretenberg/benchmark/protogalaxy_bench/protogalaxy.bench.cpp @@ -6,8 +6,8 @@ using namespace benchmark; -namespace bb::honk { -using Flavor = flavor::Ultra; +namespace bb { +using Flavor = UltraFlavor; using Instance = ProverInstance_; using Instances = ProverInstances_; using ProtoGalaxyProver = ProtoGalaxyProver_; @@ -38,6 +38,6 @@ void fold_one(State& state) noexcept } BENCHMARK(fold_one)->/* vary the circuit size */ DenseRange(14, 20)->Unit(kMillisecond); -} // namespace bb::honk +} // namespace bb BENCHMARK_MAIN(); diff --git a/barretenberg/cpp/src/barretenberg/benchmark/relations_bench/relations.bench.cpp b/barretenberg/cpp/src/barretenberg/benchmark/relations_bench/relations.bench.cpp index 076da57aa17..45d2c1acbe2 100644 --- a/barretenberg/cpp/src/barretenberg/benchmark/relations_bench/relations.bench.cpp +++ b/barretenberg/cpp/src/barretenberg/benchmark/relations_bench/relations.bench.cpp @@ -8,8 +8,6 @@ namespace { auto& engine = bb::numeric::get_debug_randomness(); } -using namespace bb::honk::sumcheck; - namespace bb::benchmark::relations { using Fr = bb::fr; @@ -33,28 +31,28 @@ template void execute_relation(::benchmark: Relation::accumulate(accumulator, new_value, params, 1); } } -BENCHMARK(execute_relation>); -BENCHMARK(execute_relation>); -BENCHMARK(execute_relation>); -BENCHMARK(execute_relation>); -BENCHMARK(execute_relation>); -BENCHMARK(execute_relation>); - -BENCHMARK(execute_relation>); - -BENCHMARK(execute_relation>); -BENCHMARK(execute_relation>); -BENCHMARK(execute_relation>); -BENCHMARK(execute_relation>); -BENCHMARK(execute_relation>); -BENCHMARK(execute_relation>); - -BENCHMARK(execute_relation>); -BENCHMARK(execute_relation>); -BENCHMARK(execute_relation>); -BENCHMARK(execute_relation>); -BENCHMARK(execute_relation>); -BENCHMARK(execute_relation>); +BENCHMARK(execute_relation>); +BENCHMARK(execute_relation>); +BENCHMARK(execute_relation>); +BENCHMARK(execute_relation>); +BENCHMARK(execute_relation>); +BENCHMARK(execute_relation>); + +BENCHMARK(execute_relation>); + +BENCHMARK(execute_relation>); +BENCHMARK(execute_relation>); +BENCHMARK(execute_relation>); +BENCHMARK(execute_relation>); +BENCHMARK(execute_relation>); +BENCHMARK(execute_relation>); + +BENCHMARK(execute_relation>); +BENCHMARK(execute_relation>); +BENCHMARK(execute_relation>); +BENCHMARK(execute_relation>); +BENCHMARK(execute_relation>); +BENCHMARK(execute_relation>); } // namespace bb::benchmark::relations diff --git a/barretenberg/cpp/src/barretenberg/benchmark/ultra_bench/mock_proofs.hpp b/barretenberg/cpp/src/barretenberg/benchmark/ultra_bench/mock_proofs.hpp index 369a5bd8576..da9c1f2f108 100644 --- a/barretenberg/cpp/src/barretenberg/benchmark/ultra_bench/mock_proofs.hpp +++ b/barretenberg/cpp/src/barretenberg/benchmark/ultra_bench/mock_proofs.hpp @@ -48,13 +48,13 @@ template void generate_basic_arithmetic_circuit(Builder& buil } // ultrahonk -inline honk::UltraProver get_prover(honk::UltraComposer& composer, - void (*test_circuit_function)(honk::UltraComposer::CircuitBuilder&, size_t), - size_t num_iterations) +inline UltraProver get_prover(UltraComposer& composer, + void (*test_circuit_function)(UltraComposer::CircuitBuilder&, size_t), + size_t num_iterations) { - honk::UltraComposer::CircuitBuilder builder; + UltraComposer::CircuitBuilder builder; test_circuit_function(builder, num_iterations); - std::shared_ptr instance = composer.create_instance(builder); + std::shared_ptr instance = composer.create_instance(builder); return composer.create_prover(instance); } @@ -70,7 +70,7 @@ inline plonk::Prover get_prover(plonk::StandardComposer& composer, // ultraplonk inline plonk::UltraProver get_prover(plonk::UltraComposer& composer, - void (*test_circuit_function)(honk::UltraComposer::CircuitBuilder&, size_t), + void (*test_circuit_function)(UltraComposer::CircuitBuilder&, size_t), size_t num_iterations) { plonk::UltraComposer::CircuitBuilder builder; diff --git a/barretenberg/cpp/src/barretenberg/benchmark/ultra_bench/ultra_honk.bench.cpp b/barretenberg/cpp/src/barretenberg/benchmark/ultra_bench/ultra_honk.bench.cpp index c0320b135a3..29139186659 100644 --- a/barretenberg/cpp/src/barretenberg/benchmark/ultra_bench/ultra_honk.bench.cpp +++ b/barretenberg/cpp/src/barretenberg/benchmark/ultra_bench/ultra_honk.bench.cpp @@ -14,7 +14,7 @@ static void construct_proof_ultrahonk(State& state, void (*test_circuit_function)(UltraCircuitBuilder&, size_t)) noexcept { size_t num_iterations = 10; // 10x the circuit - bb::mock_proofs::construct_proof_with_specified_num_iterations( + bb::mock_proofs::construct_proof_with_specified_num_iterations( state, test_circuit_function, num_iterations); } @@ -24,7 +24,7 @@ static void construct_proof_ultrahonk(State& state, static void construct_proof_ultrahonk_power_of_2(State& state) noexcept { auto log2_of_gates = static_cast(state.range(0)); - bb::mock_proofs::construct_proof_with_specified_num_iterations( + bb::mock_proofs::construct_proof_with_specified_num_iterations( state, &bb::mock_proofs::generate_basic_arithmetic_circuit, log2_of_gates); } diff --git a/barretenberg/cpp/src/barretenberg/benchmark/ultra_bench/ultra_honk_rounds.bench.cpp b/barretenberg/cpp/src/barretenberg/benchmark/ultra_bench/ultra_honk_rounds.bench.cpp index 18066f4d370..e91343143a8 100644 --- a/barretenberg/cpp/src/barretenberg/benchmark/ultra_bench/ultra_honk_rounds.bench.cpp +++ b/barretenberg/cpp/src/barretenberg/benchmark/ultra_bench/ultra_honk_rounds.bench.cpp @@ -27,7 +27,7 @@ enum { * @param prover - The ultrahonk prover. * @param index - The pass to measure. **/ -BBERG_PROFILE static void test_round_inner(State& state, honk::UltraProver& prover, size_t index) noexcept +BBERG_PROFILE static void test_round_inner(State& state, UltraProver& prover, size_t index) noexcept { auto time_if_index = [&](size_t target_index, auto&& func) -> void { if (index == target_index) { @@ -53,9 +53,9 @@ BBERG_PROFILE static void test_round(State& state, size_t index) noexcept for (auto _ : state) { state.PauseTiming(); - honk::UltraComposer composer; + UltraComposer composer; // TODO(https://github.com/AztecProtocol/barretenberg/issues/761) benchmark both sparse and dense circuits - honk::UltraProver prover = bb::mock_proofs::get_prover( + UltraProver prover = bb::mock_proofs::get_prover( composer, &bb::stdlib::generate_ecdsa_verification_test_circuit, 10); test_round_inner(state, prover, index); state.ResumeTiming(); diff --git a/barretenberg/cpp/src/barretenberg/commitment_schemes/claim.hpp b/barretenberg/cpp/src/barretenberg/commitment_schemes/claim.hpp index 2ef8c69637e..61f32b8d6d1 100644 --- a/barretenberg/cpp/src/barretenberg/commitment_schemes/claim.hpp +++ b/barretenberg/cpp/src/barretenberg/commitment_schemes/claim.hpp @@ -3,7 +3,7 @@ #include "barretenberg/commitment_schemes/commitment_key.hpp" #include "barretenberg/polynomials/polynomial.hpp" -namespace bb::honk::pcs { +namespace bb { /** * @brief Opening pair (r,v) for some witness polynomial p(X) such that p(r) = v * @@ -72,4 +72,4 @@ template class OpeningClaim { bool operator==(const OpeningClaim& other) const = default; }; -} // namespace bb::honk::pcs +} // namespace bb diff --git a/barretenberg/cpp/src/barretenberg/commitment_schemes/commit.bench.cpp b/barretenberg/cpp/src/barretenberg/commitment_schemes/commit.bench.cpp index e0b87c902d6..61525c1cd6d 100644 --- a/barretenberg/cpp/src/barretenberg/commitment_schemes/commit.bench.cpp +++ b/barretenberg/cpp/src/barretenberg/commitment_schemes/commit.bench.cpp @@ -5,8 +5,7 @@ namespace bb { -template -std::shared_ptr> create_commitment_key(const size_t num_points) +template std::shared_ptr> create_commitment_key(const size_t num_points) { std::string srs_path; if constexpr (std::same_as) { @@ -16,7 +15,7 @@ std::shared_ptr> create_commitment_key(const siz srs_path = "../srs_db/grumpkin"; } auto crs_factory = std::make_shared>(srs_path, num_points); - return std::make_shared>(num_points, crs_factory); + return std::make_shared>(num_points, crs_factory); } constexpr size_t MAX_LOG_NUM_POINTS = 24; diff --git a/barretenberg/cpp/src/barretenberg/commitment_schemes/commitment_key.hpp b/barretenberg/cpp/src/barretenberg/commitment_schemes/commitment_key.hpp index 201a022fdb5..73369a2965d 100644 --- a/barretenberg/cpp/src/barretenberg/commitment_schemes/commitment_key.hpp +++ b/barretenberg/cpp/src/barretenberg/commitment_schemes/commitment_key.hpp @@ -19,7 +19,7 @@ #include #include -namespace bb::honk::pcs { +namespace bb { /** * @brief CommitmentKey object over a pairing group 𝔾₁. @@ -74,4 +74,4 @@ template class CommitmentKey { std::shared_ptr> srs; }; -} // namespace bb::honk::pcs +} // namespace bb diff --git a/barretenberg/cpp/src/barretenberg/commitment_schemes/commitment_key.test.hpp b/barretenberg/cpp/src/barretenberg/commitment_schemes/commitment_key.test.hpp index 3350e2ed867..69d7cdc05dd 100644 --- a/barretenberg/cpp/src/barretenberg/commitment_schemes/commitment_key.test.hpp +++ b/barretenberg/cpp/src/barretenberg/commitment_schemes/commitment_key.test.hpp @@ -13,7 +13,7 @@ #include -namespace bb::honk::pcs { +namespace bb { template inline std::shared_ptr CreateCommitmentKey(); @@ -202,8 +202,5 @@ typename std::shared_ptr> CommitmentTest::ve using CommitmentSchemeParams = ::testing::Types; using IpaCommitmentSchemeParams = ::testing::Types; -// IMPROVEMENT: reinstate typed-tests for multiple field types, i.e.: -// using CommitmentSchemeParams = -// ::testing::Types, fake::Params, kzg::Params>; -} // namespace bb::honk::pcs +} // namespace bb diff --git a/barretenberg/cpp/src/barretenberg/commitment_schemes/gemini/gemini.cpp b/barretenberg/cpp/src/barretenberg/commitment_schemes/gemini/gemini.cpp index 0d1890abd66..19e815f8ab5 100644 --- a/barretenberg/cpp/src/barretenberg/commitment_schemes/gemini/gemini.cpp +++ b/barretenberg/cpp/src/barretenberg/commitment_schemes/gemini/gemini.cpp @@ -42,7 +42,7 @@ * The verifier is able to computed the simulated commitments to A₀₊(X) and A₀₋(X) * since they are linear-combinations of the commitments [fⱼ] and [gⱼ]. */ -namespace bb::honk::pcs::gemini { +namespace bb { /** * @brief Computes d-1 fold polynomials Fold_i, i = 1, ..., d-1 @@ -141,7 +141,7 @@ std::vector> GeminiProver_< * @param r_challenge univariate opening challenge */ template -ProverOutput GeminiProver_::compute_fold_polynomial_evaluations( +GeminiProverOutput GeminiProver_::compute_fold_polynomial_evaluations( std::span mle_opening_point, std::vector&& gemini_polynomials, const Fr& r_challenge) { const size_t num_variables = mle_opening_point.size(); // m @@ -150,7 +150,7 @@ ProverOutput GeminiProver_::compute_fold_polynomial_evaluations( Polynomial& batched_G = gemini_polynomials[1]; // G(X) = ∑ⱼ ρᵏ⁺ʲ gⱼ(X) // Compute univariate opening queries rₗ = r^{2ˡ} for l = 0, 1, ..., m-1 - std::vector r_squares = squares_of_r(r_challenge, num_variables); + std::vector r_squares = gemini::squares_of_r(r_challenge, num_variables); // Compute G/r Fr r_inv = r_challenge.invert(); @@ -188,4 +188,4 @@ ProverOutput GeminiProver_::compute_fold_polynomial_evaluations( template class GeminiProver_; template class GeminiProver_; -}; // namespace bb::honk::pcs::gemini +}; // namespace bb diff --git a/barretenberg/cpp/src/barretenberg/commitment_schemes/gemini/gemini.hpp b/barretenberg/cpp/src/barretenberg/commitment_schemes/gemini/gemini.hpp index c417b4b76b3..6edf56c0b4b 100644 --- a/barretenberg/cpp/src/barretenberg/commitment_schemes/gemini/gemini.hpp +++ b/barretenberg/cpp/src/barretenberg/commitment_schemes/gemini/gemini.hpp @@ -42,7 +42,7 @@ * The verifier is able to computed the simulated commitments to A₀₊(X) and A₀₋(X) * since they are linear-combinations of the commitments [fⱼ] and [gⱼ]. */ -namespace bb::honk::pcs::gemini { +namespace bb { /** * @brief Prover output (evalutation pair, witness) that can be passed on to Shplonk batch opening. @@ -57,11 +57,12 @@ namespace bb::honk::pcs::gemini { * ] * @tparam Curve CommitmentScheme parameters */ -template struct ProverOutput { +template struct GeminiProverOutput { std::vector> opening_pairs; std::vector> witnesses; }; +namespace gemini { /** * @brief Compute powers of challenge ρ * @@ -96,6 +97,7 @@ template inline std::vector squares_of_r(const Fr r, const size_t } return squares; }; +} // namespace gemini template class GeminiProver_ { using Fr = typename Curve::ScalarField; @@ -106,10 +108,10 @@ template class GeminiProver_ { Polynomial&& batched_unshifted, Polynomial&& batched_to_be_shifted); - static ProverOutput compute_fold_polynomial_evaluations(std::span mle_opening_point, - std::vector&& gemini_polynomials, - const Fr& r_challenge); -}; // namespace bb::honk::pcs::gemini + static GeminiProverOutput compute_fold_polynomial_evaluations(std::span mle_opening_point, + std::vector&& gemini_polynomials, + const Fr& r_challenge); +}; // namespace bb template class GeminiVerifier_ { using Fr = typename Curve::ScalarField; @@ -148,7 +150,7 @@ template class GeminiVerifier_ { // compute vector of powers of random evaluation point r const Fr r = transcript->get_challenge("Gemini:r"); - std::vector r_squares = squares_of_r(r, num_variables); + std::vector r_squares = gemini::squares_of_r(r, num_variables); // Get evaluations a_i, i = 0,...,m-1 from transcript std::vector evaluations; @@ -261,7 +263,6 @@ template class GeminiVerifier_ { return { C0_r_pos, C0_r_neg }; } +}; -}; // namespace bb::honk::pcs::gemini - -} // namespace bb::honk::pcs::gemini +} // namespace bb diff --git a/barretenberg/cpp/src/barretenberg/commitment_schemes/gemini/gemini.test.cpp b/barretenberg/cpp/src/barretenberg/commitment_schemes/gemini/gemini.test.cpp index 09f65bbc635..0574dcfa115 100644 --- a/barretenberg/cpp/src/barretenberg/commitment_schemes/gemini/gemini.test.cpp +++ b/barretenberg/cpp/src/barretenberg/commitment_schemes/gemini/gemini.test.cpp @@ -8,9 +8,6 @@ #include using namespace bb; -using namespace bb::honk; -using namespace bb::honk::pcs; -using namespace bb::honk::pcs::gemini; template class GeminiTest : public CommitmentTest { using GeminiProver = GeminiProver_; @@ -32,7 +29,7 @@ template class GeminiTest : public CommitmentTest { const Fr rho = Fr::random_element(); - std::vector rhos = pcs::gemini::powers_of_rho(rho, multilinear_evaluations.size()); + std::vector rhos = gemini::powers_of_rho(rho, multilinear_evaluations.size()); // Compute batched multivariate evaluation Fr batched_evaluation = Fr::zero(); diff --git a/barretenberg/cpp/src/barretenberg/commitment_schemes/ipa/ipa.hpp b/barretenberg/cpp/src/barretenberg/commitment_schemes/ipa/ipa.hpp index 666ac255aa4..ccac4dbdc2f 100644 --- a/barretenberg/cpp/src/barretenberg/commitment_schemes/ipa/ipa.hpp +++ b/barretenberg/cpp/src/barretenberg/commitment_schemes/ipa/ipa.hpp @@ -14,7 +14,7 @@ * https://hackmd.io/q-A8y6aITWyWJrvsGGMWNA?view. * */ -namespace bb::honk::pcs::ipa { +namespace bb { template class IPA { using Fr = typename Curve::ScalarField; using GroupElement = typename Curve::Element; @@ -288,4 +288,4 @@ template class IPA { } }; -} // namespace bb::honk::pcs::ipa \ No newline at end of file +} // namespace bb \ No newline at end of file diff --git a/barretenberg/cpp/src/barretenberg/commitment_schemes/ipa/ipa.test.cpp b/barretenberg/cpp/src/barretenberg/commitment_schemes/ipa/ipa.test.cpp index e68f79f4861..b1d61d63df4 100644 --- a/barretenberg/cpp/src/barretenberg/commitment_schemes/ipa/ipa.test.cpp +++ b/barretenberg/cpp/src/barretenberg/commitment_schemes/ipa/ipa.test.cpp @@ -10,10 +10,8 @@ #include using namespace bb; -using namespace bb::honk; -using namespace bb::honk::pcs; -using namespace bb::honk::pcs::ipa; +namespace { using Curve = curve::Grumpkin; class IPATest : public CommitmentTest { @@ -24,6 +22,7 @@ class IPATest : public CommitmentTest { using VK = VerifierCommitmentKey; using Polynomial = bb::Polynomial; }; +} // namespace TEST_F(IPATest, CommitOnManyZeroCoeffPolyWorks) { @@ -88,10 +87,10 @@ TEST_F(IPATest, Open) TEST_F(IPATest, GeminiShplonkIPAWithShift) { using IPA = IPA; - using ShplonkProver = shplonk::ShplonkProver_; - using ShplonkVerifier = shplonk::ShplonkVerifier_; - using GeminiProver = gemini::GeminiProver_; - using GeminiVerifier = gemini::GeminiVerifier_; + using ShplonkProver = ShplonkProver_; + using ShplonkVerifier = ShplonkVerifier_; + using GeminiProver = GeminiProver_; + using GeminiVerifier = GeminiVerifier_; const size_t n = 8; const size_t log_n = 3; diff --git a/barretenberg/cpp/src/barretenberg/commitment_schemes/kzg/kzg.hpp b/barretenberg/cpp/src/barretenberg/commitment_schemes/kzg/kzg.hpp index 3780b10ef85..1e4a0f1b18e 100644 --- a/barretenberg/cpp/src/barretenberg/commitment_schemes/kzg/kzg.hpp +++ b/barretenberg/cpp/src/barretenberg/commitment_schemes/kzg/kzg.hpp @@ -9,7 +9,7 @@ #include #include -namespace bb::honk::pcs::kzg { +namespace bb { template class KZG { using CK = CommitmentKey; @@ -101,4 +101,4 @@ template class KZG { return { P_0, P_1 }; }; }; -} // namespace bb::honk::pcs::kzg +} // namespace bb diff --git a/barretenberg/cpp/src/barretenberg/commitment_schemes/kzg/kzg.test.cpp b/barretenberg/cpp/src/barretenberg/commitment_schemes/kzg/kzg.test.cpp index 30c02c0543a..9e45ffff90a 100644 --- a/barretenberg/cpp/src/barretenberg/commitment_schemes/kzg/kzg.test.cpp +++ b/barretenberg/cpp/src/barretenberg/commitment_schemes/kzg/kzg.test.cpp @@ -12,7 +12,7 @@ #include #include -namespace bb::honk::pcs::kzg { +namespace bb { template class KZGTest : public CommitmentTest { public: @@ -57,10 +57,10 @@ TYPED_TEST(KZGTest, single) */ TYPED_TEST(KZGTest, GeminiShplonkKzgWithShift) { - using ShplonkProver = shplonk::ShplonkProver_; - using ShplonkVerifier = shplonk::ShplonkVerifier_; - using GeminiProver = gemini::GeminiProver_; - using GeminiVerifier = gemini::GeminiVerifier_; + using ShplonkProver = ShplonkProver_; + using ShplonkVerifier = ShplonkVerifier_; + using GeminiProver = GeminiProver_; + using GeminiVerifier = GeminiVerifier_; using KZG = KZG; using Fr = typename TypeParam::ScalarField; using GroupElement = typename TypeParam::Element; @@ -177,4 +177,4 @@ TYPED_TEST(KZGTest, GeminiShplonkKzgWithShift) EXPECT_EQ(verified, true); } -} // namespace bb::honk::pcs::kzg +} // namespace bb diff --git a/barretenberg/cpp/src/barretenberg/commitment_schemes/shplonk/shplonk.hpp b/barretenberg/cpp/src/barretenberg/commitment_schemes/shplonk/shplonk.hpp index 7f0f53093a4..a73ffa37a8f 100644 --- a/barretenberg/cpp/src/barretenberg/commitment_schemes/shplonk/shplonk.hpp +++ b/barretenberg/cpp/src/barretenberg/commitment_schemes/shplonk/shplonk.hpp @@ -18,7 +18,7 @@ * The challenges are ρ (batching) and r (random evaluation). * */ -namespace bb::honk::pcs::shplonk { +namespace bb { /** * @brief Polynomial G(X) = Q(X) - ∑ₖ ẑₖ(r)⋅( Bₖ(X) − Tₖ(z) ), where Q(X) = ∑ₖ ( Bₖ(X) − Tₖ(X) ) / zₖ(X) @@ -33,7 +33,7 @@ template using OutputWitness = bb::Polynomial struct ProverOutput { +template struct ShplonkProverOutput { OpeningPair opening_pair; // single opening pair (challenge, evaluation) OutputWitness witness; // single polynomial G(X) }; @@ -97,7 +97,7 @@ template class ShplonkProver_ { * @param z_challenge * @return Output{OpeningPair, Polynomial} */ - static ProverOutput compute_partially_evaluated_batched_quotient( + static ShplonkProverOutput compute_partially_evaluated_batched_quotient( std::span> opening_pairs, std::span witness_polynomials, Polynomial&& batched_quotient_Q, @@ -271,4 +271,4 @@ template class ShplonkVerifier_ { return { { z_challenge, Fr(0) }, G_commitment }; }; }; -} // namespace bb::honk::pcs::shplonk +} // namespace bb diff --git a/barretenberg/cpp/src/barretenberg/commitment_schemes/shplonk/shplonk.test.cpp b/barretenberg/cpp/src/barretenberg/commitment_schemes/shplonk/shplonk.test.cpp index 6e754ae127b..ee5168b2253 100644 --- a/barretenberg/cpp/src/barretenberg/commitment_schemes/shplonk/shplonk.test.cpp +++ b/barretenberg/cpp/src/barretenberg/commitment_schemes/shplonk/shplonk.test.cpp @@ -10,7 +10,7 @@ #include "../commitment_key.test.hpp" #include "barretenberg/commitment_schemes/claim.hpp" #include "barretenberg/polynomials/polynomial.hpp" -namespace bb::honk::pcs::shplonk { +namespace bb { template class ShplonkTest : public CommitmentTest {}; using CurveTypes = ::testing::Types; @@ -23,7 +23,7 @@ TYPED_TEST(ShplonkTest, ShplonkSimple) using ShplonkVerifier = ShplonkVerifier_; using Fr = typename TypeParam::ScalarField; using Polynomial = typename bb::Polynomial; - using OpeningPair = OpeningPair; + using OpeningPair = bb::OpeningPair; using OpeningClaim = OpeningClaim; const size_t n = 16; @@ -71,4 +71,4 @@ TYPED_TEST(ShplonkTest, ShplonkSimple) this->verify_opening_claim(verifier_claim, shplonk_prover_witness); } -} // namespace bb::honk::pcs::shplonk +} // namespace bb diff --git a/barretenberg/cpp/src/barretenberg/commitment_schemes/verification_key.hpp b/barretenberg/cpp/src/barretenberg/commitment_schemes/verification_key.hpp index 3d6429875bc..c1771ce2ce5 100644 --- a/barretenberg/cpp/src/barretenberg/commitment_schemes/verification_key.hpp +++ b/barretenberg/cpp/src/barretenberg/commitment_schemes/verification_key.hpp @@ -20,7 +20,7 @@ #include #include -namespace bb::honk::pcs { +namespace bb { template class VerifierCommitmentKey; @@ -98,4 +98,4 @@ template <> class VerifierCommitmentKey { std::shared_ptr> srs; }; -} // namespace bb::honk::pcs +} // namespace bb diff --git a/barretenberg/cpp/src/barretenberg/commitment_schemes/wrapper.hpp b/barretenberg/cpp/src/barretenberg/commitment_schemes/wrapper.hpp index a79d42e5f1f..ded625f8e39 100644 --- a/barretenberg/cpp/src/barretenberg/commitment_schemes/wrapper.hpp +++ b/barretenberg/cpp/src/barretenberg/commitment_schemes/wrapper.hpp @@ -3,7 +3,7 @@ #include "barretenberg/ecc/curves/bn254/g1.hpp" #include "gemini/gemini.hpp" -namespace bb::honk { +namespace bb { struct OpeningProof { std::vector gemini; @@ -11,4 +11,4 @@ struct OpeningProof { bb::g1::affine_element kzg; }; -} // namespace bb::honk +} // namespace bb diff --git a/barretenberg/cpp/src/barretenberg/commitment_schemes/zeromorph/zeromorph.hpp b/barretenberg/cpp/src/barretenberg/commitment_schemes/zeromorph/zeromorph.hpp index 8e805a54b6a..ce1e8c6fdd1 100644 --- a/barretenberg/cpp/src/barretenberg/commitment_schemes/zeromorph/zeromorph.hpp +++ b/barretenberg/cpp/src/barretenberg/commitment_schemes/zeromorph/zeromorph.hpp @@ -5,7 +5,7 @@ #include "barretenberg/polynomials/polynomial.hpp" #include "barretenberg/transcript/transcript.hpp" -namespace bb::honk::pcs::zeromorph { +namespace bb { /** * @brief Compute powers of a given challenge @@ -728,4 +728,4 @@ template class ZeroMorphVerifier_ { } }; -} // namespace bb::honk::pcs::zeromorph +} // namespace bb diff --git a/barretenberg/cpp/src/barretenberg/commitment_schemes/zeromorph/zeromorph.test.cpp b/barretenberg/cpp/src/barretenberg/commitment_schemes/zeromorph/zeromorph.test.cpp index e933aaa07fa..b963ecb0511 100644 --- a/barretenberg/cpp/src/barretenberg/commitment_schemes/zeromorph/zeromorph.test.cpp +++ b/barretenberg/cpp/src/barretenberg/commitment_schemes/zeromorph/zeromorph.test.cpp @@ -4,7 +4,7 @@ #include -namespace bb::honk::pcs::zeromorph { +namespace bb { template class ZeroMorphTest : public CommitmentTest { public: @@ -532,4 +532,4 @@ TYPED_TEST(ZeroMorphWithConcatenationTest, ProveAndVerify) auto verified = this->execute_zeromorph_protocol(num_unshifted, num_shifted, num_concatenated); EXPECT_TRUE(verified); } -} // namespace bb::honk::pcs::zeromorph +} // namespace bb diff --git a/barretenberg/cpp/src/barretenberg/crypto/poseidon2/poseidon2.cpp b/barretenberg/cpp/src/barretenberg/crypto/poseidon2/poseidon2.cpp index 1fce753975b..635b8dc0896 100644 --- a/barretenberg/cpp/src/barretenberg/crypto/poseidon2/poseidon2.cpp +++ b/barretenberg/cpp/src/barretenberg/crypto/poseidon2/poseidon2.cpp @@ -7,8 +7,7 @@ namespace bb::crypto { template typename Poseidon2::FF Poseidon2::hash(const std::vector::FF>& input) { - auto input_span = input; - return Sponge::hash_fixed_length(input_span); + return Sponge::hash_fixed_length(input); } /** diff --git a/barretenberg/cpp/src/barretenberg/crypto/poseidon2/poseidon2.test.cpp b/barretenberg/cpp/src/barretenberg/crypto/poseidon2/poseidon2.test.cpp index 7903d1fceb6..c18da87b739 100644 --- a/barretenberg/cpp/src/barretenberg/crypto/poseidon2/poseidon2.test.cpp +++ b/barretenberg/cpp/src/barretenberg/crypto/poseidon2/poseidon2.test.cpp @@ -52,12 +52,15 @@ TEST(Poseidon2, HashBufferConsistencyCheck) // element fr a(std::string("00000b615c4d3e2fa0b1c2d3e4f56789fedcba9876543210abcdef0123456789")); - auto input_vec = to_buffer(a); // takes field element and converts it to 32 bytes + // takes field element and converts it to 32 bytes + auto input_vec = to_buffer(a); + bb::fr result1 = crypto::Poseidon2::hash_buffer(input_vec); input_vec.erase(input_vec.begin()); // erase first byte since we want 31 bytes + fr result2 = crypto::Poseidon2::hash_buffer(input_vec); + std::vector input{ a }; auto expected = crypto::Poseidon2::hash(input); - fr result = crypto::Poseidon2::hash_buffer(input_vec); - - EXPECT_EQ(result, expected); + EXPECT_NE(result1, expected); + EXPECT_EQ(result2, expected); } diff --git a/barretenberg/cpp/src/barretenberg/crypto/poseidon2/sponge/sponge.hpp b/barretenberg/cpp/src/barretenberg/crypto/poseidon2/sponge/sponge.hpp index 2a99b88609f..eb89c96e471 100644 --- a/barretenberg/cpp/src/barretenberg/crypto/poseidon2/sponge/sponge.hpp +++ b/barretenberg/cpp/src/barretenberg/crypto/poseidon2/sponge/sponge.hpp @@ -129,7 +129,8 @@ template */ - template static std::array hash_internal(std::span input) + template + static std::array hash_internal(std::span input) { size_t in_len = input.size(); const uint256_t iv = (static_cast(in_len) << 64) + out_len - 1; @@ -153,11 +154,11 @@ template static std::array hash_fixed_length(std::span input) + template static std::array hash_fixed_length(std::span input) { return hash_internal(input); } - static FF hash_fixed_length(std::span input) { return hash_fixed_length<1>(input)[0]; } + static FF hash_fixed_length(std::span input) { return hash_fixed_length<1>(input)[0]; } template static std::array hash_variable_length(std::span input) { diff --git a/barretenberg/cpp/src/barretenberg/dsl/acir_format/acir_format.cpp b/barretenberg/cpp/src/barretenberg/dsl/acir_format/acir_format.cpp index dfe00b03703..6831103c3c3 100644 --- a/barretenberg/cpp/src/barretenberg/dsl/acir_format/acir_format.cpp +++ b/barretenberg/cpp/src/barretenberg/dsl/acir_format/acir_format.cpp @@ -1,10 +1,14 @@ #include "acir_format.hpp" #include "barretenberg/common/log.hpp" +#include "barretenberg/dsl/acir_format/bigint_constraint.hpp" #include "barretenberg/proof_system/circuit_builder/ultra_circuit_builder.hpp" #include namespace acir_format { +template class DSLBigInts; +template class DSLBigInts; + template void build_constraints(Builder& builder, AcirFormat const& constraint_system, bool has_valid_witness_assignments) { @@ -90,11 +94,15 @@ void build_constraints(Builder& builder, AcirFormat const& constraint_system, bo } // Add big_int constraints + DSLBigInts dsl_bigints; + for (const auto& constraint : constraint_system.bigint_from_le_bytes_constraints) { + create_bigint_from_le_bytes_constraint(builder, constraint, dsl_bigints); + } for (const auto& constraint : constraint_system.bigint_operations) { - create_bigint_operations_constraint(builder, constraint); + create_bigint_operations_constraint(constraint, dsl_bigints); } - for (const auto& constraint : constraint_system.bigint_from_le_bytes_constraints) { - create_bigint_from_le_bytes_constraint(builder, constraint); + for (const auto& constraint : constraint_system.bigint_to_le_bytes_constraints) { + create_bigint_to_le_bytes_constraint(builder, constraint, dsl_bigints); } // TODO(https://github.com/AztecProtocol/barretenberg/issues/817): disable these for UGH for now since we're not yet diff --git a/barretenberg/cpp/src/barretenberg/dsl/acir_format/acir_format.hpp b/barretenberg/cpp/src/barretenberg/dsl/acir_format/acir_format.hpp index 3c053d83814..6ccf0371774 100644 --- a/barretenberg/cpp/src/barretenberg/dsl/acir_format/acir_format.hpp +++ b/barretenberg/cpp/src/barretenberg/dsl/acir_format/acir_format.hpp @@ -48,6 +48,7 @@ struct AcirFormat { std::vector ec_add_constraints; std::vector recursion_constraints; std::vector bigint_from_le_bytes_constraints; + std::vector bigint_to_le_bytes_constraints; std::vector bigint_operations; // A standard plonk arithmetic constraint, as defined in the poly_triple struct, consists of selector values @@ -80,6 +81,7 @@ struct AcirFormat { constraints, block_constraints, bigint_from_le_bytes_constraints, + bigint_to_le_bytes_constraints, bigint_operations); friend bool operator==(AcirFormat const& lhs, AcirFormat const& rhs) = default; diff --git a/barretenberg/cpp/src/barretenberg/dsl/acir_format/acir_format.test.cpp b/barretenberg/cpp/src/barretenberg/dsl/acir_format/acir_format.test.cpp index 8908b348096..fe34de33aca 100644 --- a/barretenberg/cpp/src/barretenberg/dsl/acir_format/acir_format.test.cpp +++ b/barretenberg/cpp/src/barretenberg/dsl/acir_format/acir_format.test.cpp @@ -48,6 +48,7 @@ TEST_F(AcirFormatTests, TestASingleConstraintNoPubInputs) .ec_add_constraints = {}, .recursion_constraints = {}, .bigint_from_le_bytes_constraints = {}, + .bigint_to_le_bytes_constraints = {}, .bigint_operations = {}, .constraints = { constraint }, .block_constraints = {}, @@ -161,6 +162,7 @@ TEST_F(AcirFormatTests, TestLogicGateFromNoirCircuit) .ec_add_constraints = {}, .recursion_constraints = {}, .bigint_from_le_bytes_constraints = {}, + .bigint_to_le_bytes_constraints = {}, .bigint_operations = {}, .constraints = { expr_a, expr_b, expr_c, expr_d }, .block_constraints = {} }; @@ -226,6 +228,7 @@ TEST_F(AcirFormatTests, TestSchnorrVerifyPass) .ec_add_constraints = {}, .recursion_constraints = {}, .bigint_from_le_bytes_constraints = {}, + .bigint_to_le_bytes_constraints = {}, .bigint_operations = {}, .constraints = { poly_triple{ .a = schnorr_constraint.result, @@ -319,6 +322,7 @@ TEST_F(AcirFormatTests, TestSchnorrVerifySmallRange) .ec_add_constraints = {}, .recursion_constraints = {}, .bigint_from_le_bytes_constraints = {}, + .bigint_to_le_bytes_constraints = {}, .bigint_operations = {}, .constraints = { poly_triple{ .a = schnorr_constraint.result, @@ -431,6 +435,7 @@ TEST_F(AcirFormatTests, TestVarKeccak) .ec_add_constraints = {}, .recursion_constraints = {}, .bigint_from_le_bytes_constraints = {}, + .bigint_to_le_bytes_constraints = {}, .bigint_operations = {}, .constraints = { dummy }, .block_constraints = {}, @@ -475,6 +480,7 @@ TEST_F(AcirFormatTests, TestKeccakPermutation) .ec_add_constraints = {}, .recursion_constraints = {}, .bigint_from_le_bytes_constraints = {}, + .bigint_to_le_bytes_constraints = {}, .bigint_operations = {}, .constraints = {}, .block_constraints = {} }; diff --git a/barretenberg/cpp/src/barretenberg/dsl/acir_format/acir_to_constraint_buf.hpp b/barretenberg/cpp/src/barretenberg/dsl/acir_format/acir_to_constraint_buf.hpp index 52dd9935241..7d48827ef27 100644 --- a/barretenberg/cpp/src/barretenberg/dsl/acir_format/acir_to_constraint_buf.hpp +++ b/barretenberg/cpp/src/barretenberg/dsl/acir_format/acir_to_constraint_buf.hpp @@ -256,6 +256,11 @@ void handle_blackbox_func_call(Circuit::Opcode::BlackBoxFuncCall const& arg, Aci .modulus = map(arg.modulus, [](auto& e) -> uint32_t { return e; }), .result = arg.output, }); + } else if constexpr (std::is_same_v) { + af.bigint_to_le_bytes_constraints.push_back(BigIntToLeBytes{ + .input = arg.input, + .result = map(arg.outputs, [](auto& e) { return e.value; }), + }); } else if constexpr (std::is_same_v) { af.bigint_operations.push_back(BigIntOperation{ .lhs = arg.lhs, @@ -263,12 +268,12 @@ void handle_blackbox_func_call(Circuit::Opcode::BlackBoxFuncCall const& arg, Aci .result = arg.output, .opcode = BigIntOperationType::Add, }); - } else if constexpr (std::is_same_v) { + } else if constexpr (std::is_same_v) { af.bigint_operations.push_back(BigIntOperation{ .lhs = arg.lhs, .rhs = arg.rhs, .result = arg.output, - .opcode = BigIntOperationType::Neg, + .opcode = BigIntOperationType::Sub, }); } else if constexpr (std::is_same_v) { af.bigint_operations.push_back(BigIntOperation{ diff --git a/barretenberg/cpp/src/barretenberg/dsl/acir_format/bigint_constraint.cpp b/barretenberg/cpp/src/barretenberg/dsl/acir_format/bigint_constraint.cpp index 4780e5ca36c..f4d5ea9def0 100644 --- a/barretenberg/cpp/src/barretenberg/dsl/acir_format/bigint_constraint.cpp +++ b/barretenberg/cpp/src/barretenberg/dsl/acir_format/bigint_constraint.cpp @@ -1,33 +1,464 @@ #include "bigint_constraint.hpp" +#include "barretenberg/common/assert.hpp" #include "barretenberg/dsl/types.hpp" #include "barretenberg/numeric/uint256/uint256.hpp" #include "barretenberg/stdlib/primitives/bigfield/bigfield.hpp" +#include +#include namespace acir_format { -template void create_bigint_operations_constraint(Builder& builder, const BigIntOperation& input) +ModulusId modulus_param_to_id(ModulusParam param) { - // TODO - (void)builder; - info(input); + if (Bn254FqParams::modulus_0 == param.modulus_0 && Bn254FqParams::modulus_1 == param.modulus_1 && + Bn254FqParams::modulus_2 == param.modulus_2 && Bn254FqParams::modulus_3 == param.modulus_3) { + return ModulusId::BN254_FQ; + } + if (Bn254FrParams::modulus_0 == param.modulus_0 && Bn254FrParams::modulus_1 == param.modulus_1 && + Bn254FrParams::modulus_2 == param.modulus_2 && Bn254FrParams::modulus_3 == param.modulus_3) { + return ModulusId::BN254_FR; + } + if (secp256k1::Secp256k1FqParams::modulus_0 == param.modulus_0 && + secp256k1::Secp256k1FqParams::modulus_1 == param.modulus_1 && + secp256k1::Secp256k1FqParams::modulus_2 == param.modulus_2 && + secp256k1::Secp256k1FqParams::modulus_3 == param.modulus_3) { + return ModulusId::SECP256K1_FQ; + } + if (secp256k1::Secp256k1FrParams::modulus_0 == param.modulus_0 && + secp256k1::Secp256k1FrParams::modulus_1 == param.modulus_1 && + secp256k1::Secp256k1FrParams::modulus_2 == param.modulus_2 && + secp256k1::Secp256k1FrParams::modulus_3 == param.modulus_3) { + return ModulusId::SECP256K1_FR; + } + if (secp256r1::Secp256r1FqParams::modulus_0 == param.modulus_0 && + secp256r1::Secp256r1FqParams::modulus_1 == param.modulus_1 && + secp256r1::Secp256r1FqParams::modulus_2 == param.modulus_2 && + secp256r1::Secp256r1FqParams::modulus_3 == param.modulus_3) { + return ModulusId::SECP256R1_FQ; + } + if (secp256r1::Secp256r1FrParams::modulus_0 == param.modulus_0 && + secp256r1::Secp256r1FrParams::modulus_1 == param.modulus_1 && + secp256r1::Secp256r1FrParams::modulus_2 == param.modulus_2 && + secp256r1::Secp256r1FrParams::modulus_3 == param.modulus_3) { + return ModulusId::SECP256R1_FR; + } + + return ModulusId::UNKNOWN; +} + +template void create_bigint_operations_constraint(const BigIntOperation& input, + DSLBigInts& dsl_bigint); +template void create_bigint_operations_constraint( + const BigIntOperation& input, DSLBigInts& dsl_bigint); +template void create_bigint_addition_constraint(const BigIntOperation& input, + DSLBigInts& dsl_bigint); +template void create_bigint_addition_constraint( + const BigIntOperation& input, DSLBigInts& dsl_bigint); +template void create_bigint_sub_constraint(const BigIntOperation& input, + DSLBigInts& dsl_bigint); +template void create_bigint_sub_constraint( + const BigIntOperation& input, DSLBigInts& dsl_bigint); +template void create_bigint_mul_constraint(const BigIntOperation& input, + DSLBigInts& dsl_bigint); +template void create_bigint_mul_constraint( + const BigIntOperation& input, DSLBigInts& dsl_bigint); +template void create_bigint_div_constraint(const BigIntOperation& input, + DSLBigInts& dsl_bigint); +template void create_bigint_div_constraint( + const BigIntOperation& input, DSLBigInts& dsl_bigint); + +template +void create_bigint_addition_constraint(const BigIntOperation& input, DSLBigInts& dsl_bigint) +{ + switch (dsl_bigint.get_modulus_id(input.lhs)) { + case ModulusId::BN254_FR: { + auto lhs = dsl_bigint.bn254_fr(input.lhs); + auto rhs = dsl_bigint.bn254_fr(input.rhs); + dsl_bigint.set_bn254_fr(lhs + rhs, input.result); + break; + } + case ModulusId::BN254_FQ: { + auto lhs = dsl_bigint.bn254_fq(input.lhs); + auto rhs = dsl_bigint.bn254_fq(input.rhs); + dsl_bigint.set_bn254_fq(lhs + rhs, input.result); + break; + } + case ModulusId::SECP256K1_FQ: { + auto lhs = dsl_bigint.secp256k1_fq(input.lhs); + auto rhs = dsl_bigint.secp256k1_fq(input.rhs); + dsl_bigint.set_secp256k1_fq(lhs + rhs, input.result); + break; + } + case ModulusId::SECP256K1_FR: { + auto lhs = dsl_bigint.secp256k1_fr(input.lhs); + auto rhs = dsl_bigint.secp256k1_fr(input.rhs); + dsl_bigint.set_secp256k1_fr(lhs + rhs, input.result); + break; + } + case ModulusId::SECP256R1_FQ: { + auto lhs = dsl_bigint.secp256r1_fq(input.lhs); + auto rhs = dsl_bigint.secp256r1_fq(input.rhs); + dsl_bigint.set_secp256r1_fq(lhs + rhs, input.result); + break; + } + case ModulusId::SECP256R1_FR: { + auto lhs = dsl_bigint.secp256r1_fr(input.lhs); + auto rhs = dsl_bigint.secp256r1_fr(input.rhs); + dsl_bigint.set_secp256r1_fr(lhs + rhs, input.result); + break; + } + default: { + ASSERT(false); + } + } +} + +template +void create_bigint_sub_constraint(const BigIntOperation& input, DSLBigInts& dsl_bigint) +{ + switch (dsl_bigint.get_modulus_id(input.lhs)) { + case ModulusId::BN254_FR: { + auto lhs = dsl_bigint.bn254_fr(input.lhs); + auto rhs = dsl_bigint.bn254_fr(input.rhs); + dsl_bigint.set_bn254_fr(lhs - rhs, input.result); + break; + } + case ModulusId::BN254_FQ: { + auto lhs = dsl_bigint.bn254_fq(input.lhs); + auto rhs = dsl_bigint.bn254_fq(input.rhs); + dsl_bigint.set_bn254_fq(lhs - rhs, input.result); + break; + } + case ModulusId::SECP256K1_FQ: { + auto lhs = dsl_bigint.secp256k1_fq(input.lhs); + auto rhs = dsl_bigint.secp256k1_fq(input.rhs); + dsl_bigint.set_secp256k1_fq(lhs - rhs, input.result); + break; + } + case ModulusId::SECP256K1_FR: { + auto lhs = dsl_bigint.secp256k1_fr(input.lhs); + auto rhs = dsl_bigint.secp256k1_fr(input.rhs); + dsl_bigint.set_secp256k1_fr(lhs - rhs, input.result); + break; + } + case ModulusId::SECP256R1_FQ: { + auto lhs = dsl_bigint.secp256r1_fq(input.lhs); + auto rhs = dsl_bigint.secp256r1_fq(input.rhs); + dsl_bigint.set_secp256r1_fq(lhs - rhs, input.result); + break; + } + case ModulusId::SECP256R1_FR: { + auto lhs = dsl_bigint.secp256r1_fr(input.lhs); + auto rhs = dsl_bigint.secp256r1_fr(input.rhs); + dsl_bigint.set_secp256r1_fr(lhs - rhs, input.result); + break; + } + default: { + ASSERT(false); + } + } +} + +template +void create_bigint_mul_constraint(const BigIntOperation& input, DSLBigInts& dsl_bigint) +{ + switch (dsl_bigint.get_modulus_id(input.lhs)) { + case ModulusId::BN254_FR: { + auto lhs = dsl_bigint.bn254_fr(input.lhs); + auto rhs = dsl_bigint.bn254_fr(input.rhs); + dsl_bigint.set_bn254_fr(lhs * rhs, input.result); + break; + } + case ModulusId::BN254_FQ: { + auto lhs = dsl_bigint.bn254_fq(input.lhs); + auto rhs = dsl_bigint.bn254_fq(input.rhs); + dsl_bigint.set_bn254_fq(lhs * rhs, input.result); + break; + } + case ModulusId::SECP256K1_FQ: { + auto lhs = dsl_bigint.secp256k1_fq(input.lhs); + auto rhs = dsl_bigint.secp256k1_fq(input.rhs); + dsl_bigint.set_secp256k1_fq(lhs * rhs, input.result); + break; + } + case ModulusId::SECP256K1_FR: { + auto lhs = dsl_bigint.secp256k1_fr(input.lhs); + auto rhs = dsl_bigint.secp256k1_fr(input.rhs); + dsl_bigint.set_secp256k1_fr(lhs * rhs, input.result); + break; + } + case ModulusId::SECP256R1_FQ: { + auto lhs = dsl_bigint.secp256r1_fq(input.lhs); + auto rhs = dsl_bigint.secp256r1_fq(input.rhs); + dsl_bigint.set_secp256r1_fq(lhs * rhs, input.result); + break; + } + case ModulusId::SECP256R1_FR: { + auto lhs = dsl_bigint.secp256r1_fr(input.lhs); + auto rhs = dsl_bigint.secp256r1_fr(input.rhs); + dsl_bigint.set_secp256r1_fr(lhs * rhs, input.result); + break; + } + default: { + ASSERT(false); + } + } +} + +template +void create_bigint_div_constraint(const BigIntOperation& input, DSLBigInts& dsl_bigint) +{ + switch (dsl_bigint.get_modulus_id(input.lhs)) { + case ModulusId::BN254_FR: { + auto lhs = dsl_bigint.bn254_fr(input.lhs); + auto rhs = dsl_bigint.bn254_fr(input.rhs); + dsl_bigint.set_bn254_fr(lhs / rhs, input.result); + break; + } + case ModulusId::BN254_FQ: { + auto lhs = dsl_bigint.bn254_fq(input.lhs); + auto rhs = dsl_bigint.bn254_fq(input.rhs); + dsl_bigint.set_bn254_fq(lhs / rhs, input.result); + break; + } + case ModulusId::SECP256K1_FQ: { + auto lhs = dsl_bigint.secp256k1_fq(input.lhs); + auto rhs = dsl_bigint.secp256k1_fq(input.rhs); + dsl_bigint.set_secp256k1_fq(lhs / rhs, input.result); + break; + } + case ModulusId::SECP256K1_FR: { + auto lhs = dsl_bigint.secp256k1_fr(input.lhs); + auto rhs = dsl_bigint.secp256k1_fr(input.rhs); + dsl_bigint.set_secp256k1_fr(lhs / rhs, input.result); + break; + } + case ModulusId::SECP256R1_FQ: { + auto lhs = dsl_bigint.secp256r1_fq(input.lhs); + auto rhs = dsl_bigint.secp256r1_fq(input.rhs); + dsl_bigint.set_secp256r1_fq(lhs / rhs, input.result); + break; + } + case ModulusId::SECP256R1_FR: { + auto lhs = dsl_bigint.secp256r1_fr(input.lhs); + auto rhs = dsl_bigint.secp256r1_fr(input.rhs); + dsl_bigint.set_secp256r1_fr(lhs / rhs, input.result); + break; + } + default: { + ASSERT(false); + } + } +} + +template +void create_bigint_operations_constraint(const BigIntOperation& input, DSLBigInts& dsl_bigint) +{ + switch (input.opcode) { + case BigIntOperationType::Add: { + create_bigint_addition_constraint(input, dsl_bigint); + break; + } + case BigIntOperationType::Sub: { + create_bigint_sub_constraint(input, dsl_bigint); + break; + } + case BigIntOperationType::Mul: { + create_bigint_mul_constraint(input, dsl_bigint); + break; + } + case BigIntOperationType::Div: { + create_bigint_div_constraint(input, dsl_bigint); + break; + } + default: { + ASSERT(false); + } + } } -template void create_bigint_operations_constraint(UltraCircuitBuilder& builder, - const BigIntOperation& input); -template void create_bigint_operations_constraint(GoblinUltraCircuitBuilder& builder, - const BigIntOperation& input); +template +void create_bigint_from_le_bytes_constraint(Builder& builder, + const BigIntFromLeBytes& input, + DSLBigInts& dsl_bigints) +{ + using big_bn254_fq = bb::stdlib::bigfield; + using big_bn254_fr = bb::stdlib::bigfield; + using big_secp256k1_fq = bb::stdlib::bigfield; + using big_secp256k1_fr = bb::stdlib::bigfield; + using big_secp256r1_fq = bb::stdlib::bigfield; + using big_secp256r1_fr = bb::stdlib::bigfield; + using field_ct = bb::stdlib::field_t; + using byte_array_ct = bb::stdlib::byte_array; + + // Construct the modulus from its bytes + uint64_t modulus_64 = 0; + uint64_t base = 1; + std::vector modulus_limbs; + for (std::size_t i = 0; i < 32; ++i) { + if (i < input.modulus.size()) { + modulus_64 += input.modulus[i] * base; + base = base * 256; + if ((i + 1) % 8 == 0) { + modulus_limbs.push_back(modulus_64); + modulus_64 = 0; + base = 1; + } + } + } + auto modulus = ModulusParam{ .modulus_0 = modulus_limbs[0], + .modulus_1 = modulus_limbs[1], + .modulus_2 = modulus_limbs[2], + .modulus_3 = modulus_limbs[3] }; + bb::stdlib::byte_array rev_bytes = bb::stdlib::byte_array(&builder, 32); + for (size_t i = 0; i < 32; ++i) { + if (i < input.inputs.size()) { + field_ct element = field_ct::from_witness_index(&builder, input.inputs[i]); + byte_array_ct element_bytes(element, 1); + rev_bytes.write_at(element_bytes, i); + } else { + rev_bytes[i] = 0; + } + } + bb::stdlib::byte_array bytes = rev_bytes.reverse(); + + auto modulus_id = modulus_param_to_id(modulus); + + switch (modulus_id) { + case BN254_FQ: { + auto big = big_bn254_fq(bytes); + dsl_bigints.set_bn254_fq(big, input.result); + break; + } + case BN254_FR: { + auto big = big_bn254_fr(bytes); + dsl_bigints.set_bn254_fr(big, input.result); + break; + } + case SECP256K1_FQ: { + auto big = big_secp256k1_fq(bytes); + dsl_bigints.set_secp256k1_fq(big, input.result); + break; + } + case SECP256K1_FR: { + auto big = big_secp256k1_fr(bytes); + dsl_bigints.set_secp256k1_fr(big, input.result); + break; + } + case SECP256R1_FQ: { + auto big = big_secp256r1_fq(bytes); + dsl_bigints.set_secp256r1_fq(big, input.result); + break; + } + case SECP256R1_FR: { + auto big = big_secp256r1_fr(bytes); + dsl_bigints.set_secp256r1_fr(big, input.result); + break; + } + case UNKNOWN: + default: + ASSERT(false); + break; + } +} template -void create_bigint_from_le_bytes_constraint(Builder& builder, const BigIntFromLeBytes& input) +void create_bigint_to_le_bytes_constraint(Builder& builder, + const BigIntToLeBytes& input, + DSLBigInts& dsl_bigints) { - // TODO - (void)builder; - info(input); + using big_bn254_fq = bb::stdlib::bigfield; + using big_bn254_fr = bb::stdlib::bigfield; + using big_secp256k1_fq = bb::stdlib::bigfield; + using big_secp256k1_fr = bb::stdlib::bigfield; + using big_secp256r1_fq = bb::stdlib::bigfield; + using big_secp256r1_fr = bb::stdlib::bigfield; + + auto modulus_id = dsl_bigints.get_modulus_id(input.input); + bb::stdlib::byte_array byte_array; + switch (modulus_id) { + case BN254_FQ: { + big_bn254_fq big = dsl_bigints.bn254_fq(input.input); + big.self_reduce(); + byte_array = big.to_byte_array(); + + break; + } + case BN254_FR: { + big_bn254_fr big = dsl_bigints.bn254_fr(input.input); + big.self_reduce(); + byte_array = big.to_byte_array(); + break; + } + case SECP256K1_FQ: { + big_secp256k1_fq big = dsl_bigints.secp256k1_fq(input.input); + big.self_reduce(); + byte_array = big.to_byte_array(); + break; + } + case SECP256K1_FR: { + big_secp256k1_fr big = dsl_bigints.secp256k1_fr(input.input); + big.self_reduce(); + byte_array = big.to_byte_array(); + break; + } + case SECP256R1_FQ: { + big_secp256r1_fq big = dsl_bigints.secp256r1_fq(input.input); + big.self_reduce(); + byte_array = big.to_byte_array(); + break; + } + case SECP256R1_FR: { + big_secp256r1_fr big = dsl_bigints.secp256r1_fr(input.input); + big.self_reduce(); + byte_array = big.to_byte_array(); + break; + } + case UNKNOWN: + default: + ASSERT(false); + break; + } + byte_array = byte_array.reverse(); + ASSERT(input.result.size() <= byte_array.size()); + for (size_t i = 0; i < byte_array.size(); ++i) { + if (i < input.result.size()) { + + // This should instead use assert_equal: builder.assert_equal(byte_array[i].normalize().witness_index, + // input.result[i]); but unit tests require this because they do not constraint the witness, and then if we + // use assert_equal in that case, we can generate a proof for non matching values (cf test_assert_equal in + // field.test.cpp). We should check that Noir always constraint the results of to_bytes + poly_triple assert_equal{ + .a = byte_array[i].normalize().witness_index, + .b = input.result[i], + .c = 0, + .q_m = 0, + .q_l = 1, + .q_r = -1, + .q_o = 0, + .q_c = 0, + }; + builder.create_poly_gate(assert_equal); + } else { + byte_array[i].normalize().is_zero(); + } + } } template void create_bigint_from_le_bytes_constraint(UltraCircuitBuilder& builder, - const BigIntFromLeBytes& input); -template void create_bigint_from_le_bytes_constraint(GoblinUltraCircuitBuilder& builder, - const BigIntFromLeBytes& input); + const BigIntFromLeBytes& input, + DSLBigInts& dsl_bigints); +template void create_bigint_from_le_bytes_constraint( + GoblinUltraCircuitBuilder& builder, + const BigIntFromLeBytes& input, + DSLBigInts& dsl_bigints); +template void create_bigint_to_le_bytes_constraint(UltraCircuitBuilder& builder, + const BigIntToLeBytes& input, + DSLBigInts& dsl_bigints); + +template void create_bigint_to_le_bytes_constraint( + GoblinUltraCircuitBuilder& builder, + const BigIntToLeBytes& input, + DSLBigInts& dsl_bigints); } // namespace acir_format diff --git a/barretenberg/cpp/src/barretenberg/dsl/acir_format/bigint_constraint.hpp b/barretenberg/cpp/src/barretenberg/dsl/acir_format/bigint_constraint.hpp index 8b21ee5e784..1feb0fffce1 100644 --- a/barretenberg/cpp/src/barretenberg/dsl/acir_format/bigint_constraint.hpp +++ b/barretenberg/cpp/src/barretenberg/dsl/acir_format/bigint_constraint.hpp @@ -16,7 +16,7 @@ struct BigIntFromLeBytes { friend bool operator==(BigIntFromLeBytes const& lhs, BigIntFromLeBytes const& rhs) = default; }; -enum BigIntOperationType { Add, Neg, Mul, Div }; +enum BigIntOperationType { Add, Sub, Mul, Div }; struct BigIntOperation { uint32_t lhs; @@ -29,7 +29,177 @@ struct BigIntOperation { friend bool operator==(BigIntOperation const& lhs, BigIntOperation const& rhs) = default; }; -template void create_bigint_operations_constraint(Builder& builder, const BigIntOperation& input); +struct BigIntToLeBytes { + uint32_t input; + std::vector result; + + // For serialization, update with any new fields + MSGPACK_FIELDS(input, result); + friend bool operator==(BigIntToLeBytes const& lhs, BigIntToLeBytes const& rhs) = default; +}; + +/// Enumerates the supported modulus types for big integer operations. +/// Specifies whether a bigint refers to a BN254/SECP256K1/SECP256R1 Fq or Fr modulus. +enum ModulusId { + BN254_FQ = 0, + BN254_FR, + SECP256K1_FQ, + SECP256K1_FR, + SECP256R1_FQ, + SECP256R1_FR, + UNKNOWN, +}; + +/// 256-bit modulus value for a field element +/// The modulus is represented by 4 64-bits limbs +/// Used to define the modulus for big integer operations. +class ModulusParam { + public: + uint64_t modulus_0; + uint64_t modulus_1; + uint64_t modulus_2; + uint64_t modulus_3; +}; + +template class DSLBigInts { + using big_bn254_fq = bb::stdlib::bigfield; + using big_bn254_fr = bb::stdlib::bigfield; + using big_secp256k1_fq = bb::stdlib::bigfield; + using big_secp256k1_fr = bb::stdlib::bigfield; + using big_secp256r1_fq = bb::stdlib::bigfield; + using big_secp256r1_fr = bb::stdlib::bigfield; + + private: + std::map m_bn254_fq; + std::map m_bn254_fr; + std::map m_secp256k1_fq; + std::map m_secp256k1_fr; + std::map m_secp256r1_fq; + std::map m_secp256r1_fr; + + public: + DSLBigInts() = default; + + ModulusId get_modulus_id(uint32_t bigint_id) + { + if (this->m_bn254_fq.contains(bigint_id)) { + return ModulusId::BN254_FQ; + } + if (this->m_bn254_fr.contains(bigint_id)) { + return ModulusId::BN254_FR; + } + if (this->m_secp256k1_fq.contains(bigint_id)) { + return ModulusId::SECP256K1_FQ; + } + if (this->m_secp256k1_fr.contains(bigint_id)) { + return ModulusId::SECP256K1_FR; + } + if (this->m_secp256r1_fq.contains(bigint_id)) { + return ModulusId::SECP256R1_FQ; + } + if (this->m_secp256r1_fr.contains(bigint_id)) { + return ModulusId::SECP256R1_FR; + } + + return ModulusId::UNKNOWN; + } + + big_bn254_fr bn254_fr(uint32_t bigint_id) + { + if (this->m_bn254_fr.contains(bigint_id)) { + return this->m_bn254_fr[bigint_id]; + } + ASSERT(false); + return { 0 }; + } + + void set_bn254_fr(const big_bn254_fr& bigint, uint32_t bigint_id) { this->m_bn254_fr[bigint_id] = bigint; } + + big_bn254_fq bn254_fq(uint32_t bigint_id) + { + if (this->m_bn254_fq.contains(bigint_id)) { + return this->m_bn254_fq[bigint_id]; + } + ASSERT(false); + return { 0 }; + } + + void set_bn254_fq(const big_bn254_fq& bigint, uint32_t bigint_id) { this->m_bn254_fq[bigint_id] = bigint; } + + big_secp256r1_fq secp256r1_fq(uint32_t bigint_id) + { + if (this->m_secp256r1_fq.contains(bigint_id)) { + return this->m_secp256r1_fq[bigint_id]; + } + ASSERT(false); + return { 0 }; + } + + void set_secp256r1_fq(const big_secp256r1_fq& bigint, uint32_t bigint_id) + { + this->m_secp256r1_fq[bigint_id] = bigint; + } + + big_secp256r1_fr secp256r1_fr(uint32_t bigint_id) + { + if (this->m_secp256r1_fr.contains(bigint_id)) { + return this->m_secp256r1_fr[bigint_id]; + } + ASSERT(false); + return { 0 }; + } + + void set_secp256r1_fr(const big_secp256r1_fr& bigint, uint32_t bigint_id) + { + this->m_secp256r1_fr[bigint_id] = bigint; + } + + big_secp256k1_fq secp256k1_fq(uint32_t bigint_id) + { + if (this->m_secp256k1_fq.contains(bigint_id)) { + return this->m_secp256k1_fq[bigint_id]; + } + ASSERT(false); + return { 0 }; + } + + void set_secp256k1_fq(const big_secp256k1_fq& bigint, uint32_t bigint_id) + { + this->m_secp256k1_fq[bigint_id] = bigint; + } + + big_secp256k1_fr secp256k1_fr(uint32_t bigint_id) + { + if (this->m_secp256k1_fr.contains(bigint_id)) { + return this->m_secp256k1_fr[bigint_id]; + } + return { 0 }; + } + + void set_secp256k1_fr(const big_secp256k1_fr& bigint, uint32_t bigint_id) + { + this->m_secp256k1_fr[bigint_id] = bigint; + } +}; + template -void create_bigint_from_le_bytes_constraint(Builder& builder, const BigIntFromLeBytes& input); +void create_bigint_from_le_bytes_constraint(Builder& builder, + const BigIntFromLeBytes& input, + DSLBigInts& dsl_bigints); +template +void create_bigint_to_le_bytes_constraint(Builder& builder, + const BigIntToLeBytes& input, + DSLBigInts& dsl_bigints); + +template +void create_bigint_operations_constraint(const BigIntOperation& input, DSLBigInts& dsl_bigints); +template +void create_bigint_addition_constraint(const BigIntOperation& input, DSLBigInts& dsl_bigints); +template +void create_bigint_sub_constraint(const BigIntOperation& input, DSLBigInts& dsl_bigints); +template +void create_bigint_mul_constraint(const BigIntOperation& input, DSLBigInts& dsl_bigints); +template +void create_bigint_div_constraint(const BigIntOperation& input, DSLBigInts& dsl_bigints); + } // namespace acir_format \ No newline at end of file diff --git a/barretenberg/cpp/src/barretenberg/dsl/acir_format/bigint_constraint.test.cpp b/barretenberg/cpp/src/barretenberg/dsl/acir_format/bigint_constraint.test.cpp index 77717980a4e..161c6076692 100644 --- a/barretenberg/cpp/src/barretenberg/dsl/acir_format/bigint_constraint.test.cpp +++ b/barretenberg/cpp/src/barretenberg/dsl/acir_format/bigint_constraint.test.cpp @@ -1,8 +1,10 @@ #include "bigint_constraint.hpp" #include "acir_format.hpp" +#include "barretenberg/numeric/uint256/uint256.hpp" #include "barretenberg/plonk/proof_system/types/proof.hpp" #include "barretenberg/plonk/proof_system/verification_key/verification_key.hpp" +#include #include #include @@ -12,42 +14,225 @@ class BigIntTests : public ::testing::Test { protected: static void SetUpTestSuite() { bb::srs::init_crs_factory("../srs_db/ignition"); } }; +using fr = field; -TEST_F(BigIntTests, TestBigIntConstraintDummy) +std::tuple +generate_big_int_op_constraint_with_modulus( + BigIntOperationType op, fr lhs, fr rhs, WitnessVector& witness_values, const std::vector& modulus) { - // Dummy Test: to be updated when big ints opcodes are implemented - BigIntOperation add_constraint{ - .lhs = 1, - .rhs = 2, - .result = 3, - .opcode = BigIntOperationType::Add, + // CAUTION We assume here the operands and the result fit into one byte! + // So trying to divide 7/2 won't work, but 8/2 will do. + auto lhs_id = static_cast(witness_values.size()); + witness_values.push_back(lhs); + auto rhs_id = static_cast(witness_values.size()); + witness_values.push_back(rhs); + BigIntFromLeBytes from_le_bytes_constraint_bigint_lhs{ + .inputs = { lhs_id }, + .modulus = modulus, + .result = lhs_id, }; - BigIntOperation neg_constraint{ - .lhs = 1, - .rhs = 2, - .result = 3, - .opcode = BigIntOperationType::Neg, + BigIntFromLeBytes from_le_bytes_constraint_bigint_rhs{ + .inputs = { rhs_id }, + .modulus = modulus, + .result = rhs_id, }; - BigIntOperation mul_constraint{ - .lhs = 1, - .rhs = 2, - .result = 3, - .opcode = BigIntOperationType::Mul, + + auto result = static_cast(witness_values.size()); + BigIntOperation constraint{ + .lhs = lhs_id, + .rhs = rhs_id, + .result = result, + .opcode = op, + }; + // Expecting the result to be just one byte long + BigIntToLeBytes to_bytes{ + .input = result, + .result = { static_cast(witness_values.size()) }, + }; + // overflow is NOT supported, you have to make sure there is no overflow/underflow. + fr value = 0; + switch (op) { + case Add: + value = witness_values[lhs_id] + witness_values[rhs_id]; + break; + case Sub: + value = witness_values[lhs_id] - witness_values[rhs_id]; + break; + case Mul: + value = witness_values[lhs_id] * witness_values[rhs_id]; + break; + case Div: + value = witness_values[lhs_id] / witness_values[rhs_id]; + break; + default: + ASSERT(false); + break; + } + + witness_values.push_back(value); + return { from_le_bytes_constraint_bigint_lhs, from_le_bytes_constraint_bigint_rhs, constraint, to_bytes }; +} + +std::tuple generate_big_int_op_constraint( + BigIntOperationType op, fr lhs, fr rhs, WitnessVector& witness_values) +{ + // modulus is bn254/fq + return generate_big_int_op_constraint_with_modulus( + op, + lhs, + rhs, + witness_values, + { + 0x47, 0xFD, 0x7C, 0xD8, 0x16, 0x8C, 0x20, 0x3C, 0x8d, 0xca, 0x71, 0x68, 0x91, 0x6a, 0x81, 0x97, + 0x5d, 0x58, 0x81, 0x81, 0xb6, 0x45, 0x50, 0xb8, 0x29, 0xa0, 0x31, 0xe1, 0x72, 0x4e, 0x64, 0x30, + }); +} + +std::tuple +generate_big_int_op_constraint_secpk1_fr(BigIntOperationType op, fr lhs, fr rhs, WitnessVector& witness_values) +{ + return generate_big_int_op_constraint_with_modulus( + op, lhs, rhs, witness_values, { 0x41, 0x41, 0x36, 0xD0, 0x8C, 0x5E, 0xD2, 0xBF, 0x3B, 0xA0, 0x48, + 0xAF, 0xE6, 0xDC, 0xAE, 0xBA, 0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }); +} + +std::tuple +generate_big_int_op_constraint_secpk1_fq(BigIntOperationType op, fr lhs, fr rhs, WitnessVector& witness_values) +{ + return generate_big_int_op_constraint_with_modulus( + op, lhs, rhs, witness_values, { 0x2F, 0xFC, 0xFF, 0xFF, 0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }); +} +void apply_constraints(AcirFormat& constraint_system, + std::tuple constraints) +{ + constraint_system.bigint_from_le_bytes_constraints.push_back(get<0>(constraints)); + constraint_system.bigint_from_le_bytes_constraints.push_back(get<1>(constraints)); + constraint_system.bigint_to_le_bytes_constraints.push_back(get<3>(constraints)); + constraint_system.bigint_operations.push_back(get<2>(constraints)); +} + +std::tuple generate_big_int_op_constraint_with_id(BigIntOperationType op, + uint32_t lhs_id, + uint32_t rhs_id, + WitnessVector& witness_values) +{ + // lhs_id, rhs_id are big int it, so we can generate the operation directly + auto result = static_cast(witness_values.size()); + BigIntOperation constraint{ + .lhs = lhs_id, + .rhs = rhs_id, + .result = result, + .opcode = op, + }; + // Expecting the result to be just one byte long + BigIntToLeBytes to_bytes{ + .input = result, + .result = { static_cast(witness_values.size()) }, }; - BigIntOperation div_constraint{ + // overflow is NOT supported, you have to make sure there is no overflow/underflow. + fr value = 0; + switch (op) { + case Add: + value = witness_values[lhs_id] + witness_values[rhs_id]; + break; + case Sub: + value = witness_values[lhs_id] - witness_values[rhs_id]; + break; + case Mul: + value = witness_values[lhs_id] * witness_values[rhs_id]; + break; + case Div: + value = witness_values[lhs_id] / witness_values[rhs_id]; + break; + default: + ASSERT(false); + break; + } + + witness_values.push_back(value); + return { constraint, to_bytes }; +} + +// Based on TestBigIntConstraintSimple, we generate constraints for multiple operations at the same time. +TEST_F(BigIntTests, TestBigIntConstraintMultiple) +{ + WitnessVector witness; + auto contraints = generate_big_int_op_constraint(BigIntOperationType::Add, fr(3), fr(1), witness); + auto contraints2 = generate_big_int_op_constraint(BigIntOperationType::Add, fr(3), fr(1), witness); + auto contraints3 = generate_big_int_op_constraint(BigIntOperationType::Sub, fr(5), fr(2), witness); + auto contraints4 = generate_big_int_op_constraint(BigIntOperationType::Mul, fr(5), fr(3), witness); + auto contraints5 = generate_big_int_op_constraint(BigIntOperationType::Div, fr(8), fr(2), witness); + AcirFormat constraint_system{ + .varnum = static_cast(witness.size() + 1), + .recursive = false, + .public_inputs = {}, + .logic_constraints = {}, + .range_constraints = {}, + .sha256_constraints = {}, + .schnorr_constraints = {}, + .ecdsa_k1_constraints = {}, + .ecdsa_r1_constraints = {}, + .blake2s_constraints = {}, + .blake3_constraints = {}, + .keccak_constraints = {}, + .keccak_var_constraints = {}, + .keccak_permutations = {}, + .pedersen_constraints = {}, + .pedersen_hash_constraints = {}, + .fixed_base_scalar_mul_constraints = {}, + .ec_add_constraints = {}, + .recursion_constraints = {}, + .bigint_from_le_bytes_constraints = {}, + .bigint_to_le_bytes_constraints = {}, + .bigint_operations = {}, + .constraints = {}, + .block_constraints = {}, + }; + apply_constraints(constraint_system, contraints); + apply_constraints(constraint_system, contraints2); + apply_constraints(constraint_system, contraints3); + apply_constraints(constraint_system, contraints4); + apply_constraints(constraint_system, contraints5); + constraint_system.varnum = static_cast(witness.size() + 1); + + auto builder = create_circuit(constraint_system, /*size_hint*/ 0, witness); + + auto composer = Composer(); + auto prover = composer.create_ultra_with_keccak_prover(builder); + auto proof = prover.construct_proof(); + EXPECT_TRUE(builder.check_circuit()); + auto verifier = composer.create_ultra_with_keccak_verifier(builder); + EXPECT_EQ(verifier.verify_proof(proof), true); +} + +TEST_F(BigIntTests, TestBigIntConstraintSimple) +{ + // 3 + 3 = 6 + // 3 = bigint(1) = from_bytes(w(1)) + // 6 = bigint(2) = to_bytes(w(2)) + BigIntOperation add_constraint{ .lhs = 1, - .rhs = 2, - .result = 3, - .opcode = BigIntOperationType::Div, + .rhs = 1, + .result = 2, + .opcode = BigIntOperationType::Add, }; - BigIntFromLeBytes from_le_bytes_constraint{ - .inputs = { 0 }, - .modulus = { 23 }, + + BigIntFromLeBytes from_le_bytes_constraint_bigint1{ + .inputs = { 1 }, + .modulus = { 0x47, 0xFD, 0x7C, 0xD8, 0x16, 0x8C, 0x20, 0x3C, 0x8d, 0xca, 0x71, 0x68, 0x91, 0x6a, 0x81, 0x97, + 0x5d, 0x58, 0x81, 0x81, 0xb6, 0x45, 0x50, 0xb8, 0x29, 0xa0, 0x31, 0xe1, 0x72, 0x4e, 0x64, 0x30, }, .result = 1, }; + BigIntToLeBytes result2_to_le_bytes{ + .input = 2, .result = { 2 }, // 3+3=6 + }; + AcirFormat constraint_system{ - .varnum = 4, + .varnum = 5, .recursive = false, .public_inputs = {}, .logic_constraints = {}, @@ -66,22 +251,135 @@ TEST_F(BigIntTests, TestBigIntConstraintDummy) .fixed_base_scalar_mul_constraints = {}, .ec_add_constraints = {}, .recursion_constraints = {}, - .bigint_from_le_bytes_constraints = { from_le_bytes_constraint }, - .bigint_operations = { add_constraint, neg_constraint, mul_constraint, div_constraint }, + .bigint_from_le_bytes_constraints = { from_le_bytes_constraint_bigint1 }, + .bigint_to_le_bytes_constraints = { result2_to_le_bytes }, + .bigint_operations = { add_constraint }, .constraints = {}, .block_constraints = {}, }; - WitnessVector witness{ 0, 0, 1 }; + WitnessVector witness{ + 0, 3, 6, 3, 0, + }; + auto builder = create_circuit(constraint_system, /*size_hint*/ 0, witness); + auto composer = Composer(); + auto prover = composer.create_ultra_with_keccak_prover(builder); + auto proof = prover.construct_proof(); + EXPECT_TRUE(builder.check_circuit()); + auto verifier = composer.create_ultra_with_keccak_verifier(builder); + EXPECT_EQ(verifier.verify_proof(proof), true); +} + +// Based on TestBigIntConstraintMultiple, we generate constraints re-using the bigfields created by the first two +// operations +TEST_F(BigIntTests, TestBigIntConstraintReuse) +{ + WitnessVector witness; + auto contraints = generate_big_int_op_constraint_secpk1_fr(BigIntOperationType::Add, fr(3), fr(1), witness); + auto contraints2 = generate_big_int_op_constraint_secpk1_fr(BigIntOperationType::Sub, fr(5), fr(2), witness); + auto contraints3 = generate_big_int_op_constraint_with_id(BigIntOperationType::Mul, 0, 5, witness); + auto contraints4 = generate_big_int_op_constraint_with_id(BigIntOperationType::Div, 0, 1, witness); + auto contraints5 = generate_big_int_op_constraint_with_id(BigIntOperationType::Sub, 7, 1, witness); + + AcirFormat constraint_system{ + .varnum = static_cast(witness.size() + 1), + .recursive = false, + .public_inputs = {}, + .logic_constraints = {}, + .range_constraints = {}, + .sha256_constraints = {}, + .schnorr_constraints = {}, + .ecdsa_k1_constraints = {}, + .ecdsa_r1_constraints = {}, + .blake2s_constraints = {}, + .blake3_constraints = {}, + .keccak_constraints = {}, + .keccak_var_constraints = {}, + .keccak_permutations = {}, + .pedersen_constraints = {}, + .pedersen_hash_constraints = {}, + .fixed_base_scalar_mul_constraints = {}, + .ec_add_constraints = {}, + .recursion_constraints = {}, + .bigint_from_le_bytes_constraints = {}, + .bigint_to_le_bytes_constraints = {}, + .bigint_operations = {}, + .constraints = {}, + .block_constraints = {}, + }; + apply_constraints(constraint_system, contraints); + apply_constraints(constraint_system, contraints2); + constraint_system.bigint_to_le_bytes_constraints.push_back(get<1>(contraints3)); + constraint_system.bigint_operations.push_back(get<0>(contraints3)); + constraint_system.bigint_to_le_bytes_constraints.push_back(get<1>(contraints4)); + constraint_system.bigint_operations.push_back(get<0>(contraints4)); + constraint_system.bigint_to_le_bytes_constraints.push_back(get<1>(contraints5)); + constraint_system.bigint_operations.push_back(get<0>(contraints5)); + constraint_system.varnum = static_cast(witness.size() + 1); + auto builder = create_circuit(constraint_system, /*size_hint*/ 0, witness); auto composer = Composer(); auto prover = composer.create_ultra_with_keccak_prover(builder); auto proof = prover.construct_proof(); - + EXPECT_TRUE(builder.check_circuit()); auto verifier = composer.create_ultra_with_keccak_verifier(builder); + EXPECT_EQ(verifier.verify_proof(proof), true); +} +TEST_F(BigIntTests, TestBigIntConstraintReuse2) +{ + WitnessVector witness; + auto contraints = generate_big_int_op_constraint_secpk1_fq(BigIntOperationType::Add, fr(3), fr(1), witness); + auto contraints2 = generate_big_int_op_constraint_secpk1_fq(BigIntOperationType::Sub, fr(5), fr(2), witness); + auto contraints3 = generate_big_int_op_constraint_with_id(BigIntOperationType::Add, 0, 5, witness); + auto contraints4 = generate_big_int_op_constraint_with_id(BigIntOperationType::Sub, 0, 1, witness); + auto contraints5 = generate_big_int_op_constraint_with_id(BigIntOperationType::Sub, 7, 1, witness); + + AcirFormat constraint_system{ + .varnum = static_cast(witness.size() + 1), + .recursive = false, + .public_inputs = {}, + .logic_constraints = {}, + .range_constraints = {}, + .sha256_constraints = {}, + .schnorr_constraints = {}, + .ecdsa_k1_constraints = {}, + .ecdsa_r1_constraints = {}, + .blake2s_constraints = {}, + .blake3_constraints = {}, + .keccak_constraints = {}, + .keccak_var_constraints = {}, + .keccak_permutations = {}, + .pedersen_constraints = {}, + .pedersen_hash_constraints = {}, + .fixed_base_scalar_mul_constraints = {}, + .ec_add_constraints = {}, + .recursion_constraints = {}, + .bigint_from_le_bytes_constraints = {}, + .bigint_to_le_bytes_constraints = {}, + .bigint_operations = {}, + .constraints = {}, + .block_constraints = {}, + }; + apply_constraints(constraint_system, contraints); + apply_constraints(constraint_system, contraints2); + constraint_system.bigint_to_le_bytes_constraints.push_back(get<1>(contraints3)); + constraint_system.bigint_operations.push_back(get<0>(contraints3)); + constraint_system.bigint_to_le_bytes_constraints.push_back(get<1>(contraints4)); + constraint_system.bigint_operations.push_back(get<0>(contraints4)); + constraint_system.bigint_to_le_bytes_constraints.push_back(get<1>(contraints5)); + constraint_system.bigint_operations.push_back(get<0>(contraints5)); + constraint_system.varnum = static_cast(witness.size() + 1); + + auto builder = create_circuit(constraint_system, /*size_hint*/ 0, witness); + + auto composer = Composer(); + auto prover = composer.create_ultra_with_keccak_prover(builder); + auto proof = prover.construct_proof(); + EXPECT_TRUE(builder.check_circuit()); + auto verifier = composer.create_ultra_with_keccak_verifier(builder); EXPECT_EQ(verifier.verify_proof(proof), true); } diff --git a/barretenberg/cpp/src/barretenberg/dsl/acir_format/block_constraint.test.cpp b/barretenberg/cpp/src/barretenberg/dsl/acir_format/block_constraint.test.cpp index a88e89de566..90daa030f6e 100644 --- a/barretenberg/cpp/src/barretenberg/dsl/acir_format/block_constraint.test.cpp +++ b/barretenberg/cpp/src/barretenberg/dsl/acir_format/block_constraint.test.cpp @@ -129,6 +129,7 @@ TEST_F(UltraPlonkRAM, TestBlockConstraint) .ec_add_constraints = {}, .recursion_constraints = {}, .bigint_from_le_bytes_constraints = {}, + .bigint_to_le_bytes_constraints = {}, .bigint_operations = {}, .constraints = {}, .block_constraints = { block }, diff --git a/barretenberg/cpp/src/barretenberg/dsl/acir_format/ec_operations.test.cpp b/barretenberg/cpp/src/barretenberg/dsl/acir_format/ec_operations.test.cpp index d64110d938d..67af3597c9a 100644 --- a/barretenberg/cpp/src/barretenberg/dsl/acir_format/ec_operations.test.cpp +++ b/barretenberg/cpp/src/barretenberg/dsl/acir_format/ec_operations.test.cpp @@ -68,6 +68,7 @@ TEST_F(EcOperations, TestECOperations) .ec_add_constraints = { ec_add_constraint }, .recursion_constraints = {}, .bigint_from_le_bytes_constraints = {}, + .bigint_to_le_bytes_constraints = {}, .bigint_operations = {}, .constraints = {}, .block_constraints = {}, diff --git a/barretenberg/cpp/src/barretenberg/dsl/acir_format/ecdsa_secp256k1.test.cpp b/barretenberg/cpp/src/barretenberg/dsl/acir_format/ecdsa_secp256k1.test.cpp index ba6c67b2162..e0ea17fb13b 100644 --- a/barretenberg/cpp/src/barretenberg/dsl/acir_format/ecdsa_secp256k1.test.cpp +++ b/barretenberg/cpp/src/barretenberg/dsl/acir_format/ecdsa_secp256k1.test.cpp @@ -108,6 +108,7 @@ TEST_F(ECDSASecp256k1, TestECDSAConstraintSucceed) .ec_add_constraints = {}, .recursion_constraints = {}, .bigint_from_le_bytes_constraints = {}, + .bigint_to_le_bytes_constraints = {}, .bigint_operations = {}, .constraints = {}, .block_constraints = {}, @@ -154,6 +155,7 @@ TEST_F(ECDSASecp256k1, TestECDSACompilesForVerifier) .ec_add_constraints = {}, .recursion_constraints = {}, .bigint_from_le_bytes_constraints = {}, + .bigint_to_le_bytes_constraints = {}, .bigint_operations = {}, .constraints = {}, .block_constraints = {}, @@ -195,6 +197,7 @@ TEST_F(ECDSASecp256k1, TestECDSAConstraintFail) .ec_add_constraints = {}, .recursion_constraints = {}, .bigint_from_le_bytes_constraints = {}, + .bigint_to_le_bytes_constraints = {}, .bigint_operations = {}, .constraints = {}, .block_constraints = {}, diff --git a/barretenberg/cpp/src/barretenberg/dsl/acir_format/ecdsa_secp256r1.test.cpp b/barretenberg/cpp/src/barretenberg/dsl/acir_format/ecdsa_secp256r1.test.cpp index ee9f4e2faff..86ed2428d67 100644 --- a/barretenberg/cpp/src/barretenberg/dsl/acir_format/ecdsa_secp256r1.test.cpp +++ b/barretenberg/cpp/src/barretenberg/dsl/acir_format/ecdsa_secp256r1.test.cpp @@ -143,6 +143,7 @@ TEST(ECDSASecp256r1, test_hardcoded) .ec_add_constraints = {}, .recursion_constraints = {}, .bigint_from_le_bytes_constraints = {}, + .bigint_to_le_bytes_constraints = {}, .bigint_operations = {}, .constraints = {}, .block_constraints = {}, @@ -190,6 +191,7 @@ TEST(ECDSASecp256r1, TestECDSAConstraintSucceed) .ec_add_constraints = {}, .recursion_constraints = {}, .bigint_from_le_bytes_constraints = {}, + .bigint_to_le_bytes_constraints = {}, .bigint_operations = {}, .constraints = {}, .block_constraints = {}, @@ -235,6 +237,7 @@ TEST(ECDSASecp256r1, TestECDSACompilesForVerifier) .ec_add_constraints = {}, .recursion_constraints = {}, .bigint_from_le_bytes_constraints = {}, + .bigint_to_le_bytes_constraints = {}, .bigint_operations = {}, .constraints = {}, .block_constraints = {}, @@ -275,6 +278,7 @@ TEST(ECDSASecp256r1, TestECDSAConstraintFail) .ec_add_constraints = {}, .recursion_constraints = {}, .bigint_from_le_bytes_constraints = {}, + .bigint_to_le_bytes_constraints = {}, .bigint_operations = {}, .constraints = {}, .block_constraints = {}, diff --git a/barretenberg/cpp/src/barretenberg/dsl/acir_format/recursion_constraint.test.cpp b/barretenberg/cpp/src/barretenberg/dsl/acir_format/recursion_constraint.test.cpp index cc8fde631b4..0a22466ce88 100644 --- a/barretenberg/cpp/src/barretenberg/dsl/acir_format/recursion_constraint.test.cpp +++ b/barretenberg/cpp/src/barretenberg/dsl/acir_format/recursion_constraint.test.cpp @@ -101,6 +101,7 @@ Builder create_inner_circuit() .ec_add_constraints = {}, .recursion_constraints = {}, .bigint_from_le_bytes_constraints = {}, + .bigint_to_le_bytes_constraints = {}, .bigint_operations = {}, .constraints = { expr_a, expr_b, expr_c, expr_d }, .block_constraints = {} }; @@ -255,6 +256,7 @@ Builder create_outer_circuit(std::vector& inner_circuits) .ec_add_constraints = {}, .recursion_constraints = recursion_constraints, .bigint_from_le_bytes_constraints = {}, + .bigint_to_le_bytes_constraints = {}, .bigint_operations = {}, .constraints = {}, .block_constraints = {} }; diff --git a/barretenberg/cpp/src/barretenberg/dsl/acir_format/serde/acir.hpp b/barretenberg/cpp/src/barretenberg/dsl/acir_format/serde/acir.hpp index 02adc0e63e6..7de4fe12cbe 100644 --- a/barretenberg/cpp/src/barretenberg/dsl/acir_format/serde/acir.hpp +++ b/barretenberg/cpp/src/barretenberg/dsl/acir_format/serde/acir.hpp @@ -206,14 +206,14 @@ struct BlackBoxFuncCall { static BigIntAdd bincodeDeserialize(std::vector); }; - struct BigIntNeg { + struct BigIntSub { uint32_t lhs; uint32_t rhs; uint32_t output; - friend bool operator==(const BigIntNeg&, const BigIntNeg&); + friend bool operator==(const BigIntSub&, const BigIntSub&); std::vector bincodeSerialize() const; - static BigIntNeg bincodeDeserialize(std::vector); + static BigIntSub bincodeDeserialize(std::vector); }; struct BigIntMul { @@ -293,7 +293,7 @@ struct BlackBoxFuncCall { Keccakf1600, RecursiveAggregation, BigIntAdd, - BigIntNeg, + BigIntSub, BigIntMul, BigIntDiv, BigIntFromLeBytes, @@ -637,14 +637,14 @@ struct BlackBoxOp { static BigIntAdd bincodeDeserialize(std::vector); }; - struct BigIntNeg { + struct BigIntSub { Circuit::MemoryAddress lhs; Circuit::MemoryAddress rhs; Circuit::MemoryAddress output; - friend bool operator==(const BigIntNeg&, const BigIntNeg&); + friend bool operator==(const BigIntSub&, const BigIntSub&); std::vector bincodeSerialize() const; - static BigIntNeg bincodeDeserialize(std::vector); + static BigIntSub bincodeDeserialize(std::vector); }; struct BigIntMul { @@ -719,7 +719,7 @@ struct BlackBoxOp { FixedBaseScalarMul, EmbeddedCurveAdd, BigIntAdd, - BigIntNeg, + BigIntSub, BigIntMul, BigIntDiv, BigIntFromLeBytes, @@ -845,6 +845,7 @@ struct BrilligOpcode { struct Const { Circuit::MemoryAddress destination; + uint32_t bit_size; Circuit::Value value; friend bool operator==(const Const&, const Const&); @@ -1077,6 +1078,29 @@ struct Opcode { static Opcode bincodeDeserialize(std::vector); }; +struct ExpressionWidth { + + struct Unbounded { + friend bool operator==(const Unbounded&, const Unbounded&); + std::vector bincodeSerialize() const; + static Unbounded bincodeDeserialize(std::vector); + }; + + struct Bounded { + uint64_t width; + + friend bool operator==(const Bounded&, const Bounded&); + std::vector bincodeSerialize() const; + static Bounded bincodeDeserialize(std::vector); + }; + + std::variant value; + + friend bool operator==(const ExpressionWidth&, const ExpressionWidth&); + std::vector bincodeSerialize() const; + static ExpressionWidth bincodeDeserialize(std::vector); +}; + struct OpcodeLocation { struct Acir { @@ -1114,6 +1138,7 @@ struct PublicInputs { struct Circuit { uint32_t current_witness_index; std::vector opcodes; + ExpressionWidth expression_width; std::vector private_parameters; PublicInputs public_parameters; PublicInputs return_values; @@ -3046,7 +3071,7 @@ Circuit::BlackBoxFuncCall::BigIntAdd serde::Deserializable BlackBoxFuncCall::BigIntNeg::bincodeSerialize() const +inline std::vector BlackBoxFuncCall::BigIntSub::bincodeSerialize() const { auto serializer = serde::BincodeSerializer(); - serde::Serializable::serialize(*this, serializer); + serde::Serializable::serialize(*this, serializer); return std::move(serializer).bytes(); } -inline BlackBoxFuncCall::BigIntNeg BlackBoxFuncCall::BigIntNeg::bincodeDeserialize(std::vector input) +inline BlackBoxFuncCall::BigIntSub BlackBoxFuncCall::BigIntSub::bincodeDeserialize(std::vector input) { auto deserializer = serde::BincodeDeserializer(input); - auto value = serde::Deserializable::deserialize(deserializer); + auto value = serde::Deserializable::deserialize(deserializer); if (deserializer.get_buffer_offset() < input.size()) { throw_or_abort("Some input bytes were not read"); } @@ -3081,8 +3106,8 @@ inline BlackBoxFuncCall::BigIntNeg BlackBoxFuncCall::BigIntNeg::bincodeDeseriali template <> template -void serde::Serializable::serialize( - const Circuit::BlackBoxFuncCall::BigIntNeg& obj, Serializer& serializer) +void serde::Serializable::serialize( + const Circuit::BlackBoxFuncCall::BigIntSub& obj, Serializer& serializer) { serde::Serializable::serialize(obj.lhs, serializer); serde::Serializable::serialize(obj.rhs, serializer); @@ -3091,10 +3116,10 @@ void serde::Serializable::serialize( template <> template -Circuit::BlackBoxFuncCall::BigIntNeg serde::Deserializable::deserialize( +Circuit::BlackBoxFuncCall::BigIntSub serde::Deserializable::deserialize( Deserializer& deserializer) { - Circuit::BlackBoxFuncCall::BigIntNeg obj; + Circuit::BlackBoxFuncCall::BigIntSub obj; obj.lhs = serde::Deserializable::deserialize(deserializer); obj.rhs = serde::Deserializable::deserialize(deserializer); obj.output = serde::Deserializable::deserialize(deserializer); @@ -4248,7 +4273,7 @@ Circuit::BlackBoxOp::BigIntAdd serde::Deserializable BlackBoxOp::BigIntNeg::bincodeSerialize() const +inline std::vector BlackBoxOp::BigIntSub::bincodeSerialize() const { auto serializer = serde::BincodeSerializer(); - serde::Serializable::serialize(*this, serializer); + serde::Serializable::serialize(*this, serializer); return std::move(serializer).bytes(); } -inline BlackBoxOp::BigIntNeg BlackBoxOp::BigIntNeg::bincodeDeserialize(std::vector input) +inline BlackBoxOp::BigIntSub BlackBoxOp::BigIntSub::bincodeDeserialize(std::vector input) { auto deserializer = serde::BincodeDeserializer(input); - auto value = serde::Deserializable::deserialize(deserializer); + auto value = serde::Deserializable::deserialize(deserializer); if (deserializer.get_buffer_offset() < input.size()) { throw_or_abort("Some input bytes were not read"); } @@ -4283,7 +4308,7 @@ inline BlackBoxOp::BigIntNeg BlackBoxOp::BigIntNeg::bincodeDeserialize(std::vect template <> template -void serde::Serializable::serialize(const Circuit::BlackBoxOp::BigIntNeg& obj, +void serde::Serializable::serialize(const Circuit::BlackBoxOp::BigIntSub& obj, Serializer& serializer) { serde::Serializable::serialize(obj.lhs, serializer); @@ -4293,10 +4318,10 @@ void serde::Serializable::serialize(const Circui template <> template -Circuit::BlackBoxOp::BigIntNeg serde::Deserializable::deserialize( +Circuit::BlackBoxOp::BigIntSub serde::Deserializable::deserialize( Deserializer& deserializer) { - Circuit::BlackBoxOp::BigIntNeg obj; + Circuit::BlackBoxOp::BigIntSub obj; obj.lhs = serde::Deserializable::deserialize(deserializer); obj.rhs = serde::Deserializable::deserialize(deserializer); obj.output = serde::Deserializable::deserialize(deserializer); @@ -5336,6 +5361,9 @@ inline bool operator==(const BrilligOpcode::Const& lhs, const BrilligOpcode::Con if (!(lhs.destination == rhs.destination)) { return false; } + if (!(lhs.bit_size == rhs.bit_size)) { + return false; + } if (!(lhs.value == rhs.value)) { return false; } @@ -5367,6 +5395,7 @@ void serde::Serializable::serialize(const Circuit Serializer& serializer) { serde::Serializable::serialize(obj.destination, serializer); + serde::Serializable::serialize(obj.bit_size, serializer); serde::Serializable::serialize(obj.value, serializer); } @@ -5377,6 +5406,7 @@ Circuit::BrilligOpcode::Const serde::Deserializable::deserialize(deserializer); + obj.bit_size = serde::Deserializable::deserialize(deserializer); obj.value = serde::Deserializable::deserialize(deserializer); return obj; } @@ -5927,6 +5957,9 @@ inline bool operator==(const Circuit& lhs, const Circuit& rhs) if (!(lhs.opcodes == rhs.opcodes)) { return false; } + if (!(lhs.expression_width == rhs.expression_width)) { + return false; + } if (!(lhs.private_parameters == rhs.private_parameters)) { return false; } @@ -5971,6 +6004,7 @@ void serde::Serializable::serialize(const Circuit::Circuit& ob serializer.increase_container_depth(); serde::Serializable::serialize(obj.current_witness_index, serializer); serde::Serializable::serialize(obj.opcodes, serializer); + serde::Serializable::serialize(obj.expression_width, serializer); serde::Serializable::serialize(obj.private_parameters, serializer); serde::Serializable::serialize(obj.public_parameters, serializer); serde::Serializable::serialize(obj.return_values, serializer); @@ -5987,6 +6021,7 @@ Circuit::Circuit serde::Deserializable::deserialize(Deserializ Circuit::Circuit obj; obj.current_witness_index = serde::Deserializable::deserialize(deserializer); obj.opcodes = serde::Deserializable::deserialize(deserializer); + obj.expression_width = serde::Deserializable::deserialize(deserializer); obj.private_parameters = serde::Deserializable::deserialize(deserializer); obj.public_parameters = serde::Deserializable::deserialize(deserializer); obj.return_values = serde::Deserializable::deserialize(deserializer); @@ -6225,6 +6260,144 @@ Circuit::Expression serde::Deserializable::deserialize(Dese namespace Circuit { +inline bool operator==(const ExpressionWidth& lhs, const ExpressionWidth& rhs) +{ + if (!(lhs.value == rhs.value)) { + return false; + } + return true; +} + +inline std::vector ExpressionWidth::bincodeSerialize() const +{ + auto serializer = serde::BincodeSerializer(); + serde::Serializable::serialize(*this, serializer); + return std::move(serializer).bytes(); +} + +inline ExpressionWidth ExpressionWidth::bincodeDeserialize(std::vector input) +{ + auto deserializer = serde::BincodeDeserializer(input); + auto value = serde::Deserializable::deserialize(deserializer); + if (deserializer.get_buffer_offset() < input.size()) { + throw_or_abort("Some input bytes were not read"); + } + return value; +} + +} // end of namespace Circuit + +template <> +template +void serde::Serializable::serialize(const Circuit::ExpressionWidth& obj, + Serializer& serializer) +{ + serializer.increase_container_depth(); + serde::Serializable::serialize(obj.value, serializer); + serializer.decrease_container_depth(); +} + +template <> +template +Circuit::ExpressionWidth serde::Deserializable::deserialize(Deserializer& deserializer) +{ + deserializer.increase_container_depth(); + Circuit::ExpressionWidth obj; + obj.value = serde::Deserializable::deserialize(deserializer); + deserializer.decrease_container_depth(); + return obj; +} + +namespace Circuit { + +inline bool operator==(const ExpressionWidth::Unbounded& lhs, const ExpressionWidth::Unbounded& rhs) +{ + return true; +} + +inline std::vector ExpressionWidth::Unbounded::bincodeSerialize() const +{ + auto serializer = serde::BincodeSerializer(); + serde::Serializable::serialize(*this, serializer); + return std::move(serializer).bytes(); +} + +inline ExpressionWidth::Unbounded ExpressionWidth::Unbounded::bincodeDeserialize(std::vector input) +{ + auto deserializer = serde::BincodeDeserializer(input); + auto value = serde::Deserializable::deserialize(deserializer); + if (deserializer.get_buffer_offset() < input.size()) { + throw_or_abort("Some input bytes were not read"); + } + return value; +} + +} // end of namespace Circuit + +template <> +template +void serde::Serializable::serialize(const Circuit::ExpressionWidth::Unbounded& obj, + Serializer& serializer) +{} + +template <> +template +Circuit::ExpressionWidth::Unbounded serde::Deserializable::deserialize( + Deserializer& deserializer) +{ + Circuit::ExpressionWidth::Unbounded obj; + return obj; +} + +namespace Circuit { + +inline bool operator==(const ExpressionWidth::Bounded& lhs, const ExpressionWidth::Bounded& rhs) +{ + if (!(lhs.width == rhs.width)) { + return false; + } + return true; +} + +inline std::vector ExpressionWidth::Bounded::bincodeSerialize() const +{ + auto serializer = serde::BincodeSerializer(); + serde::Serializable::serialize(*this, serializer); + return std::move(serializer).bytes(); +} + +inline ExpressionWidth::Bounded ExpressionWidth::Bounded::bincodeDeserialize(std::vector input) +{ + auto deserializer = serde::BincodeDeserializer(input); + auto value = serde::Deserializable::deserialize(deserializer); + if (deserializer.get_buffer_offset() < input.size()) { + throw_or_abort("Some input bytes were not read"); + } + return value; +} + +} // end of namespace Circuit + +template <> +template +void serde::Serializable::serialize(const Circuit::ExpressionWidth::Bounded& obj, + Serializer& serializer) +{ + serde::Serializable::serialize(obj.width, serializer); +} + +template <> +template +Circuit::ExpressionWidth::Bounded serde::Deserializable::deserialize( + Deserializer& deserializer) +{ + Circuit::ExpressionWidth::Bounded obj; + obj.width = serde::Deserializable::deserialize(deserializer); + return obj; +} + +namespace Circuit { + inline bool operator==(const FunctionInput& lhs, const FunctionInput& rhs) { if (!(lhs.witness == rhs.witness)) { diff --git a/barretenberg/cpp/src/barretenberg/eccvm/eccvm_composer.cpp b/barretenberg/cpp/src/barretenberg/eccvm/eccvm_composer.cpp index 530e36f047b..e111aac9469 100644 --- a/barretenberg/cpp/src/barretenberg/eccvm/eccvm_composer.cpp +++ b/barretenberg/cpp/src/barretenberg/eccvm/eccvm_composer.cpp @@ -2,13 +2,13 @@ #include "barretenberg/proof_system/composer/composer_lib.hpp" #include "barretenberg/proof_system/composer/permutation_lib.hpp" -namespace bb::honk { +namespace bb { /** * @brief Compute witness polynomials * */ -template void ECCVMComposer_::compute_witness(CircuitConstructor& circuit_constructor) +template void ECCVMComposer_::compute_witness(CircuitConstructor& circuit_constructor) { if (computed_witness) { return; @@ -26,7 +26,7 @@ template void ECCVMComposer_::compute_witness(Circu computed_witness = true; } -template +template ECCVMProver_ ECCVMComposer_::create_prover(CircuitConstructor& circuit_constructor, const std::shared_ptr& transcript) { @@ -45,7 +45,7 @@ ECCVMProver_ ECCVMComposer_::create_prover(CircuitConstructor& c * * @return The verifier. * */ -template +template ECCVMVerifier_ ECCVMComposer_::create_verifier(CircuitConstructor& circuit_constructor, const std::shared_ptr& transcript) { @@ -61,7 +61,7 @@ ECCVMVerifier_ ECCVMComposer_::create_verifier(CircuitConstructo return output_state; } -template +template std::shared_ptr ECCVMComposer_::compute_proving_key( CircuitConstructor& circuit_constructor) { @@ -97,7 +97,7 @@ std::shared_ptr ECCVMComposer_::compute_pro * * @return Pointer to created circuit verification key. * */ -template +template std::shared_ptr ECCVMComposer_::compute_verification_key( CircuitConstructor& circuit_constructor) { @@ -117,6 +117,6 @@ std::shared_ptr ECCVMComposer_::comput verification_key->lagrange_last = commitment_key->commit(proving_key->lagrange_last); return verification_key; } -template class ECCVMComposer_; +template class ECCVMComposer_; -} // namespace bb::honk +} // namespace bb diff --git a/barretenberg/cpp/src/barretenberg/eccvm/eccvm_composer.hpp b/barretenberg/cpp/src/barretenberg/eccvm/eccvm_composer.hpp index e8a57b012cd..98f880a3823 100644 --- a/barretenberg/cpp/src/barretenberg/eccvm/eccvm_composer.hpp +++ b/barretenberg/cpp/src/barretenberg/eccvm/eccvm_composer.hpp @@ -7,8 +7,8 @@ #include "barretenberg/srs/factories/file_crs_factory.hpp" #include "barretenberg/srs/global_crs.hpp" -namespace bb::honk { -template class ECCVMComposer_ { +namespace bb { +template class ECCVMComposer_ { public: using FF = typename Flavor::FF; using CircuitConstructor = ECCVMCircuitBuilder; @@ -35,7 +35,7 @@ template class ECCVMComposer_ { bool contains_recursive_proof = false; bool computed_witness = false; ECCVMComposer_() - requires(std::same_as) + requires(std::same_as) { crs_factory_ = bb::srs::get_grumpkin_crs_factory(); }; @@ -75,6 +75,6 @@ template class ECCVMComposer_ { }; // TODO(#532): this pattern is weird; is this not instantiating the templates? -using ECCVMComposer = ECCVMComposer_; +using ECCVMComposer = ECCVMComposer_; -} // namespace bb::honk +} // namespace bb diff --git a/barretenberg/cpp/src/barretenberg/eccvm/eccvm_composer.test.cpp b/barretenberg/cpp/src/barretenberg/eccvm/eccvm_composer.test.cpp index bd995155314..812f842dee3 100644 --- a/barretenberg/cpp/src/barretenberg/eccvm/eccvm_composer.test.cpp +++ b/barretenberg/cpp/src/barretenberg/eccvm/eccvm_composer.test.cpp @@ -13,14 +13,13 @@ #include "barretenberg/sumcheck/sumcheck_round.hpp" using namespace bb; -using namespace bb::honk; template class ECCVMComposerTests : public ::testing::Test { protected: // TODO(640): The Standard Honk on Grumpkin test suite fails unless the SRS is initialized for every test. void SetUp() override { - if constexpr (std::is_same::value) { + if constexpr (std::is_same::value) { srs::init_grumpkin_crs_factory("../srs_db/grumpkin"); } else { srs::init_crs_factory("../srs_db/ignition"); @@ -28,7 +27,7 @@ template class ECCVMComposerTests : public ::testing::Test { }; }; -using FlavorTypes = ::testing::Types; +using FlavorTypes = ::testing::Types; TYPED_TEST_SUITE(ECCVMComposerTests, FlavorTypes); namespace { diff --git a/barretenberg/cpp/src/barretenberg/eccvm/eccvm_prover.cpp b/barretenberg/cpp/src/barretenberg/eccvm/eccvm_prover.cpp index 071a63dfb4a..ec5cba49084 100644 --- a/barretenberg/cpp/src/barretenberg/eccvm/eccvm_prover.cpp +++ b/barretenberg/cpp/src/barretenberg/eccvm/eccvm_prover.cpp @@ -10,7 +10,7 @@ #include "barretenberg/relations/permutation_relation.hpp" #include "barretenberg/sumcheck/sumcheck.hpp" -namespace bb::honk { +namespace bb { /** * Create ECCVMProver_ from proving key, witness and manifest. @@ -20,7 +20,7 @@ namespace bb::honk { * * @tparam settings Settings class. * */ -template +template ECCVMProver_::ECCVMProver_(const std::shared_ptr& input_key, const std::shared_ptr& commitment_key, const std::shared_ptr& transcript) @@ -44,7 +44,7 @@ ECCVMProver_::ECCVMProver_(const std::shared_ptr void ECCVMProver_::execute_preamble_round() +template void ECCVMProver_::execute_preamble_round() { const auto circuit_size = static_cast(key->circuit_size); @@ -55,7 +55,7 @@ template void ECCVMProver_::execute_preamble_round( * @brief Compute commitments to the first three wires * */ -template void ECCVMProver_::execute_wire_commitments_round() +template void ECCVMProver_::execute_wire_commitments_round() { auto wire_polys = key->get_wires(); auto labels = commitment_labels.get_wires(); @@ -68,7 +68,7 @@ template void ECCVMProver_::execute_wire_commitment * @brief Compute sorted witness-table accumulator * */ -template void ECCVMProver_::execute_log_derivative_commitments_round() +template void ECCVMProver_::execute_log_derivative_commitments_round() { // Compute and add beta to relation parameters auto [beta, gamma] = challenges_to_field_elements(transcript->get_challenges("beta", "gamma")); @@ -83,7 +83,7 @@ template void ECCVMProver_::execute_log_derivative_ gamma * (gamma + beta_sqr) * (gamma + beta_sqr + beta_sqr) * (gamma + beta_sqr + beta_sqr + beta_sqr); relation_parameters.eccvm_set_permutation_delta = relation_parameters.eccvm_set_permutation_delta.invert(); // Compute inverse polynomial for our logarithmic-derivative lookup method - logderivative_library::compute_logderivative_inverse( + compute_logderivative_inverse( prover_polynomials, relation_parameters, key->circuit_size); transcript->send_to_verifier(commitment_labels.lookup_inverses, commitment_key->commit(key->lookup_inverses)); prover_polynomials.lookup_inverses = key->lookup_inverses.share(); @@ -93,10 +93,10 @@ template void ECCVMProver_::execute_log_derivative_ * @brief Compute permutation and lookup grand product polynomials and commitments * */ -template void ECCVMProver_::execute_grand_product_computation_round() +template void ECCVMProver_::execute_grand_product_computation_round() { // Compute permutation grand product and their commitments - permutation_library::compute_permutation_grand_products(key, prover_polynomials, relation_parameters); + compute_permutation_grand_products(key, prover_polynomials, relation_parameters); transcript->send_to_verifier(commitment_labels.z_perm, commitment_key->commit(key->z_perm)); } @@ -105,9 +105,9 @@ template void ECCVMProver_::execute_grand_product_c * @brief Run Sumcheck resulting in u = (u_1,...,u_d) challenges and all evaluations at u being calculated. * */ -template void ECCVMProver_::execute_relation_check_rounds() +template void ECCVMProver_::execute_relation_check_rounds() { - using Sumcheck = sumcheck::SumcheckProver; + using Sumcheck = SumcheckProver; auto sumcheck = Sumcheck(key->circuit_size, transcript); FF alpha = transcript->get_challenge("Sumcheck:alpha"); @@ -123,13 +123,13 @@ template void ECCVMProver_::execute_relation_check_ * - Compute d+1 Fold polynomials and their evaluations. * * */ -template void ECCVMProver_::execute_univariatization_round() +template void ECCVMProver_::execute_univariatization_round() { const size_t NUM_POLYNOMIALS = Flavor::NUM_ALL_ENTITIES; // Generate batching challenge ρ and powers 1,ρ,…,ρᵐ⁻¹ FF rho = transcript->get_challenge("rho"); - std::vector rhos = pcs::gemini::powers_of_rho(rho, NUM_POLYNOMIALS); + std::vector rhos = gemini::powers_of_rho(rho, NUM_POLYNOMIALS); // Batch the unshifted polynomials and the to-be-shifted polynomials using ρ Polynomial batched_poly_unshifted(key->circuit_size); // batched unshifted polynomials @@ -166,7 +166,7 @@ template void ECCVMProver_::execute_univariatizatio * - Compute and aggregate opening pairs (challenge, evaluation) for each of d Fold polynomials. * - Add d-many Fold evaluations a_i, i = 0, ..., d-1 to the transcript, excluding eval of Fold_{r}^(0) * */ -template void ECCVMProver_::execute_pcs_evaluation_round() +template void ECCVMProver_::execute_pcs_evaluation_round() { const FF r_challenge = transcript->get_challenge("Gemini:r"); gemini_output = Gemini::compute_fold_polynomial_evaluations( @@ -183,7 +183,7 @@ template void ECCVMProver_::execute_pcs_evaluation_ * - Do Fiat-Shamir to get "nu" challenge. * - Compute commitment [Q]_1 * */ -template void ECCVMProver_::execute_shplonk_batched_quotient_round() +template void ECCVMProver_::execute_shplonk_batched_quotient_round() { nu_challenge = transcript->get_challenge("Shplonk:nu"); @@ -198,7 +198,7 @@ template void ECCVMProver_::execute_shplonk_batched * - Do Fiat-Shamir to get "z" challenge. * - Compute polynomial Q(X) - Q_z(X) * */ -template void ECCVMProver_::execute_shplonk_partial_evaluation_round() +template void ECCVMProver_::execute_shplonk_partial_evaluation_round() { const FF z_challenge = transcript->get_challenge("Shplonk:z"); @@ -210,7 +210,7 @@ template void ECCVMProver_::execute_shplonk_partial * - For KZG, this is the quotient commitment [W]_1 * - For IPA, the vectors L and R * */ -template void ECCVMProver_::execute_final_pcs_round() +template void ECCVMProver_::execute_final_pcs_round() { PCS::compute_opening_proof(commitment_key, shplonk_output.opening_pair, shplonk_output.witness, transcript); } @@ -221,7 +221,7 @@ template void ECCVMProver_::execute_final_pcs_round * * @tparam Flavor */ -template void ECCVMProver_::execute_transcript_consistency_univariate_opening_round() +template void ECCVMProver_::execute_transcript_consistency_univariate_opening_round() { // Since IPA cannot currently handle polynomials for which the latter half of the coefficients are 0, we hackily // batch the constant polynomial 1 in with the 5 transcript polynomials. See issue #768 for more details. @@ -274,13 +274,13 @@ template void ECCVMProver_::execute_transcript_cons translation_batching_challenge_v = transcript->get_challenge("Translation:batching_challenge"); } -template honk::proof& ECCVMProver_::export_proof() +template HonkProof& ECCVMProver_::export_proof() { proof = transcript->export_proof(); return proof; } -template honk::proof& ECCVMProver_::construct_proof() +template HonkProof& ECCVMProver_::construct_proof() { execute_preamble_round(); @@ -307,6 +307,6 @@ template honk::proof& ECCVMProver_::construct_proof return export_proof(); } -template class ECCVMProver_; +template class ECCVMProver_; -} // namespace bb::honk +} // namespace bb diff --git a/barretenberg/cpp/src/barretenberg/eccvm/eccvm_prover.hpp b/barretenberg/cpp/src/barretenberg/eccvm/eccvm_prover.hpp index 96f3e76a309..a5051d6d4f9 100644 --- a/barretenberg/cpp/src/barretenberg/eccvm/eccvm_prover.hpp +++ b/barretenberg/cpp/src/barretenberg/eccvm/eccvm_prover.hpp @@ -8,11 +8,11 @@ #include "barretenberg/sumcheck/sumcheck_output.hpp" #include "barretenberg/transcript/transcript.hpp" -namespace bb::honk { +namespace bb { -// We won't compile this class with honk::flavor::Standard, but we will like want to compile it (at least for testing) +// We won't compile this class with Standard, but we will like want to compile it (at least for testing) // with a flavor that uses the curve Grumpkin, or a flavor that does/does not have zk, etc. -template class ECCVMProver_ { +template class ECCVMProver_ { using FF = typename Flavor::FF; using PCS = typename Flavor::PCS; @@ -42,8 +42,8 @@ template class ECCVMProver_ { BBERG_PROFILE void execute_final_pcs_round(); BBERG_PROFILE void execute_transcript_consistency_univariate_opening_round(); - honk::proof& export_proof(); - honk::proof& construct_proof(); + HonkProof& export_proof(); + HonkProof& construct_proof(); std::shared_ptr transcript; @@ -71,16 +71,16 @@ template class ECCVMProver_ { FF evaluation_challenge_x; FF translation_batching_challenge_v; // to be rederived by the translator verifier - sumcheck::SumcheckOutput sumcheck_output; - pcs::gemini::ProverOutput gemini_output; - pcs::shplonk::ProverOutput shplonk_output; + SumcheckOutput sumcheck_output; + GeminiProverOutput gemini_output; + ShplonkProverOutput shplonk_output; std::shared_ptr commitment_key; - using Gemini = pcs::gemini::GeminiProver_; - using Shplonk = pcs::shplonk::ShplonkProver_; + using Gemini = GeminiProver_; + using Shplonk = ShplonkProver_; private: - honk::proof proof; + HonkProof proof; }; -} // namespace bb::honk +} // namespace bb diff --git a/barretenberg/cpp/src/barretenberg/eccvm/eccvm_transcript.test.cpp b/barretenberg/cpp/src/barretenberg/eccvm/eccvm_transcript.test.cpp index 2b4e69d3624..73dafdf3c68 100644 --- a/barretenberg/cpp/src/barretenberg/eccvm/eccvm_transcript.test.cpp +++ b/barretenberg/cpp/src/barretenberg/eccvm/eccvm_transcript.test.cpp @@ -7,13 +7,12 @@ #include using namespace bb; -using namespace bb::honk; template class ECCVMTranscriptTests : public ::testing::Test { public: void SetUp() override { - if constexpr (std::is_same::value) { + if constexpr (std::is_same::value) { srs::init_grumpkin_crs_factory("../srs_db/grumpkin"); } else { srs::init_crs_factory("../srs_db/ignition"); @@ -222,7 +221,7 @@ template class ECCVMTranscriptTests : public ::testing::Test { numeric::RNG& engine = numeric::get_debug_randomness(); -using FlavorTypes = testing::Types; +using FlavorTypes = testing::Types; TYPED_TEST_SUITE(ECCVMTranscriptTests, FlavorTypes); /** diff --git a/barretenberg/cpp/src/barretenberg/eccvm/eccvm_verifier.cpp b/barretenberg/cpp/src/barretenberg/eccvm/eccvm_verifier.cpp index 82780b09eb3..58cf1e656c3 100644 --- a/barretenberg/cpp/src/barretenberg/eccvm/eccvm_verifier.cpp +++ b/barretenberg/cpp/src/barretenberg/eccvm/eccvm_verifier.cpp @@ -4,10 +4,7 @@ #include "barretenberg/numeric/bitop/get_msb.hpp" #include "barretenberg/transcript/transcript.hpp" -using namespace bb; -using namespace bb::honk::sumcheck; - -namespace bb::honk { +namespace bb { template ECCVMVerifier_::ECCVMVerifier_(const std::shared_ptr& verifier_key) : key(verifier_key) @@ -32,19 +29,18 @@ template ECCVMVerifier_& ECCVMVerifier_::opera * @brief This function verifies an ECCVM Honk proof for given program settings. * */ -template bool ECCVMVerifier_::verify_proof(const honk::proof& proof) +template bool ECCVMVerifier_::verify_proof(const HonkProof& proof) { using FF = typename Flavor::FF; using GroupElement = typename Flavor::GroupElement; using Commitment = typename Flavor::Commitment; using PCS = typename Flavor::PCS; using Curve = typename Flavor::Curve; - using Gemini = pcs::gemini::GeminiVerifier_; - using Shplonk = pcs::shplonk::ShplonkVerifier_; + using Gemini = GeminiVerifier_; + using Shplonk = ShplonkVerifier_; using VerifierCommitments = typename Flavor::VerifierCommitments; using CommitmentLabels = typename Flavor::CommitmentLabels; using Transcript = typename Flavor::Transcript; - using OpeningClaim = typename pcs::OpeningClaim; RelationParameters relation_parameters; @@ -183,7 +179,7 @@ template bool ECCVMVerifier_::verify_proof(const honk: const size_t NUM_POLYNOMIALS = Flavor::NUM_ALL_ENTITIES; // Compute powers of batching challenge rho FF rho = transcript->get_challenge("rho"); - std::vector rhos = pcs::gemini::powers_of_rho(rho, NUM_POLYNOMIALS); + std::vector rhos = gemini::powers_of_rho(rho, NUM_POLYNOMIALS); // Compute batched multivariate evaluation FF batched_evaluation = FF::zero(); @@ -273,14 +269,14 @@ template bool ECCVMVerifier_::verify_proof(const honk: } // Construct and verify batched opening claim - OpeningClaim batched_univariate_claim = { { evaluation_challenge_x, batched_transcript_eval }, - batched_commitment }; + OpeningClaim batched_univariate_claim = { { evaluation_challenge_x, batched_transcript_eval }, + batched_commitment }; univariate_opening_verified = PCS::verify(pcs_verification_key, batched_univariate_claim, transcript); } return sumcheck_verified.value() && multivariate_opening_verified && univariate_opening_verified; } -template class ECCVMVerifier_; +template class ECCVMVerifier_; -} // namespace bb::honk +} // namespace bb diff --git a/barretenberg/cpp/src/barretenberg/eccvm/eccvm_verifier.hpp b/barretenberg/cpp/src/barretenberg/eccvm/eccvm_verifier.hpp index 998bd5ed034..958453b42ea 100644 --- a/barretenberg/cpp/src/barretenberg/eccvm/eccvm_verifier.hpp +++ b/barretenberg/cpp/src/barretenberg/eccvm/eccvm_verifier.hpp @@ -3,7 +3,7 @@ #include "barretenberg/honk/proof_system/types/proof.hpp" #include "barretenberg/sumcheck/sumcheck.hpp" -namespace bb::honk { +namespace bb { template class ECCVMVerifier_ { using FF = typename Flavor::FF; using Commitment = typename Flavor::Commitment; @@ -30,7 +30,7 @@ template class ECCVMVerifier_ { ECCVMVerifier_& operator=(ECCVMVerifier_&& other) noexcept; ~ECCVMVerifier_() = default; - bool verify_proof(const honk::proof& proof); + bool verify_proof(const HonkProof& proof); std::shared_ptr key; std::map commitments; @@ -39,6 +39,6 @@ template class ECCVMVerifier_ { std::shared_ptr transcript; }; -using ECCVMVerifierGrumpkin = ECCVMVerifier_; +using ECCVMVerifierGrumpkin = ECCVMVerifier_; -} // namespace bb::honk +} // namespace bb diff --git a/barretenberg/cpp/src/barretenberg/flavor/ecc_vm.hpp b/barretenberg/cpp/src/barretenberg/flavor/ecc_vm.hpp index 8745101e633..ba3c2df1abf 100644 --- a/barretenberg/cpp/src/barretenberg/flavor/ecc_vm.hpp +++ b/barretenberg/cpp/src/barretenberg/flavor/ecc_vm.hpp @@ -26,7 +26,7 @@ // NOLINTBEGIN(cppcoreguidelines-avoid-const-or-ref-data-members) -namespace bb::honk::flavor { +namespace bb { template class ECCVMBase { public: @@ -42,8 +42,8 @@ template class ECCVMBa using GroupElement = typename G1::element; using Commitment = typename G1::affine_element; using CommitmentHandle = typename G1::affine_element; - using CommitmentKey = pcs::CommitmentKey; - using VerifierCommitmentKey = pcs::VerifierCommitmentKey; + using CommitmentKey = bb::CommitmentKey; + using VerifierCommitmentKey = bb::VerifierCommitmentKey; using RelationSeparator = FF; static constexpr size_t NUM_WIRES = 74; @@ -58,16 +58,16 @@ template class ECCVMBa // The total number of witness entities not including shifts. static constexpr size_t NUM_WITNESS_ENTITIES = 76; - using GrandProductRelations = std::tuple>; + using GrandProductRelations = std::tuple>; // define the tuple of Relations that comprise the Sumcheck relation - using Relations = std::tuple, - sumcheck::ECCVMPointTableRelation, - sumcheck::ECCVMWnafRelation, - sumcheck::ECCVMMSMRelation, - sumcheck::ECCVMSetRelation, - sumcheck::ECCVMLookupRelation>; - - using LookupRelation = sumcheck::ECCVMLookupRelation; + using Relations = std::tuple, + ECCVMPointTableRelation, + ECCVMWnafRelation, + ECCVMMSMRelation, + ECCVMSetRelation, + ECCVMLookupRelation>; + + using LookupRelation = ECCVMLookupRelation; static constexpr size_t MAX_PARTIAL_RELATION_LENGTH = compute_max_partial_relation_length(); // BATCHED_RELATION_PARTIAL_LENGTH = algebraic degree of sumcheck relation *after* multiplying by the `pow_zeta` @@ -613,7 +613,7 @@ template class ECCVMBa Transcript() = default; - Transcript(const honk::proof& proof) + Transcript(const HonkProof& proof) : BaseTranscript(proof) {} @@ -793,10 +793,10 @@ template class ECCVMBa } shplonk_q_comm = BaseTranscript::template deserialize_from_buffer(BaseTranscript::proof_data, num_frs_read); - if (std::is_same>::value) { + if (std::is_same>::value) { kzg_w_comm = BaseTranscript::template deserialize_from_buffer(BaseTranscript::proof_data, num_frs_read); - } else if (std::is_same>::value) { + } else if (std::is_same>::value) { ipa_poly_degree = BaseTranscript::template deserialize_from_buffer(BaseTranscript::proof_data, num_frs_read); auto log_poly_degree = static_cast(numeric::get_msb(ipa_poly_degree)); @@ -907,9 +907,9 @@ template class ECCVMBa BaseTranscript::template serialize_to_buffer(gemini_a_evals[i], BaseTranscript::proof_data); } BaseTranscript::template serialize_to_buffer(shplonk_q_comm, BaseTranscript::proof_data); - if (std::is_same>::value) { + if (std::is_same>::value) { BaseTranscript::template serialize_to_buffer(kzg_w_comm, BaseTranscript::proof_data); - } else if (std::is_same>::value) { + } else if (std::is_same>::value) { BaseTranscript::template serialize_to_buffer(ipa_poly_degree, BaseTranscript::proof_data); auto log_poly_degree = static_cast(numeric::get_msb(ipa_poly_degree)); for (size_t i = 0; i < log_poly_degree; ++i) { @@ -924,8 +924,8 @@ template class ECCVMBa }; }; -class ECCVM : public ECCVMBase> {}; +class ECCVMFlavor : public ECCVMBase> {}; // NOLINTEND(cppcoreguidelines-avoid-const-or-ref-data-members) -} // namespace bb::honk::flavor +} // namespace bb diff --git a/barretenberg/cpp/src/barretenberg/flavor/flavor.hpp b/barretenberg/cpp/src/barretenberg/flavor/flavor.hpp index 3272ed95164..fd45588e9c6 100644 --- a/barretenberg/cpp/src/barretenberg/flavor/flavor.hpp +++ b/barretenberg/cpp/src/barretenberg/flavor/flavor.hpp @@ -76,7 +76,7 @@ #include #include -namespace bb::honk::flavor { +namespace bb { /** * @brief Base class template containing circuit-specifying data. @@ -255,16 +255,16 @@ template static constexpr auto create_tu } } -} // namespace bb::honk::flavor +} // namespace bb // Forward declare honk flavors -namespace bb::honk::flavor { -class Ultra; -class ECCVM; -class GoblinUltra; -template class UltraRecursive_; -template class GoblinUltraRecursive_; -} // namespace bb::honk::flavor +namespace bb { +class UltraFlavor; +class ECCVMFlavor; +class GoblinUltraFlavor; +template class UltraRecursiveFlavor_; +template class GoblinUltraRecursiveFlavor_; +} // namespace bb // Forward declare plonk flavors namespace bb::plonk::flavor { @@ -286,34 +286,32 @@ template concept IsPlonkFlavor = IsAnyOf; template -concept IsHonkFlavor = IsAnyOf; +concept IsHonkFlavor = IsAnyOf; template -concept IsUltraFlavor = IsAnyOf; +concept IsUltraFlavor = IsAnyOf; template -concept IsGoblinFlavor = IsAnyOf, - honk::flavor::GoblinUltraRecursive_>; +concept IsGoblinFlavor = IsAnyOf, + GoblinUltraRecursiveFlavor_>; template -concept IsRecursiveFlavor = IsAnyOf, - honk::flavor::UltraRecursive_, - honk::flavor::GoblinUltraRecursive_, - honk::flavor::GoblinUltraRecursive_>; - -template concept IsGrumpkinFlavor = IsAnyOf; +concept IsRecursiveFlavor = IsAnyOf, + UltraRecursiveFlavor_, + GoblinUltraRecursiveFlavor_, + GoblinUltraRecursiveFlavor_>; -template concept IsFoldingFlavor = IsAnyOf, - honk::flavor::UltraRecursive_, - honk::flavor::GoblinUltraRecursive_, - honk::flavor::GoblinUltraRecursive_>; +template concept IsGrumpkinFlavor = IsAnyOf; -template concept UltraFlavor = IsAnyOf; +template concept IsFoldingFlavor = IsAnyOf, + UltraRecursiveFlavor_, + GoblinUltraRecursiveFlavor_, + GoblinUltraRecursiveFlavor_>; -template concept ECCVMFlavor = IsAnyOf; +template concept IsECCVMFlavor = IsAnyOf; template inline std::string flavor_get_label(Container&& container, const Element& element) { diff --git a/barretenberg/cpp/src/barretenberg/flavor/flavor.test.cpp b/barretenberg/cpp/src/barretenberg/flavor/flavor.test.cpp index 3eb36f5fdc2..89886373557 100644 --- a/barretenberg/cpp/src/barretenberg/flavor/flavor.test.cpp +++ b/barretenberg/cpp/src/barretenberg/flavor/flavor.test.cpp @@ -8,7 +8,7 @@ using namespace bb; TEST(Flavor, Getters) { - using Flavor = honk::flavor::Ultra; + using Flavor = UltraFlavor; using FF = Flavor::FF; using ProvingKey = typename Flavor::ProvingKey; @@ -43,7 +43,7 @@ TEST(Flavor, Getters) TEST(Flavor, AllEntitiesSpecialMemberFunctions) { - using Flavor = honk::flavor::Ultra; + using Flavor = UltraFlavor; using FF = Flavor::FF; using PartiallyEvaluatedMultivariates = Flavor::PartiallyEvaluatedMultivariates; using Polynomial = bb::Polynomial; @@ -69,7 +69,7 @@ TEST(Flavor, AllEntitiesSpecialMemberFunctions) TEST(Flavor, GetRow) { - using Flavor = honk::flavor::Ultra; + using Flavor = UltraFlavor; using FF = typename Flavor::FF; std::array, Flavor::NUM_ALL_ENTITIES> data; std::generate(data.begin(), data.end(), []() { diff --git a/barretenberg/cpp/src/barretenberg/flavor/generated/AvmMini_flavor.hpp b/barretenberg/cpp/src/barretenberg/flavor/generated/AvmMini_flavor.hpp index 19b18ec3d79..a249820db28 100644 --- a/barretenberg/cpp/src/barretenberg/flavor/generated/AvmMini_flavor.hpp +++ b/barretenberg/cpp/src/barretenberg/flavor/generated/AvmMini_flavor.hpp @@ -18,13 +18,13 @@ #include "barretenberg/relations/generated/AvmMini/mem_trace.hpp" #include "barretenberg/transcript/transcript.hpp" -namespace bb::honk::flavor { +namespace bb { class AvmMiniFlavor { public: using Curve = curve::BN254; using G1 = Curve::Group; - using PCS = pcs::kzg::KZG; + using PCS = KZG; using FF = G1::subgroup_field; using Polynomial = bb::Polynomial; @@ -32,8 +32,8 @@ class AvmMiniFlavor { using GroupElement = G1::element; using Commitment = G1::affine_element; using CommitmentHandle = G1::affine_element; - using CommitmentKey = pcs::CommitmentKey; - using VerifierCommitmentKey = pcs::VerifierCommitmentKey; + using CommitmentKey = bb::CommitmentKey; + using VerifierCommitmentKey = bb::VerifierCommitmentKey; using RelationSeparator = FF; static constexpr size_t NUM_PRECOMPUTED_ENTITIES = 2; @@ -898,4 +898,4 @@ class AvmMiniFlavor { }; }; -} // namespace bb::honk::flavor +} // namespace bb diff --git a/barretenberg/cpp/src/barretenberg/flavor/generated/Toy_flavor.hpp b/barretenberg/cpp/src/barretenberg/flavor/generated/Toy_flavor.hpp index 258d4c3d8a0..83f540cfd8b 100644 --- a/barretenberg/cpp/src/barretenberg/flavor/generated/Toy_flavor.hpp +++ b/barretenberg/cpp/src/barretenberg/flavor/generated/Toy_flavor.hpp @@ -17,13 +17,13 @@ #include "barretenberg/relations/generated/Toy/two_column_perm.hpp" #include "barretenberg/transcript/transcript.hpp" -namespace bb::honk::flavor { +namespace bb { class ToyFlavor { public: using Curve = curve::BN254; using G1 = Curve::Group; - using PCS = pcs::kzg::KZG; + using PCS = KZG; using FF = G1::subgroup_field; using Polynomial = bb::Polynomial; @@ -31,8 +31,8 @@ class ToyFlavor { using GroupElement = G1::element; using Commitment = G1::affine_element; using CommitmentHandle = G1::affine_element; - using CommitmentKey = pcs::CommitmentKey; - using VerifierCommitmentKey = pcs::VerifierCommitmentKey; + using CommitmentKey = bb::CommitmentKey; + using VerifierCommitmentKey = bb::VerifierCommitmentKey; using RelationSeparator = FF; static constexpr size_t NUM_PRECOMPUTED_ENTITIES = 1; @@ -42,7 +42,7 @@ class ToyFlavor { // the unshifted and one for the shifted static constexpr size_t NUM_ALL_ENTITIES = 17; - using Relations = std::tuple, sumcheck::two_column_perm_relation>; + using Relations = std::tuple, two_column_perm_relation>; static constexpr size_t MAX_PARTIAL_RELATION_LENGTH = compute_max_partial_relation_length(); @@ -367,4 +367,4 @@ class ToyFlavor { }; }; -} // namespace bb::honk::flavor +} // namespace bb diff --git a/barretenberg/cpp/src/barretenberg/flavor/goblin_translator.hpp b/barretenberg/cpp/src/barretenberg/flavor/goblin_translator.hpp index f18a480f176..8f0fe89209d 100644 --- a/barretenberg/cpp/src/barretenberg/flavor/goblin_translator.hpp +++ b/barretenberg/cpp/src/barretenberg/flavor/goblin_translator.hpp @@ -16,20 +16,20 @@ #include "barretenberg/relations/translator_vm/translator_permutation_relation.hpp" #include "relation_definitions.hpp" -namespace bb::honk::flavor { +namespace bb { -class GoblinTranslator { +class GoblinTranslatorFlavor { public: static constexpr size_t mini_circuit_size = 2048; using CircuitBuilder = GoblinTranslatorCircuitBuilder; using Curve = curve::BN254; - using PCS = pcs::kzg::KZG; + using PCS = KZG; using GroupElement = Curve::Element; using Commitment = Curve::AffineElement; using CommitmentHandle = Curve::AffineElement; - using CommitmentKey = pcs::CommitmentKey; - using VerifierCommitmentKey = pcs::VerifierCommitmentKey; + using CommitmentKey = bb::CommitmentKey; + using VerifierCommitmentKey = bb::VerifierCommitmentKey; using FF = Curve::ScalarField; using BF = Curve::BaseField; using Polynomial = bb::Polynomial; @@ -1138,4 +1138,4 @@ class GoblinTranslator { using Transcript = BaseTranscript; }; -} // namespace bb::honk::flavor \ No newline at end of file +} // namespace bb \ No newline at end of file diff --git a/barretenberg/cpp/src/barretenberg/flavor/goblin_ultra.hpp b/barretenberg/cpp/src/barretenberg/flavor/goblin_ultra.hpp index ed247351c52..5ff14f552aa 100644 --- a/barretenberg/cpp/src/barretenberg/flavor/goblin_ultra.hpp +++ b/barretenberg/cpp/src/barretenberg/flavor/goblin_ultra.hpp @@ -20,9 +20,9 @@ #include "barretenberg/transcript/transcript.hpp" #include "relation_definitions.hpp" -namespace bb::honk::flavor { +namespace bb { -class GoblinUltra { +class GoblinUltraFlavor { public: using CircuitBuilder = GoblinUltraCircuitBuilder; using Curve = curve::BN254; @@ -30,11 +30,11 @@ class GoblinUltra { using GroupElement = Curve::Element; using Commitment = Curve::AffineElement; using CommitmentHandle = Curve::AffineElement; - using PCS = pcs::kzg::KZG; + using PCS = KZG; using Polynomial = bb::Polynomial; using PolynomialHandle = std::span; - using CommitmentKey = pcs::CommitmentKey; - using VerifierCommitmentKey = pcs::VerifierCommitmentKey; + using CommitmentKey = bb::CommitmentKey; + using VerifierCommitmentKey = bb::VerifierCommitmentKey; static constexpr size_t NUM_WIRES = CircuitBuilder::NUM_WIRES; // The number of multivariate polynomials on which a sumcheck prover sumcheck operates (including shifts). We often @@ -380,36 +380,35 @@ class GoblinUltra { calldata_read_counts = "CALLDATA_READ_COUNTS"; lookup_inverses = "LOOKUP_INVERSES"; - // The ones beginning with "__" are only used for debugging - q_c = "__Q_C"; - q_l = "__Q_L"; - q_r = "__Q_R"; - q_o = "__Q_O"; - q_4 = "__Q_4"; - q_m = "__Q_M"; - q_arith = "__Q_ARITH"; - q_sort = "__Q_SORT"; - q_elliptic = "__Q_ELLIPTIC"; - q_aux = "__Q_AUX"; - q_lookup = "__Q_LOOKUP"; - q_busread = "__Q_BUSREAD"; - q_poseidon2_external = "__Q_POSEIDON2_EXTERNAL"; - q_poseidon2_internal = "__Q_POSEIDON2_INTERNAL"; - sigma_1 = "__SIGMA_1"; - sigma_2 = "__SIGMA_2"; - sigma_3 = "__SIGMA_3"; - sigma_4 = "__SIGMA_4"; - id_1 = "__ID_1"; - id_2 = "__ID_2"; - id_3 = "__ID_3"; - id_4 = "__ID_4"; - table_1 = "__TABLE_1"; - table_2 = "__TABLE_2"; - table_3 = "__TABLE_3"; - table_4 = "__TABLE_4"; - lagrange_first = "__LAGRANGE_FIRST"; - lagrange_last = "__LAGRANGE_LAST"; - lagrange_ecc_op = "__Q_ECC_OP_QUEUE"; + q_c = "Q_C"; + q_l = "Q_L"; + q_r = "Q_R"; + q_o = "Q_O"; + q_4 = "Q_4"; + q_m = "Q_M"; + q_arith = "Q_ARITH"; + q_sort = "Q_SORT"; + q_elliptic = "Q_ELLIPTIC"; + q_aux = "Q_AUX"; + q_lookup = "Q_LOOKUP"; + q_busread = "Q_BUSREAD"; + q_poseidon2_external = "Q_POSEIDON2_EXTERNAL"; + q_poseidon2_internal = "Q_POSEIDON2_INTERNAL"; + sigma_1 = "SIGMA_1"; + sigma_2 = "SIGMA_2"; + sigma_3 = "SIGMA_3"; + sigma_4 = "SIGMA_4"; + id_1 = "ID_1"; + id_2 = "ID_2"; + id_3 = "ID_3"; + id_4 = "ID_4"; + table_1 = "TABLE_1"; + table_2 = "TABLE_2"; + table_3 = "TABLE_3"; + table_4 = "TABLE_4"; + lagrange_first = "LAGRANGE_FIRST"; + lagrange_last = "LAGRANGE_LAST"; + lagrange_ecc_op = "Q_ECC_OP_QUEUE"; }; }; @@ -458,15 +457,16 @@ class GoblinUltra { this->w_l = commitments.w_l; this->w_r = commitments.w_r; this->w_o = commitments.w_o; - this->sorted_accum = commitments.sorted_accum; this->w_4 = commitments.w_4; + this->sorted_accum = commitments.sorted_accum; this->z_perm = commitments.z_perm; this->z_lookup = commitments.z_lookup; this->ecc_op_wire_1 = commitments.ecc_op_wire_1; this->ecc_op_wire_2 = commitments.ecc_op_wire_2; this->ecc_op_wire_3 = commitments.ecc_op_wire_3; + this->ecc_op_wire_4 = commitments.ecc_op_wire_4; this->calldata = commitments.calldata; - this->calldata = commitments.calldata_read_counts; + this->calldata_read_counts = commitments.calldata_read_counts; this->lookup_inverses = commitments.lookup_inverses; } } @@ -506,7 +506,7 @@ class GoblinUltra { Transcript_() = default; - Transcript_(const honk::proof& proof) + Transcript_(const HonkProof& proof) : BaseTranscript(proof) {} @@ -591,4 +591,4 @@ class GoblinUltra { using Transcript = Transcript_; }; -} // namespace bb::honk::flavor +} // namespace bb diff --git a/barretenberg/cpp/src/barretenberg/flavor/goblin_ultra_recursive.hpp b/barretenberg/cpp/src/barretenberg/flavor/goblin_ultra_recursive.hpp index e1146ea4b70..16cfefff849 100644 --- a/barretenberg/cpp/src/barretenberg/flavor/goblin_ultra_recursive.hpp +++ b/barretenberg/cpp/src/barretenberg/flavor/goblin_ultra_recursive.hpp @@ -22,7 +22,7 @@ #include "barretenberg/stdlib/primitives/field/field.hpp" #include "barretenberg/stdlib/recursion/honk/transcript/transcript.hpp" -namespace bb::honk::flavor { +namespace bb { /** * @brief The recursive counterpart to the "native" Goblin Ultra flavor. @@ -38,7 +38,7 @@ namespace bb::honk::flavor { * * @tparam BuilderType Determines the arithmetization of the verifier circuit defined based on this flavor. */ -template class GoblinUltraRecursive_ { +template class GoblinUltraRecursiveFlavor_ { public: using CircuitBuilder = BuilderType; // Determines arithmetization of circuit instantiated with this flavor using Curve = stdlib::bn254; @@ -46,25 +46,26 @@ template class GoblinUltraRecursive_ { using FF = typename Curve::ScalarField; using Commitment = typename Curve::Element; using CommitmentHandle = typename Curve::Element; - using NativeVerificationKey = flavor::GoblinUltra::VerificationKey; + using NativeFlavor = GoblinUltraFlavor; + using NativeVerificationKey = NativeFlavor::VerificationKey; // Note(luke): Eventually this may not be needed at all - using VerifierCommitmentKey = pcs::VerifierCommitmentKey; + using VerifierCommitmentKey = bb::VerifierCommitmentKey; - static constexpr size_t NUM_WIRES = flavor::GoblinUltra::NUM_WIRES; + static constexpr size_t NUM_WIRES = GoblinUltraFlavor::NUM_WIRES; // The number of multivariate polynomials on which a sumcheck prover sumcheck operates (including shifts). We often // need containers of this size to hold related data, so we choose a name more agnostic than `NUM_POLYNOMIALS`. // Note: this number does not include the individual sorted list polynomials. - static constexpr size_t NUM_ALL_ENTITIES = flavor::GoblinUltra::NUM_ALL_ENTITIES; + static constexpr size_t NUM_ALL_ENTITIES = GoblinUltraFlavor::NUM_ALL_ENTITIES; // The number of polynomials precomputed to describe a circuit and to aid a prover in constructing a satisfying // assignment of witnesses. We again choose a neutral name. - static constexpr size_t NUM_PRECOMPUTED_ENTITIES = flavor::GoblinUltra::NUM_PRECOMPUTED_ENTITIES; + static constexpr size_t NUM_PRECOMPUTED_ENTITIES = GoblinUltraFlavor::NUM_PRECOMPUTED_ENTITIES; // The total number of witness entities not including shifts. - static constexpr size_t NUM_WITNESS_ENTITIES = flavor::GoblinUltra::NUM_WITNESS_ENTITIES; + static constexpr size_t NUM_WITNESS_ENTITIES = GoblinUltraFlavor::NUM_WITNESS_ENTITIES; // define the tuple of Relations that comprise the Sumcheck relation // Reuse the Relations from GoblinUltra - using Relations = GoblinUltra::Relations_; + using Relations = GoblinUltraFlavor::Relations_; static constexpr size_t MAX_PARTIAL_RELATION_LENGTH = compute_max_partial_relation_length(); static constexpr size_t MAX_TOTAL_RELATION_LENGTH = compute_max_total_relation_length(); @@ -90,9 +91,9 @@ template class GoblinUltraRecursive_ { * @brief A field element for each entity of the flavor. These entities represent the prover polynomials evaluated * at one point. */ - class AllValues : public GoblinUltra::AllEntities { + class AllValues : public GoblinUltraFlavor::AllEntities { public: - using Base = GoblinUltra::AllEntities; + using Base = GoblinUltraFlavor::AllEntities; using Base::Base; }; /** @@ -104,7 +105,7 @@ template class GoblinUltraRecursive_ { * circuits. * This differs from GoblinUltra in how we construct the commitments. */ - class VerificationKey : public VerificationKey_> { + class VerificationKey : public VerificationKey_> { public: VerificationKey(const size_t circuit_size, const size_t num_public_inputs) { @@ -160,13 +161,13 @@ template class GoblinUltraRecursive_ { /** * @brief A container for the witness commitments. */ - using WitnessCommitments = GoblinUltra::WitnessEntities; + using WitnessCommitments = GoblinUltraFlavor::WitnessEntities; - using CommitmentLabels = GoblinUltra::CommitmentLabels; + using CommitmentLabels = GoblinUltraFlavor::CommitmentLabels; // Reuse the VerifierCommitments from GoblinUltra - using VerifierCommitments = GoblinUltra::VerifierCommitments_; + using VerifierCommitments = GoblinUltraFlavor::VerifierCommitments_; // Reuse the transcript from GoblinUltra using Transcript = bb::stdlib::recursion::honk::Transcript; }; -} // namespace bb::honk::flavor +} // namespace bb diff --git a/barretenberg/cpp/src/barretenberg/flavor/ultra.hpp b/barretenberg/cpp/src/barretenberg/flavor/ultra.hpp index 466cac1c869..ae2232f8685 100644 --- a/barretenberg/cpp/src/barretenberg/flavor/ultra.hpp +++ b/barretenberg/cpp/src/barretenberg/flavor/ultra.hpp @@ -16,9 +16,9 @@ #include "barretenberg/relations/ultra_arithmetic_relation.hpp" #include "barretenberg/transcript/transcript.hpp" -namespace bb::honk::flavor { +namespace bb { -class Ultra { +class UltraFlavor { public: using CircuitBuilder = UltraCircuitBuilder; using Curve = curve::BN254; @@ -26,11 +26,11 @@ class Ultra { using GroupElement = Curve::Element; using Commitment = Curve::AffineElement; using CommitmentHandle = Curve::AffineElement; - using PCS = pcs::kzg::KZG; + using PCS = KZG; using Polynomial = bb::Polynomial; using PolynomialHandle = std::span; - using CommitmentKey = pcs::CommitmentKey; - using VerifierCommitmentKey = pcs::VerifierCommitmentKey; + using CommitmentKey = bb::CommitmentKey; + using VerifierCommitmentKey = bb::VerifierCommitmentKey; static constexpr size_t NUM_WIRES = CircuitBuilder::NUM_WIRES; // The number of multivariate polynomials on which a sumcheck prover sumcheck operates (including shifts). We often @@ -575,4 +575,4 @@ class Ultra { }; }; -} // namespace bb::honk::flavor +} // namespace bb diff --git a/barretenberg/cpp/src/barretenberg/flavor/ultra_recursive.hpp b/barretenberg/cpp/src/barretenberg/flavor/ultra_recursive.hpp index 94955d72f75..0c8aede2d37 100644 --- a/barretenberg/cpp/src/barretenberg/flavor/ultra_recursive.hpp +++ b/barretenberg/cpp/src/barretenberg/flavor/ultra_recursive.hpp @@ -30,7 +30,7 @@ #include "barretenberg/stdlib/primitives/curves/bn254.hpp" #include "barretenberg/stdlib/primitives/field/field.hpp" -namespace bb::honk::flavor { +namespace bb { /** * @brief The recursive counterpart to the "native" Ultra flavor. @@ -46,7 +46,7 @@ namespace bb::honk::flavor { * * @tparam BuilderType Determines the arithmetization of the verifier circuit defined based on this flavor. */ -template class UltraRecursive_ { +template class UltraRecursiveFlavor_ { public: using CircuitBuilder = BuilderType; // Determines arithmetization of circuit instantiated with this flavor using Curve = stdlib::bn254; @@ -54,12 +54,13 @@ template class UltraRecursive_ { using Commitment = typename Curve::Element; using CommitmentHandle = typename Curve::Element; using FF = typename Curve::ScalarField; - using NativeVerificationKey = flavor::Ultra::VerificationKey; + using NativeFlavor = UltraFlavor; + using NativeVerificationKey = NativeFlavor::VerificationKey; // Note(luke): Eventually this may not be needed at all - using VerifierCommitmentKey = pcs::VerifierCommitmentKey; + using VerifierCommitmentKey = bb::VerifierCommitmentKey; - static constexpr size_t NUM_WIRES = flavor::Ultra::NUM_WIRES; + static constexpr size_t NUM_WIRES = UltraFlavor::NUM_WIRES; // The number of multivariate polynomials on which a sumcheck prover sumcheck operates (including shifts). We often // need containers of this size to hold related data, so we choose a name more agnostic than `NUM_POLYNOMIALS`. // Note: this number does not include the individual sorted list polynomials. @@ -421,4 +422,4 @@ template class UltraRecursive_ { using Transcript = bb::stdlib::recursion::honk::Transcript; }; -} // namespace bb::honk::flavor +} // namespace bb diff --git a/barretenberg/cpp/src/barretenberg/goblin/full_goblin_recursion.test.cpp b/barretenberg/cpp/src/barretenberg/goblin/full_goblin_recursion.test.cpp index 04968199532..dcc1323d781 100644 --- a/barretenberg/cpp/src/barretenberg/goblin/full_goblin_recursion.test.cpp +++ b/barretenberg/cpp/src/barretenberg/goblin/full_goblin_recursion.test.cpp @@ -10,8 +10,8 @@ #include "barretenberg/ultra_honk/ultra_composer.hpp" #include + using namespace bb; -using namespace bb::honk; class GoblinRecursionTests : public ::testing::Test { protected: diff --git a/barretenberg/cpp/src/barretenberg/goblin/goblin.hpp b/barretenberg/cpp/src/barretenberg/goblin/goblin.hpp index 4913695c918..3b028be637e 100644 --- a/barretenberg/cpp/src/barretenberg/goblin/goblin.hpp +++ b/barretenberg/cpp/src/barretenberg/goblin/goblin.hpp @@ -1,48 +1,49 @@ #pragma once #include "barretenberg/eccvm/eccvm_composer.hpp" +#include "barretenberg/flavor/goblin_ultra.hpp" #include "barretenberg/proof_system/circuit_builder/eccvm/eccvm_circuit_builder.hpp" #include "barretenberg/proof_system/circuit_builder/goblin_translator_circuit_builder.hpp" #include "barretenberg/proof_system/circuit_builder/goblin_ultra_circuit_builder.hpp" #include "barretenberg/proof_system/instance_inspector.hpp" #include "barretenberg/stdlib/recursion/honk/verifier/merge_recursive_verifier.hpp" #include "barretenberg/translator_vm/goblin_translator_composer.hpp" +#include "barretenberg/ultra_honk/merge_prover.hpp" +#include "barretenberg/ultra_honk/merge_verifier.hpp" #include "barretenberg/ultra_honk/ultra_composer.hpp" namespace bb { class Goblin { - using HonkProof = bb::honk::proof; - using GUHFlavor = bb::honk::flavor::GoblinUltra; using GoblinUltraCircuitBuilder = bb::GoblinUltraCircuitBuilder; - using GUHVerificationKey = GUHFlavor::VerificationKey; - using Commitment = GUHFlavor::Commitment; - using FF = GUHFlavor::FF; + using Commitment = GoblinUltraFlavor::Commitment; + using FF = GoblinUltraFlavor::FF; public: using Builder = GoblinUltraCircuitBuilder; using Fr = bb::fr; - using Transcript = bb::honk::BaseTranscript; + using Transcript = bb::BaseTranscript; - using GoblinUltraComposer = bb::honk::UltraComposer_; - using GoblinUltraVerifier = bb::honk::UltraVerifier_; + using GoblinUltraComposer = bb::UltraComposer_; + using GoblinUltraVerifier = bb::UltraVerifier_; using OpQueue = bb::ECCOpQueue; - using ECCVMFlavor = bb::honk::flavor::ECCVM; + using ECCVMFlavor = bb::ECCVMFlavor; using ECCVMBuilder = bb::ECCVMCircuitBuilder; - using ECCVMComposer = bb::honk::ECCVMComposer; - using ECCVMProver = bb::honk::ECCVMProver_; + using ECCVMComposer = bb::ECCVMComposer; + using ECCVMProver = bb::ECCVMProver_; using TranslatorBuilder = bb::GoblinTranslatorCircuitBuilder; - using TranslatorComposer = bb::honk::GoblinTranslatorComposer; + using TranslatorComposer = bb::GoblinTranslatorComposer; using RecursiveMergeVerifier = bb::stdlib::recursion::goblin::MergeRecursiveVerifier_; - using MergeVerifier = bb::honk::MergeVerifier_; + using MergeProver = bb::MergeProver; + using MergeVerifier = bb::MergeVerifier; /** * @brief Output of goblin::accumulate; an Ultra proof and the corresponding verification key * */ struct AccumulationOutput { HonkProof proof; - std::shared_ptr verification_key; + std::shared_ptr verification_key; }; struct Proof { @@ -109,7 +110,7 @@ class Goblin { auto ultra_proof = prover.construct_proof(); // Construct and store the merge proof to be recursively verified on the next call to accumulate - auto merge_prover = composer.create_merge_prover(op_queue); + MergeProver merge_prover{ op_queue }; merge_proof = merge_prover.construct_proof(); if (!merge_proof_exists) { @@ -213,7 +214,7 @@ class Goblin { // TODO(https://github.com/AztecProtocol/barretenberg/issues/811): no merge prover for now since we're not // mocking the first set of ecc ops // // Construct and store the merge proof to be recursively verified on the next call to accumulate - // auto merge_prover = composer.create_merge_prover(op_queue); + // MergeProver merge_prover{ op_queue }; // merge_proof = merge_prover.construct_proof(); // if (!merge_proof_exists) { diff --git a/barretenberg/cpp/src/barretenberg/goblin/mock_circuits.hpp b/barretenberg/cpp/src/barretenberg/goblin/mock_circuits.hpp index db98486ddbb..576fc798ae0 100644 --- a/barretenberg/cpp/src/barretenberg/goblin/mock_circuits.hpp +++ b/barretenberg/cpp/src/barretenberg/goblin/mock_circuits.hpp @@ -22,11 +22,11 @@ class GoblinMockCircuits { using FF = Curve::ScalarField; using Fbase = Curve::BaseField; using Point = Curve::AffineElement; - using CommitmentKey = bb::honk::pcs::CommitmentKey; + using CommitmentKey = bb::CommitmentKey; using OpQueue = bb::ECCOpQueue; using GoblinUltraBuilder = bb::GoblinUltraCircuitBuilder; - using Flavor = bb::honk::flavor::GoblinUltra; - using RecursiveFlavor = bb::honk::flavor::GoblinUltraRecursive_; + using Flavor = bb::GoblinUltraFlavor; + using RecursiveFlavor = bb::GoblinUltraRecursiveFlavor_; using RecursiveVerifier = bb::stdlib::recursion::honk::UltraRecursiveVerifier_; using KernelInput = Goblin::AccumulationOutput; static constexpr size_t NUM_OP_QUEUE_COLUMNS = Flavor::NUM_WIRES; diff --git a/barretenberg/cpp/src/barretenberg/goblin/mock_circuits_pinning.test.cpp b/barretenberg/cpp/src/barretenberg/goblin/mock_circuits_pinning.test.cpp index 1135a559b92..6d642bf5bc8 100644 --- a/barretenberg/cpp/src/barretenberg/goblin/mock_circuits_pinning.test.cpp +++ b/barretenberg/cpp/src/barretenberg/goblin/mock_circuits_pinning.test.cpp @@ -5,7 +5,6 @@ #include using namespace bb; -using namespace bb::honk; /** * @brief For benchmarking, we want to be sure that our mocking functions create circuits of a known size. We control diff --git a/barretenberg/cpp/src/barretenberg/honk/proof_system/logderivative_library.hpp b/barretenberg/cpp/src/barretenberg/honk/proof_system/logderivative_library.hpp index adf3355d618..9e124684c3e 100644 --- a/barretenberg/cpp/src/barretenberg/honk/proof_system/logderivative_library.hpp +++ b/barretenberg/cpp/src/barretenberg/honk/proof_system/logderivative_library.hpp @@ -1,7 +1,7 @@ #pragma once #include -namespace bb::honk::logderivative_library { +namespace bb { /** * @brief Compute the inverse polynomial I(X) required for logderivative lookups @@ -246,4 +246,4 @@ void accumulate_logderivative_permutation_subrelation_contributions(ContainerOve std::get<1>(accumulator) -= permutation_relation.template compute_write_term_predicate(in) * denominator_accumulator[1]; } -} // namespace bb::honk::logderivative_library \ No newline at end of file +} // namespace bb \ No newline at end of file diff --git a/barretenberg/cpp/src/barretenberg/honk/proof_system/permutation_library.hpp b/barretenberg/cpp/src/barretenberg/honk/proof_system/permutation_library.hpp index 6deaa03df7a..59744f96b20 100644 --- a/barretenberg/cpp/src/barretenberg/honk/proof_system/permutation_library.hpp +++ b/barretenberg/cpp/src/barretenberg/honk/proof_system/permutation_library.hpp @@ -3,7 +3,7 @@ #include "barretenberg/polynomials/polynomial.hpp" #include -namespace bb::honk::permutation_library { +namespace bb { /** * @brief Compute a permutation grand product polynomial Z_perm(X) @@ -221,8 +221,8 @@ template void compute_concatenated_pol * changed ∈ [0 , 2¹⁴ - 1]. To do this, we use several virtual concatenated wires, each of which represents a subset * or original wires (concatenated_range_constraints_). We also generate several new polynomials of the same length * as concatenated ones. These polynomials have values within range, but they are also constrained by the - * GoblinTranslator's GenPermSort relation, which ensures that sequential values differ by not more than 3, the last - * value is the maximum and the first value is zero (zero at the start allows us not to dance around shifts). + * GoblinTranslatorFlavor's GenPermSort relation, which ensures that sequential values differ by not more than 3, the + * last value is the maximum and the first value is zero (zero at the start allows us not to dance around shifts). * * Ideally, we could simply rearrange the values in concatenated_.._0 ,..., concatenated_.._3 and get denominator * polynomials (ordered_constraints), but we could get the worst case scenario: each value in the polynomials is @@ -435,4 +435,4 @@ inline void compute_lagrange_polynomials_for_goblin_translator(auto proving_key, proving_key->lagrange_second = lagrange_polynomial_second.share(); } -} // namespace bb::honk::permutation_library \ No newline at end of file +} // namespace bb \ No newline at end of file diff --git a/barretenberg/cpp/src/barretenberg/honk/proof_system/types/proof.hpp b/barretenberg/cpp/src/barretenberg/honk/proof_system/types/proof.hpp index 1e40a20d95d..091d310d5c2 100644 --- a/barretenberg/cpp/src/barretenberg/honk/proof_system/types/proof.hpp +++ b/barretenberg/cpp/src/barretenberg/honk/proof_system/types/proof.hpp @@ -2,8 +2,8 @@ #include "barretenberg/ecc/curves/bn254/fr.hpp" #include -namespace bb::honk { +namespace bb { -using proof = std::vector; +using HonkProof = std::vector; -} // namespace bb::honk \ No newline at end of file +} // namespace bb \ No newline at end of file diff --git a/barretenberg/cpp/src/barretenberg/honk/utils/testing.hpp b/barretenberg/cpp/src/barretenberg/honk/utils/testing.hpp index 69613d67398..b9f1fb8f4d8 100644 --- a/barretenberg/cpp/src/barretenberg/honk/utils/testing.hpp +++ b/barretenberg/cpp/src/barretenberg/honk/utils/testing.hpp @@ -2,7 +2,7 @@ #include "barretenberg/common/zip_view.hpp" #include "barretenberg/polynomials/polynomial.hpp" -namespace bb::honk { +namespace bb { /** * @brief Get a ProverPolynomials instance initialized to sequential values starting at 0. * @details Values are assigned according to the order specified in the underlying array of the flavor class. The @@ -43,4 +43,4 @@ template typename Flavor::ProverPolynomials get_zero_prover_po return prover_polynomials; } -} // namespace bb::honk \ No newline at end of file +} // namespace bb \ No newline at end of file diff --git a/barretenberg/cpp/src/barretenberg/plonk/composer/composer_lib.cpp b/barretenberg/cpp/src/barretenberg/plonk/composer/composer_lib.cpp index 21cc5dabe46..86bc6201c5d 100644 --- a/barretenberg/cpp/src/barretenberg/plonk/composer/composer_lib.cpp +++ b/barretenberg/cpp/src/barretenberg/plonk/composer/composer_lib.cpp @@ -50,7 +50,7 @@ std::shared_ptr compute_verification_key_common( auto circuit_verification_key = std::make_shared( proving_key->circuit_size, proving_key->num_public_inputs, vrs, proving_key->circuit_type); // TODO(kesha): Dirty hack for now. Need to actually make commitment-agnositc - using KZGCommitmentKey = honk::pcs::CommitmentKey; + using KZGCommitmentKey = bb::CommitmentKey; auto commitment_key = KZGCommitmentKey(proving_key->circuit_size, proving_key->reference_string); for (size_t i = 0; i < proving_key->polynomial_manifest.size(); ++i) { diff --git a/barretenberg/cpp/src/barretenberg/plonk/proof_system/types/prover_settings.hpp b/barretenberg/cpp/src/barretenberg/plonk/proof_system/types/prover_settings.hpp index eaf863a1c7b..88dd0d26e89 100644 --- a/barretenberg/cpp/src/barretenberg/plonk/proof_system/types/prover_settings.hpp +++ b/barretenberg/cpp/src/barretenberg/plonk/proof_system/types/prover_settings.hpp @@ -12,7 +12,7 @@ class settings_base { class standard_settings : public settings_base { public: - using Arithmetization = arithmetization::Standard; + using Arithmetization = StandardArith; static constexpr size_t num_challenge_bytes = 16; static constexpr transcript::HashType hash_type = transcript::HashType::PedersenBlake3s; static constexpr size_t program_width = 3; diff --git a/barretenberg/cpp/src/barretenberg/proof_system/arithmetization/arithmetization.hpp b/barretenberg/cpp/src/barretenberg/proof_system/arithmetization/arithmetization.hpp index 0a5c4ec1089..5bdf8b3faab 100644 --- a/barretenberg/cpp/src/barretenberg/proof_system/arithmetization/arithmetization.hpp +++ b/barretenberg/cpp/src/barretenberg/proof_system/arithmetization/arithmetization.hpp @@ -5,7 +5,7 @@ #include #include -namespace arithmetization { +namespace bb { /** * @brief Specify the structure of a CircuitBuilder @@ -32,7 +32,7 @@ namespace arithmetization { // These are not magic numbers and they should not be written with global constants. These parameters are not accessible // through clearly named static class members. -template class Standard { +template class StandardArith { public: static constexpr size_t NUM_WIRES = 3; static constexpr size_t NUM_SELECTORS = 5; @@ -53,7 +53,7 @@ template class Standard { const SelectorType& q_3() const { return selectors[3]; }; const SelectorType& q_c() const { return selectors[4]; }; - Standard() + StandardArith() : selectors(NUM_SELECTORS) {} @@ -70,7 +70,7 @@ template class Standard { inline static const std::vector selector_names = { "q_m", "q_1", "q_2", "q_3", "q_c" }; }; -template class Ultra { +template class UltraArith { public: static constexpr size_t NUM_WIRES = 4; static constexpr size_t NUM_SELECTORS = 11; @@ -133,7 +133,7 @@ template class Ultra { * * @tparam FF_ */ -template class UltraHonk { +template class UltraHonkArith { public: static constexpr size_t NUM_WIRES = 4; static constexpr size_t NUM_SELECTORS = 14; @@ -200,9 +200,9 @@ template class UltraHonk { inline static const std::vector selector_names = {}; }; -class GoblinTranslator { +class GoblinTranslatorArith { public: static constexpr size_t NUM_WIRES = 81; static constexpr size_t NUM_SELECTORS = 0; }; -} // namespace arithmetization \ No newline at end of file +} // namespace bb \ No newline at end of file diff --git a/barretenberg/cpp/src/barretenberg/proof_system/circuit_builder/eccvm/eccvm_circuit_builder.hpp b/barretenberg/cpp/src/barretenberg/proof_system/circuit_builder/eccvm/eccvm_circuit_builder.hpp index 7569275796e..a60c840d379 100644 --- a/barretenberg/cpp/src/barretenberg/proof_system/circuit_builder/eccvm/eccvm_circuit_builder.hpp +++ b/barretenberg/cpp/src/barretenberg/proof_system/circuit_builder/eccvm/eccvm_circuit_builder.hpp @@ -505,11 +505,8 @@ template class ECCVMCircuitBuilder { auto polynomials = compute_polynomials(); const size_t num_rows = polynomials.get_polynomial_size(); - bb::honk::logderivative_library::compute_logderivative_inverse>( - polynomials, params, num_rows); - - honk::permutation_library::compute_permutation_grand_product>( - num_rows, polynomials, params); + compute_logderivative_inverse>(polynomials, params, num_rows); + compute_permutation_grand_product>(num_rows, polynomials, params); polynomials.z_perm_shift = Polynomial(polynomials.z_perm.shifted()); @@ -538,20 +535,16 @@ template class ECCVMCircuitBuilder { }; bool result = true; - result = result && evaluate_relation.template operator()>( - "ECCVMTranscriptRelation"); - result = result && evaluate_relation.template operator()>( - "ECCVMPointTableRelation"); - result = - result && evaluate_relation.template operator()>("ECCVMWnafRelation"); result = - result && evaluate_relation.template operator()>("ECCVMMSMRelation"); + result && evaluate_relation.template operator()>("ECCVMTranscriptRelation"); result = - result && evaluate_relation.template operator()>("ECCVMSetRelation"); + result && evaluate_relation.template operator()>("ECCVMPointTableRelation"); + result = result && evaluate_relation.template operator()>("ECCVMWnafRelation"); + result = result && evaluate_relation.template operator()>("ECCVMMSMRelation"); + result = result && evaluate_relation.template operator()>("ECCVMSetRelation"); - using LookupRelation = honk::sumcheck::ECCVMLookupRelation; - typename honk::sumcheck::ECCVMLookupRelation::SumcheckArrayOfValuesOverSubrelations - lookup_result; + using LookupRelation = ECCVMLookupRelation; + typename ECCVMLookupRelation::SumcheckArrayOfValuesOverSubrelations lookup_result; for (auto& r : lookup_result) { r = 0; } diff --git a/barretenberg/cpp/src/barretenberg/proof_system/circuit_builder/eccvm/eccvm_circuit_builder.test.cpp b/barretenberg/cpp/src/barretenberg/proof_system/circuit_builder/eccvm/eccvm_circuit_builder.test.cpp index 18bacda13ef..54e0b7a8a79 100644 --- a/barretenberg/cpp/src/barretenberg/proof_system/circuit_builder/eccvm/eccvm_circuit_builder.test.cpp +++ b/barretenberg/cpp/src/barretenberg/proof_system/circuit_builder/eccvm/eccvm_circuit_builder.test.cpp @@ -7,11 +7,12 @@ using namespace bb; namespace { auto& engine = numeric::get_debug_randomness(); -} template class ECCVMCircuitBuilderTests : public ::testing::Test {}; -using FlavorTypes = ::testing::Types; +using FlavorTypes = ::testing::Types; +} // namespace + TYPED_TEST_SUITE(ECCVMCircuitBuilderTests, FlavorTypes); TYPED_TEST(ECCVMCircuitBuilderTests, BaseCase) diff --git a/barretenberg/cpp/src/barretenberg/proof_system/circuit_builder/generated/AvmMini_circuit_builder.hpp b/barretenberg/cpp/src/barretenberg/proof_system/circuit_builder/generated/AvmMini_circuit_builder.hpp index baef5adc856..5392923eb1f 100644 --- a/barretenberg/cpp/src/barretenberg/proof_system/circuit_builder/generated/AvmMini_circuit_builder.hpp +++ b/barretenberg/cpp/src/barretenberg/proof_system/circuit_builder/generated/AvmMini_circuit_builder.hpp @@ -16,8 +16,6 @@ #include "barretenberg/relations/generated/AvmMini/avm_mini.hpp" #include "barretenberg/relations/generated/AvmMini/mem_trace.hpp" -using namespace bb; - namespace bb { template struct AvmMiniFullRow { @@ -105,7 +103,7 @@ template struct AvmMiniFullRow { class AvmMiniCircuitBuilder { public: - using Flavor = bb::honk::flavor::AvmMiniFlavor; + using Flavor = bb::AvmMiniFlavor; using FF = Flavor::FF; using Row = AvmMiniFullRow; diff --git a/barretenberg/cpp/src/barretenberg/proof_system/circuit_builder/generated/Toy_circuit_builder.hpp b/barretenberg/cpp/src/barretenberg/proof_system/circuit_builder/generated/Toy_circuit_builder.hpp index 3491f983291..207b5a9e21e 100644 --- a/barretenberg/cpp/src/barretenberg/proof_system/circuit_builder/generated/Toy_circuit_builder.hpp +++ b/barretenberg/cpp/src/barretenberg/proof_system/circuit_builder/generated/Toy_circuit_builder.hpp @@ -16,8 +16,6 @@ #include "barretenberg/relations/generated/Toy/toy_avm.hpp" #include "barretenberg/relations/generated/Toy/two_column_perm.hpp" -using namespace bb; - namespace bb { template struct ToyFullRow { @@ -42,7 +40,7 @@ template struct ToyFullRow { class ToyCircuitBuilder { public: - using Flavor = bb::honk::flavor::ToyFlavor; + using Flavor = bb::ToyFlavor; using FF = Flavor::FF; using Row = ToyFullRow; @@ -137,8 +135,7 @@ class ToyCircuitBuilder { const auto evaluate_logderivative = [&](const std::string& lookup_name) { // Check the logderivative relation - bb::honk::logderivative_library::compute_logderivative_inverse( - polys, params, num_rows); + bb::compute_logderivative_inverse(polys, params, num_rows); typename LogDerivativeSettings::SumcheckArrayOfValuesOverSubrelations lookup_result; @@ -162,11 +159,10 @@ class ToyCircuitBuilder { return false; } - if (!evaluate_logderivative.template operator()>( - "two_column_perm")) { + if (!evaluate_logderivative.template operator()>("two_column_perm")) { return false; } - if (!evaluate_logderivative.template operator()>("lookup_xor")) { + if (!evaluate_logderivative.template operator()>("lookup_xor")) { return false; } diff --git a/barretenberg/cpp/src/barretenberg/proof_system/circuit_builder/goblin_translator_circuit_builder.hpp b/barretenberg/cpp/src/barretenberg/proof_system/circuit_builder/goblin_translator_circuit_builder.hpp index 41865d083a1..14c2c368f23 100644 --- a/barretenberg/cpp/src/barretenberg/proof_system/circuit_builder/goblin_translator_circuit_builder.hpp +++ b/barretenberg/cpp/src/barretenberg/proof_system/circuit_builder/goblin_translator_circuit_builder.hpp @@ -77,7 +77,7 @@ class GoblinTranslatorCircuitBuilder : public CircuitBuilderBase { // We don't need templating for Goblin using Fr = bb::fr; using Fq = bb::fq; - using Arithmetization = arithmetization::GoblinTranslator; + using Arithmetization = GoblinTranslatorArith; public: static constexpr size_t NUM_WIRES = Arithmetization::NUM_WIRES; diff --git a/barretenberg/cpp/src/barretenberg/proof_system/circuit_builder/goblin_ultra_circuit_builder.cpp b/barretenberg/cpp/src/barretenberg/proof_system/circuit_builder/goblin_ultra_circuit_builder.cpp index 428409bf73f..c2630db7b7b 100644 --- a/barretenberg/cpp/src/barretenberg/proof_system/circuit_builder/goblin_ultra_circuit_builder.cpp +++ b/barretenberg/cpp/src/barretenberg/proof_system/circuit_builder/goblin_ultra_circuit_builder.cpp @@ -12,7 +12,7 @@ namespace bb { template void GoblinUltraCircuitBuilder_::finalize_circuit() { - UltraCircuitBuilder_>::finalize_circuit(); + UltraCircuitBuilder_>::finalize_circuit(); } /** @@ -26,7 +26,7 @@ template void GoblinUltraCircuitBuilder_::finalize_circuit() template void GoblinUltraCircuitBuilder_::add_gates_to_ensure_all_polys_are_non_zero() { // Most polynomials are handled via the conventional Ultra method - UltraCircuitBuilder_>::add_gates_to_ensure_all_polys_are_non_zero(); + UltraCircuitBuilder_>::add_gates_to_ensure_all_polys_are_non_zero(); // All that remains is to handle databus related and poseidon2 related polynomials. In what follows we populate the // calldata with some mock data then constuct a single calldata read gate @@ -448,7 +448,7 @@ inline FF GoblinUltraCircuitBuilder_::compute_poseidon2_internal_identity(FF template bool GoblinUltraCircuitBuilder_::check_circuit() { bool result = true; - if (!UltraCircuitBuilder_>::check_circuit()) { + if (!UltraCircuitBuilder_>::check_circuit()) { return false; } diff --git a/barretenberg/cpp/src/barretenberg/proof_system/circuit_builder/goblin_ultra_circuit_builder.hpp b/barretenberg/cpp/src/barretenberg/proof_system/circuit_builder/goblin_ultra_circuit_builder.hpp index 072a7d10357..a338b88549e 100644 --- a/barretenberg/cpp/src/barretenberg/proof_system/circuit_builder/goblin_ultra_circuit_builder.hpp +++ b/barretenberg/cpp/src/barretenberg/proof_system/circuit_builder/goblin_ultra_circuit_builder.hpp @@ -7,12 +7,12 @@ namespace bb { using namespace bb; -template class GoblinUltraCircuitBuilder_ : public UltraCircuitBuilder_> { +template class GoblinUltraCircuitBuilder_ : public UltraCircuitBuilder_> { public: static constexpr std::string_view NAME_STRING = "GoblinUltraArithmetization"; static constexpr CircuitType CIRCUIT_TYPE = CircuitType::ULTRA; static constexpr size_t DEFAULT_NON_NATIVE_FIELD_LIMB_BITS = - UltraCircuitBuilder_>::DEFAULT_NON_NATIVE_FIELD_LIMB_BITS; + UltraCircuitBuilder_>::DEFAULT_NON_NATIVE_FIELD_LIMB_BITS; size_t num_ecc_op_gates = 0; // number of ecc op "gates" (rows); these are placed at the start of the circuit @@ -29,7 +29,7 @@ template class GoblinUltraCircuitBuilder_ : public UltraCircuitBui using SelectorVector = std::vector>; // Wires storing ecc op queue data; values are indices into the variables array - std::array::NUM_WIRES> ecc_op_wires; + std::array::NUM_WIRES> ecc_op_wires; WireVector& ecc_op_wire_1() { return std::get<0>(ecc_op_wires); }; WireVector& ecc_op_wire_2() { return std::get<1>(ecc_op_wires); }; @@ -67,7 +67,7 @@ template class GoblinUltraCircuitBuilder_ : public UltraCircuitBui public: GoblinUltraCircuitBuilder_(const size_t size_hint = 0, std::shared_ptr op_queue_in = std::make_shared()) - : UltraCircuitBuilder_>(size_hint) + : UltraCircuitBuilder_>(size_hint) , op_queue(op_queue_in) { // Set indices to constants corresponding to Goblin ECC op codes @@ -95,7 +95,7 @@ template class GoblinUltraCircuitBuilder_ : public UltraCircuitBui auto& witness_values, std::vector& public_inputs, size_t varnum) - : UltraCircuitBuilder_>(/*size_hint=*/0, witness_values, public_inputs, varnum) + : UltraCircuitBuilder_>(/*size_hint=*/0, witness_values, public_inputs, varnum) , op_queue(op_queue_in) { // Set indices to constants corresponding to Goblin ECC op codes @@ -119,7 +119,7 @@ template class GoblinUltraCircuitBuilder_ : public UltraCircuitBui */ size_t get_num_gates() const override { - auto num_ultra_gates = UltraCircuitBuilder_>::get_num_gates(); + auto num_ultra_gates = UltraCircuitBuilder_>::get_num_gates(); return num_ultra_gates + num_ecc_op_gates; } @@ -134,7 +134,7 @@ template class GoblinUltraCircuitBuilder_ : public UltraCircuitBui size_t romcount = 0; size_t ramcount = 0; size_t nnfcount = 0; - UltraCircuitBuilder_>::get_num_gates_split_into_components( + UltraCircuitBuilder_>::get_num_gates_split_into_components( count, rangecount, romcount, ramcount, nnfcount); size_t total = count + romcount + ramcount + rangecount + num_ecc_op_gates; diff --git a/barretenberg/cpp/src/barretenberg/proof_system/circuit_builder/standard_circuit_builder.cpp b/barretenberg/cpp/src/barretenberg/proof_system/circuit_builder/standard_circuit_builder.cpp index fd8500a0a71..ca7167c2e16 100644 --- a/barretenberg/cpp/src/barretenberg/proof_system/circuit_builder/standard_circuit_builder.cpp +++ b/barretenberg/cpp/src/barretenberg/proof_system/circuit_builder/standard_circuit_builder.cpp @@ -7,8 +7,6 @@ #include "barretenberg/serialize/cbind.hpp" #include "barretenberg/serialize/msgpack.hpp" -using namespace bb; - namespace bb { /** diff --git a/barretenberg/cpp/src/barretenberg/proof_system/circuit_builder/standard_circuit_builder.hpp b/barretenberg/cpp/src/barretenberg/proof_system/circuit_builder/standard_circuit_builder.hpp index 9f0bdc141de..a8c1fa20436 100644 --- a/barretenberg/cpp/src/barretenberg/proof_system/circuit_builder/standard_circuit_builder.hpp +++ b/barretenberg/cpp/src/barretenberg/proof_system/circuit_builder/standard_circuit_builder.hpp @@ -11,7 +11,7 @@ namespace bb { template class StandardCircuitBuilder_ : public CircuitBuilderBase { public: - using Arithmetization = arithmetization::Standard; + using Arithmetization = StandardArith; static constexpr size_t NUM_WIRES = Arithmetization::NUM_WIRES; // Keeping NUM_WIRES, at least temporarily, for backward compatibility static constexpr size_t program_width = Arithmetization::NUM_WIRES; diff --git a/barretenberg/cpp/src/barretenberg/proof_system/circuit_builder/toy_avm/toy_avm_circuit_builder.test.cpp b/barretenberg/cpp/src/barretenberg/proof_system/circuit_builder/toy_avm/toy_avm_circuit_builder.test.cpp index 25e182c0a46..7c395269104 100644 --- a/barretenberg/cpp/src/barretenberg/proof_system/circuit_builder/toy_avm/toy_avm_circuit_builder.test.cpp +++ b/barretenberg/cpp/src/barretenberg/proof_system/circuit_builder/toy_avm/toy_avm_circuit_builder.test.cpp @@ -17,8 +17,7 @@ auto& engine = numeric::get_debug_randomness(); */ TEST(ToyAVMCircuitBuilder, BaseCase) { - - using FF = honk::flavor::ToyFlavor::FF; + using FF = ToyFlavor::FF; using Builder = ToyCircuitBuilder; using Row = Builder::Row; Builder circuit_builder; diff --git a/barretenberg/cpp/src/barretenberg/proof_system/circuit_builder/ultra_circuit_builder.cpp b/barretenberg/cpp/src/barretenberg/proof_system/circuit_builder/ultra_circuit_builder.cpp index 9845b2ab06e..28a6959b830 100644 --- a/barretenberg/cpp/src/barretenberg/proof_system/circuit_builder/ultra_circuit_builder.cpp +++ b/barretenberg/cpp/src/barretenberg/proof_system/circuit_builder/ultra_circuit_builder.cpp @@ -10,8 +10,6 @@ #include #include -using namespace bb; - namespace bb { template void UltraCircuitBuilder_::finalize_circuit() @@ -2887,8 +2885,8 @@ inline typename Arithmetization::FF UltraCircuitBuilder_::compu const FF y_3 = w_3_shifted_value; const FF q_sign = q_1_value; const FF q_is_double = q_m_value; - constexpr FF curve_b = CircuitBuilderBase>::EmbeddedCurve::Group::curve_b; - static_assert(CircuitBuilderBase>::EmbeddedCurve::Group::curve_a == 0); + constexpr FF curve_b = CircuitBuilderBase>::EmbeddedCurve::Group::curve_b; + static_assert(CircuitBuilderBase>::EmbeddedCurve::Group::curve_a == 0); FF x_diff = x_2 - x_1; FF y1_sqr = y_1.sqr(); @@ -3484,8 +3482,8 @@ template bool UltraCircuitBuilder_:: circuit_backup.restore_prefinilized_state(this); return result; } -template class UltraCircuitBuilder_>; -template class UltraCircuitBuilder_>; +template class UltraCircuitBuilder_>; +template class UltraCircuitBuilder_>; // To enable this we need to template plookup // template class UltraCircuitBuilder_; diff --git a/barretenberg/cpp/src/barretenberg/proof_system/circuit_builder/ultra_circuit_builder.hpp b/barretenberg/cpp/src/barretenberg/proof_system/circuit_builder/ultra_circuit_builder.hpp index 4ee4751b403..055db48379d 100644 --- a/barretenberg/cpp/src/barretenberg/proof_system/circuit_builder/ultra_circuit_builder.hpp +++ b/barretenberg/cpp/src/barretenberg/proof_system/circuit_builder/ultra_circuit_builder.hpp @@ -1171,5 +1171,5 @@ class UltraCircuitBuilder_ : public CircuitBuilderBase>; +using UltraCircuitBuilder = UltraCircuitBuilder_>; } // namespace bb diff --git a/barretenberg/cpp/src/barretenberg/proof_system/composer/composer_lib.test.cpp b/barretenberg/cpp/src/barretenberg/proof_system/composer/composer_lib.test.cpp index aad30452664..9e45324e0d3 100644 --- a/barretenberg/cpp/src/barretenberg/proof_system/composer/composer_lib.test.cpp +++ b/barretenberg/cpp/src/barretenberg/proof_system/composer/composer_lib.test.cpp @@ -10,7 +10,7 @@ using namespace bb; class ComposerLibTests : public ::testing::Test { protected: - using Flavor = honk::flavor::Ultra; + using Flavor = UltraFlavor; using FF = typename Flavor::FF; Flavor::CircuitBuilder circuit_constructor; Flavor::ProvingKey proving_key = []() { diff --git a/barretenberg/cpp/src/barretenberg/proof_system/composer/permutation_lib.test.cpp b/barretenberg/cpp/src/barretenberg/proof_system/composer/permutation_lib.test.cpp index 3fc4d2bcb3c..bde1e500a41 100644 --- a/barretenberg/cpp/src/barretenberg/proof_system/composer/permutation_lib.test.cpp +++ b/barretenberg/cpp/src/barretenberg/proof_system/composer/permutation_lib.test.cpp @@ -10,7 +10,7 @@ using namespace bb; class PermutationHelperTests : public ::testing::Test { protected: - using Flavor = honk::flavor::Ultra; + using Flavor = UltraFlavor; using FF = typename Flavor::FF; using ProvingKey = Flavor::ProvingKey; Flavor::CircuitBuilder circuit_constructor; diff --git a/barretenberg/cpp/src/barretenberg/proof_system/library/grand_product_delta.hpp b/barretenberg/cpp/src/barretenberg/proof_system/library/grand_product_delta.hpp index c49d5e278d3..a68b398b118 100644 --- a/barretenberg/cpp/src/barretenberg/proof_system/library/grand_product_delta.hpp +++ b/barretenberg/cpp/src/barretenberg/proof_system/library/grand_product_delta.hpp @@ -1,7 +1,7 @@ #pragma once #include -namespace bb::honk { +namespace bb { /** * @brief Compute the correction term for the permutation argument. @@ -83,4 +83,4 @@ Field compute_lookup_grand_product_delta(const Field& beta, const Field& gamma, return gamma_by_one_plus_beta.pow(domain_size); // (γ(1 + β))^n } -} // namespace bb::honk \ No newline at end of file +} // namespace bb \ No newline at end of file diff --git a/barretenberg/cpp/src/barretenberg/proof_system/library/grand_product_library.hpp b/barretenberg/cpp/src/barretenberg/proof_system/library/grand_product_library.hpp index b131c0c2e7b..897d5a63642 100644 --- a/barretenberg/cpp/src/barretenberg/proof_system/library/grand_product_library.hpp +++ b/barretenberg/cpp/src/barretenberg/proof_system/library/grand_product_library.hpp @@ -7,7 +7,7 @@ #include "barretenberg/relations/relation_parameters.hpp" #include -namespace bb::honk::grand_product_library { +namespace bb { // TODO(luke): This contains utilities for grand product computation and is not specific to the permutation grand // product. Update comments accordingly. @@ -167,4 +167,4 @@ void compute_grand_products(std::shared_ptr& key, }); } -} // namespace bb::honk::grand_product_library \ No newline at end of file +} // namespace bb \ No newline at end of file diff --git a/barretenberg/cpp/src/barretenberg/proof_system/library/grand_product_library.test.cpp b/barretenberg/cpp/src/barretenberg/proof_system/library/grand_product_library.test.cpp index 7e78b77e3cd..502b9ca7cb4 100644 --- a/barretenberg/cpp/src/barretenberg/proof_system/library/grand_product_library.test.cpp +++ b/barretenberg/cpp/src/barretenberg/proof_system/library/grand_product_library.test.cpp @@ -7,7 +7,6 @@ #include "barretenberg/srs/factories/file_crs_factory.hpp" #include using namespace bb; -using namespace bb::honk; template class GrandProductTests : public testing::Test { @@ -101,8 +100,7 @@ template class GrandProductTests : public testing::Test { ASSERT(Flavor::NUM_WIRES == 4); using RHS = typename bb::UltraPermutationRelation; static_assert(std::same_as); - grand_product_library::compute_grand_product( - proving_key->circuit_size, prover_polynomials, params); + compute_grand_product(proving_key->circuit_size, prover_polynomials, params); // Method 2: Compute z_perm locally using the simplest non-optimized syntax possible. The comment below, // which describes the computation in 4 steps, is adapted from a similar comment in @@ -184,7 +182,7 @@ template class GrandProductTests : public testing::Test { static const size_t num_public_inputs = 0; // Instatiate a proving_key and make a pointer to it. This will be used to instantiate a Prover. - using Flavor = flavor::Ultra; + using Flavor = UltraFlavor; auto proving_key = std::make_shared(circuit_size, num_public_inputs); // Construct mock wire and permutation polynomials. @@ -259,8 +257,7 @@ template class GrandProductTests : public testing::Test { using LHS = typename std::tuple_element::type; using RHS = LookupRelation; static_assert(std::same_as); - grand_product_library::compute_grand_product( - proving_key->circuit_size, prover_polynomials, params); + compute_grand_product(proving_key->circuit_size, prover_polynomials, params); // Method 2: Compute the lookup grand product polynomial Z_lookup: // @@ -341,7 +338,7 @@ TYPED_TEST_SUITE(GrandProductTests, FieldTypes); TYPED_TEST(GrandProductTests, GrandProductPermutation) { - TestFixture::template test_permutation_grand_product_construction(); + TestFixture::template test_permutation_grand_product_construction(); } TYPED_TEST(GrandProductTests, GrandProductLookup) diff --git a/barretenberg/cpp/src/barretenberg/protogalaxy/combiner.test.cpp b/barretenberg/cpp/src/barretenberg/protogalaxy/combiner.test.cpp index 132ba614498..d78b066a94a 100644 --- a/barretenberg/cpp/src/barretenberg/protogalaxy/combiner.test.cpp +++ b/barretenberg/cpp/src/barretenberg/protogalaxy/combiner.test.cpp @@ -7,9 +7,8 @@ #include using namespace bb; -using namespace bb::honk; -using Flavor = honk::flavor::Ultra; +using Flavor = UltraFlavor; using Polynomial = typename Flavor::Polynomial; using FF = typename Flavor::FF; @@ -42,7 +41,7 @@ TEST(Protogalaxy, CombinerOn2Instances) for (size_t idx = 0; idx < NUM_INSTANCES; idx++) { auto instance = std::make_shared(); - auto prover_polynomials = honk::get_sequential_prover_polynomials( + auto prover_polynomials = get_sequential_prover_polynomials( /*log_circuit_size=*/1, idx * 128); restrict_to_standard_arithmetic_relation(prover_polynomials); instance->prover_polynomials = std::move(prover_polynomials); @@ -74,7 +73,7 @@ TEST(Protogalaxy, CombinerOn2Instances) for (size_t idx = 0; idx < NUM_INSTANCES; idx++) { auto instance = std::make_shared(); - auto prover_polynomials = honk::get_zero_prover_polynomials( + auto prover_polynomials = get_zero_prover_polynomials( /*log_circuit_size=*/1); restrict_to_standard_arithmetic_relation(prover_polynomials); instance->prover_polynomials = std::move(prover_polynomials); @@ -165,7 +164,7 @@ TEST(Protogalaxy, CombinerOn4Instances) for (size_t idx = 0; idx < NUM_INSTANCES; idx++) { auto instance = std::make_shared(); - auto prover_polynomials = honk::get_zero_prover_polynomials( + auto prover_polynomials = get_zero_prover_polynomials( /*log_circuit_size=*/1); instance->prover_polynomials = std::move(prover_polynomials); instance->instance_size = 2; diff --git a/barretenberg/cpp/src/barretenberg/protogalaxy/decider_prover.cpp b/barretenberg/cpp/src/barretenberg/protogalaxy/decider_prover.cpp index f8f5e651e37..51d55e9766a 100644 --- a/barretenberg/cpp/src/barretenberg/protogalaxy/decider_prover.cpp +++ b/barretenberg/cpp/src/barretenberg/protogalaxy/decider_prover.cpp @@ -1,7 +1,7 @@ #include "decider_prover.hpp" #include "barretenberg/sumcheck/sumcheck.hpp" -namespace bb::honk { +namespace bb { /** * Create DeciderProver_ from an accumulator. @@ -11,7 +11,7 @@ namespace bb::honk { * * @tparam a type of UltraFlavor * */ -template +template DeciderProver_::DeciderProver_(const std::shared_ptr& inst, const std::shared_ptr& commitment_key, const std::shared_ptr& transcript) @@ -24,7 +24,7 @@ DeciderProver_::DeciderProver_(const std::shared_ptr& inst, * @brief Add ϕ, \vec{β}, e to the transcript. These are produced in the last round of folding that was carried out * before deciding. */ -template void DeciderProver_::execute_preamble_round() +template void DeciderProver_::execute_preamble_round() { const auto accumulator_size = static_cast(accumulator->instance_size); const auto num_public_inputs = static_cast(accumulator->public_inputs.size()); @@ -70,9 +70,9 @@ template void DeciderProver_::execute_preamble_roun * challenges and all evaluations at u being calculated. * */ -template void DeciderProver_::execute_relation_check_rounds() +template void DeciderProver_::execute_relation_check_rounds() { - using Sumcheck = sumcheck::SumcheckProver; + using Sumcheck = SumcheckProver; auto instance_size = accumulator->instance_size; auto sumcheck = Sumcheck(instance_size, transcript); sumcheck_output = sumcheck.prove(accumulator); @@ -83,7 +83,7 @@ template void DeciderProver_::execute_relation_chec * @details See https://hackmd.io/dlf9xEwhTQyE3hiGbq4FsA?view for a complete description of the unrolled protocol. * * */ -template void DeciderProver_::execute_zeromorph_rounds() +template void DeciderProver_::execute_zeromorph_rounds() { ZeroMorph::prove(accumulator->prover_polynomials.get_unshifted(), accumulator->prover_polynomials.get_to_be_shifted(), @@ -94,13 +94,13 @@ template void DeciderProver_::execute_zeromorph_rou transcript); } -template honk::proof& DeciderProver_::export_proof() +template HonkProof& DeciderProver_::export_proof() { proof = transcript->proof_data; return proof; } -template honk::proof& DeciderProver_::construct_proof() +template HonkProof& DeciderProver_::construct_proof() { // Add ϕ, \vec{β*}, e* to transcript execute_preamble_round(); @@ -115,7 +115,7 @@ template honk::proof& DeciderProver_::construct_pro return export_proof(); } -template class DeciderProver_; -template class DeciderProver_; +template class DeciderProver_; +template class DeciderProver_; -} // namespace bb::honk +} // namespace bb diff --git a/barretenberg/cpp/src/barretenberg/protogalaxy/decider_prover.hpp b/barretenberg/cpp/src/barretenberg/protogalaxy/decider_prover.hpp index 3114446b9c6..68440d5129b 100644 --- a/barretenberg/cpp/src/barretenberg/protogalaxy/decider_prover.hpp +++ b/barretenberg/cpp/src/barretenberg/protogalaxy/decider_prover.hpp @@ -8,9 +8,9 @@ #include "barretenberg/sumcheck/sumcheck_output.hpp" #include "barretenberg/transcript/transcript.hpp" -namespace bb::honk { +namespace bb { -template class DeciderProver_ { +template class DeciderProver_ { using FF = typename Flavor::FF; using Commitment = typename Flavor::Commitment; using CommitmentKey = typename Flavor::CommitmentKey; @@ -32,8 +32,8 @@ template class DeciderProver_ { BBERG_PROFILE void execute_relation_check_rounds(); BBERG_PROFILE void execute_zeromorph_rounds(); - honk::proof& export_proof(); - honk::proof& construct_proof(); + HonkProof& export_proof(); + HonkProof& construct_proof(); std::shared_ptr accumulator; @@ -45,16 +45,16 @@ template class DeciderProver_ { Polynomial quotient_W; - sumcheck::SumcheckOutput sumcheck_output; + SumcheckOutput sumcheck_output; std::shared_ptr commitment_key; - using ZeroMorph = pcs::zeromorph::ZeroMorphProver_; + using ZeroMorph = ZeroMorphProver_; private: - honk::proof proof; + HonkProof proof; }; -using DeciderProver = DeciderProver_; +using DeciderProver = DeciderProver_; -} // namespace bb::honk +} // namespace bb diff --git a/barretenberg/cpp/src/barretenberg/protogalaxy/decider_verifier.cpp b/barretenberg/cpp/src/barretenberg/protogalaxy/decider_verifier.cpp index ef86acfcb2e..1c6601613fb 100644 --- a/barretenberg/cpp/src/barretenberg/protogalaxy/decider_verifier.cpp +++ b/barretenberg/cpp/src/barretenberg/protogalaxy/decider_verifier.cpp @@ -4,10 +4,7 @@ #include "barretenberg/sumcheck/instance/verifier_instance.hpp" #include "barretenberg/transcript/transcript.hpp" -using namespace bb; -using namespace bb::honk::sumcheck; - -namespace bb::honk { +namespace bb { template DeciderVerifier_::DeciderVerifier_(const std::shared_ptr& transcript, @@ -26,12 +23,12 @@ DeciderVerifier_::DeciderVerifier_() * e*). * */ -template bool DeciderVerifier_::verify_proof(const honk::proof& proof) +template bool DeciderVerifier_::verify_proof(const HonkProof& proof) { using FF = typename Flavor::FF; using Commitment = typename Flavor::Commitment; using Curve = typename Flavor::Curve; - using ZeroMorph = pcs::zeromorph::ZeroMorphVerifier_; + using ZeroMorph = ZeroMorphVerifier_; using Instance = VerifierInstance_; using VerifierCommitments = typename Flavor::VerifierCommitments; @@ -107,7 +104,7 @@ template bool DeciderVerifier_::verify_proof(const hon return sumcheck_verified.value() && verified; } -template class DeciderVerifier_; -template class DeciderVerifier_; +template class DeciderVerifier_; +template class DeciderVerifier_; -} // namespace bb::honk +} // namespace bb diff --git a/barretenberg/cpp/src/barretenberg/protogalaxy/decider_verifier.hpp b/barretenberg/cpp/src/barretenberg/protogalaxy/decider_verifier.hpp index 3e9b5607673..70ca2033617 100644 --- a/barretenberg/cpp/src/barretenberg/protogalaxy/decider_verifier.hpp +++ b/barretenberg/cpp/src/barretenberg/protogalaxy/decider_verifier.hpp @@ -5,7 +5,7 @@ #include "barretenberg/srs/global_crs.hpp" #include "barretenberg/sumcheck/sumcheck.hpp" -namespace bb::honk { +namespace bb { template class DeciderVerifier_ { using FF = typename Flavor::FF; using Commitment = typename Flavor::Commitment; @@ -18,7 +18,7 @@ template class DeciderVerifier_ { explicit DeciderVerifier_(const std::shared_ptr& transcript, const std::shared_ptr& verifier_key = nullptr); - bool verify_proof(const honk::proof& proof); + bool verify_proof(const HonkProof& proof); std::shared_ptr key; std::map commitments; @@ -26,6 +26,6 @@ template class DeciderVerifier_ { std::shared_ptr transcript; }; -using DeciderVerifier = DeciderVerifier_; +using DeciderVerifier = DeciderVerifier_; -} // namespace bb::honk +} // namespace bb diff --git a/barretenberg/cpp/src/barretenberg/protogalaxy/folding_result.hpp b/barretenberg/cpp/src/barretenberg/protogalaxy/folding_result.hpp index 55bbbd826ac..4bf3eb88fff 100644 --- a/barretenberg/cpp/src/barretenberg/protogalaxy/folding_result.hpp +++ b/barretenberg/cpp/src/barretenberg/protogalaxy/folding_result.hpp @@ -2,7 +2,7 @@ #include "barretenberg/flavor/flavor.hpp" #include "barretenberg/relations/relation_parameters.hpp" #include "barretenberg/sumcheck/instance/prover_instance.hpp" -namespace bb::honk { +namespace bb { /** * @brief The result of running the Protogalaxy prover containing a new accumulator (relaxed instance) as well as the * proof data to instantiate the verifier transcript. @@ -15,4 +15,4 @@ template struct FoldingResult { // TODO(https://github.com/AztecProtocol/barretenberg/issues/656): turn folding data into a struct std::vector folding_data; }; -} // namespace bb::honk \ No newline at end of file +} // namespace bb \ No newline at end of file diff --git a/barretenberg/cpp/src/barretenberg/protogalaxy/protogalaxy_prover.cpp b/barretenberg/cpp/src/barretenberg/protogalaxy/protogalaxy_prover.cpp index 6a138c51a51..c0efde0a3d8 100644 --- a/barretenberg/cpp/src/barretenberg/protogalaxy/protogalaxy_prover.cpp +++ b/barretenberg/cpp/src/barretenberg/protogalaxy/protogalaxy_prover.cpp @@ -1,6 +1,6 @@ #include "protogalaxy_prover.hpp" #include "barretenberg/flavor/flavor.hpp" -namespace bb::honk { +namespace bb { template void ProtoGalaxyProver_::finalise_and_send_instance(std::shared_ptr instance, const std::string& domain_separator) @@ -34,6 +34,27 @@ void ProtoGalaxyProver_::finalise_and_send_instance(std::shared transcript->send_to_verifier(domain_separator + "_" + wire_labels[idx], wire_comms[idx]); } + if constexpr (IsGoblinFlavor) { + // Commit to Goblin ECC op wires + witness_commitments.ecc_op_wire_1 = commitment_key->commit(instance->proving_key->ecc_op_wire_1); + witness_commitments.ecc_op_wire_2 = commitment_key->commit(instance->proving_key->ecc_op_wire_2); + witness_commitments.ecc_op_wire_3 = commitment_key->commit(instance->proving_key->ecc_op_wire_3); + witness_commitments.ecc_op_wire_4 = commitment_key->commit(instance->proving_key->ecc_op_wire_4); + + auto op_wire_comms = instance->witness_commitments.get_ecc_op_wires(); + auto labels = commitment_labels.get_ecc_op_wires(); + for (size_t idx = 0; idx < Flavor::NUM_WIRES; ++idx) { + transcript->send_to_verifier(domain_separator + "_" + labels[idx], op_wire_comms[idx]); + } + // Commit to DataBus columns + witness_commitments.calldata = commitment_key->commit(instance->proving_key->calldata); + witness_commitments.calldata_read_counts = commitment_key->commit(instance->proving_key->calldata_read_counts); + transcript->send_to_verifier(domain_separator + "_" + commitment_labels.calldata, + instance->witness_commitments.calldata); + transcript->send_to_verifier(domain_separator + "_" + commitment_labels.calldata_read_counts, + instance->witness_commitments.calldata_read_counts); + } + auto eta = transcript->get_challenge(domain_separator + "_eta"); instance->compute_sorted_accumulator_polynomials(eta); @@ -47,6 +68,16 @@ void ProtoGalaxyProver_::finalise_and_send_instance(std::shared transcript->send_to_verifier(domain_separator + "_" + commitment_labels.w_4, witness_commitments.w_4); auto [beta, gamma] = transcript->get_challenges(domain_separator + "_beta", domain_separator + "_gamma"); + + if constexpr (IsGoblinFlavor) { + // Compute and commit to the logderivative inverse used in DataBus + instance->compute_logderivative_inverse(beta, gamma); + instance->witness_commitments.lookup_inverses = + commitment_key->commit(instance->prover_polynomials.lookup_inverses); + transcript->send_to_verifier(domain_separator + "_" + commitment_labels.lookup_inverses, + instance->witness_commitments.lookup_inverses); + } + instance->compute_grand_product_polynomials(beta, gamma); witness_commitments.z_perm = commitment_key->commit(instance->prover_polynomials.z_perm); @@ -303,10 +334,9 @@ FoldingResult ProtoGalaxyProver_proof_data; res.accumulator = next_accumulator; - return res; } -template class ProtoGalaxyProver_>; -template class ProtoGalaxyProver_>; -} // namespace bb::honk \ No newline at end of file +template class ProtoGalaxyProver_>; +template class ProtoGalaxyProver_>; +} // namespace bb \ No newline at end of file diff --git a/barretenberg/cpp/src/barretenberg/protogalaxy/protogalaxy_prover.hpp b/barretenberg/cpp/src/barretenberg/protogalaxy/protogalaxy_prover.hpp index 5a0794c3dd7..026c83a618c 100644 --- a/barretenberg/cpp/src/barretenberg/protogalaxy/protogalaxy_prover.hpp +++ b/barretenberg/cpp/src/barretenberg/protogalaxy/protogalaxy_prover.hpp @@ -11,7 +11,7 @@ #include "barretenberg/relations/utils.hpp" #include "barretenberg/sumcheck/instance/instances.hpp" -namespace bb::honk { +namespace bb { template class ProtoGalaxyProver_ { public: using ProverInstances = ProverInstances_; @@ -127,16 +127,23 @@ template class ProtoGalaxyProver_ { std::shared_ptr get_accumulator() { return instances[0]; } /** - * @brief Compute the values of the full Honk relation at each row in the execution trace, f_i(ω) in the - * ProtoGalaxy paper, given the evaluations of all the prover polynomials and α (the parameter that helps establish - * each subrelation is independently valid in Honk - from the Plonk paper, DO NOT confuse with α in ProtoGalaxy), + * @brief Compute the values of the full Honk relation at each row in the execution trace, representing f_i(ω) in + * the ProtoGalaxy paper, given the evaluations of all the prover polynomials and \vec{α} (the batching challenges + * that help establishing each subrelation is independently valid in Honk - from the Plonk paper, DO NOT confuse + * with α in ProtoGalaxy). + * + * @details When folding GoblinUltra instances, one of the relations is linearly dependent. We define such relations + * as acting on the entire execution trace and hence requiring to be accumulated separately as we iterate over each + * row. At the end of the function, the linearly dependent contribution is accumulated at index 0 representing the + * sum f_0(ω) + α_j*g(ω) where f_0 represents the full honk evaluation at row 0, g(ω) is the linearly dependent + * subrelation and α_j is its corresponding batching challenge. */ static std::vector compute_full_honk_evaluations(const ProverPolynomials& instance_polynomials, const RelationSeparator& alpha, const RelationParameters& relation_parameters) { auto instance_size = instance_polynomials.get_polynomial_size(); - + FF linearly_dependent_contribution = FF(0); std::vector full_honk_evaluations(instance_size); for (size_t row = 0; row < instance_size; row++) { auto row_evaluations = instance_polynomials.get_row(row); @@ -150,17 +157,22 @@ template class ProtoGalaxyProver_ { auto output = FF(0); auto running_challenge = FF(1); - Utils::scale_and_batch_elements(relation_evaluations, alpha, running_challenge, output); + + // Sum relation evaluations, batched by their corresponding relation separator challenge, to get the value + // of the full honk relation at a specific row + Utils::scale_and_batch_elements( + relation_evaluations, alpha, running_challenge, output, linearly_dependent_contribution); full_honk_evaluations[row] = output; } + full_honk_evaluations[0] += linearly_dependent_contribution; return full_honk_evaluations; } /** - * @brief Recursively compute the parent nodes of each level in there, starting from the leaves. Note that at each - * level, the resulting parent nodes will be polynomials of degree (level + 1) because we multiply by an additional - * factor of X. + * @brief Recursively compute the parent nodes of each level in the tree, starting from the leaves. Note that at + * each level, the resulting parent nodes will be polynomials of degree (level+1) because we multiply by an + * additional factor of X. */ static std::vector construct_coefficients_tree(const std::vector& betas, const std::vector& deltas, @@ -307,7 +319,8 @@ template class ProtoGalaxyProver_ { FF pow_challenge = pow_betas[idx]; // Accumulate the i-th row's univariate contribution. Note that the relation parameters passed to this - // function have already been folded + // function have already been folded. Moreover, linear-dependent relations that act over the entire + // execution trace rather than on rows, will not be multiplied by the pow challenge. accumulate_relation_univariates( thread_univariate_accumulators[thread_idx], extended_univariates[thread_idx], @@ -323,6 +336,7 @@ template class ProtoGalaxyProver_ { // Batch the univariate contributions from each sub-relation to obtain the round univariate return batch_over_relations(univariate_accumulators, instances.alphas); } + static ExtendedUnivariateWithRandomization batch_over_relations(TupleOfTuplesOfUnivariates& univariate_accumulators, const CombinedRelationSeparator& alpha) { @@ -331,7 +345,7 @@ template class ProtoGalaxyProver_ { auto result = std::get<0>(std::get<0>(univariate_accumulators)) .template extend_to(); size_t idx = 0; - auto scale_and_sum = [&](auto& element) { + auto scale_and_sum = [&](auto& element) { auto extended = element.template extend_to(); extended *= alpha[idx]; result += extended; @@ -416,7 +430,8 @@ template class ProtoGalaxyProver_ { } /** - * @brief Compute the next accumulator (ϕ*, ω*\vec{\beta*}, e*), send the public data ϕ* and the folding parameters + * @brief Compute the next accumulator (ϕ*, ω*, \vec{\beta*}, e*), send the public data ϕ* and the folding + * parameters * (\vec{\beta*}, e*) to the verifier and return the complete accumulator * * @details At this stage, we assume that the instances have the same size and the same number of public parameter.s @@ -434,4 +449,4 @@ template class ProtoGalaxyProver_ { const FF& compressed_perturbator); }; -} // namespace bb::honk +} // namespace bb diff --git a/barretenberg/cpp/src/barretenberg/protogalaxy/protogalaxy_verifier.cpp b/barretenberg/cpp/src/barretenberg/protogalaxy/protogalaxy_verifier.cpp index 5c8331e0aaf..bee65a68010 100644 --- a/barretenberg/cpp/src/barretenberg/protogalaxy/protogalaxy_verifier.cpp +++ b/barretenberg/cpp/src/barretenberg/protogalaxy/protogalaxy_verifier.cpp @@ -1,6 +1,6 @@ #include "protogalaxy_verifier.hpp" #include "barretenberg/proof_system/library/grand_product_delta.hpp" -namespace bb::honk { +namespace bb { template void ProtoGalaxyVerifier_::receive_accumulator(const std::shared_ptr& inst, @@ -87,6 +87,22 @@ void ProtoGalaxyVerifier_::receive_and_finalise_instance(cons witness_commitments.w_r = transcript->template receive_from_prover(domain_separator + "_" + labels.w_r); witness_commitments.w_o = transcript->template receive_from_prover(domain_separator + "_" + labels.w_o); + if constexpr (IsGoblinFlavor) { + // Get commitments to the ECC wire polynomials and databus polynomials + witness_commitments.ecc_op_wire_1 = + transcript->template receive_from_prover(domain_separator + "_" + labels.ecc_op_wire_1); + witness_commitments.ecc_op_wire_2 = + transcript->template receive_from_prover(domain_separator + "_" + labels.ecc_op_wire_2); + witness_commitments.ecc_op_wire_3 = + transcript->template receive_from_prover(domain_separator + "_" + labels.ecc_op_wire_3); + witness_commitments.ecc_op_wire_4 = + transcript->template receive_from_prover(domain_separator + "_" + labels.ecc_op_wire_4); + witness_commitments.calldata = + transcript->template receive_from_prover(domain_separator + "_" + labels.calldata); + witness_commitments.calldata_read_counts = + transcript->template receive_from_prover(domain_separator + "_" + labels.calldata_read_counts); + } + // Get challenge for sorted list batching and wire four memory records commitment auto eta = transcript->get_challenge(domain_separator + "_eta"); witness_commitments.sorted_accum = @@ -95,6 +111,13 @@ void ProtoGalaxyVerifier_::receive_and_finalise_instance(cons // Get permutation challenges and commitment to permutation and lookup grand products auto [beta, gamma] = transcript->get_challenges(domain_separator + "_beta", domain_separator + "_gamma"); + + if constexpr (IsGoblinFlavor) { + // If Goblin (i.e. using DataBus) receive commitments to log-deriv inverses polynomial + witness_commitments.lookup_inverses = transcript->template receive_from_prover( + domain_separator + "_" + commitment_labels.lookup_inverses); + } + witness_commitments.z_perm = transcript->template receive_from_prover(domain_separator + "_" + labels.z_perm); witness_commitments.z_lookup = @@ -288,6 +311,6 @@ bool ProtoGalaxyVerifier_::verify_folding_proof(const std::ve return verified; } -template class ProtoGalaxyVerifier_>; -template class ProtoGalaxyVerifier_>; -} // namespace bb::honk \ No newline at end of file +template class ProtoGalaxyVerifier_>; +template class ProtoGalaxyVerifier_>; +} // namespace bb \ No newline at end of file diff --git a/barretenberg/cpp/src/barretenberg/protogalaxy/protogalaxy_verifier.hpp b/barretenberg/cpp/src/barretenberg/protogalaxy/protogalaxy_verifier.hpp index cbb23d6cc72..5743a888a0f 100644 --- a/barretenberg/cpp/src/barretenberg/protogalaxy/protogalaxy_verifier.hpp +++ b/barretenberg/cpp/src/barretenberg/protogalaxy/protogalaxy_verifier.hpp @@ -6,7 +6,7 @@ #include "barretenberg/sumcheck/instance/instances.hpp" #include "barretenberg/transcript/transcript.hpp" -namespace bb::honk { +namespace bb { template class ProtoGalaxyVerifier_ { public: using Flavor = typename VerifierInstances::Flavor; @@ -86,4 +86,4 @@ template class ProtoGalaxyVerifier_ { bool verify_folding_proof(const std::vector&); }; -} // namespace bb::honk +} // namespace bb diff --git a/barretenberg/cpp/src/barretenberg/relations/databus_lookup_relation.hpp b/barretenberg/cpp/src/barretenberg/relations/databus_lookup_relation.hpp index 77a1f0b3744..eb79bb21efe 100644 --- a/barretenberg/cpp/src/barretenberg/relations/databus_lookup_relation.hpp +++ b/barretenberg/cpp/src/barretenberg/relations/databus_lookup_relation.hpp @@ -175,9 +175,9 @@ template class DatabusLookupRelationImpl { const Parameters& params, const FF& scaling_factor) { - honk::logderivative_library:: - accumulate_logderivative_lookup_subrelation_contributions>( - accumulator, in, params, scaling_factor); + + accumulate_logderivative_lookup_subrelation_contributions>( + accumulator, in, params, scaling_factor); } }; diff --git a/barretenberg/cpp/src/barretenberg/relations/ecc_vm/ecc_lookup_relation.cpp b/barretenberg/cpp/src/barretenberg/relations/ecc_vm/ecc_lookup_relation.cpp index 72bb7b89bc1..46fc53baad3 100644 --- a/barretenberg/cpp/src/barretenberg/relations/ecc_vm/ecc_lookup_relation.cpp +++ b/barretenberg/cpp/src/barretenberg/relations/ecc_vm/ecc_lookup_relation.cpp @@ -3,7 +3,7 @@ #include "barretenberg/honk/proof_system/logderivative_library.hpp" #include "ecc_msm_relation.hpp" -namespace bb::honk::sumcheck { +namespace bb { /** * @brief Expression for ECCVM lookup tables. @@ -25,11 +25,11 @@ void ECCVMLookupRelationImpl::accumulate(ContainerOverSubrelations& accumula const Parameters& params, const FF& scaling_factor) { - logderivative_library::accumulate_logderivative_lookup_subrelation_contributions>( + accumulate_logderivative_lookup_subrelation_contributions>( accumulator, in, params, scaling_factor); } template class ECCVMLookupRelationImpl; -DEFINE_SUMCHECK_RELATION_CLASS(ECCVMLookupRelationImpl, flavor::ECCVM); +DEFINE_SUMCHECK_RELATION_CLASS(ECCVMLookupRelationImpl, ECCVMFlavor); -} // namespace bb::honk::sumcheck +} // namespace bb diff --git a/barretenberg/cpp/src/barretenberg/relations/ecc_vm/ecc_lookup_relation.hpp b/barretenberg/cpp/src/barretenberg/relations/ecc_vm/ecc_lookup_relation.hpp index e41177bedd4..fd89cbe5819 100644 --- a/barretenberg/cpp/src/barretenberg/relations/ecc_vm/ecc_lookup_relation.hpp +++ b/barretenberg/cpp/src/barretenberg/relations/ecc_vm/ecc_lookup_relation.hpp @@ -7,7 +7,7 @@ #include "barretenberg/polynomials/univariate.hpp" #include "barretenberg/relations/relation_types.hpp" -namespace bb::honk::sumcheck { +namespace bb { template class ECCVMLookupRelationImpl { public: @@ -247,4 +247,4 @@ template class ECCVMLookupRelationImpl { template using ECCVMLookupRelation = Relation>; -} // namespace bb::honk::sumcheck +} // namespace bb diff --git a/barretenberg/cpp/src/barretenberg/relations/ecc_vm/ecc_msm_relation.cpp b/barretenberg/cpp/src/barretenberg/relations/ecc_vm/ecc_msm_relation.cpp index 7cb0f9b088f..44f11fe6a58 100644 --- a/barretenberg/cpp/src/barretenberg/relations/ecc_vm/ecc_msm_relation.cpp +++ b/barretenberg/cpp/src/barretenberg/relations/ecc_vm/ecc_msm_relation.cpp @@ -2,7 +2,7 @@ #include "barretenberg/flavor/ecc_vm.hpp" #include "barretenberg/flavor/relation_definitions.hpp" -namespace bb::honk::sumcheck { +namespace bb { /** * @brief MSM relations that evaluate the Strauss multiscalar multiplication algorithm. @@ -392,6 +392,6 @@ void ECCVMMSMRelationImpl::accumulate(ContainerOverSubrelations& accumulator } template class ECCVMMSMRelationImpl; -DEFINE_SUMCHECK_RELATION_CLASS(ECCVMMSMRelationImpl, flavor::ECCVM); +DEFINE_SUMCHECK_RELATION_CLASS(ECCVMMSMRelationImpl, ECCVMFlavor); -} // namespace bb::honk::sumcheck +} // namespace bb diff --git a/barretenberg/cpp/src/barretenberg/relations/ecc_vm/ecc_msm_relation.hpp b/barretenberg/cpp/src/barretenberg/relations/ecc_vm/ecc_msm_relation.hpp index 6011790fe5c..51e15f608ed 100644 --- a/barretenberg/cpp/src/barretenberg/relations/ecc_vm/ecc_msm_relation.hpp +++ b/barretenberg/cpp/src/barretenberg/relations/ecc_vm/ecc_msm_relation.hpp @@ -1,7 +1,7 @@ #pragma once #include "barretenberg/relations/relation_types.hpp" -namespace bb::honk::sumcheck { +namespace bb { /** * @brief MSM relations that evaluate the Strauss multiscalar multiplication algorithm. @@ -51,4 +51,4 @@ template class ECCVMMSMRelationImpl { template using ECCVMMSMRelation = Relation>; -} // namespace bb::honk::sumcheck +} // namespace bb diff --git a/barretenberg/cpp/src/barretenberg/relations/ecc_vm/ecc_point_table_relation.cpp b/barretenberg/cpp/src/barretenberg/relations/ecc_vm/ecc_point_table_relation.cpp index 57ca0bc7ea4..a6ef32a0376 100644 --- a/barretenberg/cpp/src/barretenberg/relations/ecc_vm/ecc_point_table_relation.cpp +++ b/barretenberg/cpp/src/barretenberg/relations/ecc_vm/ecc_point_table_relation.cpp @@ -2,7 +2,7 @@ #include "barretenberg/flavor/ecc_vm.hpp" #include "barretenberg/flavor/relation_definitions.hpp" -namespace bb::honk::sumcheck { +namespace bb { /** * @brief ECCVMPointTableRelationImpl @@ -173,6 +173,6 @@ void ECCVMPointTableRelationImpl::accumulate(ContainerOverSubrelations& accu } template class ECCVMPointTableRelationImpl; -DEFINE_SUMCHECK_RELATION_CLASS(ECCVMPointTableRelationImpl, flavor::ECCVM); +DEFINE_SUMCHECK_RELATION_CLASS(ECCVMPointTableRelationImpl, ECCVMFlavor); -} // namespace bb::honk::sumcheck +} // namespace bb diff --git a/barretenberg/cpp/src/barretenberg/relations/ecc_vm/ecc_point_table_relation.hpp b/barretenberg/cpp/src/barretenberg/relations/ecc_vm/ecc_point_table_relation.hpp index 2d850420a94..771e54018fd 100644 --- a/barretenberg/cpp/src/barretenberg/relations/ecc_vm/ecc_point_table_relation.hpp +++ b/barretenberg/cpp/src/barretenberg/relations/ecc_vm/ecc_point_table_relation.hpp @@ -1,7 +1,7 @@ #pragma once #include "barretenberg/relations/relation_types.hpp" -namespace bb::honk::sumcheck { +namespace bb { /** * @brief ECCVMPointTableRelationImpl @@ -30,4 +30,4 @@ template class ECCVMPointTableRelationImpl { template using ECCVMPointTableRelation = Relation>; -} // namespace bb::honk::sumcheck +} // namespace bb diff --git a/barretenberg/cpp/src/barretenberg/relations/ecc_vm/ecc_set_relation.cpp b/barretenberg/cpp/src/barretenberg/relations/ecc_vm/ecc_set_relation.cpp index 7dea0fe450e..d52e0599c91 100644 --- a/barretenberg/cpp/src/barretenberg/relations/ecc_vm/ecc_set_relation.cpp +++ b/barretenberg/cpp/src/barretenberg/relations/ecc_vm/ecc_set_relation.cpp @@ -2,7 +2,7 @@ #include "barretenberg/flavor/relation_definitions.hpp" #include "ecc_msm_relation.hpp" -namespace bb::honk::sumcheck { +namespace bb { /** * @brief Performs list-equivalence checks for the ECCVM @@ -394,7 +394,7 @@ void ECCVMSetRelationImpl::accumulate(ContainerOverSubrelations& accumulator } template class ECCVMSetRelationImpl; -DEFINE_SUMCHECK_RELATION_CLASS(ECCVMSetRelationImpl, flavor::ECCVM); -DEFINE_SUMCHECK_PERMUTATION_CLASS(ECCVMSetRelationImpl, flavor::ECCVM); +DEFINE_SUMCHECK_RELATION_CLASS(ECCVMSetRelationImpl, ECCVMFlavor); +DEFINE_SUMCHECK_PERMUTATION_CLASS(ECCVMSetRelationImpl, ECCVMFlavor); -} // namespace bb::honk::sumcheck +} // namespace bb diff --git a/barretenberg/cpp/src/barretenberg/relations/ecc_vm/ecc_set_relation.hpp b/barretenberg/cpp/src/barretenberg/relations/ecc_vm/ecc_set_relation.hpp index 6d4add0f7f2..41043a88134 100644 --- a/barretenberg/cpp/src/barretenberg/relations/ecc_vm/ecc_set_relation.hpp +++ b/barretenberg/cpp/src/barretenberg/relations/ecc_vm/ecc_set_relation.hpp @@ -7,7 +7,7 @@ #include "barretenberg/polynomials/univariate.hpp" #include "barretenberg/relations/relation_types.hpp" -namespace bb::honk::sumcheck { +namespace bb { template class ECCVMSetRelationImpl { public: @@ -46,4 +46,4 @@ template class ECCVMSetRelationImpl { template using ECCVMSetRelation = Relation>; -} // namespace bb::honk::sumcheck +} // namespace bb diff --git a/barretenberg/cpp/src/barretenberg/relations/ecc_vm/ecc_transcript_relation.cpp b/barretenberg/cpp/src/barretenberg/relations/ecc_vm/ecc_transcript_relation.cpp index 40fa62f7591..5e617a02a00 100644 --- a/barretenberg/cpp/src/barretenberg/relations/ecc_vm/ecc_transcript_relation.cpp +++ b/barretenberg/cpp/src/barretenberg/relations/ecc_vm/ecc_transcript_relation.cpp @@ -5,7 +5,7 @@ #include "barretenberg/flavor/ecc_vm.hpp" #include "barretenberg/flavor/relation_definitions.hpp" -namespace bb::honk::sumcheck { +namespace bb { /** * @brief ECCVMTranscriptRelationImpl evaluates the correctness of the ECCVM transcript columns @@ -256,6 +256,6 @@ void ECCVMTranscriptRelationImpl::accumulate(ContainerOverSubrelations& accu } template class ECCVMTranscriptRelationImpl; -DEFINE_SUMCHECK_RELATION_CLASS(ECCVMTranscriptRelationImpl, flavor::ECCVM); +DEFINE_SUMCHECK_RELATION_CLASS(ECCVMTranscriptRelationImpl, ECCVMFlavor); -} // namespace bb::honk::sumcheck +} // namespace bb diff --git a/barretenberg/cpp/src/barretenberg/relations/ecc_vm/ecc_transcript_relation.hpp b/barretenberg/cpp/src/barretenberg/relations/ecc_vm/ecc_transcript_relation.hpp index b690db33a8d..ef511e41331 100644 --- a/barretenberg/cpp/src/barretenberg/relations/ecc_vm/ecc_transcript_relation.hpp +++ b/barretenberg/cpp/src/barretenberg/relations/ecc_vm/ecc_transcript_relation.hpp @@ -4,7 +4,7 @@ #include "barretenberg/ecc/curves/grumpkin/grumpkin.hpp" #include "barretenberg/relations/relation_types.hpp" -namespace bb::honk::sumcheck { +namespace bb { /** * @brief ECCVMTranscriptRelationImpl evaluates the correctness of the ECCVM transcript columns @@ -55,4 +55,4 @@ template class ECCVMTranscriptRelationImpl { template using ECCVMTranscriptRelation = Relation>; -} // namespace bb::honk::sumcheck +} // namespace bb diff --git a/barretenberg/cpp/src/barretenberg/relations/ecc_vm/ecc_wnaf_relation.cpp b/barretenberg/cpp/src/barretenberg/relations/ecc_vm/ecc_wnaf_relation.cpp index 82e832deb0d..b8077336928 100644 --- a/barretenberg/cpp/src/barretenberg/relations/ecc_vm/ecc_wnaf_relation.cpp +++ b/barretenberg/cpp/src/barretenberg/relations/ecc_vm/ecc_wnaf_relation.cpp @@ -2,7 +2,7 @@ #include "barretenberg/flavor/ecc_vm.hpp" #include "barretenberg/flavor/relation_definitions.hpp" -namespace bb::honk::sumcheck { +namespace bb { /** * @brief ECCVMWnafRelationImpl evaluates relations that convert scalar multipliers into 4-bit WNAF slices @@ -217,6 +217,6 @@ void ECCVMWnafRelationImpl::accumulate(ContainerOverSubrelations& accumulato } template class ECCVMWnafRelationImpl; -DEFINE_SUMCHECK_RELATION_CLASS(ECCVMWnafRelationImpl, flavor::ECCVM); +DEFINE_SUMCHECK_RELATION_CLASS(ECCVMWnafRelationImpl, ECCVMFlavor); -} // namespace bb::honk::sumcheck +} // namespace bb diff --git a/barretenberg/cpp/src/barretenberg/relations/ecc_vm/ecc_wnaf_relation.hpp b/barretenberg/cpp/src/barretenberg/relations/ecc_vm/ecc_wnaf_relation.hpp index 22faa56f6fc..4373d1e7f44 100644 --- a/barretenberg/cpp/src/barretenberg/relations/ecc_vm/ecc_wnaf_relation.hpp +++ b/barretenberg/cpp/src/barretenberg/relations/ecc_vm/ecc_wnaf_relation.hpp @@ -1,7 +1,7 @@ #pragma once #include "barretenberg/relations/relation_types.hpp" -namespace bb::honk::sumcheck { +namespace bb { /** * @brief ECCVMWnafRelationImpl evaluates relations that convert scalar multipliers into 4-bit WNAF slices * @details Each WNAF slice is a 4-bit slice representing one of 16 integers { -15, -13, ..., 15 } @@ -48,4 +48,4 @@ template class ECCVMWnafRelationImpl { template using ECCVMWnafRelation = Relation>; -} // namespace bb::honk::sumcheck +} // namespace bb diff --git a/barretenberg/cpp/src/barretenberg/relations/generated/Toy/lookup_xor.hpp b/barretenberg/cpp/src/barretenberg/relations/generated/Toy/lookup_xor.hpp index 40f6e5481a8..b94e500d57d 100644 --- a/barretenberg/cpp/src/barretenberg/relations/generated/Toy/lookup_xor.hpp +++ b/barretenberg/cpp/src/barretenberg/relations/generated/Toy/lookup_xor.hpp @@ -7,7 +7,7 @@ #include #include -namespace bb::honk::sumcheck { +namespace bb { /** * @brief This class contains an example of how to set LookupSettings classes used by the @@ -19,7 +19,7 @@ namespace bb::honk::sumcheck { * 3) Update "DECLARE_LOOKUP_IMPLEMENTATIONS_FOR_ALL_SETTINGS" and "DEFINE_LOOKUP_IMPLEMENTATIONS_FOR_ALL_SETTINGS" to * include the new settings * 4) Add the relation with the chosen settings to Relations in the flavor (for example,"` - * using Relations = std::tuple>;)` * */ @@ -171,4 +171,4 @@ class lookup_xor_lookup_settings { template using lookup_xor_relation = GenericLookupRelation; template using lookup_xor = GenericLookup; -} // namespace bb::honk::sumcheck +} // namespace bb diff --git a/barretenberg/cpp/src/barretenberg/relations/generated/Toy/two_column_perm.hpp b/barretenberg/cpp/src/barretenberg/relations/generated/Toy/two_column_perm.hpp index 77391e221b0..c9eb36311cb 100644 --- a/barretenberg/cpp/src/barretenberg/relations/generated/Toy/two_column_perm.hpp +++ b/barretenberg/cpp/src/barretenberg/relations/generated/Toy/two_column_perm.hpp @@ -7,7 +7,7 @@ #include #include -namespace bb::honk::sumcheck { +namespace bb { class two_column_perm_permutation_settings { public: @@ -91,4 +91,4 @@ template using two_column_perm_relation = GenericPermutationRelation; template using two_column_perm = GenericPermutation; -} // namespace bb::honk::sumcheck +} // namespace bb diff --git a/barretenberg/cpp/src/barretenberg/relations/generic_lookup/generic_lookup_relation.hpp b/barretenberg/cpp/src/barretenberg/relations/generic_lookup/generic_lookup_relation.hpp index ce779b7c0eb..18b9c872101 100644 --- a/barretenberg/cpp/src/barretenberg/relations/generic_lookup/generic_lookup_relation.hpp +++ b/barretenberg/cpp/src/barretenberg/relations/generic_lookup/generic_lookup_relation.hpp @@ -24,7 +24,7 @@ #include "barretenberg/polynomials/univariate.hpp" #include "barretenberg/relations/relation_types.hpp" -namespace bb::honk::sumcheck { +namespace bb { /** * @brief Specifies positions of elements in the tuple of entities received from methods in the Settings class * @@ -468,9 +468,8 @@ template class GenericLookupRelationImpl { const Parameters& params, const FF& scaling_factor) { - logderivative_library:: - accumulate_logderivative_lookup_subrelation_contributions>( - accumulator, in, params, scaling_factor); + accumulate_logderivative_lookup_subrelation_contributions>( + accumulator, in, params, scaling_factor); } }; @@ -479,4 +478,4 @@ using GenericLookupRelation = Relation>; template using GenericLookup = GenericLookupRelationImpl; -} // namespace bb::honk::sumcheck \ No newline at end of file +} // namespace bb \ No newline at end of file diff --git a/barretenberg/cpp/src/barretenberg/relations/generic_permutation/generic_permutation_relation.hpp b/barretenberg/cpp/src/barretenberg/relations/generic_permutation/generic_permutation_relation.hpp index 89ff480a9c5..084132abfa3 100644 --- a/barretenberg/cpp/src/barretenberg/relations/generic_permutation/generic_permutation_relation.hpp +++ b/barretenberg/cpp/src/barretenberg/relations/generic_permutation/generic_permutation_relation.hpp @@ -15,7 +15,7 @@ #include "barretenberg/polynomials/univariate.hpp" #include "barretenberg/relations/relation_types.hpp" -namespace bb::honk::sumcheck { +namespace bb { /** * @brief Specifies positions of elements in the tuple of entities received from methods in the Settings class * @@ -202,9 +202,9 @@ template class GenericPermutationRelationImpl const Parameters& params, const FF& scaling_factor) { - logderivative_library::accumulate_logderivative_permutation_subrelation_contributions< - FF, - GenericPermutationRelationImpl>(accumulator, in, params, scaling_factor); + accumulate_logderivative_permutation_subrelation_contributions>( + accumulator, in, params, scaling_factor); } }; @@ -213,4 +213,4 @@ using GenericPermutationRelation = Relation using GenericPermutation = GenericPermutationRelationImpl; -} // namespace bb::honk::sumcheck +} // namespace bb diff --git a/barretenberg/cpp/src/barretenberg/relations/translator_vm/goblin_translator_relation_consistency.test.cpp b/barretenberg/cpp/src/barretenberg/relations/translator_vm/goblin_translator_relation_consistency.test.cpp index 4f8093f9ad8..890810aee0a 100644 --- a/barretenberg/cpp/src/barretenberg/relations/translator_vm/goblin_translator_relation_consistency.test.cpp +++ b/barretenberg/cpp/src/barretenberg/relations/translator_vm/goblin_translator_relation_consistency.test.cpp @@ -16,7 +16,7 @@ using namespace bb; -using Flavor = honk::flavor::GoblinTranslator; +using Flavor = GoblinTranslatorFlavor; using FF = typename Flavor::FF; using InputElements = typename Flavor::AllValues; diff --git a/barretenberg/cpp/src/barretenberg/relations/translator_vm/translator_decomposition_relation.cpp b/barretenberg/cpp/src/barretenberg/relations/translator_vm/translator_decomposition_relation.cpp index d2822cd9a6c..07691f0aa21 100644 --- a/barretenberg/cpp/src/barretenberg/relations/translator_vm/translator_decomposition_relation.cpp +++ b/barretenberg/cpp/src/barretenberg/relations/translator_vm/translator_decomposition_relation.cpp @@ -617,6 +617,6 @@ void GoblinTranslatorDecompositionRelationImpl::accumulate(ContainerOverSubr }; template class GoblinTranslatorDecompositionRelationImpl; -DEFINE_SUMCHECK_RELATION_CLASS(GoblinTranslatorDecompositionRelationImpl, honk::flavor::GoblinTranslator); +DEFINE_SUMCHECK_RELATION_CLASS(GoblinTranslatorDecompositionRelationImpl, GoblinTranslatorFlavor); } // namespace bb diff --git a/barretenberg/cpp/src/barretenberg/relations/translator_vm/translator_extra_relations.cpp b/barretenberg/cpp/src/barretenberg/relations/translator_vm/translator_extra_relations.cpp index eaf08ada3db..5852d95e681 100644 --- a/barretenberg/cpp/src/barretenberg/relations/translator_vm/translator_extra_relations.cpp +++ b/barretenberg/cpp/src/barretenberg/relations/translator_vm/translator_extra_relations.cpp @@ -149,7 +149,7 @@ void GoblinTranslatorAccumulatorTransferRelationImpl::accumulate(ContainerOv template class GoblinTranslatorOpcodeConstraintRelationImpl; template class GoblinTranslatorAccumulatorTransferRelationImpl; -DEFINE_SUMCHECK_RELATION_CLASS(GoblinTranslatorOpcodeConstraintRelationImpl, honk::flavor::GoblinTranslator); -DEFINE_SUMCHECK_RELATION_CLASS(GoblinTranslatorAccumulatorTransferRelationImpl, honk::flavor::GoblinTranslator); +DEFINE_SUMCHECK_RELATION_CLASS(GoblinTranslatorOpcodeConstraintRelationImpl, GoblinTranslatorFlavor); +DEFINE_SUMCHECK_RELATION_CLASS(GoblinTranslatorAccumulatorTransferRelationImpl, GoblinTranslatorFlavor); } // namespace bb diff --git a/barretenberg/cpp/src/barretenberg/relations/translator_vm/translator_gen_perm_sort_relation.cpp b/barretenberg/cpp/src/barretenberg/relations/translator_vm/translator_gen_perm_sort_relation.cpp index 24db1101cc3..fe5c222a8cc 100644 --- a/barretenberg/cpp/src/barretenberg/relations/translator_vm/translator_gen_perm_sort_relation.cpp +++ b/barretenberg/cpp/src/barretenberg/relations/translator_vm/translator_gen_perm_sort_relation.cpp @@ -127,6 +127,6 @@ void GoblinTranslatorGenPermSortRelationImpl::accumulate(ContainerOverSubrel }; template class GoblinTranslatorGenPermSortRelationImpl; -DEFINE_SUMCHECK_RELATION_CLASS(GoblinTranslatorGenPermSortRelationImpl, honk::flavor::GoblinTranslator); +DEFINE_SUMCHECK_RELATION_CLASS(GoblinTranslatorGenPermSortRelationImpl, GoblinTranslatorFlavor); } // namespace bb diff --git a/barretenberg/cpp/src/barretenberg/relations/translator_vm/translator_non_native_field_relation.cpp b/barretenberg/cpp/src/barretenberg/relations/translator_vm/translator_non_native_field_relation.cpp index 71ce173b8f3..d4231625ff3 100644 --- a/barretenberg/cpp/src/barretenberg/relations/translator_vm/translator_non_native_field_relation.cpp +++ b/barretenberg/cpp/src/barretenberg/relations/translator_vm/translator_non_native_field_relation.cpp @@ -278,6 +278,6 @@ void GoblinTranslatorNonNativeFieldRelationImpl::accumulate(ContainerOverSub }; template class GoblinTranslatorNonNativeFieldRelationImpl; -DEFINE_SUMCHECK_RELATION_CLASS(GoblinTranslatorNonNativeFieldRelationImpl, honk::flavor::GoblinTranslator); +DEFINE_SUMCHECK_RELATION_CLASS(GoblinTranslatorNonNativeFieldRelationImpl, GoblinTranslatorFlavor); } // namespace bb diff --git a/barretenberg/cpp/src/barretenberg/relations/translator_vm/translator_permutation_relation.cpp b/barretenberg/cpp/src/barretenberg/relations/translator_vm/translator_permutation_relation.cpp index 74d4364b8e0..de6aa1d350d 100644 --- a/barretenberg/cpp/src/barretenberg/relations/translator_vm/translator_permutation_relation.cpp +++ b/barretenberg/cpp/src/barretenberg/relations/translator_vm/translator_permutation_relation.cpp @@ -60,6 +60,6 @@ void GoblinTranslatorPermutationRelationImpl::accumulate(ContainerOverSubrel }; template class GoblinTranslatorPermutationRelationImpl; -DEFINE_SUMCHECK_RELATION_CLASS(GoblinTranslatorPermutationRelationImpl, honk::flavor::GoblinTranslator); +DEFINE_SUMCHECK_RELATION_CLASS(GoblinTranslatorPermutationRelationImpl, GoblinTranslatorFlavor); } // namespace bb diff --git a/barretenberg/cpp/src/barretenberg/relations/utils.hpp b/barretenberg/cpp/src/barretenberg/relations/utils.hpp index 331967359f3..8ef5f80c588 100644 --- a/barretenberg/cpp/src/barretenberg/relations/utils.hpp +++ b/barretenberg/cpp/src/barretenberg/relations/utils.hpp @@ -113,8 +113,7 @@ template class RelationUtils { template static constexpr void add_tuples(std::tuple& tuple_1, const std::tuple& tuple_2) { - auto add_tuples_helper = [&](std::index_sequence) - { + auto add_tuples_helper = [&](std::index_sequence) { ((std::get(tuple_1) += std::get(tuple_2)), ...); }; @@ -184,7 +183,7 @@ template class RelationUtils { }; /** - * @brief Scale elements, which in sumcheck represent evaluations of subrelations, by different challenges then sum + * @brief Scale elements, representing evaluations of subrelations, by separate challenges then sum them * @param challenges Array of NUM_SUBRELATIONS - 1 challenges (because the first subrelation does not need to be * scaled) * @param result Batched result @@ -208,7 +207,49 @@ template class RelationUtils { } /** - * @brief Scale elements by consecutive powers of the challenge then sum + * @brief Scales elements, representing evaluations of polynomials in subrelations, by separate challenges and then + * sum them together. This function has identical functionality with the one above with the caveat that one such + * evaluation is part of a linearly dependent subrelation and hence needs to be accumulated separately. + * + * @details Such functionality is needed when computing the evaluation of the full relation at a specific row in + * the execution trace because a linearly dependent subrelation does not act on a specific row but rather on the + * entire execution trace. + * + * @param tuple + * @param challenges + * @param current_scalar + * @param result + * @param linearly_dependent_contribution + */ + static void scale_and_batch_elements(auto& tuple, + const RelationSeparator& challenges, + FF current_scalar, + FF& result, + FF& linearly_dependent_contribution) + requires bb::IsFoldingFlavor + { + size_t idx = 0; + std::array tmp{ current_scalar }; + + std::copy(challenges.begin(), challenges.end(), tmp.begin() + 1); + + auto scale_by_challenge_and_accumulate = + [&](Element& element) { + using Relation = typename std::tuple_element_t; + const bool is_subrelation_linearly_independent = + bb::subrelation_is_linearly_independent(); + if (is_subrelation_linearly_independent) { + result += element * tmp[idx]; + } else { + linearly_dependent_contribution += element * tmp[idx]; + } + idx++; + }; + apply_to_tuple_of_arrays_elements(scale_by_challenge_and_accumulate, tuple); + } + + /** + * @brief Scale elements by consecutive powers of a given challenge then sum the result * @param result Batched result */ static void scale_and_batch_elements(auto& tuple, const RelationSeparator& challenge, FF current_scalar, FF& result) @@ -240,5 +281,33 @@ template class RelationUtils { apply_to_tuple_of_arrays(operation, tuple); } } + + /** + * @brief Recursive template function to apply a specific operation on each element of several arrays in a tuple + * + * @details We need this method in addition to the apply_to_tuple_of_arrays when we aim to perform different + * operations depending on the array element. More explicitly, in our codebase this method is used when the elements + * of array are values of subrelations and we want to accumulate some of these values separately (the linearly + * dependent contribution when we compute the evaluation of full rel_U(G)H at particular row.) + */ + template + static void apply_to_tuple_of_arrays_elements(Operation&& operation, std::tuple& tuple) + { + using Relation = typename std::tuple_element_t; + const auto subrelation_length = Relation::SUBRELATION_PARTIAL_LENGTHS.size(); + auto& element = std::get(tuple); + + // Invoke the operation with outer_idx (array index) and inner_idx (element index) as template arguments + operation.template operator()(element[inner_idx]); + + if constexpr (inner_idx + 1 < subrelation_length) { + // Recursively call for the next element within the same array + apply_to_tuple_of_arrays_elements(std::forward(operation), + tuple); + } else if constexpr (outer_idx + 1 < sizeof...(Ts)) { + // Move to the next array in the tuple + apply_to_tuple_of_arrays_elements(std::forward(operation), tuple); + } + } }; } // namespace bb diff --git a/barretenberg/cpp/src/barretenberg/stdlib/hash/poseidon2/poseidon2.cpp b/barretenberg/cpp/src/barretenberg/stdlib/hash/poseidon2/poseidon2.cpp index d113d2a3cb8..705493bf345 100644 --- a/barretenberg/cpp/src/barretenberg/stdlib/hash/poseidon2/poseidon2.cpp +++ b/barretenberg/cpp/src/barretenberg/stdlib/hash/poseidon2/poseidon2.cpp @@ -14,8 +14,7 @@ template field_t poseidon2::hash(C& builder, const std::vecto * This should just call the sponge variable length hash function * */ - auto input{ inputs }; - return Sponge::hash_fixed_length(builder, input); + return Sponge::hash_fixed_length(builder, inputs); } /** diff --git a/barretenberg/cpp/src/barretenberg/stdlib/hash/poseidon2/sponge/sponge.hpp b/barretenberg/cpp/src/barretenberg/stdlib/hash/poseidon2/sponge/sponge.hpp index bccebbd152c..6d79834aa95 100644 --- a/barretenberg/cpp/src/barretenberg/stdlib/hash/poseidon2/sponge/sponge.hpp +++ b/barretenberg/cpp/src/barretenberg/stdlib/hash/poseidon2/sponge/sponge.hpp @@ -135,7 +135,7 @@ template */ template - static std::array hash_internal(Builder& builder, std::span input) + static std::array hash_internal(Builder& builder, std::span input) { size_t in_len = input.size(); const uint256_t iv = (static_cast(in_len) << 64) + out_len - 1; @@ -160,11 +160,11 @@ template - static std::array hash_fixed_length(Builder& builder, std::span input) + static std::array hash_fixed_length(Builder& builder, std::span input) { return hash_internal(builder, input); } - static field_t hash_fixed_length(Builder& builder, std::span input) + static field_t hash_fixed_length(Builder& builder, std::span input) { return hash_fixed_length<1>(builder, input)[0]; } diff --git a/barretenberg/cpp/src/barretenberg/stdlib/primitives/circuit_builders/circuit_builders_fwd.hpp b/barretenberg/cpp/src/barretenberg/stdlib/primitives/circuit_builders/circuit_builders_fwd.hpp index ca1e082d04d..6c0d18f5fd5 100644 --- a/barretenberg/cpp/src/barretenberg/stdlib/primitives/circuit_builders/circuit_builders_fwd.hpp +++ b/barretenberg/cpp/src/barretenberg/stdlib/primitives/circuit_builders/circuit_builders_fwd.hpp @@ -9,25 +9,18 @@ construction in stdlib and contains macros for explicit instantiation. #pragma once #include -namespace bb::honk::flavor { -class Standard; -class Ultra; -} // namespace bb::honk::flavor - namespace bb { +class StandardFlavor; +class UltraFlavor; class Bn254FrParams; class Bn254FqParams; template struct alignas(32) field; -} // namespace bb -namespace arithmetization { -template class Ultra; -} // namespace arithmetization -namespace bb { +template class UltraArith; template class StandardCircuitBuilder_; -using StandardCircuitBuilder = StandardCircuitBuilder_>; -using StandardGrumpkinCircuitBuilder = StandardCircuitBuilder_>; +using StandardCircuitBuilder = StandardCircuitBuilder_>; +using StandardGrumpkinCircuitBuilder = StandardCircuitBuilder_>; template class UltraCircuitBuilder_; -using UltraCircuitBuilder = UltraCircuitBuilder_>>; +using UltraCircuitBuilder = UltraCircuitBuilder_>>; template class GoblinUltraCircuitBuilder_; -using GoblinUltraCircuitBuilder = GoblinUltraCircuitBuilder_>; +using GoblinUltraCircuitBuilder = GoblinUltraCircuitBuilder_>; } // namespace bb \ No newline at end of file diff --git a/barretenberg/cpp/src/barretenberg/stdlib/recursion/honk/transcript/transcript.hpp b/barretenberg/cpp/src/barretenberg/stdlib/recursion/honk/transcript/transcript.hpp index 723ad1f7cf0..fc36ffcdded 100644 --- a/barretenberg/cpp/src/barretenberg/stdlib/recursion/honk/transcript/transcript.hpp +++ b/barretenberg/cpp/src/barretenberg/stdlib/recursion/honk/transcript/transcript.hpp @@ -18,7 +18,7 @@ template class Transcript { public: using field_ct = field_t; using FF = bb::fr; - using NativeTranscript = bb::honk::BaseTranscript; + using NativeTranscript = BaseTranscript; using StdlibTypes = utility::StdlibTypesUtility; static constexpr size_t HASH_OUTPUT_SIZE = NativeTranscript::HASH_OUTPUT_SIZE; @@ -28,7 +28,7 @@ template class Transcript { Transcript() = default; - Transcript(Builder* builder, const bb::honk::proof& proof_data) + Transcript(Builder* builder, const bb::HonkProof& proof_data) : native_transcript(proof_data) , builder(builder){}; diff --git a/barretenberg/cpp/src/barretenberg/stdlib/recursion/honk/transcript/transcript.test.cpp b/barretenberg/cpp/src/barretenberg/stdlib/recursion/honk/transcript/transcript.test.cpp index 307e388e368..09c8620c619 100644 --- a/barretenberg/cpp/src/barretenberg/stdlib/recursion/honk/transcript/transcript.test.cpp +++ b/barretenberg/cpp/src/barretenberg/stdlib/recursion/honk/transcript/transcript.test.cpp @@ -11,10 +11,9 @@ namespace bb::stdlib::recursion::honk { using Builder = UltraCircuitBuilder; -using UltraFlavor = ::bb::honk::flavor::Ultra; -using UltraRecursiveFlavor = ::bb::honk::flavor::UltraRecursive_; +using UltraRecursiveFlavor = UltraRecursiveFlavor_; using FF = fr; -using BaseTranscript = ::bb::honk::BaseTranscript; +using BaseTranscript = BaseTranscript; /** * @brief Create some mock data; add it to the provided prover transcript in various mock rounds diff --git a/barretenberg/cpp/src/barretenberg/stdlib/recursion/honk/verifier/decider_recursive_verifier.cpp b/barretenberg/cpp/src/barretenberg/stdlib/recursion/honk/verifier/decider_recursive_verifier.cpp index 101615f51e9..5c7ef744e28 100644 --- a/barretenberg/cpp/src/barretenberg/stdlib/recursion/honk/verifier/decider_recursive_verifier.cpp +++ b/barretenberg/cpp/src/barretenberg/stdlib/recursion/honk/verifier/decider_recursive_verifier.cpp @@ -17,15 +17,14 @@ DeciderRecursiveVerifier_::DeciderRecursiveVerifier_(Builder* builder) * */ template -std::array DeciderRecursiveVerifier_::verify_proof( - const bb::honk::proof& proof) +std::array DeciderRecursiveVerifier_::verify_proof(const HonkProof& proof) { - using Sumcheck = ::bb::honk::sumcheck::SumcheckVerifier; + using Sumcheck = ::bb::SumcheckVerifier; using Curve = typename Flavor::Curve; - using ZeroMorph = ::bb::honk::pcs::zeromorph::ZeroMorphVerifier_; + using ZeroMorph = ::bb::ZeroMorphVerifier_; using VerifierCommitments = typename Flavor::VerifierCommitments; using Transcript = typename Flavor::Transcript; - using Instance = typename ::bb::honk::VerifierInstance_; + using Instance = VerifierInstance_; static constexpr size_t NUM_SUBRELATIONS = Flavor::NUM_SUBRELATIONS; transcript = std::make_shared(builder, proof); @@ -91,6 +90,6 @@ std::array DeciderRecursiveVerifier_:: return pairing_points; } -template class DeciderRecursiveVerifier_>; -template class DeciderRecursiveVerifier_>; +template class DeciderRecursiveVerifier_>; +template class DeciderRecursiveVerifier_>; } // namespace bb::stdlib::recursion::honk diff --git a/barretenberg/cpp/src/barretenberg/stdlib/recursion/honk/verifier/decider_recursive_verifier.hpp b/barretenberg/cpp/src/barretenberg/stdlib/recursion/honk/verifier/decider_recursive_verifier.hpp index ba6dc021bed..56f8ec1c46d 100644 --- a/barretenberg/cpp/src/barretenberg/stdlib/recursion/honk/verifier/decider_recursive_verifier.hpp +++ b/barretenberg/cpp/src/barretenberg/stdlib/recursion/honk/verifier/decider_recursive_verifier.hpp @@ -19,7 +19,7 @@ template class DeciderRecursiveVerifier_ { public: explicit DeciderRecursiveVerifier_(Builder* builder); - PairingPoints verify_proof(const bb::honk::proof& proof); + PairingPoints verify_proof(const HonkProof& proof); std::map commitments; std::shared_ptr pcs_verification_key; diff --git a/barretenberg/cpp/src/barretenberg/stdlib/recursion/honk/verifier/goblin_verifier.test.cpp b/barretenberg/cpp/src/barretenberg/stdlib/recursion/honk/verifier/goblin_verifier.test.cpp index b64bfcf418d..9052d25c071 100644 --- a/barretenberg/cpp/src/barretenberg/stdlib/recursion/honk/verifier/goblin_verifier.test.cpp +++ b/barretenberg/cpp/src/barretenberg/stdlib/recursion/honk/verifier/goblin_verifier.test.cpp @@ -18,11 +18,8 @@ namespace bb::stdlib::recursion::honk { */ template class GoblinRecursiveVerifierTest : public testing::Test { - // Define types relevant for testing - using UltraFlavor = ::bb::honk::flavor::Ultra; - using GoblinUltraFlavor = ::bb::honk::flavor::GoblinUltra; - using UltraComposer = ::bb::honk::UltraComposer_; - using GoblinUltraComposer = ::bb::honk::UltraComposer_; + using UltraComposer = UltraComposer_; + using GoblinUltraComposer = UltraComposer_; // Define types for the inner circuit, i.e. the circuit whose proof will be recursively verified using InnerFlavor = GoblinUltraFlavor; @@ -34,7 +31,7 @@ template class GoblinRecursiveVerifierTest : public testi // Types for recursive verifier circuit using OuterBuilder = BuilderType; - using RecursiveFlavor = ::bb::honk::flavor::GoblinUltraRecursive_; + using RecursiveFlavor = GoblinUltraRecursiveFlavor_; using RecursiveVerifier = UltraRecursiveVerifier_; using VerificationKey = typename RecursiveVerifier::VerificationKey; diff --git a/barretenberg/cpp/src/barretenberg/stdlib/recursion/honk/verifier/merge_recursive_verifier.cpp b/barretenberg/cpp/src/barretenberg/stdlib/recursion/honk/verifier/merge_recursive_verifier.cpp index 6d809e7ad5a..28fbe6d92df 100644 --- a/barretenberg/cpp/src/barretenberg/stdlib/recursion/honk/verifier/merge_recursive_verifier.cpp +++ b/barretenberg/cpp/src/barretenberg/stdlib/recursion/honk/verifier/merge_recursive_verifier.cpp @@ -16,7 +16,7 @@ MergeRecursiveVerifier_::MergeRecursiveVerifier_(CircuitBuilder* */ template std::array::Element, 2> MergeRecursiveVerifier_::verify_proof( - const bb::honk::proof& proof) + const HonkProof& proof) { transcript = std::make_shared(builder, proof); diff --git a/barretenberg/cpp/src/barretenberg/stdlib/recursion/honk/verifier/merge_recursive_verifier.hpp b/barretenberg/cpp/src/barretenberg/stdlib/recursion/honk/verifier/merge_recursive_verifier.hpp index 411b44fd472..9e5a76fbc8d 100644 --- a/barretenberg/cpp/src/barretenberg/stdlib/recursion/honk/verifier/merge_recursive_verifier.hpp +++ b/barretenberg/cpp/src/barretenberg/stdlib/recursion/honk/verifier/merge_recursive_verifier.hpp @@ -11,19 +11,19 @@ template class MergeRecursiveVerifier_ { using FF = typename Curve::ScalarField; using Commitment = typename Curve::Element; using GroupElement = typename Curve::Element; - using KZG = ::bb::honk::pcs::kzg::KZG; - using OpeningClaim = ::bb::honk::pcs::OpeningClaim; + using KZG = ::bb::KZG; + using OpeningClaim = ::bb::OpeningClaim; using PairingPoints = std::array; using Transcript = honk::Transcript; CircuitBuilder* builder; std::shared_ptr transcript; - static constexpr size_t NUM_WIRES = arithmetization::UltraHonk::NUM_WIRES; + static constexpr size_t NUM_WIRES = UltraHonkArith::NUM_WIRES; explicit MergeRecursiveVerifier_(CircuitBuilder* builder); - PairingPoints verify_proof(const bb::honk::proof& proof); + PairingPoints verify_proof(const HonkProof& proof); }; } // namespace bb::stdlib::recursion::goblin diff --git a/barretenberg/cpp/src/barretenberg/stdlib/recursion/honk/verifier/merge_verifier.test.cpp b/barretenberg/cpp/src/barretenberg/stdlib/recursion/honk/verifier/merge_verifier.test.cpp index 5c242885de2..af5b40ecfc3 100644 --- a/barretenberg/cpp/src/barretenberg/stdlib/recursion/honk/verifier/merge_verifier.test.cpp +++ b/barretenberg/cpp/src/barretenberg/stdlib/recursion/honk/verifier/merge_verifier.test.cpp @@ -20,8 +20,7 @@ class RecursiveMergeVerifierTest : public testing::Test { using RecursiveMergeVerifier = MergeRecursiveVerifier_; // Define types relevant for inner circuit - using GoblinUltraFlavor = ::bb::honk::flavor::GoblinUltra; - using GoblinUltraComposer = ::bb::honk::UltraComposer_; + using GoblinUltraComposer = UltraComposer_; using InnerFlavor = GoblinUltraFlavor; using InnerComposer = GoblinUltraComposer; using InnerBuilder = typename InnerComposer::CircuitBuilder; @@ -29,7 +28,7 @@ class RecursiveMergeVerifierTest : public testing::Test { // Define additional types for testing purposes using Commitment = InnerFlavor::Commitment; using FF = InnerFlavor::FF; - using VerifierCommitmentKey = ::bb::honk::pcs::VerifierCommitmentKey; + using VerifierCommitmentKey = bb::VerifierCommitmentKey; public: static void SetUpTestSuite() { bb::srs::init_crs_factory("../srs_db/ignition"); } @@ -49,7 +48,7 @@ class RecursiveMergeVerifierTest : public testing::Test { // Generate a proof over the inner circuit InnerComposer inner_composer; - auto merge_prover = inner_composer.create_merge_prover(op_queue); + MergeProver merge_prover{ op_queue }; auto merge_proof = merge_prover.construct_proof(); // Create a recursive merge verification circuit for the merge proof @@ -62,7 +61,7 @@ class RecursiveMergeVerifierTest : public testing::Test { // Check 1: Perform native merge verification then perform the pairing on the outputs of the recursive merge // verifier and check that the result agrees. - auto native_verifier = inner_composer.create_merge_verifier(); + MergeVerifier native_verifier; bool verified_native = native_verifier.verify_proof(merge_proof); VerifierCommitmentKey pcs_verification_key(0, srs::get_crs_factory()); auto verified_recursive = diff --git a/barretenberg/cpp/src/barretenberg/stdlib/recursion/honk/verifier/protogalaxy_recursive_verifier.cpp b/barretenberg/cpp/src/barretenberg/stdlib/recursion/honk/verifier/protogalaxy_recursive_verifier.cpp index d1fdaeee01b..e0fed9ac6a2 100644 --- a/barretenberg/cpp/src/barretenberg/stdlib/recursion/honk/verifier/protogalaxy_recursive_verifier.cpp +++ b/barretenberg/cpp/src/barretenberg/stdlib/recursion/honk/verifier/protogalaxy_recursive_verifier.cpp @@ -94,6 +94,21 @@ void ProtoGalaxyRecursiveVerifier_::receive_and_finalise_inst witness_commitments.w_r = transcript->template receive_from_prover(domain_separator + "_" + labels.w_r); witness_commitments.w_o = transcript->template receive_from_prover(domain_separator + "_" + labels.w_o); + if constexpr (IsGoblinFlavor) { + witness_commitments.ecc_op_wire_1 = + transcript->template receive_from_prover(domain_separator + "_" + labels.ecc_op_wire_1); + witness_commitments.ecc_op_wire_2 = + transcript->template receive_from_prover(domain_separator + "_" + labels.ecc_op_wire_2); + witness_commitments.ecc_op_wire_3 = + transcript->template receive_from_prover(domain_separator + "_" + labels.ecc_op_wire_3); + witness_commitments.ecc_op_wire_4 = + transcript->template receive_from_prover(domain_separator + "_" + labels.ecc_op_wire_4); + witness_commitments.calldata = + transcript->template receive_from_prover(domain_separator + "_" + labels.calldata); + witness_commitments.calldata_read_counts = + transcript->template receive_from_prover(domain_separator + "_" + labels.calldata_read_counts); + } + // Get challenge for sorted list batching and wire four memory records commitment auto eta = transcript->get_challenge(domain_separator + "_eta"); witness_commitments.sorted_accum = @@ -102,16 +117,22 @@ void ProtoGalaxyRecursiveVerifier_::receive_and_finalise_inst // Get permutation challenges and commitment to permutation and lookup grand products auto [beta, gamma] = transcript->get_challenges(domain_separator + "_beta", domain_separator + "_gamma"); + + // If Goblin (i.e. using DataBus) receive commitments to log-deriv inverses polynomial + if constexpr (IsGoblinFlavor) { + witness_commitments.lookup_inverses = transcript->template receive_from_prover( + domain_separator + "_" + commitment_labels.lookup_inverses); + } + witness_commitments.z_perm = transcript->template receive_from_prover(domain_separator + "_" + labels.z_perm); witness_commitments.z_lookup = transcript->template receive_from_prover(domain_separator + "_" + labels.z_lookup); // Compute correction terms for grand products - const FF public_input_delta = bb::honk::compute_public_input_delta( + const FF public_input_delta = compute_public_input_delta( inst->public_inputs, beta, gamma, inst->instance_size, inst->pub_inputs_offset); - const FF lookup_grand_product_delta = - bb::honk::compute_lookup_grand_product_delta(beta, gamma, inst->instance_size); + const FF lookup_grand_product_delta = compute_lookup_grand_product_delta(beta, gamma, inst->instance_size); inst->relation_parameters = RelationParameters{ eta, beta, gamma, public_input_delta, lookup_grand_product_delta }; @@ -164,7 +185,7 @@ template void ProtoGalaxyRecursiveVerifier_ -void ProtoGalaxyRecursiveVerifier_::verify_folding_proof(const bb::honk::proof& proof) +void ProtoGalaxyRecursiveVerifier_::verify_folding_proof(const HonkProof& proof) { using Transcript = typename Flavor::Transcript; using ElementNative = typename Flavor::Curve::ElementNative; @@ -313,8 +334,7 @@ void ProtoGalaxyRecursiveVerifier_::verify_folding_proof(cons } } +template class ProtoGalaxyRecursiveVerifier_, 2>>; template class ProtoGalaxyRecursiveVerifier_< - bb::honk::VerifierInstances_, 2>>; -template class ProtoGalaxyRecursiveVerifier_< - bb::honk::VerifierInstances_, 2>>; + VerifierInstances_, 2>>; } // namespace bb::stdlib::recursion::honk \ No newline at end of file diff --git a/barretenberg/cpp/src/barretenberg/stdlib/recursion/honk/verifier/protogalaxy_recursive_verifier.hpp b/barretenberg/cpp/src/barretenberg/stdlib/recursion/honk/verifier/protogalaxy_recursive_verifier.hpp index 7d4305a7ff5..15fc8dabae3 100644 --- a/barretenberg/cpp/src/barretenberg/stdlib/recursion/honk/verifier/protogalaxy_recursive_verifier.hpp +++ b/barretenberg/cpp/src/barretenberg/stdlib/recursion/honk/verifier/protogalaxy_recursive_verifier.hpp @@ -91,7 +91,7 @@ template class ProtoGalaxyRecursiveVerifier_ { * by the prover, are expressed as constraints. */ - void verify_folding_proof(const bb::honk::proof& proof); + void verify_folding_proof(const HonkProof& proof); /** * @brief Evaluates the perturbator at a given scalar, in a sequential manner for the recursive setting. diff --git a/barretenberg/cpp/src/barretenberg/stdlib/recursion/honk/verifier/protogalaxy_recursive_verifier.test.cpp b/barretenberg/cpp/src/barretenberg/stdlib/recursion/honk/verifier/protogalaxy_recursive_verifier.test.cpp index 61dee74084f..0912edf91ce 100644 --- a/barretenberg/cpp/src/barretenberg/stdlib/recursion/honk/verifier/protogalaxy_recursive_verifier.test.cpp +++ b/barretenberg/cpp/src/barretenberg/stdlib/recursion/honk/verifier/protogalaxy_recursive_verifier.test.cpp @@ -8,32 +8,32 @@ #include "barretenberg/ultra_honk/ultra_composer.hpp" namespace bb::stdlib::recursion::honk { -class ProtogalaxyRecursiveTest : public testing::Test { +template class ProtoGalaxyRecursiveTests : public testing::Test { public: // Define types relevant for testing - using UltraFlavor = ::bb::honk::flavor::Ultra; - using GoblinUltraFlavor = ::bb::honk::flavor::GoblinUltra; - using UltraComposer = ::bb::honk::UltraComposer_; - using GoblinUltraComposer = ::bb::honk::UltraComposer_; - - using InnerFlavor = UltraFlavor; - using InnerComposer = UltraComposer; - using Instance = ::bb::honk::ProverInstance_; + using UltraComposer = ::bb::UltraComposer_; + using GoblinUltraComposer = ::bb::UltraComposer_; + + using InnerFlavor = typename RecursiveFlavor::NativeFlavor; + using InnerComposer = ::bb::UltraComposer_; + using Instance = ::bb::ProverInstance_; using InnerBuilder = typename InnerComposer::CircuitBuilder; using InnerCurve = bn254; - using Commitment = InnerFlavor::Commitment; - using FF = InnerFlavor::FF; + using Commitment = typename InnerFlavor::Commitment; + using FF = typename InnerFlavor::FF; - // Types for recursive verifier circuit - // cannot do on Goblin + // Types for veryfing a recursive verifier circuit using OuterBuilder = GoblinUltraCircuitBuilder; - using RecursiveFlavor = ::bb::honk::flavor::UltraRecursive_; - using RecursiveVerifierInstances = ::bb::honk::VerifierInstances_; + using OuterComposer = GoblinUltraComposer; + + using RecursiveVerifierInstances = ::bb::VerifierInstances_; using FoldingRecursiveVerifier = ProtoGalaxyRecursiveVerifier_; using DeciderRecursiveVerifier = DeciderRecursiveVerifier_; - using DeciderVerifier = ::bb::honk::DeciderVerifier_; - using NativeVerifierInstances = ::bb::honk::VerifierInstances_; - using NativeFoldingVerifier = bb::honk::ProtoGalaxyVerifier_; + using DeciderVerifier = DeciderVerifier_; + using NativeVerifierInstances = VerifierInstances_; + using NativeFoldingVerifier = ProtoGalaxyVerifier_; + + static void SetUpTestSuite() { bb::srs::init_crs_factory("../srs_db/ignition"); } // Helper for getting composer for prover/verifier of recursive (outer) circuit template static auto get_outer_composer() @@ -57,12 +57,13 @@ class ProtogalaxyRecursiveTest : public testing::Test { */ static void create_inner_circuit(InnerBuilder& builder, size_t log_num_gates = 10) { - using fr_ct = InnerCurve::ScalarField; - using fq_ct = InnerCurve::BaseField; - using public_witness_ct = InnerCurve::public_witness_ct; - using witness_ct = InnerCurve::witness_ct; - using byte_array_ct = InnerCurve::byte_array_ct; + using fr_ct = typename InnerCurve::ScalarField; + using fq_ct = typename InnerCurve::BaseField; + using public_witness_ct = typename InnerCurve::public_witness_ct; + using witness_ct = typename InnerCurve::witness_ct; + using byte_array_ct = typename InnerCurve::byte_array_ct; using fr = typename InnerCurve::ScalarFieldNative; + using point = typename InnerCurve::AffineElementNative; // Create 2^log_n many add gates based on input log num gates const size_t num_gates = 1 << log_num_gates; @@ -101,14 +102,87 @@ class ProtogalaxyRecursiveTest : public testing::Test { fq_ct big_b(fr_ct(witness_ct(&builder, bigfield_data_b.to_montgomery_form())), fr_ct(witness_ct(&builder, 0))); big_a* big_b; + + if constexpr (IsGoblinBuilder) { + auto p = point::one() * fr::random_element(); + auto scalar = fr::random_element(); + builder.queue_ecc_mul_accum(p, scalar); + builder.queue_ecc_eq(); + } }; - public: - static void SetUpTestSuite() { bb::srs::init_crs_factory("../srs_db/ignition"); } + static std::shared_ptr fold_and_verify_native(const std::vector>& instances, + InnerComposer& composer) + { + auto folding_prover = composer.create_folding_prover(instances); + auto folding_verifier = composer.create_folding_verifier(); + + auto proof = folding_prover.fold_instances(); + auto next_accumulator = proof.accumulator; + auto res = folding_verifier.verify_folding_proof(proof.folding_data); + EXPECT_EQ(res, true); + return next_accumulator; + } - static std::shared_ptr fold_and_verify(const std::vector>& instances, - InnerComposer& inner_composer) + /** + *@brief Create inner circuit and call check_circuit on it + */ + static void test_inner_circuit() + { + InnerBuilder builder; + + create_inner_circuit(builder); + + bool result = builder.check_circuit(); + EXPECT_EQ(result, true); + }; + + /** + * @brief Ensure that evaluating the perturbator in the recursive folding verifier returns the same result as + * evaluating in Polynomial class. + * + */ + static void test_new_evaluate() { + OuterBuilder builder; + using fr_ct = bn254::ScalarField; + using fr = bn254::ScalarFieldNative; + + std::vector coeffs; + std::vector coeffs_ct; + for (size_t idx = 0; idx < 8; idx++) { + auto el = fr::random_element(); + coeffs.emplace_back(el); + coeffs_ct.emplace_back(fr_ct(&builder, el)); + } + Polynomial poly(coeffs); + fr point = fr::random_element(); + fr_ct point_ct(fr_ct(&builder, point)); + auto res1 = poly.evaluate(point); + + auto res2 = FoldingRecursiveVerifier::evaluate_perturbator(coeffs_ct, point_ct); + EXPECT_EQ(res1, res2.get_value()); + }; + + /** + * @brief Tests a simple recursive fold that is valid works as expected. + * + */ + static void test_recursive_folding() + { + // Create two arbitrary circuits for the first round of folding + InnerBuilder builder1; + + create_inner_circuit(builder1); + InnerBuilder builder2; + builder2.add_public_variable(FF(1)); + create_inner_circuit(builder2); + + InnerComposer inner_composer = InnerComposer(); + auto instance1 = inner_composer.create_instance(builder1); + auto instance2 = inner_composer.create_instance(builder2); + auto instances = std::vector>{ instance1, instance2 }; + // Generate a folding proof auto inner_folding_prover = inner_composer.create_folding_prover(instances); auto inner_folding_proof = inner_folding_prover.fold_instances(); @@ -117,16 +191,16 @@ class ProtogalaxyRecursiveTest : public testing::Test { OuterBuilder outer_folding_circuit; FoldingRecursiveVerifier verifier{ &outer_folding_circuit }; verifier.verify_folding_proof(inner_folding_proof.folding_data); - info("Recursive Verifier with Ultra instances: num gates = ", outer_folding_circuit.num_gates); + info("Folding Recursive Verifier: num gates = ", outer_folding_circuit.num_gates); // Perform native folding verification and ensure it returns the same result (either true or false) as calling // check_circuit on the recursive folding verifier auto native_folding_verifier = inner_composer.create_folding_verifier(); auto native_folding_result = native_folding_verifier.verify_folding_proof(inner_folding_proof.folding_data); - EXPECT_EQ(native_folding_result, outer_folding_circuit.check_circuit()); + EXPECT_EQ(native_folding_result, !outer_folding_circuit.failed()); - // Ensure that the underlying native and recursive folding verification algorithms agree by ensuring - // the manifests produced by each agree. + // Ensure that the underlying native and recursive folding verification algorithms agree by ensuring the + // manifestsproduced by each agree. auto recursive_folding_manifest = verifier.transcript->get_manifest(); auto native_folding_manifest = native_folding_verifier.transcript->get_manifest(); @@ -137,214 +211,196 @@ class ProtogalaxyRecursiveTest : public testing::Test { // Check for a failure flag in the recursive verifier circuit EXPECT_EQ(outer_folding_circuit.failed(), false) << outer_folding_circuit.err(); - return inner_folding_proof.accumulator; - } -}; -/** - * @brief Create inner circuit and call check_circuit on it - * - */ -TEST_F(ProtogalaxyRecursiveTest, InnerCircuit) -{ - InnerBuilder builder; + { + auto composer = OuterComposer(); + auto instance = composer.create_instance(outer_folding_circuit); + auto prover = composer.create_prover(instance); + auto verifier = composer.create_verifier(instance); + auto proof = prover.construct_proof(); + bool verified = verifier.verify_proof(proof); - create_inner_circuit(builder); + ASSERT(verified); + } + }; - bool result = builder.check_circuit(); - EXPECT_EQ(result, true); -} + /** + * @brief Perform two rounds of folding valid circuits and then recursive verify the final decider proof, + * make sure the verifer circuits pass check_circuit(). Ensure that the algorithm of the recursive and native + * verifiers are identical by checking the manifests + */ + // TODO(https://github.com/AztecProtocol/barretenberg/issues/844): Fold the recursive folding verifier in tests once + // we can fold instances of different sizes. + static void test_full_protogalaxy_recursive() + { + // Create two arbitrary circuits for the first round of folding + InnerBuilder builder1; + + create_inner_circuit(builder1); + InnerBuilder builder2; + builder2.add_public_variable(FF(1)); + create_inner_circuit(builder2); + + InnerComposer inner_composer = InnerComposer(); + auto instance1 = inner_composer.create_instance(builder1); + auto instance2 = inner_composer.create_instance(builder2); + auto instances = std::vector>{ instance1, instance2 }; + + auto accumulator = fold_and_verify_native(instances, inner_composer); + + // Create another circuit to do a second round of folding + InnerBuilder builder3; + create_inner_circuit(builder3); + auto instance3 = inner_composer.create_instance(builder3); + instances = std::vector>{ accumulator, instance3 }; + + accumulator = fold_and_verify_native(instances, inner_composer); + + // Create a decider proof for the relaxed instance obtained through folding + auto inner_decider_prover = inner_composer.create_decider_prover(accumulator); + auto inner_decider_proof = inner_decider_prover.construct_proof(); + + // Create a decider verifier circuit for recursively verifying the decider proof + OuterBuilder outer_decider_circuit; + DeciderRecursiveVerifier decider_verifier{ &outer_decider_circuit }; + auto pairing_points = decider_verifier.verify_proof(inner_decider_proof); + info("Decider Recursive Verifier: num gates = ", outer_decider_circuit.num_gates); + // Check for a failure flag in the recursive verifier circuit + EXPECT_EQ(outer_decider_circuit.failed(), false) << outer_decider_circuit.err(); + + // Perform native verification then perform the pairing on the outputs of the recursive + // decider verifier and check that the result agrees. + DeciderVerifier native_decider_verifier = inner_composer.create_decider_verifier(accumulator); + auto native_result = native_decider_verifier.verify_proof(inner_decider_proof); + auto recursive_result = native_decider_verifier.pcs_verification_key->pairing_check( + pairing_points[0].get_value(), pairing_points[1].get_value()); + EXPECT_EQ(native_result, recursive_result); + + // Ensure that the underlying native and recursive decider verification algorithms agree by ensuring + // the manifests produced are the same. + auto recursive_decider_manifest = decider_verifier.transcript->get_manifest(); + auto native_decider_manifest = native_decider_verifier.transcript->get_manifest(); + for (size_t i = 0; i < recursive_decider_manifest.size(); ++i) { + EXPECT_EQ(recursive_decider_manifest[i], native_decider_manifest[i]); + } -/** - * @brief Ensure that evaluating the perturbator in the recursive folding verifier returns the same result as - * evaluating in Polynomial class. - * - */ -TEST_F(ProtogalaxyRecursiveTest, NewEvaluate) -{ - OuterBuilder builder; - using fr_ct = bn254::ScalarField; - using fr = bn254::ScalarFieldNative; - - std::vector coeffs; - std::vector coeffs_ct; - for (size_t idx = 0; idx < 8; idx++) { - auto el = fr::random_element(); - coeffs.emplace_back(el); - coeffs_ct.emplace_back(fr_ct(&builder, el)); - } - Polynomial poly(coeffs); - fr point = fr::random_element(); - fr_ct point_ct(fr_ct(&builder, point)); - auto res1 = poly.evaluate(point); + // Construct and verify a proof of the recursive decider verifier circuit + { + auto composer = OuterComposer(); + auto instance = composer.create_instance(outer_decider_circuit); + auto prover = composer.create_prover(instance); + auto verifier = composer.create_verifier(instance); + auto proof = prover.construct_proof(); + bool verified = verifier.verify_proof(proof); - auto res2 = FoldingRecursiveVerifier::evaluate_perturbator(coeffs_ct, point_ct); - EXPECT_EQ(res1, res2.get_value()); -} + ASSERT(verified); + } + }; -/** - * @brief Tests a simple recursive fold that is valid works as expected. - * - */ -TEST_F(ProtogalaxyRecursiveTest, RecursiveFoldingTest) -{ - // Create two arbitrary circuits for the first round of folding - InnerBuilder builder1; + static void test_tampered_decider_proof() + { + // Create two arbitrary circuits for the first round of folding + InnerBuilder builder1; - create_inner_circuit(builder1); - InnerBuilder builder2; - builder2.add_public_variable(FF(1)); - create_inner_circuit(builder2); + create_inner_circuit(builder1); + InnerBuilder builder2; + builder2.add_public_variable(FF(1)); + create_inner_circuit(builder2); - InnerComposer inner_composer = InnerComposer(); - auto instance1 = inner_composer.create_instance(builder1); - auto instance2 = inner_composer.create_instance(builder2); - auto instances = std::vector>{ instance1, instance2 }; + InnerComposer inner_composer = InnerComposer(); + auto instance1 = inner_composer.create_instance(builder1); + auto instance2 = inner_composer.create_instance(builder2); + auto instances = std::vector>{ instance1, instance2 }; - fold_and_verify(instances, inner_composer); -} + auto accumulator = fold_and_verify_native(instances, inner_composer); -/** - * @brief Recursively verify two rounds of folding valid circuits and then recursive verify the final decider proof, - * make sure the verifer circuits pass check_circuit(). Ensure that the algorithm of the recursive and native verifiers - * are identical by checking the manifests + // Tamper with the accumulator by changing the target sum + accumulator->target_sum = FF::random_element(); - */ -TEST_F(ProtogalaxyRecursiveTest, FullProtogalaxyRecursiveTest) -{ + // Create a decider proof for the relaxed instance obtained through folding + auto inner_decider_prover = inner_composer.create_decider_prover(accumulator); + auto inner_decider_proof = inner_decider_prover.construct_proof(); - // Create two arbitrary circuits for the first round of folding - InnerBuilder builder1; - - create_inner_circuit(builder1); - InnerBuilder builder2; - builder2.add_public_variable(FF(1)); - create_inner_circuit(builder2); - - InnerComposer inner_composer = InnerComposer(); - auto instance1 = inner_composer.create_instance(builder1); - auto instance2 = inner_composer.create_instance(builder2); - auto instances = std::vector>{ instance1, instance2 }; - - auto accumulator = fold_and_verify(instances, inner_composer); - - // Create another circuit to do a second round of folding - InnerBuilder builder3; - create_inner_circuit(builder3); - auto instance3 = inner_composer.create_instance(builder3); - instances = std::vector>{ accumulator, instance3 }; - - accumulator = fold_and_verify(instances, inner_composer); - - // Create a decider proof for the relaxed instance obtained through folding - auto inner_decider_prover = inner_composer.create_decider_prover(accumulator); - auto inner_decider_proof = inner_decider_prover.construct_proof(); - - // Create a decider verifier circuit for recursively verifying the decider proof - OuterBuilder outer_decider_circuit; - DeciderRecursiveVerifier decider_verifier{ &outer_decider_circuit }; - auto pairing_points = decider_verifier.verify_proof(inner_decider_proof); - info("Decider Recursive Verifier: num gates = ", outer_decider_circuit.num_gates); - // Check for a failure flag in the recursive verifier circuit - EXPECT_EQ(outer_decider_circuit.failed(), false) << outer_decider_circuit.err(); - - // Perform native verification then perform the pairing on the outputs of the recursive - // decider verifier and check that the result agrees. - DeciderVerifier native_decider_verifier = inner_composer.create_decider_verifier(accumulator); - auto native_result = native_decider_verifier.verify_proof(inner_decider_proof); - auto recursive_result = native_decider_verifier.pcs_verification_key->pairing_check(pairing_points[0].get_value(), - pairing_points[1].get_value()); - EXPECT_EQ(native_result, recursive_result); - - // Ensure that the underlying native and recursive decider verification algorithms agree by ensuring - // the manifests produced are the same. - auto recursive_decider_manifest = decider_verifier.transcript->get_manifest(); - auto native_decider_manifest = native_decider_verifier.transcript->get_manifest(); - for (size_t i = 0; i < recursive_decider_manifest.size(); ++i) { - EXPECT_EQ(recursive_decider_manifest[i], native_decider_manifest[i]); - } + // Create a decider verifier circuit for recursively verifying the decider proof + OuterBuilder outer_decider_circuit; + DeciderRecursiveVerifier decider_verifier{ &outer_decider_circuit }; + decider_verifier.verify_proof(inner_decider_proof); + info("Decider Recursive Verifier: num gates = ", outer_decider_circuit.num_gates); + + // We expect the decider circuit check to fail due to the bad proof + EXPECT_FALSE(outer_decider_circuit.check_circuit()); + }; - // Construct and verify a proof of the recursive decider verifier circuit + static void test_tampered_accumulator() { - auto composer = get_outer_composer(); - auto instance = composer.create_instance(outer_decider_circuit); - auto prover = composer.create_prover(instance); - auto verifier = composer.create_verifier(instance); - auto proof = prover.construct_proof(); - bool verified = verifier.verify_proof(proof); - - ASSERT(verified); - } -} + // Create two arbitrary circuits for the first round of folding + InnerBuilder builder1; -TEST_F(ProtogalaxyRecursiveTest, TamperedDeciderProof) -{ - // Create two arbitrary circuits for the first round of folding - InnerBuilder builder1; + create_inner_circuit(builder1); + InnerBuilder builder2; + builder2.add_public_variable(FF(1)); + create_inner_circuit(builder2); + + InnerComposer inner_composer = InnerComposer(); + auto instance1 = inner_composer.create_instance(builder1); + auto instance2 = inner_composer.create_instance(builder2); + auto instances = std::vector>{ instance1, instance2 }; + + auto accumulator = fold_and_verify_native(instances, inner_composer); + + // Create another circuit to do a second round of folding + InnerBuilder builder3; + create_inner_circuit(builder3); + auto instance3 = inner_composer.create_instance(builder3); + + // Tamper with the accumulator + instances = std::vector>{ accumulator, instance3 }; + accumulator->prover_polynomials.w_l[1] = FF::random_element(); - create_inner_circuit(builder1); - InnerBuilder builder2; - builder2.add_public_variable(FF(1)); - create_inner_circuit(builder2); + // Generate a folding proof + auto inner_folding_prover = inner_composer.create_folding_prover(instances); + auto inner_folding_proof = inner_folding_prover.fold_instances(); + + // Create a recursive folding verifier circuit for the folding proof of the two instances + OuterBuilder outer_folding_circuit; + FoldingRecursiveVerifier verifier{ &outer_folding_circuit }; + verifier.verify_folding_proof(inner_folding_proof.folding_data); + EXPECT_EQ(outer_folding_circuit.check_circuit(), false); + }; +}; - InnerComposer inner_composer = InnerComposer(); - auto instance1 = inner_composer.create_instance(builder1); - auto instance2 = inner_composer.create_instance(builder2); - auto instances = std::vector>{ instance1, instance2 }; +using FlavorTypes = testing::Types, + UltraRecursiveFlavor_>; +TYPED_TEST_SUITE(ProtoGalaxyRecursiveTests, FlavorTypes); - auto accumulator = fold_and_verify(instances, inner_composer); +TYPED_TEST(ProtoGalaxyRecursiveTests, InnerCircuit) +{ + TestFixture::test_inner_circuit(); +} + +TYPED_TEST(ProtoGalaxyRecursiveTests, NewEvaluate) +{ + TestFixture::test_new_evaluate(); +} - // Tamper with the accumulator by changing the target sum - accumulator->target_sum = FF::random_element(); +TYPED_TEST(ProtoGalaxyRecursiveTests, RecursiveFoldingTest) +{ + TestFixture::test_recursive_folding(); +} - // Create a decider proof for the relaxed instance obtained through folding - auto inner_decider_prover = inner_composer.create_decider_prover(accumulator); - auto inner_decider_proof = inner_decider_prover.construct_proof(); +TYPED_TEST(ProtoGalaxyRecursiveTests, FullProtogalaxyRecursiveTest) +{ - // Create a decider verifier circuit for recursively verifying the decider proof - OuterBuilder outer_decider_circuit; - DeciderRecursiveVerifier decider_verifier{ &outer_decider_circuit }; - decider_verifier.verify_proof(inner_decider_proof); - info("Decider Recursive Verifier: num gates = ", outer_decider_circuit.num_gates); + TestFixture::test_full_protogalaxy_recursive(); +} - // We expect the decider circuit check to fail due to the bad proof - EXPECT_FALSE(outer_decider_circuit.check_circuit()); +TYPED_TEST(ProtoGalaxyRecursiveTests, TamperedDeciderProof) +{ + TestFixture::test_tampered_decider_proof(); } -TEST_F(ProtogalaxyRecursiveTest, TamperedAccumulator) +TYPED_TEST(ProtoGalaxyRecursiveTests, TamperedAccumulator) { - // Create two arbitrary circuits for the first round of folding - InnerBuilder builder1; - - create_inner_circuit(builder1); - InnerBuilder builder2; - builder2.add_public_variable(FF(1)); - create_inner_circuit(builder2); - - InnerComposer inner_composer = InnerComposer(); - auto instance1 = inner_composer.create_instance(builder1); - auto instance2 = inner_composer.create_instance(builder2); - auto instances = std::vector>{ instance1, instance2 }; - - auto accumulator = fold_and_verify(instances, inner_composer); - - // Create another circuit to do a second round of folding - InnerBuilder builder3; - create_inner_circuit(builder3); - auto instance3 = inner_composer.create_instance(builder3); - - // Tamper with the accumulator - instances = std::vector>{ accumulator, instance3 }; - accumulator->prover_polynomials.w_l[1] = FF::random_element(); - - // Generate a folding proof - auto inner_folding_prover = inner_composer.create_folding_prover(instances); - auto inner_folding_proof = inner_folding_prover.fold_instances(); - - // Create a recursive folding verifier circuit for the folding proof of the two instances - OuterBuilder outer_folding_circuit; - FoldingRecursiveVerifier verifier{ &outer_folding_circuit }; - verifier.verify_folding_proof(inner_folding_proof.folding_data); - EXPECT_EQ(outer_folding_circuit.check_circuit(), false); + TestFixture::test_tampered_accumulator(); } } // namespace bb::stdlib::recursion::honk \ No newline at end of file diff --git a/barretenberg/cpp/src/barretenberg/stdlib/recursion/honk/verifier/ultra_recursive_verifier.cpp b/barretenberg/cpp/src/barretenberg/stdlib/recursion/honk/verifier/ultra_recursive_verifier.cpp index 8e86410d3d0..b6e6b4edfed 100644 --- a/barretenberg/cpp/src/barretenberg/stdlib/recursion/honk/verifier/ultra_recursive_verifier.cpp +++ b/barretenberg/cpp/src/barretenberg/stdlib/recursion/honk/verifier/ultra_recursive_verifier.cpp @@ -18,11 +18,11 @@ UltraRecursiveVerifier_::UltraRecursiveVerifier_( * */ template -std::array UltraRecursiveVerifier_::verify_proof(const bb::honk::proof& proof) +std::array UltraRecursiveVerifier_::verify_proof(const HonkProof& proof) { - using Sumcheck = ::bb::honk::sumcheck::SumcheckVerifier; + using Sumcheck = ::bb::SumcheckVerifier; using Curve = typename Flavor::Curve; - using ZeroMorph = ::bb::honk::pcs::zeromorph::ZeroMorphVerifier_; + using ZeroMorph = ::bb::ZeroMorphVerifier_; using VerifierCommitments = typename Flavor::VerifierCommitments; using CommitmentLabels = typename Flavor::CommitmentLabels; using RelationParams = ::bb::RelationParameters; @@ -86,9 +86,9 @@ std::array UltraRecursiveVerifier_::ve transcript->template receive_from_prover(commitment_labels.lookup_inverses); } - const FF public_input_delta = bb::honk::compute_public_input_delta( + const FF public_input_delta = compute_public_input_delta( public_inputs, beta, gamma, circuit_size, static_cast(pub_inputs_offset.get_value())); - const FF lookup_grand_product_delta = bb::honk::compute_lookup_grand_product_delta(beta, gamma, circuit_size); + const FF lookup_grand_product_delta = compute_lookup_grand_product_delta(beta, gamma, circuit_size); relation_parameters.beta = beta; relation_parameters.gamma = gamma; @@ -124,8 +124,8 @@ std::array UltraRecursiveVerifier_::ve return pairing_points; } -template class UltraRecursiveVerifier_>; -template class UltraRecursiveVerifier_>; -template class UltraRecursiveVerifier_>; -template class UltraRecursiveVerifier_>; +template class UltraRecursiveVerifier_>; +template class UltraRecursiveVerifier_>; +template class UltraRecursiveVerifier_>; +template class UltraRecursiveVerifier_>; } // namespace bb::stdlib::recursion::honk diff --git a/barretenberg/cpp/src/barretenberg/stdlib/recursion/honk/verifier/ultra_recursive_verifier.hpp b/barretenberg/cpp/src/barretenberg/stdlib/recursion/honk/verifier/ultra_recursive_verifier.hpp index 00bb9a9c780..5288b699452 100644 --- a/barretenberg/cpp/src/barretenberg/stdlib/recursion/honk/verifier/ultra_recursive_verifier.hpp +++ b/barretenberg/cpp/src/barretenberg/stdlib/recursion/honk/verifier/ultra_recursive_verifier.hpp @@ -23,7 +23,7 @@ template class UltraRecursiveVerifier_ { // TODO(luke): Eventually this will return something like aggregation_state but I'm simplifying for now until we // determine the exact interface. Simply returns the two pairing points. - PairingPoints verify_proof(const bb::honk::proof& proof); + PairingPoints verify_proof(const HonkProof& proof); std::shared_ptr key; std::map commitments; diff --git a/barretenberg/cpp/src/barretenberg/stdlib/recursion/honk/verifier/verifier.test.cpp b/barretenberg/cpp/src/barretenberg/stdlib/recursion/honk/verifier/verifier.test.cpp index 3ac3f72678b..7203a67a2c2 100644 --- a/barretenberg/cpp/src/barretenberg/stdlib/recursion/honk/verifier/verifier.test.cpp +++ b/barretenberg/cpp/src/barretenberg/stdlib/recursion/honk/verifier/verifier.test.cpp @@ -19,10 +19,8 @@ namespace bb::stdlib::recursion::honk { template class RecursiveVerifierTest : public testing::Test { // Define types relevant for testing - using UltraFlavor = ::bb::honk::flavor::Ultra; - using GoblinUltraFlavor = ::bb::honk::flavor::GoblinUltra; - using UltraComposer = ::bb::honk::UltraComposer_; - using GoblinUltraComposer = ::bb::honk::UltraComposer_; + using UltraComposer = UltraComposer_; + using GoblinUltraComposer = UltraComposer_; using InnerFlavor = UltraFlavor; using InnerComposer = UltraComposer; @@ -32,7 +30,7 @@ template class RecursiveVerifierTest : public testing::Te using FF = InnerFlavor::FF; // Types for recursive verifier circuit - using RecursiveFlavor = ::bb::honk::flavor::UltraRecursive_; + using RecursiveFlavor = UltraRecursiveFlavor_; using RecursiveVerifier = UltraRecursiveVerifier_; using OuterBuilder = BuilderType; using VerificationKey = typename RecursiveVerifier::VerificationKey; diff --git a/barretenberg/cpp/src/barretenberg/sumcheck/instance/instances.hpp b/barretenberg/cpp/src/barretenberg/sumcheck/instance/instances.hpp index d8262e40d8f..db792938bd5 100644 --- a/barretenberg/cpp/src/barretenberg/sumcheck/instance/instances.hpp +++ b/barretenberg/cpp/src/barretenberg/sumcheck/instance/instances.hpp @@ -2,7 +2,7 @@ #include "barretenberg/sumcheck/instance/prover_instance.hpp" #include "barretenberg/sumcheck/instance/verifier_instance.hpp" -namespace bb::honk { +namespace bb { template struct ProverInstances_ { public: @@ -105,4 +105,4 @@ template struct VerifierInstances_ { std::generate(_data.begin(), _data.end(), []() { return std::make_unique(); }); }; }; -} // namespace bb::honk +} // namespace bb diff --git a/barretenberg/cpp/src/barretenberg/sumcheck/instance/prover_instance.cpp b/barretenberg/cpp/src/barretenberg/sumcheck/instance/prover_instance.cpp index 9bb8ebddc69..5479420510d 100644 --- a/barretenberg/cpp/src/barretenberg/sumcheck/instance/prover_instance.cpp +++ b/barretenberg/cpp/src/barretenberg/sumcheck/instance/prover_instance.cpp @@ -5,7 +5,7 @@ #include "barretenberg/proof_system/library/grand_product_delta.hpp" #include "barretenberg/proof_system/library/grand_product_library.hpp" -namespace bb::honk { +namespace bb { /** * @brief Helper method to compute quantities like total number of gates and dyadic circuit size * @@ -407,7 +407,7 @@ void ProverInstance_::compute_logderivative_inverse(FF beta, FF gamma) relation_parameters.gamma = gamma; // Compute permutation and lookup grand product polynomials - logderivative_library::compute_logderivative_inverse( + bb::compute_logderivative_inverse( prover_polynomials, relation_parameters, proving_key->circuit_size); } @@ -422,10 +422,10 @@ template void ProverInstance_::compute_grand_product_poly relation_parameters.lookup_grand_product_delta = lookup_grand_product_delta; // Compute permutation and lookup grand product polynomials - grand_product_library::compute_grand_products(proving_key, prover_polynomials, relation_parameters); + compute_grand_products(proving_key, prover_polynomials, relation_parameters); } -template class ProverInstance_; -template class ProverInstance_; +template class ProverInstance_; +template class ProverInstance_; -} // namespace bb::honk +} // namespace bb diff --git a/barretenberg/cpp/src/barretenberg/sumcheck/instance/prover_instance.hpp b/barretenberg/cpp/src/barretenberg/sumcheck/instance/prover_instance.hpp index 74106338322..3ab3a2da938 100644 --- a/barretenberg/cpp/src/barretenberg/sumcheck/instance/prover_instance.hpp +++ b/barretenberg/cpp/src/barretenberg/sumcheck/instance/prover_instance.hpp @@ -5,7 +5,7 @@ #include "barretenberg/proof_system/composer/composer_lib.hpp" #include "barretenberg/relations/relation_parameters.hpp" -namespace bb::honk { +namespace bb { /** * @brief An Instance is normally constructed from a finalized circuit and it's role is to compute all the polynomials * involved in creating a proof and, if requested, the verification key. @@ -107,4 +107,4 @@ template class ProverInstance_ { void add_plookup_memory_records_to_wire_4(FF); }; -} // namespace bb::honk +} // namespace bb diff --git a/barretenberg/cpp/src/barretenberg/sumcheck/instance/prover_instance.test.cpp b/barretenberg/cpp/src/barretenberg/sumcheck/instance/prover_instance.test.cpp index 86c51e5ed1c..1c9e58e5811 100644 --- a/barretenberg/cpp/src/barretenberg/sumcheck/instance/prover_instance.test.cpp +++ b/barretenberg/cpp/src/barretenberg/sumcheck/instance/prover_instance.test.cpp @@ -6,7 +6,6 @@ #include "barretenberg/srs/factories/file_crs_factory.hpp" #include using namespace bb; -using namespace bb::honk; template class InstanceTests : public testing::Test { using FF = typename Flavor::FF; @@ -81,7 +80,7 @@ template class InstanceTests : public testing::Test { }; }; -using FlavorTypes = testing::Types; +using FlavorTypes = testing::Types; TYPED_TEST_SUITE(InstanceTests, FlavorTypes); TYPED_TEST(InstanceTests, SortedListAccumulator) diff --git a/barretenberg/cpp/src/barretenberg/sumcheck/instance/verifier_instance.hpp b/barretenberg/cpp/src/barretenberg/sumcheck/instance/verifier_instance.hpp index 05a6a7444e2..9ba56880f84 100644 --- a/barretenberg/cpp/src/barretenberg/sumcheck/instance/verifier_instance.hpp +++ b/barretenberg/cpp/src/barretenberg/sumcheck/instance/verifier_instance.hpp @@ -2,7 +2,7 @@ #include "barretenberg/flavor/flavor.hpp" #include "barretenberg/relations/relation_parameters.hpp" -namespace bb::honk { +namespace bb { template class VerifierInstance_ { public: using FF = typename Flavor::FF; @@ -28,4 +28,4 @@ template class VerifierInstance_ { WitnessCommitments witness_commitments; CommitmentLabels commitment_labels; }; -} // namespace bb::honk \ No newline at end of file +} // namespace bb \ No newline at end of file diff --git a/barretenberg/cpp/src/barretenberg/sumcheck/partial_evaluation.test.cpp b/barretenberg/cpp/src/barretenberg/sumcheck/partial_evaluation.test.cpp index 83c5084988a..f10e968e6c8 100644 --- a/barretenberg/cpp/src/barretenberg/sumcheck/partial_evaluation.test.cpp +++ b/barretenberg/cpp/src/barretenberg/sumcheck/partial_evaluation.test.cpp @@ -3,11 +3,13 @@ #include -using namespace bb::honk::sumcheck; +using namespace bb; +namespace { template class PartialEvaluationTests : public testing::Test {}; -using Flavors = testing::Types; +using Flavors = testing::Types; +} // namespace TYPED_TEST_SUITE(PartialEvaluationTests, Flavors); diff --git a/barretenberg/cpp/src/barretenberg/sumcheck/sumcheck.hpp b/barretenberg/cpp/src/barretenberg/sumcheck/sumcheck.hpp index 7f32a7b9fc7..e3829102c87 100644 --- a/barretenberg/cpp/src/barretenberg/sumcheck/sumcheck.hpp +++ b/barretenberg/cpp/src/barretenberg/sumcheck/sumcheck.hpp @@ -5,7 +5,7 @@ #include "barretenberg/transcript/transcript.hpp" #include "sumcheck_round.hpp" -namespace bb::honk::sumcheck { +namespace bb { template class SumcheckProver { @@ -257,4 +257,4 @@ template class SumcheckVerifier { return SumcheckOutput{ multivariate_challenge, purported_evaluations, verified }; }; }; -} // namespace bb::honk::sumcheck +} // namespace bb diff --git a/barretenberg/cpp/src/barretenberg/sumcheck/sumcheck.test.cpp b/barretenberg/cpp/src/barretenberg/sumcheck/sumcheck.test.cpp index 81a58a3f169..ccb952dc19f 100644 --- a/barretenberg/cpp/src/barretenberg/sumcheck/sumcheck.test.cpp +++ b/barretenberg/cpp/src/barretenberg/sumcheck/sumcheck.test.cpp @@ -11,10 +11,11 @@ #include "barretenberg/ultra_honk/ultra_composer.hpp" #include + using namespace bb; -using namespace bb::honk; -using namespace bb::honk::sumcheck; -using Flavor = honk::flavor::Ultra; + +namespace { +using Flavor = UltraFlavor; using FF = typename Flavor::FF; using ProverPolynomials = typename Flavor::ProverPolynomials; using RelationSeparator = Flavor::RelationSeparator; @@ -37,6 +38,7 @@ ProverPolynomials construct_ultra_full_polynomials(auto& input_polynomials) } return full_polynomials; } +} // namespace class SumcheckTests : public ::testing::Test { protected: diff --git a/barretenberg/cpp/src/barretenberg/sumcheck/sumcheck_output.hpp b/barretenberg/cpp/src/barretenberg/sumcheck/sumcheck_output.hpp index ea25b076ff8..65624855545 100644 --- a/barretenberg/cpp/src/barretenberg/sumcheck/sumcheck_output.hpp +++ b/barretenberg/cpp/src/barretenberg/sumcheck/sumcheck_output.hpp @@ -4,7 +4,7 @@ #include #include -namespace bb::honk::sumcheck { +namespace bb { /** * @brief Contains the multi-linear evaluations of the polynomials at the challenge point 'u'. @@ -20,4 +20,4 @@ template struct SumcheckOutput { // Whether or not the claimed multilinear evaluations and final sumcheck evaluation have been confirmed std::optional verified = false; // optional b/c this struct is shared by the Prover/Verifier }; -} // namespace bb::honk::sumcheck +} // namespace bb diff --git a/barretenberg/cpp/src/barretenberg/sumcheck/sumcheck_round.hpp b/barretenberg/cpp/src/barretenberg/sumcheck/sumcheck_round.hpp index 4b06970542f..5e9edef2f96 100644 --- a/barretenberg/cpp/src/barretenberg/sumcheck/sumcheck_round.hpp +++ b/barretenberg/cpp/src/barretenberg/sumcheck/sumcheck_round.hpp @@ -7,7 +7,7 @@ #include "barretenberg/relations/relation_types.hpp" #include "barretenberg/relations/utils.hpp" -namespace bb::honk::sumcheck { +namespace bb { /* Notation: The polynomial P(X0, X1) that is the low-degree extension of its values vij = P(i,j) @@ -335,4 +335,4 @@ template class SumcheckVerifierRound { return output; } }; -} // namespace bb::honk::sumcheck +} // namespace bb diff --git a/barretenberg/cpp/src/barretenberg/sumcheck/sumcheck_round.test.cpp b/barretenberg/cpp/src/barretenberg/sumcheck/sumcheck_round.test.cpp index 5091717988e..98381ca823e 100644 --- a/barretenberg/cpp/src/barretenberg/sumcheck/sumcheck_round.test.cpp +++ b/barretenberg/cpp/src/barretenberg/sumcheck/sumcheck_round.test.cpp @@ -3,16 +3,8 @@ #include "barretenberg/relations/utils.hpp" #include -using namespace bb; -using namespace bb::honk; -using namespace bb::honk::sumcheck; - -using bb::BarycentricData; -using bb::Univariate; -using Flavor = flavor::Ultra; -using FF = typename Flavor::FF; -using Utils = RelationUtils; +using namespace bb; /** * @brief Test SumcheckRound functions for operations on tuples (and tuples of tuples) of Univariates @@ -20,7 +12,7 @@ using Utils = RelationUtils; */ TEST(SumcheckRound, SumcheckTupleOfTuplesOfUnivariates) { - using Flavor = honk::flavor::Ultra; + using Flavor = UltraFlavor; using FF = typename Flavor::FF; using RelationSeparator = typename Flavor::RelationSeparator; @@ -38,7 +30,7 @@ TEST(SumcheckRound, SumcheckTupleOfTuplesOfUnivariates) challenge[0] = 5; challenge[1] = challenge[0].sqr(); FF running_challenge = 1; - Utils::scale_univariates(tuple_of_tuples, challenge, running_challenge); + RelationUtils::scale_univariates(tuple_of_tuples, challenge, running_challenge); // Use extend_and_batch_univariates to extend to MAX_LENGTH then accumulate PowPolynomial pow_polynomial({ 1 }); @@ -54,7 +46,7 @@ TEST(SumcheckRound, SumcheckTupleOfTuplesOfUnivariates) EXPECT_EQ(result, result_expected); // Reinitialize univariate accumulators to zero - Utils::zero_univariates(tuple_of_tuples); + RelationUtils::zero_univariates(tuple_of_tuples); // Check that reinitialization was successful Univariate expected_1({ 0, 0, 0 }); @@ -71,7 +63,7 @@ TEST(SumcheckRound, SumcheckTupleOfTuplesOfUnivariates) */ TEST(SumcheckRound, TuplesOfEvaluationArrays) { - using Flavor = honk::flavor::Ultra; + using Flavor = UltraFlavor; using Utils = RelationUtils; using FF = typename Flavor::FF; using RelationSeparator = typename Flavor::RelationSeparator; @@ -111,7 +103,7 @@ TEST(SumcheckRound, TuplesOfEvaluationArrays) */ TEST(SumcheckRound, AddTuplesOfTuplesOfUnivariates) { - using Flavor = honk::flavor::Ultra; + using Flavor = UltraFlavor; using FF = typename Flavor::FF; // Define some arbitrary univariates @@ -133,7 +125,7 @@ TEST(SumcheckRound, AddTuplesOfTuplesOfUnivariates) auto tuple_of_tuples_2 = std::make_tuple(std::make_tuple(univariate_4), std::make_tuple(univariate_5, univariate_6)); - Utils::add_nested_tuples(tuple_of_tuples_1, tuple_of_tuples_2); + RelationUtils::add_nested_tuples(tuple_of_tuples_1, tuple_of_tuples_2); EXPECT_EQ(std::get<0>(std::get<0>(tuple_of_tuples_1)), expected_sum_1); EXPECT_EQ(std::get<0>(std::get<1>(tuple_of_tuples_1)), expected_sum_2); diff --git a/barretenberg/cpp/src/barretenberg/transcript/transcript.hpp b/barretenberg/cpp/src/barretenberg/transcript/transcript.hpp index aaa3b193d98..b94e18c13d2 100644 --- a/barretenberg/cpp/src/barretenberg/transcript/transcript.hpp +++ b/barretenberg/cpp/src/barretenberg/transcript/transcript.hpp @@ -10,12 +10,12 @@ // #define LOG_CHALLENGES // #define LOG_INTERACTIONS -namespace bb::honk { +namespace bb { template -concept Loggable = (std::same_as || std::same_as || - std::same_as || std::same_as || - std::same_as); +concept Loggable = + (std::same_as || std::same_as || std::same_as || + std::same_as || std::same_as); // class TranscriptManifest; class TranscriptManifest { @@ -66,7 +66,7 @@ class BaseTranscript { public: using Fr = bb::fr; using Poseidon2Params = crypto::Poseidon2Bn254ScalarFieldParams; - using Proof = honk::proof; + using Proof = HonkProof; BaseTranscript() = default; @@ -368,4 +368,4 @@ template std::array challenges_to_fie std::move(arr.begin(), arr.end(), result.begin()); return result; } -} // namespace bb::honk +} // namespace bb diff --git a/barretenberg/cpp/src/barretenberg/transcript/transcript.test.cpp b/barretenberg/cpp/src/barretenberg/transcript/transcript.test.cpp index 05ff79c73e5..2d70ad4a24f 100644 --- a/barretenberg/cpp/src/barretenberg/transcript/transcript.test.cpp +++ b/barretenberg/cpp/src/barretenberg/transcript/transcript.test.cpp @@ -6,7 +6,7 @@ using namespace bb; using FF = fr; using Fr = fr; using Fq = fq; -using Transcript = honk::BaseTranscript; +using Transcript = BaseTranscript; /** * @brief Test sending, receiving, and exporting proofs diff --git a/barretenberg/cpp/src/barretenberg/translator_vm/goblin_translator_composer.cpp b/barretenberg/cpp/src/barretenberg/translator_vm/goblin_translator_composer.cpp index 64846fcc7bb..50b111ef9bc 100644 --- a/barretenberg/cpp/src/barretenberg/translator_vm/goblin_translator_composer.cpp +++ b/barretenberg/cpp/src/barretenberg/translator_vm/goblin_translator_composer.cpp @@ -11,18 +11,11 @@ #include "barretenberg/proof_system/composer/composer_lib.hpp" #include "barretenberg/proof_system/composer/permutation_lib.hpp" -namespace bb::honk { -using Flavor = honk::flavor::GoblinTranslator; -using Curve = typename Flavor::Curve; -using FF = typename Flavor::FF; -using CircuitBuilder = typename Flavor::CircuitBuilder; -using ProvingKey = typename Flavor::ProvingKey; -using VerificationKey = typename Flavor::VerificationKey; -using PCS = typename Flavor::PCS; -using CommitmentKey = typename Flavor::CommitmentKey; -using VerifierCommitmentKey = typename Flavor::VerifierCommitmentKey; -using Polynomial = typename Flavor::Polynomial; -using Transcript = typename Flavor::Transcript; +namespace { +using Flavor = bb::GoblinTranslatorFlavor; +} // namespace + +namespace bb { /** * @brief Helper method to compute quantities like total number of gates and dyadic circuit size @@ -56,16 +49,16 @@ void GoblinTranslatorComposer::compute_circuit_size_parameters(CircuitBuilder& c * @return std::vector * */ -std::vector construct_wire_polynomials_base_goblin_translator(const CircuitBuilder& circuit_builder, - const size_t dyadic_circuit_size) +std::vector construct_wire_polynomials_base_goblin_translator( + const typename Flavor::CircuitBuilder& circuit_builder, const size_t dyadic_circuit_size) { const size_t num_gates = circuit_builder.num_gates; - std::vector wire_polynomials; + std::vector wire_polynomials; // Populate the wire polynomials with values from conventional wires for (size_t wire_idx = 0; wire_idx < Flavor::NUM_WIRES; ++wire_idx) { // Expect all values to be set to 0 initially - Polynomial w_lagrange(dyadic_circuit_size); + typename Flavor::Polynomial w_lagrange(dyadic_circuit_size); // Insert conventional gate wire values into the wire polynomial for (size_t i = 0; i < num_gates; ++i) { @@ -176,12 +169,12 @@ void GoblinTranslatorComposer::compute_witness(CircuitBuilder& circuit_builder) // We construct concatenated versions of range constraint polynomials, where several polynomials are concatenated // into one. These polynomials are not commited to. - bb::honk::permutation_library::compute_concatenated_polynomials(proving_key.get()); + bb::compute_concatenated_polynomials(proving_key.get()); // We also contruct ordered polynomials, which have the same values as concatenated ones + enough values to bridge // the range from 0 to maximum range defined by the range constraint. - bb::honk::permutation_library::compute_goblin_translator_range_constraint_ordered_polynomials( - proving_key.get(), mini_circuit_dyadic_size); + bb::compute_goblin_translator_range_constraint_ordered_polynomials(proving_key.get(), + mini_circuit_dyadic_size); computed_witness = true; } @@ -265,13 +258,11 @@ std::shared_ptr GoblinTranslatorComposer::compute_p // Compute polynomials with odd and even indices set to 1 up to the minicircuit margin + lagrange polynomials at // second and second to last indices in the minicircuit - bb::honk::permutation_library::compute_lagrange_polynomials_for_goblin_translator(proving_key.get(), - mini_circuit_dyadic_size); + bb::compute_lagrange_polynomials_for_goblin_translator(proving_key.get(), mini_circuit_dyadic_size); // Compute the numerator for the permutation argument with several repetitions of steps bridging 0 and maximum range // constraint - bb::honk::permutation_library::compute_extra_range_constraint_numerator(proving_key.get(), - dyadic_circuit_size); + bb::compute_extra_range_constraint_numerator(proving_key.get(), dyadic_circuit_size); return proving_key; } @@ -282,7 +273,7 @@ std::shared_ptr GoblinTranslatorComposer::compute_p * @return Pointer to created circuit verification key. * */ -std::shared_ptr GoblinTranslatorComposer::compute_verification_key( +std::shared_ptr GoblinTranslatorComposer::compute_verification_key( const CircuitBuilder& circuit_builder) { if (verification_key) { @@ -307,4 +298,4 @@ std::shared_ptr GoblinTranslatorComposer::compute_verification_ return verification_key; } -} // namespace bb::honk +} // namespace bb diff --git a/barretenberg/cpp/src/barretenberg/translator_vm/goblin_translator_composer.hpp b/barretenberg/cpp/src/barretenberg/translator_vm/goblin_translator_composer.hpp index 55e2ed944ba..9117a03a405 100644 --- a/barretenberg/cpp/src/barretenberg/translator_vm/goblin_translator_composer.hpp +++ b/barretenberg/cpp/src/barretenberg/translator_vm/goblin_translator_composer.hpp @@ -7,10 +7,10 @@ #include "barretenberg/translator_vm/goblin_translator_prover.hpp" #include "barretenberg/translator_vm/goblin_translator_verifier.hpp" -namespace bb::honk { +namespace bb { class GoblinTranslatorComposer { public: - using Flavor = honk::flavor::GoblinTranslator; + using Flavor = GoblinTranslatorFlavor; using Curve = typename Flavor::Curve; using CircuitBuilder = typename Flavor::CircuitBuilder; using ProvingKey = typename Flavor::ProvingKey; @@ -39,7 +39,7 @@ class GoblinTranslatorComposer { size_t dyadic_circuit_size = 0; // final power-of-2 circuit size size_t mini_circuit_dyadic_size = 0; // The size of the small circuit that contains non-range constraint relations - // We only need the standard crs factory. GoblinTranslator is not supposed to be used with Grumpkin + // We only need the standard crs factory. GoblinTranslatorFlavor is not supposed to be used with Grumpkin GoblinTranslatorComposer() { crs_factory_ = bb::srs::get_crs_factory(); } GoblinTranslatorComposer(std::shared_ptr p_key, std::shared_ptr v_key) @@ -71,4 +71,4 @@ class GoblinTranslatorComposer { return commitment_key; }; }; -} // namespace bb::honk \ No newline at end of file +} // namespace bb \ No newline at end of file diff --git a/barretenberg/cpp/src/barretenberg/translator_vm/goblin_translator_composer.test.cpp b/barretenberg/cpp/src/barretenberg/translator_vm/goblin_translator_composer.test.cpp index 7221bab8ff5..05850f7366a 100644 --- a/barretenberg/cpp/src/barretenberg/translator_vm/goblin_translator_composer.test.cpp +++ b/barretenberg/cpp/src/barretenberg/translator_vm/goblin_translator_composer.test.cpp @@ -8,20 +8,18 @@ #include using namespace bb; -using namespace bb::honk; -using CircuitBuilder = flavor::GoblinTranslator::CircuitBuilder; -using Transcript = flavor::GoblinTranslator::Transcript; -using OpQueue = ECCOpQueue; namespace { +using CircuitBuilder = GoblinTranslatorFlavor::CircuitBuilder; +using Transcript = GoblinTranslatorFlavor::Transcript; +using OpQueue = ECCOpQueue; auto& engine = numeric::get_debug_randomness(); -} std::vector add_variables(auto& circuit_constructor, std::vector variables) { std::vector res; - for (size_t i = 0; i < variables.size(); i++) { - res.emplace_back(circuit_constructor.add_variable(variables[i])); + for (fr& variable : variables) { + res.emplace_back(circuit_constructor.add_variable(variable)); } return res; } @@ -39,6 +37,7 @@ class GoblinTranslatorComposerTests : public ::testing::Test { protected: static void SetUpTestSuite() { bb::srs::init_crs_factory("../srs_db/ignition"); } }; +} // namespace /** * @brief Test simple circuit with public inputs diff --git a/barretenberg/cpp/src/barretenberg/translator_vm/goblin_translator_prover.cpp b/barretenberg/cpp/src/barretenberg/translator_vm/goblin_translator_prover.cpp index da407ae15bd..e6b1e89a963 100644 --- a/barretenberg/cpp/src/barretenberg/translator_vm/goblin_translator_prover.cpp +++ b/barretenberg/cpp/src/barretenberg/translator_vm/goblin_translator_prover.cpp @@ -5,7 +5,7 @@ #include "barretenberg/proof_system/library/grand_product_library.hpp" #include "barretenberg/sumcheck/sumcheck.hpp" -namespace bb::honk { +namespace bb { /** * Create GoblinTranslatorProver from proving key, witness and manifest. @@ -126,7 +126,7 @@ void GoblinTranslatorProver::execute_grand_product_computation_round() }; } // Compute constraint permutation grand product - grand_product_library::compute_grand_products(key, prover_polynomials, relation_parameters); + compute_grand_products(key, prover_polynomials, relation_parameters); transcript->send_to_verifier(commitment_labels.z_perm, commitment_key->commit(key->z_perm)); } @@ -137,7 +137,7 @@ void GoblinTranslatorProver::execute_grand_product_computation_round() */ void GoblinTranslatorProver::execute_relation_check_rounds() { - using Sumcheck = sumcheck::SumcheckProver; + using Sumcheck = SumcheckProver; auto sumcheck = Sumcheck(key->circuit_size, transcript); FF alpha = transcript->get_challenge("Sumcheck:alpha"); @@ -155,7 +155,7 @@ void GoblinTranslatorProver::execute_relation_check_rounds() * */ void GoblinTranslatorProver::execute_zeromorph_rounds() { - using ZeroMorph = pcs::zeromorph::ZeroMorphProver_; + using ZeroMorph = ZeroMorphProver_; ZeroMorph::prove(prover_polynomials.get_unshifted(), prover_polynomials.get_to_be_shifted(), sumcheck_output.claimed_evaluations.get_unshifted(), @@ -168,13 +168,13 @@ void GoblinTranslatorProver::execute_zeromorph_rounds() prover_polynomials.get_concatenation_groups()); } -honk::proof& GoblinTranslatorProver::export_proof() +HonkProof& GoblinTranslatorProver::export_proof() { proof = transcript->export_proof(); return proof; } -honk::proof& GoblinTranslatorProver::construct_proof() +HonkProof& GoblinTranslatorProver::construct_proof() { // Add circuit size public input size and public inputs to transcript. execute_preamble_round(); @@ -197,4 +197,4 @@ honk::proof& GoblinTranslatorProver::construct_proof() return export_proof(); } -} // namespace bb::honk +} // namespace bb diff --git a/barretenberg/cpp/src/barretenberg/translator_vm/goblin_translator_prover.hpp b/barretenberg/cpp/src/barretenberg/translator_vm/goblin_translator_prover.hpp index 5709f504e9d..4db4f131385 100644 --- a/barretenberg/cpp/src/barretenberg/translator_vm/goblin_translator_prover.hpp +++ b/barretenberg/cpp/src/barretenberg/translator_vm/goblin_translator_prover.hpp @@ -4,13 +4,13 @@ #include "barretenberg/relations/relation_parameters.hpp" #include "barretenberg/sumcheck/sumcheck_output.hpp" -namespace bb::honk { +namespace bb { -// We won't compile this class with honk::flavor::Standard, but we will like want to compile it (at least for testing) +// We won't compile this class with Standard, but we will like want to compile it (at least for testing) // with a flavor that uses the curve Grumpkin, or a flavor that does/does not have zk, etc. class GoblinTranslatorProver { - using Flavor = honk::flavor::GoblinTranslator; + using Flavor = GoblinTranslatorFlavor; using FF = typename Flavor::FF; using BF = typename Flavor::BF; using Commitment = typename Flavor::Commitment; @@ -32,8 +32,8 @@ class GoblinTranslatorProver { BBERG_PROFILE void execute_grand_product_computation_round(); BBERG_PROFILE void execute_relation_check_rounds(); BBERG_PROFILE void execute_zeromorph_rounds(); - honk::proof& export_proof(); - honk::proof& construct_proof(); + HonkProof& export_proof(); + HonkProof& construct_proof(); std::shared_ptr transcript = std::make_shared(); @@ -48,10 +48,10 @@ class GoblinTranslatorProver { std::shared_ptr commitment_key; - sumcheck::SumcheckOutput sumcheck_output; + SumcheckOutput sumcheck_output; private: - honk::proof proof; + HonkProof proof; }; -} // namespace bb::honk +} // namespace bb diff --git a/barretenberg/cpp/src/barretenberg/translator_vm/goblin_translator_verifier.cpp b/barretenberg/cpp/src/barretenberg/translator_vm/goblin_translator_verifier.cpp index b83f0b449a8..6165e4f99d9 100644 --- a/barretenberg/cpp/src/barretenberg/translator_vm/goblin_translator_verifier.cpp +++ b/barretenberg/cpp/src/barretenberg/translator_vm/goblin_translator_verifier.cpp @@ -3,10 +3,7 @@ #include "barretenberg/sumcheck/sumcheck.hpp" #include "barretenberg/transcript/transcript.hpp" -using namespace bb; -using namespace bb::honk::sumcheck; - -namespace bb::honk { +namespace bb { GoblinTranslatorVerifier::GoblinTranslatorVerifier( const std::shared_ptr& verifier_key, @@ -63,9 +60,9 @@ void GoblinTranslatorVerifier::put_translation_data_in_relation_parameters(const }; /** - * @brief This function verifies an GoblinTranslator Honk proof for given program settings. + * @brief This function verifies an GoblinTranslatorFlavor Honk proof for given program settings. */ -bool GoblinTranslatorVerifier::verify_proof(const honk::proof& proof) +bool GoblinTranslatorVerifier::verify_proof(const HonkProof& proof) { batching_challenge_v = transcript->get_challenge("Translation:batching_challenge"); transcript->load_proof(proof); @@ -262,15 +259,14 @@ bool GoblinTranslatorVerifier::verify_proof(const honk::proof& proof) // Execute ZeroMorph rounds. See https://hackmd.io/dlf9xEwhTQyE3hiGbq4FsA?view for a complete description ofthe // unrolled protocol. - auto pairing_points = - pcs::zeromorph::ZeroMorphVerifier_::verify(commitments.get_unshifted(), - commitments.get_to_be_shifted(), - claimed_evaluations.get_unshifted(), - claimed_evaluations.get_shifted(), - multivariate_challenge, - transcript, - commitments.get_concatenation_groups(), - claimed_evaluations.get_concatenated_constraints()); + auto pairing_points = ZeroMorphVerifier_::verify(commitments.get_unshifted(), + commitments.get_to_be_shifted(), + claimed_evaluations.get_unshifted(), + claimed_evaluations.get_shifted(), + multivariate_challenge, + transcript, + commitments.get_concatenation_groups(), + claimed_evaluations.get_concatenated_constraints()); auto verified = pcs_verification_key->pairing_check(pairing_points[0], pairing_points[1]); @@ -312,4 +308,4 @@ bool GoblinTranslatorVerifier::verify_translation(const TranslationEvaluations& return is_value_reconstructed; } -} // namespace bb::honk +} // namespace bb diff --git a/barretenberg/cpp/src/barretenberg/translator_vm/goblin_translator_verifier.hpp b/barretenberg/cpp/src/barretenberg/translator_vm/goblin_translator_verifier.hpp index 977dc9ed8a8..1af71745bfb 100644 --- a/barretenberg/cpp/src/barretenberg/translator_vm/goblin_translator_verifier.hpp +++ b/barretenberg/cpp/src/barretenberg/translator_vm/goblin_translator_verifier.hpp @@ -3,10 +3,10 @@ #include "barretenberg/goblin/translation_evaluations.hpp" #include "barretenberg/honk/proof_system/types/proof.hpp" -namespace bb::honk { +namespace bb { class GoblinTranslatorVerifier { public: - using Flavor = honk::flavor::GoblinTranslator; + using Flavor = GoblinTranslatorFlavor; using FF = typename Flavor::FF; using BF = typename Flavor::BF; using Commitment = typename Flavor::Commitment; @@ -35,7 +35,7 @@ class GoblinTranslatorVerifier { void put_translation_data_in_relation_parameters(const uint256_t& evaluation_input_x, const BF& batching_challenge_v, const uint256_t& accumulated_result); - bool verify_proof(const honk::proof& proof); + bool verify_proof(const HonkProof& proof); bool verify_translation(const TranslationEvaluations& translation_evaluations); }; -} // namespace bb::honk +} // namespace bb diff --git a/barretenberg/cpp/src/barretenberg/ultra_honk/databus_composer.test.cpp b/barretenberg/cpp/src/barretenberg/ultra_honk/databus_composer.test.cpp index 6dcc73e1f7f..bbec6530151 100644 --- a/barretenberg/cpp/src/barretenberg/ultra_honk/databus_composer.test.cpp +++ b/barretenberg/cpp/src/barretenberg/ultra_honk/databus_composer.test.cpp @@ -10,7 +10,6 @@ #include "barretenberg/ultra_honk/ultra_composer.hpp" #include "barretenberg/ultra_honk/ultra_prover.hpp" using namespace bb; -using namespace bb::honk; namespace { auto& engine = numeric::get_debug_randomness(); @@ -23,7 +22,7 @@ class DataBusComposerTests : public ::testing::Test { using Curve = curve::BN254; using FF = Curve::ScalarField; using Point = Curve::AffineElement; - using CommitmentKey = pcs::CommitmentKey; + using CommitmentKey = bb::CommitmentKey; /** * @brief Generate a simple test circuit that includes arithmetic and goblin ecc op gates diff --git a/barretenberg/cpp/src/barretenberg/ultra_honk/goblin_ultra_composer.test.cpp b/barretenberg/cpp/src/barretenberg/ultra_honk/goblin_ultra_composer.test.cpp index ff5d21488c3..6c948a15e2f 100644 --- a/barretenberg/cpp/src/barretenberg/ultra_honk/goblin_ultra_composer.test.cpp +++ b/barretenberg/cpp/src/barretenberg/ultra_honk/goblin_ultra_composer.test.cpp @@ -5,14 +5,15 @@ #include "barretenberg/common/log.hpp" #include "barretenberg/proof_system/circuit_builder/goblin_ultra_circuit_builder.hpp" #include "barretenberg/proof_system/circuit_builder/ultra_circuit_builder.hpp" +#include "barretenberg/ultra_honk/merge_prover.hpp" +#include "barretenberg/ultra_honk/merge_verifier.hpp" #include "barretenberg/ultra_honk/ultra_composer.hpp" #include "barretenberg/ultra_honk/ultra_prover.hpp" + using namespace bb; -using namespace bb::honk; namespace { auto& engine = numeric::get_debug_randomness(); -} class GoblinUltraHonkComposerTests : public ::testing::Test { protected: @@ -21,7 +22,7 @@ class GoblinUltraHonkComposerTests : public ::testing::Test { using Curve = curve::BN254; using FF = Curve::ScalarField; using Point = Curve::AffineElement; - using CommitmentKey = pcs::CommitmentKey; + using CommitmentKey = bb::CommitmentKey; /** * @brief Generate a simple test circuit with some ECC op gates and conventional arithmetic gates @@ -72,16 +73,17 @@ class GoblinUltraHonkComposerTests : public ::testing::Test { * @brief Construct and verify a Goblin ECC op queue merge proof * */ - bool construct_and_verify_merge_proof(auto& composer, auto& op_queue) + bool construct_and_verify_merge_proof(auto& op_queue) { - auto merge_prover = composer.create_merge_prover(op_queue); - auto merge_verifier = composer.create_merge_verifier(); + MergeProver merge_prover{ op_queue }; + MergeVerifier merge_verifier; auto merge_proof = merge_prover.construct_proof(); bool verified = merge_verifier.verify_proof(merge_proof); return verified; } }; +} // namespace /** * @brief Test proof construction/verification for a circuit with ECC op gates, public inputs, and basic arithmetic @@ -108,7 +110,7 @@ TEST_F(GoblinUltraHonkComposerTests, SingleCircuit) EXPECT_TRUE(honk_verified); // Construct and verify Goblin ECC op queue Merge proof - auto merge_verified = construct_and_verify_merge_proof(composer, op_queue); + auto merge_verified = construct_and_verify_merge_proof(op_queue); EXPECT_TRUE(merge_verified); } @@ -135,7 +137,7 @@ TEST_F(GoblinUltraHonkComposerTests, MultipleCircuitsMergeOnly) auto composer = GoblinUltraComposer(); // Construct and verify Goblin ECC op queue Merge proof - auto merge_verified = construct_and_verify_merge_proof(composer, op_queue); + auto merge_verified = construct_and_verify_merge_proof(op_queue); EXPECT_TRUE(merge_verified); } } @@ -195,7 +197,7 @@ TEST_F(GoblinUltraHonkComposerTests, MultipleCircuitsHonkAndMerge) EXPECT_TRUE(honk_verified); // Construct and verify Goblin ECC op queue Merge proof - auto merge_verified = construct_and_verify_merge_proof(composer, op_queue); + auto merge_verified = construct_and_verify_merge_proof(op_queue); EXPECT_TRUE(merge_verified); } diff --git a/barretenberg/cpp/src/barretenberg/ultra_honk/goblin_ultra_transcript.test.cpp b/barretenberg/cpp/src/barretenberg/ultra_honk/goblin_ultra_transcript.test.cpp index 70247e48a0d..a557b138dae 100644 --- a/barretenberg/cpp/src/barretenberg/ultra_honk/goblin_ultra_transcript.test.cpp +++ b/barretenberg/cpp/src/barretenberg/ultra_honk/goblin_ultra_transcript.test.cpp @@ -7,13 +7,12 @@ #include using namespace bb; -using namespace bb::honk; class GoblinUltraTranscriptTests : public ::testing::Test { public: static void SetUpTestSuite() { bb::srs::init_crs_factory("../srs_db/ignition"); } - using Flavor = honk::flavor::GoblinUltra; + using Flavor = GoblinUltraFlavor; using FF = Flavor::FF; /** diff --git a/barretenberg/cpp/src/barretenberg/ultra_honk/merge_prover.cpp b/barretenberg/cpp/src/barretenberg/ultra_honk/merge_prover.cpp index c79fe9a8689..8d39901d419 100644 --- a/barretenberg/cpp/src/barretenberg/ultra_honk/merge_prover.cpp +++ b/barretenberg/cpp/src/barretenberg/ultra_honk/merge_prover.cpp @@ -1,19 +1,20 @@ #include "merge_prover.hpp" -namespace bb::honk { +namespace bb { /** - * Create MergeProver_ + * @brief Create MergeProver + * @details We require an SRS at least as large as the current op queue size in order to commit to the shifted + * per-circuit contribution t_i^{shift} * */ -template -MergeProver_::MergeProver_(const std::shared_ptr& commitment_key, - const std::shared_ptr& op_queue, - const std::shared_ptr& transcript) - : transcript(transcript) - , op_queue(op_queue) - , pcs_commitment_key(commitment_key) -{} +MergeProver::MergeProver(const std::shared_ptr& op_queue) + : op_queue(op_queue) + , pcs_commitment_key(std::make_shared(op_queue->ultra_ops[0].size())) +{ + // Update internal size data in the op queue that allows for extraction of e.g. previous aggregate transcript + op_queue->set_size_data(); +} /** * @brief Prove proper construction of the aggregate Goblin ECC op queue polynomials T_i^(j), j = 1,2,3,4. @@ -26,11 +27,12 @@ MergeProver_::MergeProver_(const std::shared_ptr& commitm * TODO(#746): Prove connection between t_i^{shift}, committed to herein, and t_i, used in the main protocol. See issue * for details (https://github.com/AztecProtocol/barretenberg/issues/746). * - * @tparam Flavor - * @return honk::proof& + * @return honk::proof */ -template honk::proof& MergeProver_::construct_proof() +HonkProof MergeProver::construct_proof() { + transcript = std::make_shared(); + size_t N = op_queue->get_current_size(); // Extract T_i, T_{i-1} @@ -40,14 +42,14 @@ template honk::proof& MergeProver_::construct_proof() ASSERT(T_prev[0].size() > 0); // Construct t_i^{shift} as T_i - T_{i-1} - std::array t_shift; - for (size_t i = 0; i < Flavor::NUM_WIRES; ++i) { + std::array t_shift; + for (size_t i = 0; i < NUM_WIRES; ++i) { t_shift[i] = Polynomial(T_current[i]); t_shift[i] -= T_prev[i]; } // Compute/get commitments [t_i^{shift}], [T_{i-1}], and [T_i] and add to transcript - std::array C_T_current; + std::array C_T_current; for (size_t idx = 0; idx < t_shift.size(); ++idx) { // Get previous transcript commitment [T_{i-1}] from op queue auto C_T_prev = op_queue->ultra_ops_commitments[idx]; @@ -72,20 +74,20 @@ template honk::proof& MergeProver_::construct_proof() // Add univariate opening claims for each polynomial. std::vector opening_claims; // Compute evaluation T_{i-1}(\kappa) - for (size_t idx = 0; idx < Flavor::NUM_WIRES; ++idx) { + for (size_t idx = 0; idx < NUM_WIRES; ++idx) { auto polynomial = Polynomial(T_prev[idx]); auto evaluation = polynomial.evaluate(kappa); transcript->send_to_verifier("T_prev_eval_" + std::to_string(idx + 1), evaluation); opening_claims.emplace_back(OpeningClaim{ polynomial, { kappa, evaluation } }); } // Compute evaluation t_i^{shift}(\kappa) - for (size_t idx = 0; idx < Flavor::NUM_WIRES; ++idx) { + for (size_t idx = 0; idx < NUM_WIRES; ++idx) { auto evaluation = t_shift[idx].evaluate(kappa); transcript->send_to_verifier("t_shift_eval_" + std::to_string(idx + 1), evaluation); opening_claims.emplace_back(OpeningClaim{ t_shift[idx], { kappa, evaluation } }); } // Compute evaluation T_i(\kappa) - for (size_t idx = 0; idx < Flavor::NUM_WIRES; ++idx) { + for (size_t idx = 0; idx < NUM_WIRES; ++idx) { auto polynomial = Polynomial(T_current[idx]); auto evaluation = polynomial.evaluate(kappa); transcript->send_to_verifier("T_current_eval_" + std::to_string(idx + 1), evaluation); @@ -112,11 +114,7 @@ template honk::proof& MergeProver_::construct_proof() auto quotient_commitment = pcs_commitment_key->commit(quotient); transcript->send_to_verifier("KZG:W", quotient_commitment); - proof = transcript->proof_data; - return proof; + return transcript->proof_data; } -template class MergeProver_; -template class MergeProver_; - -} // namespace bb::honk \ No newline at end of file +} // namespace bb diff --git a/barretenberg/cpp/src/barretenberg/ultra_honk/merge_prover.hpp b/barretenberg/cpp/src/barretenberg/ultra_honk/merge_prover.hpp index 8693f77ed8c..a615f9f816c 100644 --- a/barretenberg/cpp/src/barretenberg/ultra_honk/merge_prover.hpp +++ b/barretenberg/cpp/src/barretenberg/ultra_honk/merge_prover.hpp @@ -7,36 +7,33 @@ #include "barretenberg/proof_system/op_queue/ecc_op_queue.hpp" #include "barretenberg/transcript/transcript.hpp" -namespace bb::honk { +namespace bb { /** * @brief Prover class for the Goblin ECC op queue transcript merge protocol * - * @tparam Flavor */ -template class MergeProver_ { - using FF = typename Flavor::FF; - using Polynomial = typename Flavor::Polynomial; - using CommitmentKey = typename Flavor::CommitmentKey; - using Commitment = typename Flavor::Commitment; - using PCS = typename Flavor::PCS; - using Curve = typename Flavor::Curve; - using OpeningClaim = typename pcs::ProverOpeningClaim; - using OpeningPair = typename pcs::OpeningPair; +class MergeProver { + using Curve = curve::BN254; + using FF = Curve::ScalarField; + using Polynomial = polynomial; + using CommitmentKey = bb::CommitmentKey; + using Commitment = Curve::AffineElement; + using PCS = bb::KZG; + using OpeningClaim = typename bb::ProverOpeningClaim; using Transcript = BaseTranscript; public: std::shared_ptr transcript; - std::shared_ptr op_queue; - std::shared_ptr pcs_commitment_key; - explicit MergeProver_(const std::shared_ptr&, - const std::shared_ptr&, - const std::shared_ptr& transcript = std::make_shared()); - BBERG_PROFILE honk::proof& construct_proof(); + explicit MergeProver(const std::shared_ptr&); + + BBERG_PROFILE HonkProof construct_proof(); private: - honk::proof proof; + std::shared_ptr op_queue; + std::shared_ptr pcs_commitment_key; + static constexpr size_t NUM_WIRES = GoblinUltraFlavor::NUM_WIRES; }; -} // namespace bb::honk +} // namespace bb diff --git a/barretenberg/cpp/src/barretenberg/ultra_honk/merge_verifier.cpp b/barretenberg/cpp/src/barretenberg/ultra_honk/merge_verifier.cpp index a50c25a0d57..f8eb261b195 100644 --- a/barretenberg/cpp/src/barretenberg/ultra_honk/merge_verifier.cpp +++ b/barretenberg/cpp/src/barretenberg/ultra_honk/merge_verifier.cpp @@ -1,11 +1,9 @@ #include "merge_verifier.hpp" -namespace bb::honk { +namespace bb { -template -MergeVerifier_::MergeVerifier_() - : transcript(std::make_shared()) - , pcs_verification_key(std::make_unique(0, bb::srs::get_crs_factory())){}; +MergeVerifier::MergeVerifier() + : pcs_verification_key(std::make_unique(0, bb::srs::get_crs_factory())){}; /** * @brief Verify proper construction of the aggregate Goblin ECC op queue polynomials T_i^(j), j = 1,2,3,4. @@ -15,18 +13,17 @@ MergeVerifier_::MergeVerifier_() * M_{i-1}), where the shift magnitude M_{i-1} is the length of T_{i-1}. This protocol verfies that the aggregate op * queue has been constructed correctly via a simple Schwartz-Zippel check. Evaluations are checked via batched KZG. * - * @tparam Flavor - * @return honk::proof& + * @return HonkProof& */ -template bool MergeVerifier_::verify_proof(const honk::proof& proof) +bool MergeVerifier::verify_proof(const HonkProof& proof) { transcript = std::make_shared(proof); // Receive commitments [t_i^{shift}], [T_{i-1}], and [T_i] - std::array C_T_prev; - std::array C_t_shift; - std::array C_T_current; - for (size_t idx = 0; idx < Flavor::NUM_WIRES; ++idx) { + std::array C_T_prev; + std::array C_t_shift; + std::array C_T_current; + for (size_t idx = 0; idx < NUM_WIRES; ++idx) { C_T_prev[idx] = transcript->template receive_from_prover("T_PREV_" + std::to_string(idx + 1)); C_t_shift[idx] = transcript->template receive_from_prover("t_SHIFT_" + std::to_string(idx + 1)); C_T_current[idx] = transcript->template receive_from_prover("T_CURRENT_" + std::to_string(idx + 1)); @@ -35,27 +32,27 @@ template bool MergeVerifier_::verify_proof(const honk: FF kappa = transcript->get_challenge("kappa"); // Receive transcript poly evaluations and add corresponding univariate opening claims {(\kappa, p(\kappa), [p(X)]} - std::array T_prev_evals; - std::array t_shift_evals; - std::array T_current_evals; + std::array T_prev_evals; + std::array t_shift_evals; + std::array T_current_evals; std::vector opening_claims; - for (size_t idx = 0; idx < Flavor::NUM_WIRES; ++idx) { + for (size_t idx = 0; idx < NUM_WIRES; ++idx) { T_prev_evals[idx] = transcript->template receive_from_prover("T_prev_eval_" + std::to_string(idx + 1)); - opening_claims.emplace_back(pcs::OpeningClaim{ { kappa, T_prev_evals[idx] }, C_T_prev[idx] }); + opening_claims.emplace_back(OpeningClaim{ { kappa, T_prev_evals[idx] }, C_T_prev[idx] }); } - for (size_t idx = 0; idx < Flavor::NUM_WIRES; ++idx) { + for (size_t idx = 0; idx < NUM_WIRES; ++idx) { t_shift_evals[idx] = transcript->template receive_from_prover("t_shift_eval_" + std::to_string(idx + 1)); - opening_claims.emplace_back(pcs::OpeningClaim{ { kappa, t_shift_evals[idx] }, C_t_shift[idx] }); + opening_claims.emplace_back(OpeningClaim{ { kappa, t_shift_evals[idx] }, C_t_shift[idx] }); } - for (size_t idx = 0; idx < Flavor::NUM_WIRES; ++idx) { + for (size_t idx = 0; idx < NUM_WIRES; ++idx) { T_current_evals[idx] = transcript->template receive_from_prover("T_current_eval_" + std::to_string(idx + 1)); - opening_claims.emplace_back(pcs::OpeningClaim{ { kappa, T_current_evals[idx] }, C_T_current[idx] }); + opening_claims.emplace_back(OpeningClaim{ { kappa, T_current_evals[idx] }, C_T_current[idx] }); } // Check the identity T_i(\kappa) = T_{i-1}(\kappa) + t_i^{shift}(\kappa). If it fails, return false bool identity_checked = true; - for (size_t idx = 0; idx < Flavor::NUM_WIRES; ++idx) { + for (size_t idx = 0; idx < NUM_WIRES; ++idx) { identity_checked = identity_checked && (T_current_evals[idx] == T_prev_evals[idx] + t_shift_evals[idx]); } @@ -79,7 +76,4 @@ template bool MergeVerifier_::verify_proof(const honk: return identity_checked && verified; } -template class MergeVerifier_; -template class MergeVerifier_; - -} // namespace bb::honk \ No newline at end of file +} // namespace bb diff --git a/barretenberg/cpp/src/barretenberg/ultra_honk/merge_verifier.hpp b/barretenberg/cpp/src/barretenberg/ultra_honk/merge_verifier.hpp index a32d071eb9b..efd95773b6f 100644 --- a/barretenberg/cpp/src/barretenberg/ultra_honk/merge_verifier.hpp +++ b/barretenberg/cpp/src/barretenberg/ultra_honk/merge_verifier.hpp @@ -8,32 +8,30 @@ #include "barretenberg/srs/global_crs.hpp" #include "barretenberg/transcript/transcript.hpp" -namespace bb::honk { +namespace bb { /** * @brief Verifier class for the Goblin ECC op queue transcript merge protocol * - * @tparam Flavor */ -template class MergeVerifier_ { - using FF = typename Flavor::FF; - using Polynomial = typename Flavor::Polynomial; - using CommitmentKey = typename Flavor::CommitmentKey; - using Commitment = typename Flavor::Commitment; - using PCS = typename Flavor::PCS; - using Curve = typename Flavor::Curve; - using OpeningClaim = typename pcs::OpeningClaim; - using VerificationKey = typename Flavor::VerificationKey; - using VerifierCommitmentKey = typename Flavor::VerifierCommitmentKey; - using Transcript = typename Flavor::Transcript; +class MergeVerifier { + using Curve = curve::BN254; + using FF = typename Curve::ScalarField; + using Commitment = typename Curve::AffineElement; + using PCS = bb::KZG; + using OpeningClaim = bb::OpeningClaim; + using VerifierCommitmentKey = bb::VerifierCommitmentKey; + using Transcript = BaseTranscript; public: std::shared_ptr transcript; - std::shared_ptr op_queue; - std::shared_ptr pcs_verification_key; - explicit MergeVerifier_(); - bool verify_proof(const honk::proof& proof); + explicit MergeVerifier(); + bool verify_proof(const HonkProof& proof); + + private: + std::shared_ptr pcs_verification_key; + static constexpr size_t NUM_WIRES = GoblinUltraFlavor::NUM_WIRES; }; -} // namespace bb::honk +} // namespace bb diff --git a/barretenberg/cpp/src/barretenberg/ultra_honk/protogalaxy.test.cpp b/barretenberg/cpp/src/barretenberg/ultra_honk/protogalaxy.test.cpp index 1f41c5325ab..f0237d439f1 100644 --- a/barretenberg/cpp/src/barretenberg/ultra_honk/protogalaxy.test.cpp +++ b/barretenberg/cpp/src/barretenberg/ultra_honk/protogalaxy.test.cpp @@ -1,345 +1,444 @@ +#include "barretenberg/goblin/mock_circuits.hpp" #include "barretenberg/polynomials/pow.hpp" #include "barretenberg/protogalaxy/protogalaxy_prover.hpp" #include "barretenberg/ultra_honk/ultra_composer.hpp" #include + using namespace bb; -using namespace bb::honk; - -using Flavor = flavor::Ultra; -using VerificationKey = Flavor::VerificationKey; -using Instance = ProverInstance_; -using Instances = ProverInstances_; -using ProtoGalaxyProver = ProtoGalaxyProver_; -using FF = Flavor::FF; -using Affine = Flavor::Commitment; -using Projective = Flavor::GroupElement; -using Builder = Flavor::CircuitBuilder; -using ProverPolynomials = Flavor::ProverPolynomials; -using WitnessCommitments = typename Flavor::WitnessCommitments; -using CommitmentKey = Flavor::CommitmentKey; - -const size_t NUM_POLYNOMIALS = Flavor::NUM_ALL_ENTITIES; namespace { -auto& engine = numeric::get_debug_randomness(); -} -// TODO(https://github.com/AztecProtocol/barretenberg/issues/744): make testing utility with functionality shared -// amongst test files in the proof system -Polynomial get_random_polynomial(size_t size) -{ - auto poly = bb::Polynomial(size); - for (auto& coeff : poly) { - coeff = FF::random_element(); - } - return poly; -} -ProverPolynomials construct_ultra_full_polynomials(auto& input_polynomials) -{ - ProverPolynomials full_polynomials; - for (auto [prover_poly, input_poly] : zip_view(full_polynomials.get_all(), input_polynomials)) { - prover_poly = input_poly.share(); - } - return full_polynomials; -} - -std::shared_ptr fold_and_verify(const std::vector>& instances, - UltraComposer& composer, - bool expected_result) -{ - auto folding_prover = composer.create_folding_prover(instances); - auto folding_verifier = composer.create_folding_verifier(); - - auto proof = folding_prover.fold_instances(); - auto next_accumulator = proof.accumulator; - auto res = folding_verifier.verify_folding_proof(proof.folding_data); - EXPECT_EQ(res, expected_result); - return next_accumulator; -} - -void check_accumulator_target_sum_manual(std::shared_ptr& accumulator, bool expected_result) -{ - auto instance_size = accumulator->instance_size; - auto expected_honk_evals = ProtoGalaxyProver::compute_full_honk_evaluations( - accumulator->prover_polynomials, accumulator->alphas, accumulator->relation_parameters); - // Construct pow(\vec{betas*}) as in the paper - auto expected_pows = PowPolynomial(accumulator->gate_challenges); - expected_pows.compute_values(); - - // Compute the corresponding target sum and create a dummy accumulator - auto expected_target_sum = FF(0); - for (size_t i = 0; i < instance_size; i++) { - expected_target_sum += expected_honk_evals[i] * expected_pows[i]; - } - - EXPECT_EQ(accumulator->target_sum == expected_target_sum, expected_result); -} -void decide_and_verify(std::shared_ptr& accumulator, UltraComposer& composer, bool expected_result) -{ - auto decider_prover = composer.create_decider_prover(accumulator); - auto decider_verifier = composer.create_decider_verifier(accumulator); - auto decision = decider_prover.construct_proof(); - auto verified = decider_verifier.verify_proof(decision); - EXPECT_EQ(verified, expected_result); -} +auto& engine = numeric::get_debug_randomness(); -class ProtoGalaxyTests : public ::testing::Test { +template class ProtoGalaxyTests : public testing::Test { public: + using Composer = UltraComposer_; + using VerificationKey = typename Flavor::VerificationKey; + using Instance = ProverInstance_; + using Instances = ProverInstances_; + using ProtoGalaxyProver = ProtoGalaxyProver_; + using FF = typename Flavor::FF; + using Affine = typename Flavor::Commitment; + using Projective = typename Flavor::GroupElement; + using Builder = typename Flavor::CircuitBuilder; + using Polynomial = typename Flavor::Polynomial; + using ProverPolynomials = typename Flavor::ProverPolynomials; + using RelationParameters = bb::RelationParameters; + using WitnessCommitments = typename Flavor::WitnessCommitments; + using CommitmentKey = typename Flavor::CommitmentKey; + using PowPolynomial = bb::PowPolynomial; + static void SetUpTestSuite() { bb::srs::init_crs_factory("../srs_db/ignition"); } -}; -TEST_F(ProtoGalaxyTests, FullHonkEvaluationsValidCircuit) -{ - auto builder = Builder(); - FF a = FF::one(); - uint32_t a_idx = builder.add_public_variable(a); - FF b = FF::one(); - FF c = a + b; - uint32_t b_idx = builder.add_variable(b); - uint32_t c_idx = builder.add_variable(c); - builder.create_add_gate({ a_idx, b_idx, c_idx, 1, 1, -1, 0 }); - builder.create_add_gate({ a_idx, b_idx, c_idx, 1, 1, -1, 0 }); - - auto composer = UltraComposer(); - auto instance = composer.create_instance(builder); - instance->initialize_prover_polynomials(); - - auto eta = FF::random_element(); - auto beta = FF::random_element(); - auto gamma = FF::random_element(); - instance->compute_sorted_accumulator_polynomials(eta); - instance->compute_grand_product_polynomials(beta, gamma); - - for (auto& alpha : instance->alphas) { - alpha = FF::random_element(); + static void construct_circuit(Builder& builder) + { + if constexpr (IsGoblinFlavor) { + GoblinMockCircuits::construct_arithmetic_circuit(builder); + GoblinMockCircuits::construct_goblin_ecc_op_circuit(builder); + + } else { + FF a = FF::random_element(); + FF b = FF::random_element(); + FF c = FF::random_element(); + FF d = a + b + c; + uint32_t a_idx = builder.add_public_variable(a); + uint32_t b_idx = builder.add_variable(b); + uint32_t c_idx = builder.add_variable(c); + uint32_t d_idx = builder.add_variable(d); + + builder.create_big_add_gate({ a_idx, b_idx, c_idx, d_idx, FF(1), FF(1), FF(1), FF(-1), FF(0) }); + } } - auto full_honk_evals = ProtoGalaxyProver::compute_full_honk_evaluations( - instance->prover_polynomials, instance->alphas, instance->relation_parameters); - // Evaluations should be 0 for valid circuit - for (const auto& eval : full_honk_evals) { - EXPECT_EQ(eval, FF(0)); + static ProverPolynomials construct_full_prover_polynomials(auto& input_polynomials) + { + ProverPolynomials full_polynomials; + for (auto [prover_poly, input_poly] : zip_view(full_polynomials.get_all(), input_polynomials)) { + prover_poly = input_poly.share(); + } + return full_polynomials; } -} -TEST_F(ProtoGalaxyTests, PerturbatorCoefficients) -{ - std::vector betas = { FF(5), FF(8), FF(11) }; - std::vector deltas = { FF(2), FF(4), FF(8) }; - std::vector full_honk_evaluations = { FF(1), FF(1), FF(1), FF(1), FF(1), FF(1), FF(1), FF(1) }; - auto perturbator = ProtoGalaxyProver::construct_perturbator_coefficients(betas, deltas, full_honk_evaluations); - std::vector expected_values = { FF(648), FF(936), FF(432), FF(64) }; - EXPECT_EQ(perturbator.size(), 4); // log(instance_size) + 1 - for (size_t i = 0; i < perturbator.size(); i++) { - EXPECT_EQ(perturbator[i], expected_values[i]); - } -} - -TEST_F(ProtoGalaxyTests, PerturbatorPolynomial) -{ - using RelationSeparator = Flavor::RelationSeparator; - const size_t log_instance_size(3); - const size_t instance_size(1 << log_instance_size); - std::array, NUM_POLYNOMIALS> random_polynomials; - for (auto& poly : random_polynomials) { - poly = get_random_polynomial(instance_size); + static std::shared_ptr fold_and_verify(const std::vector>& instances, + Composer& composer, + bool expected_result) + { + auto folding_prover = composer.create_folding_prover(instances); + auto folding_verifier = composer.create_folding_verifier(); + + auto proof = folding_prover.fold_instances(); + auto next_accumulator = proof.accumulator; + auto res = folding_verifier.verify_folding_proof(proof.folding_data); + EXPECT_EQ(res, expected_result); + return next_accumulator; } - auto full_polynomials = construct_ultra_full_polynomials(random_polynomials); - auto relation_parameters = RelationParameters::get_random(); - RelationSeparator alphas; - for (auto& alpha : alphas) { - alpha = FF::random_element(); + + static void check_accumulator_target_sum_manual(std::shared_ptr& accumulator, bool expected_result) + { + auto instance_size = accumulator->instance_size; + auto expected_honk_evals = ProtoGalaxyProver::compute_full_honk_evaluations( + accumulator->prover_polynomials, accumulator->alphas, accumulator->relation_parameters); + // Construct pow(\vec{betas*}) as in the paper + auto expected_pows = PowPolynomial(accumulator->gate_challenges); + expected_pows.compute_values(); + + // Compute the corresponding target sum and create a dummy accumulator + auto expected_target_sum = FF(0); + for (size_t i = 0; i < instance_size; i++) { + expected_target_sum += expected_honk_evals[i] * expected_pows[i]; + } + EXPECT_EQ(accumulator->target_sum == expected_target_sum, expected_result); } - auto full_honk_evals = - ProtoGalaxyProver::compute_full_honk_evaluations(full_polynomials, alphas, relation_parameters); - std::vector betas(log_instance_size); - for (size_t idx = 0; idx < log_instance_size; idx++) { - betas[idx] = FF::random_element(); + static void decide_and_verify(std::shared_ptr& accumulator, Composer& composer, bool expected_result) + { + auto decider_prover = composer.create_decider_prover(accumulator); + auto decider_verifier = composer.create_decider_verifier(accumulator); + auto decider_proof = decider_prover.construct_proof(); + auto verified = decider_verifier.verify_proof(decider_proof); + EXPECT_EQ(verified, expected_result); } - // Construct pow(\vec{betas}) as in the paper - auto pow_beta = bb::PowPolynomial(betas); - pow_beta.compute_values(); + /** + * @brief For a valid circuit, ensures that computing the value of the full UH/UGH relation at each row in its + * execution trace (with the contribution of the linearly dependent one added tot he first row, in case of Goblin) + * will be 0. + * + */ + static void test_full_honk_evaluations_valid_circuit() + { + auto builder = typename Flavor::CircuitBuilder(); + construct_circuit(builder); + + auto composer = Composer(); + auto instance = composer.create_instance(builder); + instance->initialize_prover_polynomials(); + + auto eta = FF::random_element(); + auto beta = FF::random_element(); + auto gamma = FF::random_element(); + instance->compute_sorted_accumulator_polynomials(eta); + if constexpr (IsGoblinFlavor) { + instance->compute_logderivative_inverse(beta, gamma); + } + instance->compute_grand_product_polynomials(beta, gamma); + + for (auto& alpha : instance->alphas) { + alpha = FF::random_element(); + } + auto full_honk_evals = ProtoGalaxyProver::compute_full_honk_evaluations( + instance->prover_polynomials, instance->alphas, instance->relation_parameters); + + // Evaluations should be 0 for valid circuit + for (const auto& eval : full_honk_evals) { + EXPECT_EQ(eval, FF(0)); + } + } - // Compute the corresponding target sum and create a dummy accumulator - auto target_sum = FF(0); - for (size_t i = 0; i < instance_size; i++) { - target_sum += full_honk_evals[i] * pow_beta[i]; + /** + * @brief Check the coefficients of the perturbator computed from dummy \vec{β}, \vec{δ} and f_i(ω) will be the same + * as if computed manually. + * + */ + static void test_pertubator_coefficients() + { + std::vector betas = { FF(5), FF(8), FF(11) }; + std::vector deltas = { FF(2), FF(4), FF(8) }; + std::vector full_honk_evaluations = { FF(1), FF(1), FF(1), FF(1), FF(1), FF(1), FF(1), FF(1) }; + auto perturbator = ProtoGalaxyProver::construct_perturbator_coefficients(betas, deltas, full_honk_evaluations); + std::vector expected_values = { FF(648), FF(936), FF(432), FF(64) }; + EXPECT_EQ(perturbator.size(), 4); // log(instance_size) + 1 + for (size_t i = 0; i < perturbator.size(); i++) { + EXPECT_EQ(perturbator[i], expected_values[i]); + } } - auto accumulator = std::make_shared(); - accumulator->prover_polynomials = std::move(full_polynomials); - accumulator->gate_challenges = betas; - accumulator->target_sum = target_sum; - accumulator->relation_parameters = relation_parameters; - accumulator->alphas = alphas; + /** + * @brief Create a dummy accumulator and ensure coefficient 0 of the computed perturbator is the same as the + * accumulator's target sum. + * + */ + static void test_pertubator_polynomial() + { + using RelationSeparator = typename Flavor::RelationSeparator; + const size_t log_instance_size(3); + const size_t instance_size(1 << log_instance_size); + std::array, Flavor::NUM_ALL_ENTITIES> random_polynomials; + for (auto& poly : random_polynomials) { + poly = bb::Polynomial::random(instance_size); + } + auto full_polynomials = construct_full_prover_polynomials(random_polynomials); + auto relation_parameters = bb::RelationParameters::get_random(); + RelationSeparator alphas; + for (auto& alpha : alphas) { + alpha = FF::random_element(); + } + + auto full_honk_evals = + ProtoGalaxyProver::compute_full_honk_evaluations(full_polynomials, alphas, relation_parameters); + std::vector betas(log_instance_size); + for (size_t idx = 0; idx < log_instance_size; idx++) { + betas[idx] = FF::random_element(); + } + + // Construct pow(\vec{betas}) as in the paper + auto pow_beta = bb::PowPolynomial(betas); + pow_beta.compute_values(); + + // Compute the corresponding target sum and create a dummy accumulator + auto target_sum = FF(0); + for (size_t i = 0; i < instance_size; i++) { + target_sum += full_honk_evals[i] * pow_beta[i]; + } + + auto accumulator = std::make_shared(); + accumulator->prover_polynomials = std::move(full_polynomials); + accumulator->gate_challenges = betas; + accumulator->target_sum = target_sum; + accumulator->relation_parameters = relation_parameters; + accumulator->alphas = alphas; + + auto deltas = ProtoGalaxyProver::compute_round_challenge_pows(log_instance_size, FF::random_element()); + auto perturbator = ProtoGalaxyProver::compute_perturbator(accumulator, deltas); + + // Ensure the constant coefficient of the perturbator is equal to the target sum as indicated by the paper + EXPECT_EQ(perturbator[0], target_sum); + } - auto deltas = ProtoGalaxyProver::compute_round_challenge_pows(log_instance_size, FF::random_element()); - auto perturbator = ProtoGalaxyProver::compute_perturbator(accumulator, deltas); + /** + * @brief Manually compute the expected evaluations of the combiner quotient, given evaluations of the combiner and + * check them against the evaluations returned by the function. + * + */ + static void test_combiner_quotient() + { + auto compressed_perturbator = FF(2); // F(\alpha) in the paper + auto combiner = + bb::Univariate(std::array{ 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32 }); + auto combiner_quotient = ProtoGalaxyProver::compute_combiner_quotient(compressed_perturbator, combiner); + + // K(i) = (G(i) - ( L_0(i) * F(\alpha)) / Z(i), i = {2,.., 13} for ProverInstances::NUM = 2 + // K(i) = (G(i) - (1 - i) * F(\alpha)) / i * (i - 1) + auto expected_evals = bb::Univariate(std::array{ + (FF(22) - (FF(1) - FF(2)) * compressed_perturbator) / (FF(2) * FF(2 - 1)), + (FF(23) - (FF(1) - FF(3)) * compressed_perturbator) / (FF(3) * FF(3 - 1)), + (FF(24) - (FF(1) - FF(4)) * compressed_perturbator) / (FF(4) * FF(4 - 1)), + (FF(25) - (FF(1) - FF(5)) * compressed_perturbator) / (FF(5) * FF(5 - 1)), + (FF(26) - (FF(1) - FF(6)) * compressed_perturbator) / (FF(6) * FF(6 - 1)), + (FF(27) - (FF(1) - FF(7)) * compressed_perturbator) / (FF(7) * FF(7 - 1)), + (FF(28) - (FF(1) - FF(8)) * compressed_perturbator) / (FF(8) * FF(8 - 1)), + (FF(29) - (FF(1) - FF(9)) * compressed_perturbator) / (FF(9) * FF(9 - 1)), + (FF(30) - (FF(1) - FF(10)) * compressed_perturbator) / (FF(10) * FF(10 - 1)), + (FF(31) - (FF(1) - FF(11)) * compressed_perturbator) / (FF(11) * FF(11 - 1)), + (FF(32) - (FF(1) - FF(12)) * compressed_perturbator) / (FF(12) * FF(12 - 1)), + }); + + for (size_t idx = 2; idx < 7; idx++) { + EXPECT_EQ(combiner_quotient.value_at(idx), expected_evals.value_at(idx)); + } + } - // Ensure the constant coefficient of the perturbator is equal to the target sum as indicated by the paper - EXPECT_EQ(perturbator[0], target_sum); -} + /** + * @brief For two dummy instances with their relation parameter η set, check that combining them in a univariate, + * barycentrially extended to the desired number of evaluations, is performed correctly. + * + */ + static void test_combine_relation_parameters() + { + using Instances = ProverInstances_; + using Instance = typename Instances::Instance; + + Builder builder1; + auto instance1 = std::make_shared(builder1); + instance1->relation_parameters.eta = 1; + + Builder builder2; + builder2.add_variable(3); + auto instance2 = std::make_shared(builder2); + instance2->relation_parameters.eta = 3; + + Instances instances{ { instance1, instance2 } }; + ProtoGalaxyProver::combine_relation_parameters(instances); + + bb::Univariate expected_eta{ { 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23 } }; + EXPECT_EQ(instances.relation_parameters.eta, expected_eta); + } -TEST_F(ProtoGalaxyTests, CombinerQuotient) -{ - auto compressed_perturbator = FF(2); // F(\alpha) in the paper - auto combiner = Univariate(std::array{ 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32 }); - auto combiner_quotient = ProtoGalaxyProver::compute_combiner_quotient(compressed_perturbator, combiner); - - // K(i) = (G(i) - ( L_0(i) * F(\alpha)) / Z(i), i = {2,.., 13} for ProverInstances::NUM = 2 - // K(i) = (G(i) - (1 - i) * F(\alpha)) / i * (i - 1) - auto expected_evals = Univariate(std::array{ - (FF(22) - (FF(1) - FF(2)) * compressed_perturbator) / (FF(2) * FF(2 - 1)), - (FF(23) - (FF(1) - FF(3)) * compressed_perturbator) / (FF(3) * FF(3 - 1)), - (FF(24) - (FF(1) - FF(4)) * compressed_perturbator) / (FF(4) * FF(4 - 1)), - (FF(25) - (FF(1) - FF(5)) * compressed_perturbator) / (FF(5) * FF(5 - 1)), - (FF(26) - (FF(1) - FF(6)) * compressed_perturbator) / (FF(6) * FF(6 - 1)), - (FF(27) - (FF(1) - FF(7)) * compressed_perturbator) / (FF(7) * FF(7 - 1)), - (FF(28) - (FF(1) - FF(8)) * compressed_perturbator) / (FF(8) * FF(8 - 1)), - (FF(29) - (FF(1) - FF(9)) * compressed_perturbator) / (FF(9) * FF(9 - 1)), - (FF(30) - (FF(1) - FF(10)) * compressed_perturbator) / (FF(10) * FF(10 - 1)), - (FF(31) - (FF(1) - FF(11)) * compressed_perturbator) / (FF(11) * FF(11 - 1)), - (FF(32) - (FF(1) - FF(12)) * compressed_perturbator) / (FF(12) * FF(12 - 1)), - }); - - for (size_t idx = 2; idx < 7; idx++) { - EXPECT_EQ(combiner_quotient.value_at(idx), expected_evals.value_at(idx)); + /** + * @brief Given two dummy instances with the batching challenges alphas set (one for each subrelation) ensure + * combining them in a univariate of desired length works as expected. + */ + static void test_combine_alpha() + { + using Instances = ProverInstances_; + using Instance = typename Instances::Instance; + + Builder builder1; + auto instance1 = std::make_shared(builder1); + instance1->alphas.fill(2); + + Builder builder2; + builder2.add_variable(3); + auto instance2 = std::make_shared(builder2); + instance2->alphas.fill(4); + + Instances instances{ { instance1, instance2 } }; + ProtoGalaxyProver::combine_alpha(instances); + + bb::Univariate expected_alpha{ { 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26 } }; + for (const auto& alpha : instances.alphas) { + EXPECT_EQ(alpha, expected_alpha); + } } -} -TEST_F(ProtoGalaxyTests, CombineRelationParameters) -{ - using Instances = ProverInstances_; - using Instance = typename Instances::Instance; + /** + * @brief Testing two valid rounds of folding followed by the decider. + * + */ + static void test_full_protogalaxy() + { + auto composer = Composer(); + auto builder_1 = typename Flavor::CircuitBuilder(); + construct_circuit(builder_1); - Builder builder1; - auto instance1 = std::make_shared(builder1); - instance1->relation_parameters.eta = 1; + auto instance_1 = composer.create_instance(builder_1); - Builder builder2; - builder2.add_variable(3); - auto instance2 = std::make_shared(builder2); - instance2->relation_parameters.eta = 3; + auto builder_2 = typename Flavor::CircuitBuilder(); + construct_circuit(builder_2); - Instances instances{ { instance1, instance2 } }; - ProtoGalaxyProver::combine_relation_parameters(instances); + auto instance_2 = composer.create_instance(builder_2); - Univariate expected_eta{ { 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23 } }; - EXPECT_EQ(instances.relation_parameters.eta, expected_eta); -} + auto instances = std::vector>{ instance_1, instance_2 }; + auto first_accumulator = fold_and_verify(instances, composer, true); + check_accumulator_target_sum_manual(first_accumulator, true); -TEST_F(ProtoGalaxyTests, CombineAlpha) -{ - using Instances = ProverInstances_; - using Instance = typename Instances::Instance; + auto builder_3 = typename Flavor::CircuitBuilder(); + construct_circuit(builder_3); + auto instance_3 = composer.create_instance(builder_3); - Builder builder1; - auto instance1 = std::make_shared(builder1); - instance1->alphas.fill(2); + instances = std::vector>{ first_accumulator, instance_3 }; + auto second_accumulator = fold_and_verify(instances, composer, true); + check_accumulator_target_sum_manual(second_accumulator, true); - Builder builder2; - builder2.add_variable(3); - auto instance2 = std::make_shared(builder2); - instance2->alphas.fill(4); + decide_and_verify(first_accumulator, composer, true); + } - Instances instances{ { instance1, instance2 } }; - ProtoGalaxyProver::combine_alpha(instances); + /** + * @brief Ensure tampering a commitment and then calling the decider causes the decider verification to fail. + * + */ + static void test_tampered_commitment() + { + auto composer = Composer(); - Univariate expected_alpha{ { 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26 } }; - for (const auto& alpha : instances.alphas) { - EXPECT_EQ(alpha, expected_alpha); - } -} + auto builder_1 = typename Flavor::CircuitBuilder(); + construct_circuit(builder_1); -// Check both manually and using the protocol two rounds of folding -TEST_F(ProtoGalaxyTests, FullProtogalaxyTest) -{ - auto composer = UltraComposer(); + auto instance_1 = composer.create_instance(builder_1); - auto builder_1 = typename Flavor::CircuitBuilder(); - builder_1.add_public_variable(FF(1)); + auto builder_2 = typename Flavor::CircuitBuilder(); + construct_circuit(builder_2); - auto instance_1 = composer.create_instance(builder_1); + auto instance_2 = composer.create_instance(builder_2); - auto builder_2 = typename Flavor::CircuitBuilder(); - builder_2.add_public_variable(FF(1)); + auto instances = std::vector>{ instance_1, instance_2 }; + auto first_accumulator = fold_and_verify(instances, composer, true); + check_accumulator_target_sum_manual(first_accumulator, true); - auto instance_2 = composer.create_instance(builder_2); + auto builder_3 = typename Flavor::CircuitBuilder(); + construct_circuit(builder_3); + auto instance_3 = composer.create_instance(builder_3); - auto instances = std::vector>{ instance_1, instance_2 }; - auto first_accumulator = fold_and_verify(instances, composer, true); - check_accumulator_target_sum_manual(first_accumulator, true); + // tampering with the commitment should cause the decider to fail + first_accumulator->witness_commitments.w_l = Projective(Affine::random_element()); + instances = std::vector>{ first_accumulator, instance_3 }; - auto builder_3 = typename Flavor::CircuitBuilder(); - builder_3.add_public_variable(FF(1)); - auto instance_3 = composer.create_instance(builder_3); + auto second_accumulator = fold_and_verify(instances, composer, true); - instances = std::vector>{ first_accumulator, instance_3 }; - auto second_accumulator = fold_and_verify(instances, composer, true); - check_accumulator_target_sum_manual(second_accumulator, true); + decide_and_verify(second_accumulator, composer, false); + } - decide_and_verify(second_accumulator, composer, true); -} + /** + * @brief Ensure tampering an accumulator and then calling fold again causes both the folding verification and + * decider verification to fail. + * + */ + static void test_tampered_accumulator_polynomial() + { + auto composer = Composer(); -TEST_F(ProtoGalaxyTests, TamperedCommitment) -{ - auto composer = UltraComposer(); + auto builder_1 = typename Flavor::CircuitBuilder(); + construct_circuit(builder_1); - auto builder_1 = typename Flavor::CircuitBuilder(); - builder_1.add_public_variable(FF(1)); + auto instance_1 = composer.create_instance(builder_1); - auto instance_1 = composer.create_instance(builder_1); + auto builder_2 = typename Flavor::CircuitBuilder(); + construct_circuit(builder_2); - auto builder_2 = typename Flavor::CircuitBuilder(); - builder_2.add_public_variable(FF(1)); + auto instance_2 = composer.create_instance(builder_2); - auto instance_2 = composer.create_instance(builder_2); + auto instances = std::vector>{ instance_1, instance_2 }; + auto first_accumulator = fold_and_verify(instances, composer, true); + check_accumulator_target_sum_manual(first_accumulator, true); - auto instances = std::vector>{ instance_1, instance_2 }; - auto first_accumulator = fold_and_verify(instances, composer, true); - check_accumulator_target_sum_manual(first_accumulator, true); + auto builder_3 = typename Flavor::CircuitBuilder(); + construct_circuit(builder_3); + auto instance_3 = composer.create_instance(builder_3); - auto builder_3 = typename Flavor::CircuitBuilder(); - builder_3.add_public_variable(FF(1)); - auto instance_3 = composer.create_instance(builder_3); + // tampering with accumulator's polynomial should cause both folding and deciding to fail + instances = std::vector>{ first_accumulator, instance_3 }; + first_accumulator->prover_polynomials.w_l[1] = FF::random_element(); + auto second_accumulator = fold_and_verify(instances, composer, false); - // tampering with the commitment should cause the decider to fail - first_accumulator->witness_commitments.w_l = Projective(Affine::random_element()); - instances = std::vector>{ first_accumulator, instance_3 }; + decide_and_verify(second_accumulator, composer, false); + } +}; +} // namespace - auto second_accumulator = fold_and_verify(instances, composer, true); +using FlavorTypes = testing::Types; +TYPED_TEST_SUITE(ProtoGalaxyTests, FlavorTypes); - decide_and_verify(second_accumulator, composer, false); +TYPED_TEST(ProtoGalaxyTests, PerturbatorCoefficients) +{ + TestFixture::test_pertubator_coefficients(); } -TEST_F(ProtoGalaxyTests, TamperedAccumulatorPolynomial) +TYPED_TEST(ProtoGalaxyTests, FullHonkEvaluationsValidCircuit) { - auto composer = UltraComposer(); - - auto builder_1 = typename Flavor::CircuitBuilder(); - builder_1.add_public_variable(FF(1)); + TestFixture::test_full_honk_evaluations_valid_circuit(); +} - auto instance_1 = composer.create_instance(builder_1); +TYPED_TEST(ProtoGalaxyTests, PerturbatorPolynomial) +{ + TestFixture::test_pertubator_polynomial(); +} - auto builder_2 = typename Flavor::CircuitBuilder(); - builder_2.add_public_variable(FF(1)); +TYPED_TEST(ProtoGalaxyTests, CombinerQuotient) +{ + TestFixture::test_combiner_quotient(); +} - auto instance_2 = composer.create_instance(builder_2); +TYPED_TEST(ProtoGalaxyTests, CombineRelationParameters) +{ + TestFixture::test_combine_relation_parameters(); +} - auto instances = std::vector>{ instance_1, instance_2 }; - auto first_accumulator = fold_and_verify(instances, composer, true); - check_accumulator_target_sum_manual(first_accumulator, true); +TYPED_TEST(ProtoGalaxyTests, CombineAlpha) +{ + TestFixture::test_combine_alpha(); +} - auto builder_3 = typename Flavor::CircuitBuilder(); - builder_3.add_public_variable(FF(1)); - auto instance_3 = composer.create_instance(builder_3); +TYPED_TEST(ProtoGalaxyTests, FullProtogalaxyTest) +{ + TestFixture::test_full_protogalaxy(); +} - // tampering with accumulator's polynomial should cause both folding and deciding to fail - instances = std::vector>{ first_accumulator, instance_3 }; - first_accumulator->prover_polynomials.w_l[1] = FF::random_element(); - auto second_accumulator = fold_and_verify(instances, composer, false); +TYPED_TEST(ProtoGalaxyTests, TamperedCommitment) +{ + TestFixture::test_tampered_commitment(); +} - decide_and_verify(second_accumulator, composer, false); +TYPED_TEST(ProtoGalaxyTests, TamperedAccumulatorPolynomial) +{ + TestFixture::test_tampered_accumulator_polynomial(); } \ No newline at end of file diff --git a/barretenberg/cpp/src/barretenberg/ultra_honk/relation_correctness.test.cpp b/barretenberg/cpp/src/barretenberg/ultra_honk/relation_correctness.test.cpp index b9313be2496..2b5ec50f37e 100644 --- a/barretenberg/cpp/src/barretenberg/ultra_honk/relation_correctness.test.cpp +++ b/barretenberg/cpp/src/barretenberg/ultra_honk/relation_correctness.test.cpp @@ -12,7 +12,6 @@ #include "barretenberg/ultra_honk/ultra_composer.hpp" #include using namespace bb; -using namespace bb::honk; void ensure_non_zero(auto& polynomial) { @@ -253,7 +252,7 @@ class RelationCorrectnessTests : public ::testing::Test { // TODO(luke): Add a gate that sets q_arith = 3 to check secondary arithmetic relation TEST_F(RelationCorrectnessTests, UltraRelationCorrectness) { - using Flavor = flavor::Ultra; + using Flavor = UltraFlavor; using FF = typename Flavor::FF; // Create a composer and then add an assortment of gates designed to ensure that the constraint(s) represented @@ -305,7 +304,7 @@ TEST_F(RelationCorrectnessTests, UltraRelationCorrectness) TEST_F(RelationCorrectnessTests, GoblinUltraRelationCorrectness) { - using Flavor = flavor::GoblinUltra; + using Flavor = GoblinUltraFlavor; using FF = typename Flavor::FF; // Create a composer and then add an assortment of gates designed to ensure that the constraint(s) represented @@ -373,11 +372,10 @@ TEST_F(RelationCorrectnessTests, GoblinUltraRelationCorrectness) */ TEST_F(RelationCorrectnessTests, GoblinTranslatorPermutationRelationCorrectness) { - using Flavor = flavor::GoblinTranslator; + using Flavor = GoblinTranslatorFlavor; using FF = typename Flavor::FF; using ProverPolynomials = typename Flavor::ProverPolynomials; using Polynomial = bb::Polynomial; - using namespace bb::honk::permutation_library; auto& engine = numeric::get_debug_randomness(); const size_t mini_circuit_size = 2048; auto full_circuit_size = mini_circuit_size * Flavor::CONCATENATION_GROUP_SIZE; @@ -480,7 +478,7 @@ TEST_F(RelationCorrectnessTests, GoblinTranslatorPermutationRelationCorrectness) compute_concatenated_polynomials(&prover_polynomials); // Compute the grand product polynomial - grand_product_library::compute_grand_product>( + compute_grand_product>( full_circuit_size, prover_polynomials, params); prover_polynomials.z_perm_shift = prover_polynomials.z_perm.shifted(); @@ -492,7 +490,7 @@ TEST_F(RelationCorrectnessTests, GoblinTranslatorPermutationRelationCorrectness) TEST_F(RelationCorrectnessTests, GoblinTranslatorGenPermSortRelationCorrectness) { - using Flavor = flavor::GoblinTranslator; + using Flavor = GoblinTranslatorFlavor; using FF = typename Flavor::FF; using ProverPolynomials = typename Flavor::ProverPolynomials; using Polynomial = bb::Polynomial; @@ -566,13 +564,13 @@ TEST_F(RelationCorrectnessTests, GoblinTranslatorGenPermSortRelationCorrectness) } /** - * @brief Test the correctness of GoblinTranslator's extra relations (GoblinTranslatorOpcodeConstraintRelation and - * GoblinTranslatorAccumulatorTransferRelation) + * @brief Test the correctness of GoblinTranslatorFlavor's extra relations (GoblinTranslatorOpcodeConstraintRelation + * and GoblinTranslatorAccumulatorTransferRelation) * */ TEST_F(RelationCorrectnessTests, GoblinTranslatorExtraRelationsCorrectness) { - using Flavor = flavor::GoblinTranslator; + using Flavor = GoblinTranslatorFlavor; using FF = typename Flavor::FF; using ProverPolynomials = typename Flavor::ProverPolynomials; using ProverPolynomialIds = typename Flavor::ProverPolynomialIds; @@ -669,12 +667,12 @@ TEST_F(RelationCorrectnessTests, GoblinTranslatorExtraRelationsCorrectness) check_relation>(circuit_size, prover_polynomials, params); } /** - * @brief Test the correctness of GoblinTranslator's Decomposition Relation + * @brief Test the correctness of GoblinTranslatorFlavor's Decomposition Relation * */ TEST_F(RelationCorrectnessTests, GoblinTranslatorDecompositionRelationCorrectness) { - using Flavor = flavor::GoblinTranslator; + using Flavor = GoblinTranslatorFlavor; using FF = typename Flavor::FF; using BF = typename Flavor::BF; using ProverPolynomials = typename Flavor::ProverPolynomials; @@ -1043,12 +1041,12 @@ TEST_F(RelationCorrectnessTests, GoblinTranslatorDecompositionRelationCorrectnes } /** - * @brief Test the correctness of GoblinTranslator's NonNativeField Relation + * @brief Test the correctness of GoblinTranslatorFlavor's NonNativeField Relation * */ TEST_F(RelationCorrectnessTests, GoblinTranslatorNonNativeRelationCorrectness) { - using Flavor = flavor::GoblinTranslator; + using Flavor = GoblinTranslatorFlavor; using FF = typename Flavor::FF; using BF = typename Flavor::BF; using ProverPolynomials = typename Flavor::ProverPolynomials; diff --git a/barretenberg/cpp/src/barretenberg/ultra_honk/sumcheck.test.cpp b/barretenberg/cpp/src/barretenberg/ultra_honk/sumcheck.test.cpp index fe0fede946c..2f736f2ed82 100644 --- a/barretenberg/cpp/src/barretenberg/ultra_honk/sumcheck.test.cpp +++ b/barretenberg/cpp/src/barretenberg/ultra_honk/sumcheck.test.cpp @@ -15,10 +15,8 @@ #include using namespace bb; -using namespace bb::honk; -using namespace bb::honk::sumcheck; -using Flavor = honk::flavor::Ultra; +using Flavor = UltraFlavor; using FF = typename Flavor::FF; class SumcheckTestsRealCircuit : public ::testing::Test { @@ -32,7 +30,7 @@ class SumcheckTestsRealCircuit : public ::testing::Test { */ TEST_F(SumcheckTestsRealCircuit, Ultra) { - using Flavor = flavor::Ultra; + using Flavor = UltraFlavor; using FF = typename Flavor::FF; using Transcript = typename Flavor::Transcript; using RelationSeparator = typename Flavor::RelationSeparator; diff --git a/barretenberg/cpp/src/barretenberg/ultra_honk/ultra_composer.cpp b/barretenberg/cpp/src/barretenberg/ultra_honk/ultra_composer.cpp index 320c325827e..ae42bd4366a 100644 --- a/barretenberg/cpp/src/barretenberg/ultra_honk/ultra_composer.cpp +++ b/barretenberg/cpp/src/barretenberg/ultra_honk/ultra_composer.cpp @@ -4,14 +4,14 @@ #include "barretenberg/proof_system/composer/permutation_lib.hpp" #include "barretenberg/proof_system/library/grand_product_library.hpp" -namespace bb::honk { +namespace bb { /** * Compute verification key consisting of selector precommitments. * * @return Pointer to the resulting verification key of the Instance. * */ -template +template void UltraComposer_::compute_verification_key(const std::shared_ptr>& instance) { if (instance->verification_key) { @@ -64,7 +64,7 @@ void UltraComposer_::compute_verification_key(const std::shared_ptrverification_key = std::move(verification_key); } -template +template std::shared_ptr> UltraComposer_::create_instance(CircuitBuilder& circuit) { circuit.add_gates_to_ensure_all_polys_are_non_zero(); @@ -76,7 +76,7 @@ std::shared_ptr> UltraComposer_::create_instance return instance; } -template +template UltraProver_ UltraComposer_::create_prover(const std::shared_ptr& instance, const std::shared_ptr& transcript) { @@ -85,7 +85,7 @@ UltraProver_ UltraComposer_::create_prover(const std::shared_ptr return output_state; } -template +template UltraVerifier_ UltraComposer_::create_verifier(const std::shared_ptr& instance, const std::shared_ptr& transcript) { @@ -97,7 +97,7 @@ UltraVerifier_ UltraComposer_::create_verifier(const std::shared return output_state; } -template +template DeciderProver_ UltraComposer_::create_decider_prover(const std::shared_ptr& accumulator, const std::shared_ptr& transcript) { @@ -107,7 +107,7 @@ DeciderProver_ UltraComposer_::create_decider_prover(const std:: return output_state; } -template +template DeciderProver_ UltraComposer_::create_decider_prover( const std::shared_ptr& accumulator, const std::shared_ptr& commitment_key, @@ -118,7 +118,7 @@ DeciderProver_ UltraComposer_::create_decider_prover( return output_state; } -template +template DeciderVerifier_ UltraComposer_::create_decider_verifier(const std::shared_ptr& accumulator, const std::shared_ptr& transcript) { @@ -130,6 +130,6 @@ DeciderVerifier_ UltraComposer_::create_decider_verifier(const s return output_state; } -template class UltraComposer_; -template class UltraComposer_; -} // namespace bb::honk +template class UltraComposer_; +template class UltraComposer_; +} // namespace bb diff --git a/barretenberg/cpp/src/barretenberg/ultra_honk/ultra_composer.hpp b/barretenberg/cpp/src/barretenberg/ultra_honk/ultra_composer.hpp index 5d2a6a71ea2..ea929b92033 100644 --- a/barretenberg/cpp/src/barretenberg/ultra_honk/ultra_composer.hpp +++ b/barretenberg/cpp/src/barretenberg/ultra_honk/ultra_composer.hpp @@ -7,13 +7,11 @@ #include "barretenberg/protogalaxy/protogalaxy_verifier.hpp" #include "barretenberg/srs/global_crs.hpp" #include "barretenberg/sumcheck/instance/prover_instance.hpp" -#include "barretenberg/ultra_honk/merge_prover.hpp" -#include "barretenberg/ultra_honk/merge_verifier.hpp" #include "barretenberg/ultra_honk/ultra_prover.hpp" #include "barretenberg/ultra_honk/ultra_verifier.hpp" -namespace bb::honk { -template class UltraComposer_ { +namespace bb { +template class UltraComposer_ { public: using CircuitBuilder = typename Flavor::CircuitBuilder; using ProvingKey = typename Flavor::ProvingKey; @@ -83,33 +81,6 @@ template class UltraComposer_ { UltraVerifier_ create_ultra_with_keccak_verifier(CircuitBuilder& circuit); - /** - * @brief Create Prover for Goblin ECC op queue merge protocol - * - * @param op_queue - * @return MergeProver_ - * TODO(https://github.com/AztecProtocol/barretenberg/issues/804): Goblin should be responsible for constructing - * merge prover/verifier. - */ - MergeProver_ create_merge_prover( - const std::shared_ptr& op_queue, - const std::shared_ptr& transcript = std::make_shared()) - { - // Store the previous aggregate op queue size and update the current one - op_queue->set_size_data(); - // Merge requires a commitment key with size equal to that of the current op queue transcript T_i since the - // shift of the current contribution t_i will be of degree equal to deg(T_i) - auto commitment_key = compute_commitment_key(op_queue->get_current_size()); - return MergeProver_(commitment_key, op_queue, transcript); - } - - /** - * @brief Create Verifier for Goblin ECC op queue merge protocol - * - * @return MergeVerifier_ - */ - MergeVerifier_ create_merge_verifier() { return MergeVerifier_(); } - ProtoGalaxyProver_ create_folding_prover(const std::vector>& instances) { ProtoGalaxyProver_ output_state(instances, commitment_key); @@ -134,6 +105,6 @@ template class UltraComposer_ { }; // TODO(#532): this pattern is weird; is this not instantiating the templates? -using UltraComposer = UltraComposer_; -using GoblinUltraComposer = UltraComposer_; -} // namespace bb::honk +using UltraComposer = UltraComposer_; +using GoblinUltraComposer = UltraComposer_; +} // namespace bb diff --git a/barretenberg/cpp/src/barretenberg/ultra_honk/ultra_composer.test.cpp b/barretenberg/cpp/src/barretenberg/ultra_honk/ultra_composer.test.cpp index 09a1bdb72f3..205a67aad24 100644 --- a/barretenberg/cpp/src/barretenberg/ultra_honk/ultra_composer.test.cpp +++ b/barretenberg/cpp/src/barretenberg/ultra_honk/ultra_composer.test.cpp @@ -17,7 +17,6 @@ #include using namespace bb; -using namespace bb::honk; namespace { auto& engine = numeric::get_debug_randomness(); diff --git a/barretenberg/cpp/src/barretenberg/ultra_honk/ultra_prover.cpp b/barretenberg/cpp/src/barretenberg/ultra_honk/ultra_prover.cpp index 40fc15a3369..16118067408 100644 --- a/barretenberg/cpp/src/barretenberg/ultra_honk/ultra_prover.cpp +++ b/barretenberg/cpp/src/barretenberg/ultra_honk/ultra_prover.cpp @@ -1,7 +1,7 @@ #include "ultra_prover.hpp" #include "barretenberg/sumcheck/sumcheck.hpp" -namespace bb::honk { +namespace bb { /** * Create UltraProver_ from an instance. @@ -10,7 +10,7 @@ namespace bb::honk { * * @tparam a type of UltraFlavor * */ -template +template UltraProver_::UltraProver_(const std::shared_ptr& inst, const std::shared_ptr& commitment_key, const std::shared_ptr& transcript) @@ -25,7 +25,7 @@ UltraProver_::UltraProver_(const std::shared_ptr& inst, * @brief Add circuit size, public input size, and public inputs to transcript * */ -template void UltraProver_::execute_preamble_round() +template void UltraProver_::execute_preamble_round() { auto proving_key = instance->proving_key; const auto circuit_size = static_cast(proving_key->circuit_size); @@ -46,7 +46,7 @@ template void UltraProver_::execute_preamble_round( * only commited to after adding memory records. In the Goblin Flavor, we also commit to the ECC OP wires and the * DataBus columns. */ -template void UltraProver_::execute_wire_commitments_round() +template void UltraProver_::execute_wire_commitments_round() { auto& witness_commitments = instance->witness_commitments; auto& proving_key = instance->proving_key; @@ -89,7 +89,7 @@ template void UltraProver_::execute_wire_commitment * @brief Compute sorted witness-table accumulator and commit to the resulting polynomials. * */ -template void UltraProver_::execute_sorted_list_accumulator_round() +template void UltraProver_::execute_sorted_list_accumulator_round() { FF eta = transcript->get_challenge("eta"); @@ -109,7 +109,7 @@ template void UltraProver_::execute_sorted_list_acc * @brief Compute log derivative inverse polynomial and its commitment, if required * */ -template void UltraProver_::execute_log_derivative_inverse_round() +template void UltraProver_::execute_log_derivative_inverse_round() { // Compute and store challenges beta and gamma auto [beta, gamma] = challenges_to_field_elements(transcript->get_challenges("beta", "gamma")); @@ -128,7 +128,7 @@ template void UltraProver_::execute_log_derivative_ * @brief Compute permutation and lookup grand product polynomials and their commitments * */ -template void UltraProver_::execute_grand_product_computation_round() +template void UltraProver_::execute_grand_product_computation_round() { instance->compute_grand_product_polynomials(relation_parameters.beta, relation_parameters.gamma); @@ -144,9 +144,9 @@ template void UltraProver_::execute_grand_product_c * @brief Run Sumcheck resulting in u = (u_1,...,u_d) challenges and all evaluations at u being calculated. * */ -template void UltraProver_::execute_relation_check_rounds() +template void UltraProver_::execute_relation_check_rounds() { - using Sumcheck = sumcheck::SumcheckProver; + using Sumcheck = SumcheckProver; auto circuit_size = instance->proving_key->circuit_size; auto sumcheck = Sumcheck(circuit_size, transcript); RelationSeparator alphas; @@ -167,7 +167,7 @@ template void UltraProver_::execute_relation_check_ * @details See https://hackmd.io/dlf9xEwhTQyE3hiGbq4FsA?view for a complete description of the unrolled protocol. * * */ -template void UltraProver_::execute_zeromorph_rounds() +template void UltraProver_::execute_zeromorph_rounds() { ZeroMorph::prove(instance->prover_polynomials.get_unshifted(), instance->prover_polynomials.get_to_be_shifted(), @@ -178,13 +178,13 @@ template void UltraProver_::execute_zeromorph_round transcript); } -template honk::proof& UltraProver_::export_proof() +template HonkProof& UltraProver_::export_proof() { proof = transcript->proof_data; return proof; } -template honk::proof& UltraProver_::construct_proof() +template HonkProof& UltraProver_::construct_proof() { // Add circuit size public input size and public inputs to transcript-> execute_preamble_round(); @@ -212,7 +212,7 @@ template honk::proof& UltraProver_::construct_proof return export_proof(); } -template class UltraProver_; -template class UltraProver_; +template class UltraProver_; +template class UltraProver_; -} // namespace bb::honk +} // namespace bb diff --git a/barretenberg/cpp/src/barretenberg/ultra_honk/ultra_prover.hpp b/barretenberg/cpp/src/barretenberg/ultra_honk/ultra_prover.hpp index 13d3a1cc1b8..8e211390dd7 100644 --- a/barretenberg/cpp/src/barretenberg/ultra_honk/ultra_prover.hpp +++ b/barretenberg/cpp/src/barretenberg/ultra_honk/ultra_prover.hpp @@ -8,9 +8,9 @@ #include "barretenberg/sumcheck/sumcheck_output.hpp" #include "barretenberg/transcript/transcript.hpp" -namespace bb::honk { +namespace bb { -template class UltraProver_ { +template class UltraProver_ { using FF = typename Flavor::FF; using Commitment = typename Flavor::Commitment; using CommitmentKey = typename Flavor::CommitmentKey; @@ -35,8 +35,8 @@ template class UltraProver_ { BBERG_PROFILE void execute_relation_check_rounds(); BBERG_PROFILE void execute_zeromorph_rounds(); - honk::proof& export_proof(); - honk::proof& construct_proof(); + HonkProof& export_proof(); + HonkProof& construct_proof(); std::shared_ptr instance; @@ -48,17 +48,17 @@ template class UltraProver_ { Polynomial quotient_W; - sumcheck::SumcheckOutput sumcheck_output; + SumcheckOutput sumcheck_output; std::shared_ptr commitment_key; - using ZeroMorph = pcs::zeromorph::ZeroMorphProver_; + using ZeroMorph = ZeroMorphProver_; private: - honk::proof proof; + HonkProof proof; }; -using UltraProver = UltraProver_; -using GoblinUltraProver = UltraProver_; +using UltraProver = UltraProver_; +using GoblinUltraProver = UltraProver_; -} // namespace bb::honk +} // namespace bb diff --git a/barretenberg/cpp/src/barretenberg/ultra_honk/ultra_transcript.test.cpp b/barretenberg/cpp/src/barretenberg/ultra_honk/ultra_transcript.test.cpp index 3dc2e8f1d3b..609b455e22f 100644 --- a/barretenberg/cpp/src/barretenberg/ultra_honk/ultra_transcript.test.cpp +++ b/barretenberg/cpp/src/barretenberg/ultra_honk/ultra_transcript.test.cpp @@ -7,13 +7,12 @@ #include using namespace bb; -using namespace bb::honk; class UltraTranscriptTests : public ::testing::Test { public: static void SetUpTestSuite() { bb::srs::init_crs_factory("../srs_db/ignition"); } - using Flavor = honk::flavor::Ultra; + using Flavor = UltraFlavor; using FF = Flavor::FF; /** diff --git a/barretenberg/cpp/src/barretenberg/ultra_honk/ultra_verifier.cpp b/barretenberg/cpp/src/barretenberg/ultra_honk/ultra_verifier.cpp index b0ee1339dd1..4ab7b6addf3 100644 --- a/barretenberg/cpp/src/barretenberg/ultra_honk/ultra_verifier.cpp +++ b/barretenberg/cpp/src/barretenberg/ultra_honk/ultra_verifier.cpp @@ -3,10 +3,7 @@ #include "barretenberg/numeric/bitop/get_msb.hpp" #include "barretenberg/transcript/transcript.hpp" -using namespace bb; -using namespace bb::honk::sumcheck; - -namespace bb::honk { +namespace bb { template UltraVerifier_::UltraVerifier_(const std::shared_ptr& transcript, const std::shared_ptr& verifier_key) @@ -45,12 +42,12 @@ template UltraVerifier_& UltraVerifier_::opera * @brief This function verifies an Ultra Honk proof for a given Flavor. * */ -template bool UltraVerifier_::verify_proof(const honk::proof& proof) +template bool UltraVerifier_::verify_proof(const HonkProof& proof) { using FF = typename Flavor::FF; using Commitment = typename Flavor::Commitment; using Curve = typename Flavor::Curve; - using ZeroMorph = pcs::zeromorph::ZeroMorphVerifier_; + using ZeroMorph = ZeroMorphVerifier_; using VerifierCommitments = typename Flavor::VerifierCommitments; using CommitmentLabels = typename Flavor::CommitmentLabels; @@ -163,7 +160,7 @@ template bool UltraVerifier_::verify_proof(const honk: return sumcheck_verified.value() && verified; } -template class UltraVerifier_; -template class UltraVerifier_; +template class UltraVerifier_; +template class UltraVerifier_; -} // namespace bb::honk +} // namespace bb diff --git a/barretenberg/cpp/src/barretenberg/ultra_honk/ultra_verifier.hpp b/barretenberg/cpp/src/barretenberg/ultra_honk/ultra_verifier.hpp index 0c5dd4a9f1d..9e6df95ebb8 100644 --- a/barretenberg/cpp/src/barretenberg/ultra_honk/ultra_verifier.hpp +++ b/barretenberg/cpp/src/barretenberg/ultra_honk/ultra_verifier.hpp @@ -5,7 +5,7 @@ #include "barretenberg/srs/global_crs.hpp" #include "barretenberg/sumcheck/sumcheck.hpp" -namespace bb::honk { +namespace bb { template class UltraVerifier_ { using FF = typename Flavor::FF; using Commitment = typename Flavor::Commitment; @@ -24,7 +24,7 @@ template class UltraVerifier_ { UltraVerifier_& operator=(const UltraVerifier_& other) = delete; UltraVerifier_& operator=(UltraVerifier_&& other); - bool verify_proof(const honk::proof& proof); + bool verify_proof(const HonkProof& proof); std::shared_ptr key; std::map commitments; @@ -32,7 +32,7 @@ template class UltraVerifier_ { std::shared_ptr transcript; }; -using UltraVerifier = UltraVerifier_; -using GoblinUltraVerifier = UltraVerifier_; +using UltraVerifier = UltraVerifier_; +using GoblinUltraVerifier = UltraVerifier_; -} // namespace bb::honk +} // namespace bb diff --git a/barretenberg/cpp/src/barretenberg/vm/avm_trace/AvmMini_common.hpp b/barretenberg/cpp/src/barretenberg/vm/avm_trace/AvmMini_common.hpp index f8e06ef180b..fdbf49ebe57 100644 --- a/barretenberg/cpp/src/barretenberg/vm/avm_trace/AvmMini_common.hpp +++ b/barretenberg/cpp/src/barretenberg/vm/avm_trace/AvmMini_common.hpp @@ -4,7 +4,7 @@ #include "barretenberg/proof_system/circuit_builder/generated/AvmMini_circuit_builder.hpp" #include -using Flavor = bb::honk::flavor::AvmMiniFlavor; +using Flavor = bb::AvmMiniFlavor; using FF = Flavor::FF; using Row = bb::AvmMiniFullRow; diff --git a/barretenberg/cpp/src/barretenberg/vm/avm_trace/AvmMini_execution.cpp b/barretenberg/cpp/src/barretenberg/vm/avm_trace/AvmMini_execution.cpp index 22703836848..53019fb77ce 100644 --- a/barretenberg/cpp/src/barretenberg/vm/avm_trace/AvmMini_execution.cpp +++ b/barretenberg/cpp/src/barretenberg/vm/avm_trace/AvmMini_execution.cpp @@ -1,5 +1,6 @@ #include "AvmMini_execution.hpp" #include "barretenberg/common/serialize.hpp" +#include "barretenberg/common/throw_or_abort.hpp" #include "barretenberg/proof_system/circuit_builder/generated/AvmMini_circuit_builder.hpp" #include "barretenberg/vm/avm_trace/AvmMini_common.hpp" #include "barretenberg/vm/avm_trace/AvmMini_instructions.hpp" @@ -11,6 +12,8 @@ #include #include +using namespace bb; + namespace avm_trace { /** @@ -22,14 +25,14 @@ namespace avm_trace { * @throws runtime_error exception when the bytecode is invalid. * @return A zk proof of the execution. */ -honk::proof Execution::run_and_prove(std::vector const& bytecode, std::vector const& calldata) +HonkProof Execution::run_and_prove(std::vector const& bytecode, std::vector const& calldata) { auto instructions = parse(bytecode); auto trace = gen_trace(instructions, calldata); auto circuit_builder = bb::AvmMiniCircuitBuilder(); circuit_builder.set_trace(std::move(trace)); - auto composer = bb::honk::AvmMiniComposer(); + auto composer = AvmMiniComposer(); auto prover = composer.create_prover(circuit_builder); return prover.construct_proof(); } @@ -54,7 +57,7 @@ std::vector Execution::parse(std::vector const& bytecode) pos += AVM_OPCODE_BYTE_LENGTH; if (!Bytecode::is_valid(opcode_byte)) { - throw std::runtime_error("Invalid opcode byte: " + std::to_string(opcode_byte)); + throw_or_abort("Invalid opcode byte: " + std::to_string(opcode_byte)); } const auto opcode = static_cast(opcode_byte); @@ -62,12 +65,12 @@ std::vector Execution::parse(std::vector const& bytecode) if (Bytecode::has_in_tag(opcode)) { if (pos + AVM_IN_TAG_BYTE_LENGTH > length) { - throw std::runtime_error("Instruction tag missing at position " + std::to_string(pos)); + throw_or_abort("Instruction tag missing at position " + std::to_string(pos)); } in_tag_u8 = bytecode.at(pos); if (in_tag_u8 == static_cast(AvmMemoryTag::U0) || in_tag_u8 > MAX_MEM_TAG) { - throw std::runtime_error("Instruction tag is invalid at position " + std::to_string(pos) + - " value: " + std::to_string(in_tag_u8)); + throw_or_abort("Instruction tag is invalid at position " + std::to_string(pos) + + " value: " + std::to_string(in_tag_u8)); } pos += AVM_IN_TAG_BYTE_LENGTH; } @@ -107,8 +110,8 @@ std::vector Execution::parse(std::vector const& bytecode) operands_size = 20; break; default: - throw std::runtime_error("Instruction tag for SET opcode is invalid at position " + - std::to_string(pos) + " value: " + std::to_string(in_tag_u8)); + throw_or_abort("Instruction tag for SET opcode is invalid at position " + std::to_string(pos) + + " value: " + std::to_string(in_tag_u8)); break; } } else { @@ -117,7 +120,7 @@ std::vector Execution::parse(std::vector const& bytecode) } if (pos + operands_size > length) { - throw std::runtime_error("Operand is missing at position " + std::to_string(pos)); + throw_or_abort("Operand is missing at position " + std::to_string(pos)); } // We handle operands which are encoded with less than 4 bytes. diff --git a/barretenberg/cpp/src/barretenberg/vm/avm_trace/AvmMini_execution.hpp b/barretenberg/cpp/src/barretenberg/vm/avm_trace/AvmMini_execution.hpp index db6ffce56b0..6c31f52d040 100644 --- a/barretenberg/cpp/src/barretenberg/vm/avm_trace/AvmMini_execution.hpp +++ b/barretenberg/cpp/src/barretenberg/vm/avm_trace/AvmMini_execution.hpp @@ -22,7 +22,8 @@ class Execution { static std::vector parse(std::vector const& bytecode); static std::vector gen_trace(std::vector const& instructions, std::vector const& calldata); - static honk::proof run_and_prove(std::vector const& bytecode, std::vector const& calldata); + static bb::HonkProof run_and_prove(std::vector const& bytecode, + std::vector const& calldata = std::vector{}); }; } // namespace avm_trace \ No newline at end of file diff --git a/barretenberg/cpp/src/barretenberg/vm/generated/AvmMini_composer.cpp b/barretenberg/cpp/src/barretenberg/vm/generated/AvmMini_composer.cpp index a948d5a2a45..a27776eabea 100644 --- a/barretenberg/cpp/src/barretenberg/vm/generated/AvmMini_composer.cpp +++ b/barretenberg/cpp/src/barretenberg/vm/generated/AvmMini_composer.cpp @@ -6,9 +6,9 @@ #include "barretenberg/proof_system/composer/permutation_lib.hpp" #include "barretenberg/vm/generated/AvmMini_verifier.hpp" -namespace bb::honk { +namespace bb { -using Flavor = honk::flavor::AvmMiniFlavor; +using Flavor = AvmMiniFlavor; void AvmMiniComposer::compute_witness(CircuitConstructor& circuit) { if (computed_witness) { @@ -83,4 +83,4 @@ std::shared_ptr AvmMiniComposer::compute_verification_k return verification_key; } -} // namespace bb::honk +} // namespace bb diff --git a/barretenberg/cpp/src/barretenberg/vm/generated/AvmMini_composer.hpp b/barretenberg/cpp/src/barretenberg/vm/generated/AvmMini_composer.hpp index 17299dff8e7..61a6fbfa622 100644 --- a/barretenberg/cpp/src/barretenberg/vm/generated/AvmMini_composer.hpp +++ b/barretenberg/cpp/src/barretenberg/vm/generated/AvmMini_composer.hpp @@ -8,10 +8,10 @@ #include "barretenberg/vm/generated/AvmMini_prover.hpp" #include "barretenberg/vm/generated/AvmMini_verifier.hpp" -namespace bb::honk { +namespace bb { class AvmMiniComposer { public: - using Flavor = honk::flavor::AvmMiniFlavor; + using Flavor = AvmMiniFlavor; using CircuitConstructor = AvmMiniCircuitBuilder; using ProvingKey = Flavor::ProvingKey; using VerificationKey = Flavor::VerificationKey; @@ -66,4 +66,4 @@ class AvmMiniComposer { }; }; -} // namespace bb::honk +} // namespace bb diff --git a/barretenberg/cpp/src/barretenberg/vm/generated/AvmMini_prover.cpp b/barretenberg/cpp/src/barretenberg/vm/generated/AvmMini_prover.cpp index 5dc17405239..d79339a530b 100644 --- a/barretenberg/cpp/src/barretenberg/vm/generated/AvmMini_prover.cpp +++ b/barretenberg/cpp/src/barretenberg/vm/generated/AvmMini_prover.cpp @@ -11,9 +11,9 @@ #include "barretenberg/relations/permutation_relation.hpp" #include "barretenberg/sumcheck/sumcheck.hpp" -namespace bb::honk { +namespace bb { -using Flavor = honk::flavor::AvmMiniFlavor; +using Flavor = AvmMiniFlavor; using FF = Flavor::FF; /** @@ -70,7 +70,7 @@ void AvmMiniProver::execute_wire_commitments_round() */ void AvmMiniProver::execute_relation_check_rounds() { - using Sumcheck = sumcheck::SumcheckProver; + using Sumcheck = SumcheckProver; auto sumcheck = Sumcheck(key->circuit_size, transcript); @@ -99,13 +99,13 @@ void AvmMiniProver::execute_zeromorph_rounds() transcript); } -honk::proof& AvmMiniProver::export_proof() +HonkProof& AvmMiniProver::export_proof() { proof = transcript->proof_data; return proof; } -bb::honk::proof& AvmMiniProver::construct_proof() +HonkProof& AvmMiniProver::construct_proof() { // Add circuit size public input size and public inputs to transcript. execute_preamble_round(); @@ -132,4 +132,4 @@ bb::honk::proof& AvmMiniProver::construct_proof() return export_proof(); } -} // namespace bb::honk +} // namespace bb diff --git a/barretenberg/cpp/src/barretenberg/vm/generated/AvmMini_prover.hpp b/barretenberg/cpp/src/barretenberg/vm/generated/AvmMini_prover.hpp index 7c88d3b455e..726ea473bf2 100644 --- a/barretenberg/cpp/src/barretenberg/vm/generated/AvmMini_prover.hpp +++ b/barretenberg/cpp/src/barretenberg/vm/generated/AvmMini_prover.hpp @@ -8,11 +8,11 @@ #include "barretenberg/sumcheck/sumcheck_output.hpp" #include "barretenberg/transcript/transcript.hpp" -namespace bb::honk { +namespace bb { class AvmMiniProver { - using Flavor = honk::flavor::AvmMiniFlavor; + using Flavor = AvmMiniFlavor; using FF = Flavor::FF; using PCS = Flavor::PCS; using PCSCommitmentKey = Flavor::CommitmentKey; @@ -31,8 +31,8 @@ class AvmMiniProver { void execute_relation_check_rounds(); void execute_zeromorph_rounds(); - honk::proof& export_proof(); - honk::proof& construct_proof(); + HonkProof& export_proof(); + HonkProof& construct_proof(); std::shared_ptr transcript = std::make_shared(); @@ -49,14 +49,14 @@ class AvmMiniProver { Polynomial quotient_W; - sumcheck::SumcheckOutput sumcheck_output; + SumcheckOutput sumcheck_output; std::shared_ptr commitment_key; - using ZeroMorph = pcs::zeromorph::ZeroMorphProver_; + using ZeroMorph = ZeroMorphProver_; private: - honk::proof proof; + HonkProof proof; }; -} // namespace bb::honk +} // namespace bb diff --git a/barretenberg/cpp/src/barretenberg/vm/generated/AvmMini_verifier.cpp b/barretenberg/cpp/src/barretenberg/vm/generated/AvmMini_verifier.cpp index 5d18e651ac7..8d093e0fee3 100644 --- a/barretenberg/cpp/src/barretenberg/vm/generated/AvmMini_verifier.cpp +++ b/barretenberg/cpp/src/barretenberg/vm/generated/AvmMini_verifier.cpp @@ -5,10 +5,7 @@ #include "barretenberg/numeric/bitop/get_msb.hpp" #include "barretenberg/transcript/transcript.hpp" -using namespace bb; -using namespace bb::honk::sumcheck; - -namespace bb::honk { +namespace bb { AvmMiniVerifier::AvmMiniVerifier(std::shared_ptr verifier_key) : key(verifier_key) {} @@ -30,13 +27,13 @@ AvmMiniVerifier& AvmMiniVerifier::operator=(AvmMiniVerifier&& other) noexcept * @brief This function verifies an AvmMini Honk proof for given program settings. * */ -bool AvmMiniVerifier::verify_proof(const honk::proof& proof) +bool AvmMiniVerifier::verify_proof(const HonkProof& proof) { - using Flavor = honk::flavor::AvmMiniFlavor; + using Flavor = AvmMiniFlavor; using FF = Flavor::FF; using Commitment = Flavor::Commitment; // using Curve = Flavor::Curve; - // using ZeroMorph = pcs::zeromorph::ZeroMorphVerifier_; + // using ZeroMorph = ZeroMorphVerifier_; using VerifierCommitments = Flavor::VerifierCommitments; using CommitmentLabels = Flavor::CommitmentLabels; @@ -198,4 +195,4 @@ bool AvmMiniVerifier::verify_proof(const honk::proof& proof) return sumcheck_verified.value(); } -} // namespace bb::honk +} // namespace bb diff --git a/barretenberg/cpp/src/barretenberg/vm/generated/AvmMini_verifier.hpp b/barretenberg/cpp/src/barretenberg/vm/generated/AvmMini_verifier.hpp index 81aa4eea673..152950496c0 100644 --- a/barretenberg/cpp/src/barretenberg/vm/generated/AvmMini_verifier.hpp +++ b/barretenberg/cpp/src/barretenberg/vm/generated/AvmMini_verifier.hpp @@ -5,9 +5,9 @@ #include "barretenberg/honk/proof_system/types/proof.hpp" #include "barretenberg/sumcheck/sumcheck.hpp" -namespace bb::honk { +namespace bb { class AvmMiniVerifier { - using Flavor = honk::flavor::AvmMiniFlavor; + using Flavor = AvmMiniFlavor; using FF = Flavor::FF; using Commitment = Flavor::Commitment; using VerificationKey = Flavor::VerificationKey; @@ -22,7 +22,7 @@ class AvmMiniVerifier { AvmMiniVerifier& operator=(const AvmMiniVerifier& other) = delete; AvmMiniVerifier& operator=(AvmMiniVerifier&& other) noexcept; - bool verify_proof(const honk::proof& proof); + bool verify_proof(const HonkProof& proof); std::shared_ptr key; std::map commitments; @@ -30,4 +30,4 @@ class AvmMiniVerifier { std::shared_ptr transcript; }; -} // namespace bb::honk +} // namespace bb diff --git a/barretenberg/cpp/src/barretenberg/vm/generated/Toy_composer.cpp b/barretenberg/cpp/src/barretenberg/vm/generated/Toy_composer.cpp index 3f311d16311..b5c36724fd6 100644 --- a/barretenberg/cpp/src/barretenberg/vm/generated/Toy_composer.cpp +++ b/barretenberg/cpp/src/barretenberg/vm/generated/Toy_composer.cpp @@ -6,9 +6,9 @@ #include "barretenberg/proof_system/composer/permutation_lib.hpp" #include "barretenberg/vm/generated/Toy_verifier.hpp" -namespace bb::honk { +namespace bb { -using Flavor = honk::flavor::ToyFlavor; +using Flavor = ToyFlavor; void ToyComposer::compute_witness(CircuitConstructor& circuit) { if (computed_witness) { @@ -82,4 +82,4 @@ std::shared_ptr ToyComposer::compute_verification_key(C return verification_key; } -} // namespace bb::honk +} // namespace bb diff --git a/barretenberg/cpp/src/barretenberg/vm/generated/Toy_composer.hpp b/barretenberg/cpp/src/barretenberg/vm/generated/Toy_composer.hpp index 8cbbda8b712..1e6a7292413 100644 --- a/barretenberg/cpp/src/barretenberg/vm/generated/Toy_composer.hpp +++ b/barretenberg/cpp/src/barretenberg/vm/generated/Toy_composer.hpp @@ -8,10 +8,10 @@ #include "barretenberg/vm/generated/Toy_prover.hpp" #include "barretenberg/vm/generated/Toy_verifier.hpp" -namespace bb::honk { +namespace bb { class ToyComposer { public: - using Flavor = honk::flavor::ToyFlavor; + using Flavor = ToyFlavor; using CircuitConstructor = ToyCircuitBuilder; using ProvingKey = Flavor::ProvingKey; using VerificationKey = Flavor::VerificationKey; @@ -66,4 +66,4 @@ class ToyComposer { }; }; -} // namespace bb::honk +} // namespace bb diff --git a/barretenberg/cpp/src/barretenberg/vm/generated/Toy_prover.cpp b/barretenberg/cpp/src/barretenberg/vm/generated/Toy_prover.cpp index 482261dda9f..dd76091689d 100644 --- a/barretenberg/cpp/src/barretenberg/vm/generated/Toy_prover.cpp +++ b/barretenberg/cpp/src/barretenberg/vm/generated/Toy_prover.cpp @@ -11,9 +11,9 @@ #include "barretenberg/relations/permutation_relation.hpp" #include "barretenberg/sumcheck/sumcheck.hpp" -namespace bb::honk { +namespace bb { -using Flavor = honk::flavor::ToyFlavor; +using Flavor = ToyFlavor; /** * Create ToyProver from proving key, witness and manifest. @@ -68,7 +68,7 @@ void ToyProver::execute_wire_commitments_round() */ void ToyProver::execute_relation_check_rounds() { - using Sumcheck = sumcheck::SumcheckProver; + using Sumcheck = SumcheckProver; auto sumcheck = Sumcheck(key->circuit_size, transcript); FF alpha = transcript->get_challenge("Sumcheck:alpha"); std::vector gate_challenges(numeric::get_msb(key->circuit_size)); @@ -94,13 +94,13 @@ void ToyProver::execute_zeromorph_rounds() transcript); } -honk::proof& ToyProver::export_proof() +HonkProof& ToyProver::export_proof() { proof = transcript->proof_data; return proof; } -honk::proof& ToyProver::construct_proof() +HonkProof& ToyProver::construct_proof() { // Add circuit size public input size and public inputs to transcript. execute_preamble_round(); @@ -127,4 +127,4 @@ honk::proof& ToyProver::construct_proof() return export_proof(); } -} // namespace bb::honk +} // namespace bb diff --git a/barretenberg/cpp/src/barretenberg/vm/generated/Toy_prover.hpp b/barretenberg/cpp/src/barretenberg/vm/generated/Toy_prover.hpp index a0b0ec62cfa..8a807b7729a 100644 --- a/barretenberg/cpp/src/barretenberg/vm/generated/Toy_prover.hpp +++ b/barretenberg/cpp/src/barretenberg/vm/generated/Toy_prover.hpp @@ -8,11 +8,11 @@ #include "barretenberg/sumcheck/sumcheck_output.hpp" #include "barretenberg/transcript/transcript.hpp" -namespace bb::honk { +namespace bb { class ToyProver { - using Flavor = honk::flavor::ToyFlavor; + using Flavor = ToyFlavor; using FF = Flavor::FF; using PCS = Flavor::PCS; using PCSCommitmentKey = Flavor::CommitmentKey; @@ -31,8 +31,8 @@ class ToyProver { void execute_relation_check_rounds(); void execute_zeromorph_rounds(); - honk::proof& export_proof(); - honk::proof& construct_proof(); + HonkProof& export_proof(); + HonkProof& construct_proof(); std::shared_ptr transcript = std::make_shared(); @@ -49,14 +49,14 @@ class ToyProver { Polynomial quotient_W; - sumcheck::SumcheckOutput sumcheck_output; + SumcheckOutput sumcheck_output; std::shared_ptr commitment_key; - using ZeroMorph = pcs::zeromorph::ZeroMorphProver_; + using ZeroMorph = ZeroMorphProver_; private: - honk::proof proof; + HonkProof proof; }; -} // namespace bb::honk +} // namespace bb diff --git a/barretenberg/cpp/src/barretenberg/vm/generated/Toy_verifier.cpp b/barretenberg/cpp/src/barretenberg/vm/generated/Toy_verifier.cpp index f153991ed90..b430c530234 100644 --- a/barretenberg/cpp/src/barretenberg/vm/generated/Toy_verifier.cpp +++ b/barretenberg/cpp/src/barretenberg/vm/generated/Toy_verifier.cpp @@ -5,10 +5,7 @@ #include "barretenberg/numeric/bitop/get_msb.hpp" #include "barretenberg/transcript/transcript.hpp" -using namespace bb; -using namespace bb::honk::sumcheck; - -namespace bb::honk { +namespace bb { ToyVerifier::ToyVerifier(std::shared_ptr verifier_key) : key(verifier_key) {} @@ -30,13 +27,13 @@ ToyVerifier& ToyVerifier::operator=(ToyVerifier&& other) noexcept * @brief This function verifies an Toy Honk proof for given program settings. * */ -bool ToyVerifier::verify_proof(const honk::proof& proof) +bool ToyVerifier::verify_proof(const HonkProof& proof) { - using Flavor = honk::flavor::ToyFlavor; + using Flavor = ToyFlavor; using FF = Flavor::FF; using Commitment = Flavor::Commitment; // using Curve = Flavor::Curve; - // using ZeroMorph = pcs::zeromorph::ZeroMorphVerifier_; + // using ZeroMorph = ZeroMorphVerifier_; using VerifierCommitments = Flavor::VerifierCommitments; using CommitmentLabels = Flavor::CommitmentLabels; @@ -113,4 +110,4 @@ bool ToyVerifier::verify_proof(const honk::proof& proof) return sumcheck_verified.value(); } -} // namespace bb::honk +} // namespace bb diff --git a/barretenberg/cpp/src/barretenberg/vm/generated/Toy_verifier.hpp b/barretenberg/cpp/src/barretenberg/vm/generated/Toy_verifier.hpp index ce84ed8ab6b..d4bbdd2a998 100644 --- a/barretenberg/cpp/src/barretenberg/vm/generated/Toy_verifier.hpp +++ b/barretenberg/cpp/src/barretenberg/vm/generated/Toy_verifier.hpp @@ -5,9 +5,9 @@ #include "barretenberg/honk/proof_system/types/proof.hpp" #include "barretenberg/sumcheck/sumcheck.hpp" -namespace bb::honk { +namespace bb { class ToyVerifier { - using Flavor = honk::flavor::ToyFlavor; + using Flavor = ToyFlavor; using FF = Flavor::FF; using Commitment = Flavor::Commitment; using VerificationKey = Flavor::VerificationKey; @@ -22,7 +22,7 @@ class ToyVerifier { ToyVerifier& operator=(const ToyVerifier& other) = delete; ToyVerifier& operator=(ToyVerifier&& other) noexcept; - bool verify_proof(const honk::proof& proof); + bool verify_proof(const HonkProof& proof); std::shared_ptr key; std::map commitments; @@ -30,4 +30,4 @@ class ToyVerifier { std::shared_ptr transcript; }; -} // namespace bb::honk +} // namespace bb diff --git a/barretenberg/cpp/src/barretenberg/vm/tests/AvmMini_arithmetic.test.cpp b/barretenberg/cpp/src/barretenberg/vm/tests/AvmMini_arithmetic.test.cpp index 6cde3d10186..c486d6af888 100644 --- a/barretenberg/cpp/src/barretenberg/vm/tests/AvmMini_arithmetic.test.cpp +++ b/barretenberg/cpp/src/barretenberg/vm/tests/AvmMini_arithmetic.test.cpp @@ -2,7 +2,8 @@ #include "barretenberg/numeric/uint128/uint128.hpp" -using namespace numeric; +using namespace bb; +using namespace bb::numeric; namespace { using namespace tests_avm; diff --git a/barretenberg/cpp/src/barretenberg/vm/tests/AvmMini_control_flow.test.cpp b/barretenberg/cpp/src/barretenberg/vm/tests/AvmMini_control_flow.test.cpp index 11ede61acfc..a5eeeadb817 100644 --- a/barretenberg/cpp/src/barretenberg/vm/tests/AvmMini_control_flow.test.cpp +++ b/barretenberg/cpp/src/barretenberg/vm/tests/AvmMini_control_flow.test.cpp @@ -1,5 +1,7 @@ #include "AvmMini_common.test.hpp" +using namespace bb; + namespace tests_avm { using namespace avm_trace; diff --git a/barretenberg/cpp/src/barretenberg/vm/tests/AvmMini_execution.test.cpp b/barretenberg/cpp/src/barretenberg/vm/tests/AvmMini_execution.test.cpp index afe4386816d..ce2fcf868b1 100644 --- a/barretenberg/cpp/src/barretenberg/vm/tests/AvmMini_execution.test.cpp +++ b/barretenberg/cpp/src/barretenberg/vm/tests/AvmMini_execution.test.cpp @@ -10,6 +10,7 @@ #include #include +using namespace bb; namespace { void gen_proof_and_validate(std::vector const& bytecode, std::vector&& trace, @@ -19,7 +20,7 @@ void gen_proof_and_validate(std::vector const& bytecode, circuit_builder.set_trace(std::move(trace)); EXPECT_TRUE(circuit_builder.check_circuit()); - auto composer = honk::AvmMiniComposer(); + auto composer = AvmMiniComposer(); auto verifier = composer.create_verifier(circuit_builder); auto proof = avm_trace::Execution::run_and_prove(bytecode, calldata); diff --git a/barretenberg/cpp/src/barretenberg/vm/tests/AvmMini_memory.test.cpp b/barretenberg/cpp/src/barretenberg/vm/tests/AvmMini_memory.test.cpp index f51e4139539..668462d65a8 100644 --- a/barretenberg/cpp/src/barretenberg/vm/tests/AvmMini_memory.test.cpp +++ b/barretenberg/cpp/src/barretenberg/vm/tests/AvmMini_memory.test.cpp @@ -1,4 +1,7 @@ #include "AvmMini_common.test.hpp" + +using namespace bb; + namespace tests_avm { using namespace avm_trace; diff --git a/barretenberg/cpp/src/barretenberg/vm/tests/helpers.test.cpp b/barretenberg/cpp/src/barretenberg/vm/tests/helpers.test.cpp index 8377eba5ff8..dc2a1e29b77 100644 --- a/barretenberg/cpp/src/barretenberg/vm/tests/helpers.test.cpp +++ b/barretenberg/cpp/src/barretenberg/vm/tests/helpers.test.cpp @@ -15,7 +15,7 @@ void validate_trace_proof(std::vector&& trace) EXPECT_TRUE(circuit_builder.check_circuit()); - auto composer = honk::AvmMiniComposer(); + auto composer = AvmMiniComposer(); auto prover = composer.create_prover(circuit_builder); auto proof = prover.construct_proof(); diff --git a/boxes/.gitignore b/boxes/.gitignore index fd32083ab67..0b262eb6853 100644 --- a/boxes/.gitignore +++ b/boxes/.gitignore @@ -3,4 +3,4 @@ node_modules dest -src/contracts/target \ No newline at end of file +src/contracts/target diff --git a/boxes/blank-react/.eslintrc.cjs b/boxes/blank-react/.eslintrc.cjs index 8b84efd5d65..11d8d8c093c 100644 --- a/boxes/blank-react/.eslintrc.cjs +++ b/boxes/blank-react/.eslintrc.cjs @@ -1,63 +1,42 @@ module.exports = { root: true, env: { browser: true, es2020: true }, - parserOptions: { - project: './tsconfig.json', - }, extends: [ - 'eslint:recommended', - 'plugin:@typescript-eslint/recommended', - 'plugin:react-hooks/recommended', - 'plugin:import/recommended', - 'plugin:import/typescript', - 'prettier', + "eslint:recommended", + "plugin:@typescript-eslint/recommended", + "plugin:react-hooks/recommended", + "plugin:import/recommended", + "plugin:import/typescript", + "prettier", ], settings: { - 'import/resolver': { + "import/resolver": { typescript: true, node: true, }, }, - ignorePatterns: ['dest', 'webpack.config.js', '.eslintrc.cjs'], - parser: '@typescript-eslint/parser', - plugins: ['react-refresh'], - overrides: [ - { - files: ['*.ts', '*.tsx'], - parserOptions: { - project: true, - }, - }, - ], + ignorePatterns: ["dest", "webpack.config.js", ".eslintrc.cjs"], + parser: "@typescript-eslint/parser", + plugins: ["react-refresh"], rules: { - 'react-refresh/only-export-components': ['warn', { allowConstantExport: true }], - '@typescript-eslint/explicit-module-boundary-types': 'off', - '@typescript-eslint/no-non-null-assertion': 'off', - '@typescript-eslint/no-explicit-any': 'off', - '@typescript-eslint/no-empty-function': 'off', - '@typescript-eslint/await-thenable': 'error', - '@typescript-eslint/no-floating-promises': 2, - '@typescript-eslint/no-unused-vars': ['error', { argsIgnorePattern: '^_', varsIgnorePattern: '^_' }], - 'require-await': 2, - 'no-console': 'warn', - 'no-constant-condition': 'off', - camelcase: 2, - 'no-restricted-imports': [ - 'error', - { - patterns: [ - { - group: ['client-dest'], - message: "Fix this absolute garbage import. It's your duty to solve it before it spreads.", - }, - { - group: ['dest'], - message: 'You should not be importing from a build directory. Did you accidentally do a relative import?', - }, - ], - }, + "react-refresh/only-export-components": [ + "warn", + { allowConstantExport: true }, + ], + "@typescript-eslint/explicit-module-boundary-types": "off", + "@typescript-eslint/no-non-null-assertion": "off", + "@typescript-eslint/no-explicit-any": "off", + "@typescript-eslint/no-empty-function": "off", + "@typescript-eslint/await-thenable": "error", + "@typescript-eslint/no-unused-vars": [ + "error", + { argsIgnorePattern: "^_", varsIgnorePattern: "^_" }, ], - 'import/no-unresolved': 'error', - 'import/no-extraneous-dependencies': 'error', + "require-await": 2, + "no-console": "warn", + "no-constant-condition": "off", + camelcase: 2, + "import/no-unresolved": "error", + "import/no-extraneous-dependencies": "error", }, }; diff --git a/boxes/blank-react/.gitignore b/boxes/blank-react/.gitignore index 1270997806b..7e20050d72e 100644 --- a/boxes/blank-react/.gitignore +++ b/boxes/blank-react/.gitignore @@ -2,6 +2,7 @@ !.yarn/releases node_modules -dest -src/artifacts -src/contracts/target \ No newline at end of file +dist +artifacts +src/contracts/target +src/contracts/log diff --git a/boxes/blank-react/.prettierignore b/boxes/blank-react/.prettierignore deleted file mode 100644 index a72dfe54860..00000000000 --- a/boxes/blank-react/.prettierignore +++ /dev/null @@ -1,2 +0,0 @@ -src/artifacts/**/*.json -src/artifacts/**/*.ts \ No newline at end of file diff --git a/boxes/blank-react/.prettierrc.json b/boxes/blank-react/.prettierrc.json deleted file mode 100644 index 7c3bbec6848..00000000000 --- a/boxes/blank-react/.prettierrc.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "singleQuote": true, - "trailingComma": "all", - "printWidth": 120, - "arrowParens": "avoid" -} diff --git a/boxes/blank-react/README.md b/boxes/blank-react/README.md index 29a96433a8d..553fe549bca 100644 --- a/boxes/blank-react/README.md +++ b/boxes/blank-react/README.md @@ -1,80 +1,67 @@ -This is a minimal [Aztec](https://aztec.network/) Noir smart contract and frontend bootstrapped with [`aztec-cli unbox`](https://github.com/AztecProtocol/aztec-packages/tree/master/yarn-project/cli). It is recommended you use the `aztec-cli unbox blank-react` command so that the repository is copied with needed modifications from the monorepo subpackage. +# Aztec Box -## Setup +This box is a one-stop-shop for Aztec that will deploy a blank React Page. You can use it as a boilerplate to start developing your own Aztec app in seconds! -Dependencies can be installed from the root of the package: +## Prerequisites + +- You should have Docker installed. If you don't, follow [this guide](https://docs.aztec.network/dev_docs/getting_started/quickstart#install-docker). + +## Installation + +To start, run the Aztec install script: ```bash -yarn -yarn install:noir -yarn install:sandbox +bash -i <(curl -s install.aztec.network)` ``` -This sandbox requires [Docker](https://www.docker.com/) to be installed _and running_ locally. In the event the image needs updating, you can run `yarn install:sandbox` (see [sandbox docs](https://docs.aztec.network/developers/cli/main) for more information.) +After a few minutes, you should have all the Aztec CLI commands ready to run. -In addition to the usual javascript dependencies, this project requires `nargo` (package manager) and `noir` (Aztec ZK smart contract language) in addition to `@aztec/aztec-cli`. The former two are installed by `yarn install:noir`. +### 1. Launching the sandbox -## Getting started +Run: -After `yarn` has run,`yarn start:sandbox` in one terminal will launch a local instance of the Aztec sandbox via Docker Compose and `yarn start:dev` will launch a frontend app for deploying and interacting with an empty Aztec smart contract. +```bash +aztec-sandbox +``` -At this point, [http://localhost:5173](http://localhost:5173) should provide a minimal smart contract frontend. +This will install all the dependencies and run the sandbox on port 8080 together with a anvil node. -This folder should have the following directory structure: +### 2. Unboxing the box -``` -|— README.md -|— package.json -|— src - |-config.ts - Blank Contract specific configuration for the frontend. - | You may need to update this if you modify the contract functions. - |— app - |— [frontend React .tsx code files] - |- scripts - |- [helpers for frontend to interact with contract on the sandbox] - |— contracts - |— src - | The Noir smart contract source files are here. - |— main.nr - the cloned noir contract, your starting point - |- interface.nr - autogenerated from main.nr when you compile - |— Nargo.toml [Noir build file, includes Aztec smart contract dependencies] - |— artifacts - | These are both generated from `contracts/` by the compile command - |— blank_contract.json - |— blank.ts - |— tests - | A simple end2end test deploying and testing the Blank contract deploys on a local sandbox - | The test requires the sandbox and anvil to be running (`yarn start:sandbox`). - | You can run the tests with `yarn test:integration` - |- blank.contract.test.ts -``` +Unbox the box with: -Most relevant to you is likely `src/contracts/main.nr` (and the build config `src/contracts/Nargo.toml`). This contains the example blank contract logic that the frontend interacts with and is a good place to start writing Noir. +```bash +aztec-cli unbox blank-react +``` -The `src/artifacts` folder can be re-generated from the command line +and install dependencies: ```bash -yarn compile +yarn ``` -This will generate a [Contract ABI](src/artifacts/test_contract.json) and TypeScript class for the [Aztec smart contract](src/contracts/main.nr), which the frontend uses to generate the UI. +This sandbox requires [Docker](https://www.docker.com/) to be installed _and running_ locally. In the event the image needs updating, you can run `yarn install:sandbox` (see [sandbox docs](https://docs.aztec.network/developers/cli/main) for more information.) -Note: the `compile` command seems to generate a Typescript file which needs a single change - +Time to build. Run: +```bash +yarn start ``` -import TestContractArtifactJson from 'text_contract.json' assert { type: 'json' }; -// need to update the relative import to -import TestContractArtifactJson from './test_contract.json' assert { type: 'json' }; -``` -After compiling, you can re-deploy the updated noir smart contract from the web UI. The function interaction forms are generated from parsing the contract artifacts, so they should update automatically after you recompile. +Your React app is waiting for you on port 5176. Time to make it your own! + +In the `src/contracts` folder, you'll find the default contract being deployed. Don't forget to recompile with `aztec-nargo compile`! Read the [aztec.nr documentation](https://docs.aztec.network/dev_docs/contracts/main) to get started with the `aztec.nr` framework. -## Learn More +[Read the full Sandbox reference](https://docs.aztec.network/dev_docs/cli/sandbox-reference) for more info on what exactly is happening on your machine! -To learn more about Noir Smart Contract development, take a look at the following resources: +## More info -- [Awesome Noir](https://github.com/noir-lang/awesome-noir) - learn about the Noir programming language. +There are five folders in your `src` folder: -## Deploy on Aztec3 +- `app` - This is your actual React app +- `scripts` - These are the scripts the frontend is using to talk with the sandbox +- `contracts` - The Aztec Contracts you just deployed! +- `artifacts` - Auto-generated when you compile +- `test` - A boilerplate with a simple test -Coming Soon :) +Visit the [Aztec Docs](https://docs.aztec.network) for more information on how Aztec works, and the [Awesome Aztec Repository](https://github.com/AztecProtocol/awesome-aztec) for more cool projects, boilerplates and tooling. diff --git a/boxes/blank-react/index.html b/boxes/blank-react/index.html new file mode 100644 index 00000000000..7e9084bc121 --- /dev/null +++ b/boxes/blank-react/index.html @@ -0,0 +1,25 @@ + + + + + + Private Token Noir Smart Contract + + +
+ + + + diff --git a/boxes/blank-react/package.json b/boxes/blank-react/package.json index b9a9ff00dfa..ea02f332c28 100644 --- a/boxes/blank-react/package.json +++ b/boxes/blank-react/package.json @@ -3,16 +3,17 @@ "private": true, "version": "0.1.0", "type": "module", - "main": "./dest/index.js", + "main": "./dist/index.js", "scripts": { + "compile": "cd src/contracts && ${AZTEC_NARGO:-aztec-nargo} compile", + "codegen": "${AZTEC_CLI:-aztec-cli} codegen src/contracts/target -o artifacts --ts", "build": "yarn clean && yarn compile && yarn codegen && tsc -b && webpack", - "clean": "rm -rf ./dest .tsbuildinfo ./src/artifacts ./src/contracts/target", - "start": "serve -p 3000 ./dest", - "start:dev": "webpack serve --mode=development", + "clean": "rm -rf ./dist .tsbuildinfo ./artifacts ./src/contracts/target", + "prep": "yarn clean && yarn compile && yarn codegen", + "dev": "webpack serve --mode development", + "serve": "serve -p 3000 ./dist", "formatting": "prettier --check ./src && eslint ./src", "formatting:fix": "prettier -w ./src", - "compile": "cd src/contracts && ${AZTEC_NARGO:-aztec-nargo} compile", - "codegen": "${AZTEC_CLI:-aztec-cli} codegen src/contracts/target -o src/artifacts --ts", "test": "NODE_NO_WARNINGS=1 node --experimental-vm-modules $(yarn bin jest) --runInBand" }, "jest": { @@ -28,8 +29,8 @@ "moduleNameMapper": { "^(\\.{1,2}/.*)\\.js$": "$1" }, - "testRegex": "./src/.*\\.test\\.ts$", - "rootDir": "./src" + "testRegex": "tests/.*\\.test\\.ts$", + "rootDir": "./" }, "dependencies": { "@aztec/accounts": "^0.16.9", @@ -46,7 +47,6 @@ }, "devDependencies": { "@types/jest": "^29.5.0", - "@types/mocha": "^10.0.3", "@types/node": "^20.5.9", "@types/react": "^18.2.15", "@types/react-dom": "^18.2.7", @@ -62,10 +62,12 @@ "eslint-plugin-prettier": "^5.0.1", "eslint-plugin-react-hooks": "^4.6.0", "eslint-plugin-react-refresh": "^0.4.3", + "html-webpack-plugin": "^5.6.0", "jest": "^29.6.4", "postcss": "^8.4.29", "postcss-loader": "^7.3.3", "prettier": "^3.1.1", + "react-toastify": "^10.0.4", "resolve-typescript-plugin": "^2.0.1", "stream-browserify": "^3.0.0", "style-loader": "^3.3.3", @@ -79,23 +81,11 @@ "webpack-cli": "^5.1.4", "webpack-dev-server": "^4.15.1" }, - "browserslist": { - "production": [ - ">0.5%", - "not dead", - "not op_mini all" - ], - "development": [ - "last 1 chrome version", - "last 1 firefox version", - "last 1 safari version" - ] - }, "files": [ - "dest", + "dist", "src", "!*.test.*" ], - "types": "./dest/index.d.ts", + "types": "./dist/index.d.ts", "packageManager": "yarn@4.0.2" } diff --git a/boxes/blank-react/src/@types/index.d.ts b/boxes/blank-react/src/@types/index.d.ts deleted file mode 100644 index 3598bbcb0be..00000000000 --- a/boxes/blank-react/src/@types/index.d.ts +++ /dev/null @@ -1,9 +0,0 @@ -declare module '*.svg' { - const content: any; - export default content; -} - -declare module '*.module.scss' { - const content: { [className: string]: string }; - export = content; -} diff --git a/boxes/blank-react/src/app/components/contract_function_form.module.scss b/boxes/blank-react/src/app/components/contract_function_form.module.scss deleted file mode 100644 index 056dcc719ff..00000000000 --- a/boxes/blank-react/src/app/components/contract_function_form.module.scss +++ /dev/null @@ -1,66 +0,0 @@ -.input { - border: none; - outline-width: 0; - outline-color: rgba(0, 0, 0, 0); - padding: 2px 20px 0 20px; - width: 100%; - height: 45px; - color: #000; - border: 1px solid rgba(0, 0, 0, 0); - font-size: 16px; - text-align: left; - font-weight: 400; - border-radius: 10px; - text-align: left; - text-overflow: ellipsis; - transition: box-shadow 0.2s; - box-shadow: 0px 4px 10px rgba(0, 0, 0, 0.1); - background-color: white; - -webkit-appearance: none; - - &:disabled { - color: #4a4a4a; - background-color: rgba(239, 239, 239, 0.3); - background: radial-gradient(rgba(239, 239, 239, 0.3), rgba(239, 239, 239, 0.3)); - -webkit-text-fill-color: #4a4a4a; - cursor: not-allowed; - } -} - -.label { - font-weight: 450; - font-size: 18px; - display: flex; - width: 100%; - flex-direction: column; - text-align: left; - margin-bottom: 15px; - justify-content: space-between; -} - -.inputWrapper { - width: 100%; - display: flex; - gap: 15px; -} - -.field { - display: flex; - justify-content: start; - flex-direction: column; - align-items: flex-start; -} - -.content { - display: flex; - justify-content: space-between; - flex-direction: column; - margin: 30px; - width: 450px; - gap: 30px; -} - -.actionButton { - width: 100%; - align-self: center; -} diff --git a/boxes/blank-react/src/app/components/contract_function_form.tsx b/boxes/blank-react/src/app/components/contract_function_form.tsx deleted file mode 100644 index 66609bd2ab9..00000000000 --- a/boxes/blank-react/src/app/components/contract_function_form.tsx +++ /dev/null @@ -1,177 +0,0 @@ -import { CONTRACT_ADDRESS_PARAM_NAMES, pxe } from '../../config.js'; -import { callContractFunction, deployContract, viewContractFunction } from '../../scripts/index.js'; -import { convertArgs } from '../../scripts/util.js'; -import styles from './contract_function_form.module.scss'; -import { Button, Loader } from '@aztec/aztec-ui'; -import { AztecAddress, CompleteAddress, ContractArtifact, Fr, FunctionArtifact } from '@aztec/aztec.js'; -import { useFormik } from 'formik'; -import * as Yup from 'yup'; - -type NoirFunctionYupSchema = { - // hack: add `any` at the end to get the array schema to typecheck - // eslint-disable-next-line @typescript-eslint/no-explicit-any - [key: string]: Yup.NumberSchema | Yup.ArraySchema | Yup.BooleanSchema | any; -}; - -type NoirFunctionFormValues = { - [key: string]: string | number | number[] | boolean; -}; - -function generateYupSchema(functionAbi: FunctionArtifact, defaultAddress: string) { - const parameterSchema: NoirFunctionYupSchema = {}; - const initialValues: NoirFunctionFormValues = {}; - for (const param of functionAbi.parameters) { - if (CONTRACT_ADDRESS_PARAM_NAMES.includes(param.name)) { - // these are hex strings instead, but yup doesn't support bigint so we convert back to bigint on execution - parameterSchema[param.name] = Yup.string().required(); - initialValues[param.name] = defaultAddress; - continue; - } - switch (param.type.kind) { - case 'field': - parameterSchema[param.name] = Yup.number().required(); - initialValues[param.name] = 100; - break; - // not really needed for private token, since we hide the nullifier helper method which has the array input - case 'array': - // eslint-disable-next-line no-case-declarations - const arrayLength = param.type.length; - parameterSchema[param.name] = Yup.array() - .of(Yup.number()) - .min(arrayLength) - .max(arrayLength) - .transform(function (value: number[], originalValue: string) { - if (typeof originalValue === 'string') { - return originalValue.split(',').map(Number); - } - return value; - }); - initialValues[param.name] = Array(arrayLength).fill( - CONTRACT_ADDRESS_PARAM_NAMES.includes(param.name) ? defaultAddress : 200, - ); - break; - case 'boolean': - parameterSchema[param.name] = Yup.boolean().required(); - initialValues[param.name] = false; - break; - } - } - return { validationSchema: Yup.object().shape(parameterSchema), initialValues }; -} - -async function handleFunctionCall( - contractAddress: AztecAddress | undefined, - contractArtifact: ContractArtifact, - functionName: string, - args: any, - wallet: CompleteAddress, -) { - const functionAbi = contractArtifact.functions.find(f => f.name === functionName)!; - const typedArgs: any[] = convertArgs(functionAbi, args); - - if (functionName === 'constructor' && !!wallet) { - if (functionAbi === undefined) { - throw new Error('Cannot find constructor in the ABI.'); - } - // hack: addresses are stored as string in the form to avoid bigint compatibility issues with formik - // convert those back to bigints before sending - - // for now, dont let user change the salt. requires some change to the form generation if we want to let user choose one - // since everything is currently based on parsing the contractABI, and the salt parameter is not present there - const salt = Fr.random(); - return await deployContract(wallet, contractArtifact, typedArgs, salt, pxe); - } - - if (functionAbi.functionType === 'unconstrained') { - return await viewContractFunction(contractAddress!, contractArtifact, functionName, typedArgs, pxe, wallet); - } else { - const txnReceipt = await callContractFunction( - contractAddress!, - contractArtifact, - functionName, - typedArgs, - pxe, - wallet, - ); - return `Transaction ${txnReceipt.status} on block number ${txnReceipt.blockNumber}`; - } -} - -interface ContractFunctionFormProps { - wallet: CompleteAddress; - contractAddress?: AztecAddress; - contractArtifact: ContractArtifact; - functionArtifact: FunctionArtifact; - defaultAddress: string; - title?: string; - buttonText?: string; - isLoading: boolean; - disabled: boolean; - onSubmit: () => void; - onSuccess: (result: any) => void; - onError: (msg: string) => void; -} - -export function ContractFunctionForm({ - wallet, - contractAddress, - contractArtifact, - functionArtifact, - defaultAddress, - buttonText = 'Submit', - isLoading, - disabled, - onSubmit, - onSuccess, - onError, -}: ContractFunctionFormProps) { - const { validationSchema, initialValues } = generateYupSchema(functionArtifact, defaultAddress); - const formik = useFormik({ - initialValues: initialValues, - validationSchema: validationSchema, - onSubmit: async (values: any) => { - onSubmit(); - try { - const result = await handleFunctionCall( - contractAddress, - contractArtifact, - functionArtifact.name, - values, - wallet, - ); - onSuccess(result); - } catch (e: any) { - onError(e.message); - } - }, - }); - - return ( -
- {functionArtifact.parameters.map(input => ( -
- - - {formik.touched[input.name] && formik.errors[input.name] && ( -
{formik.errors[input.name]?.toString()}
- )} -
- ))} - {isLoading ? ( - - ) : ( - + + +
+ + + + +
+ + ); +} diff --git a/boxes/blank-react/src/pages/home.tsx b/boxes/blank-react/src/pages/home.tsx new file mode 100644 index 00000000000..8c0fb123667 --- /dev/null +++ b/boxes/blank-react/src/pages/home.tsx @@ -0,0 +1,18 @@ +import { ContractComponent } from "./contract"; +import { useContract } from "../hooks/useContract"; + +export function Home() { + const { contract, deploy, wait } = useContract(); + + if (!contract) { + return ( +
+ +
+ ); + } + + return ; +} diff --git a/boxes/blank-react/src/scripts/call_contract_function.ts b/boxes/blank-react/src/scripts/call_contract_function.ts deleted file mode 100644 index d80037eed84..00000000000 --- a/boxes/blank-react/src/scripts/call_contract_function.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { getWallet } from './util.js'; -import { AztecAddress, CompleteAddress, Contract, ContractArtifact, FieldsOf, PXE, TxReceipt } from '@aztec/aztec.js'; - -export async function callContractFunction( - address: AztecAddress, - artifact: ContractArtifact, - functionName: string, - typedArgs: any[], // for the exposed functions, this is an array of field elements Fr[] - pxe: PXE, - wallet: CompleteAddress, -): Promise> { - // selectedWallet is how we specify the "sender" of the transaction - const selectedWallet = await getWallet(wallet, pxe); - - // TODO: switch to the generated typescript class? - const contract = await Contract.at(address, artifact, selectedWallet); - - return contract.methods[functionName](...typedArgs) - .send() - .wait(); -} diff --git a/boxes/blank-react/src/scripts/deploy_contract.ts b/boxes/blank-react/src/scripts/deploy_contract.ts deleted file mode 100644 index 909a3587532..00000000000 --- a/boxes/blank-react/src/scripts/deploy_contract.ts +++ /dev/null @@ -1,26 +0,0 @@ -import { AztecAddress, CompleteAddress, Contract, ContractArtifact, DeployMethod, Fr, PXE } from '@aztec/aztec.js'; - -export async function deployContract( - activeWallet: CompleteAddress, - contractArtifact: ContractArtifact, - typedArgs: Fr[], // encode prior to passing in - salt: Fr, - pxe: PXE, -): Promise { - const tx = new DeployMethod( - activeWallet.publicKey, - pxe, - contractArtifact, - (a, w) => Contract.at(a, contractArtifact, w), - typedArgs, - ).send({ - contractAddressSalt: salt, - }); - await tx.wait(); - const receipt = await tx.getReceipt(); - if (receipt.contractAddress) { - return receipt.contractAddress; - } else { - throw new Error(`Contract not deployed (${receipt.toJSON()})`); - } -} diff --git a/boxes/blank-react/src/scripts/index.ts b/boxes/blank-react/src/scripts/index.ts deleted file mode 100644 index a5d6bcf1a9b..00000000000 --- a/boxes/blank-react/src/scripts/index.ts +++ /dev/null @@ -1,4 +0,0 @@ -export * from './call_contract_function.js'; -export * from './deploy_contract.js'; -export { getWallet } from './util.js'; -export * from './view_contract_function.js'; diff --git a/boxes/blank-react/src/scripts/util.ts b/boxes/blank-react/src/scripts/util.ts deleted file mode 100644 index 3f9d05bfdcb..00000000000 --- a/boxes/blank-react/src/scripts/util.ts +++ /dev/null @@ -1,36 +0,0 @@ -import { AccountWallet, CompleteAddress, Fr, FunctionArtifact, PXE, encodeArguments } from '@aztec/aztec.js'; - -import { getInitialTestAccountsWallets } from '@aztec/accounts/testing'; - -export function convertArgs(functionAbi: FunctionArtifact, args: any): Fr[] { - const untypedArgs = functionAbi.parameters.map(param => { - switch (param.type.kind) { - case 'field': - // hack: addresses are stored as string in the form to avoid bigint compatibility issues with formik - // convert those back to bigints before turning into Fr - return BigInt(args[param.name]); - default: - // they are all fields in the privatetoken contract, need more testing on other types - return args[param.name]; - } - }); - - return encodeArguments(functionAbi, untypedArgs); -} - -/** - * terminology is confusing, but the `account` points to a smart contract's public key information - * while the "wallet" has the account's private key and is used to sign transactions - * we need the "wallet" to actually submit transactions using the "account" identity - * @param account - * @param pxe - * @returns - */ -export async function getWallet(account: CompleteAddress, pxe: PXE): Promise { - const accountWallets: AccountWallet[] = await getInitialTestAccountsWallets(pxe); - const selectedWallet: AccountWallet = accountWallets.find(w => w.getAddress().equals(account.address))!; - if (!selectedWallet) { - throw new Error(`Wallet for account ${account.address.toShortString()} not found in the PXE.`); - } - return selectedWallet; -} diff --git a/boxes/blank-react/src/scripts/view_contract_function.ts b/boxes/blank-react/src/scripts/view_contract_function.ts deleted file mode 100644 index beff0032c77..00000000000 --- a/boxes/blank-react/src/scripts/view_contract_function.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { getWallet } from './util.js'; -import { AztecAddress, CompleteAddress, Contract, ContractArtifact, PXE } from '@aztec/aztec.js'; - -export async function viewContractFunction( - address: AztecAddress, - artifact: ContractArtifact, - functionName: string, - typedArgs: any[], - pxe: PXE, - wallet: CompleteAddress, -) { - // we specify the account that is calling the view function by passing in the wallet to the Contract - const selectedWallet = await getWallet(wallet, pxe); - const contract = await Contract.at(address, artifact, selectedWallet); - - return await contract.methods[functionName](...typedArgs).view({ from: wallet.address }); -} diff --git a/boxes/blank-react/src/tests/blank.contract.test.ts b/boxes/blank-react/src/tests/blank.contract.test.ts deleted file mode 100644 index 8adba3984e5..00000000000 --- a/boxes/blank-react/src/tests/blank.contract.test.ts +++ /dev/null @@ -1,59 +0,0 @@ -import { BlankContract } from '../artifacts/Blank.js'; -import { callContractFunction, deployContract, getWallet } from '../scripts/index.js'; -import { - AccountWallet, - AztecAddress, - CompleteAddress, - Contract, - Fr, - PXE, - TxStatus, - Wallet, - createDebugLogger, -} from '@aztec/aztec.js'; -import { setupEnvironment } from '../environment/index.js'; - -const logger = createDebugLogger('aztec:http-pxe-client'); - - -async function deployZKContract(owner: CompleteAddress, wallet: Wallet, pxe: PXE) { - logger('Deploying Blank contract...'); - const contractAddress = await deployContract(owner, BlankContract.artifact, [], Fr.random(), pxe); - - logger(`L2 contract deployed at ${contractAddress}`); - return BlankContract.at(contractAddress, wallet); -} - -describe('ZK Contract Tests', () => { - let wallet: AccountWallet; - let owner: CompleteAddress; - let _account2: CompleteAddress; - let _account3: CompleteAddress; - let contract: Contract; - let contractAddress: AztecAddress; - let pxe: PXE; - - beforeAll(async () => { - pxe = await setupEnvironment(); - const accounts = await pxe.getRegisteredAccounts(); - [owner, _account2, _account3] = accounts; - - wallet = await getWallet(owner, pxe); - - contract = await deployZKContract(owner, wallet, pxe); - contractAddress = contract.address; - }, 60000); - - test('call succeeds after deploy', async () => { - const callTxReceipt = await callContractFunction( - contractAddress, - contract.artifact, - 'getPublicKey', - [owner.address.toField()], - pxe, - owner, - ); - - expect(callTxReceipt.status).toBe(TxStatus.MINED); - }, 40000); -}); diff --git a/boxes/blank-react/tests/blank.contract.test.ts b/boxes/blank-react/tests/blank.contract.test.ts new file mode 100644 index 00000000000..789e952f492 --- /dev/null +++ b/boxes/blank-react/tests/blank.contract.test.ts @@ -0,0 +1,37 @@ +import { BlankContract } from '../artifacts/Blank.js'; +import { AccountWallet, Fr, Contract, TxStatus, createDebugLogger, ContractDeployer } from '@aztec/aztec.js'; +import { deployerEnv } from '../src/config.js'; + +const logger = createDebugLogger('aztec:http-pxe-client'); + +describe('ZK Contract Tests', () => { + let wallet: AccountWallet; + let contract: Contract; + const { artifact } = BlankContract; + const numberToSet = Fr.random(); + + beforeAll(async () => { + wallet = await deployerEnv.getWallet(); + const pxe = deployerEnv.pxe; + const deployer = new ContractDeployer(artifact, pxe); + const salt = Fr.random(); + const tx = deployer.deploy(Fr.random(), wallet.getCompleteAddress().address).send({ contractAddressSalt: salt }); + await tx.wait(); + const { contractAddress } = await tx.getReceipt(); + contract = await BlankContract.at(contractAddress!, wallet); + + logger(`L2 contract deployed at ${contractAddress}`); + }, 60000); + + test('Can set a number', async () => { + logger(`${await wallet.getRegisteredAccounts()}`); + const callTxReceipt = await contract.methods.setNumber(numberToSet).send().wait(); + + expect(callTxReceipt.status).toBe(TxStatus.MINED); + }, 40000); + + test('Can read a number', async () => { + const viewTxReceipt = await contract.methods.getNumber().view(); + expect(numberToSet.toBigInt()).toEqual(viewTxReceipt.value); + }, 40000); +}); diff --git a/boxes/blank-react/tsconfig.json b/boxes/blank-react/tsconfig.json index acc585a3b0e..76a1c63ac9b 100644 --- a/boxes/blank-react/tsconfig.json +++ b/boxes/blank-react/tsconfig.json @@ -1,12 +1,11 @@ { "compilerOptions": { - "rootDir": "src", - "outDir": "dest", + "outDir": "dist", "tsBuildInfoFile": ".tsbuildinfo", "target": "es2020", "lib": ["esnext", "dom", "DOM.Iterable"], - "module": "NodeNext", - "moduleResolution": "NodeNext", + "module": "ESNext", + "moduleResolution": "Bundler", "strict": true, "declaration": true, "allowSyntheticDefaultImports": true, @@ -21,5 +20,10 @@ "skipLibCheck": true, "jsx": "react-jsx" }, - "include": ["src", "src/contracts/target/*.json"] + "include": [ + "src/**/*.ts*", + "tests/**/*.ts", + "src/contracts/target/*.json", + "artifacts/**/*.ts" + ] } diff --git a/boxes/blank-react/webpack.config.js b/boxes/blank-react/webpack.config.js index 6e825d25aaf..7746f6e0b16 100644 --- a/boxes/blank-react/webpack.config.js +++ b/boxes/blank-react/webpack.config.js @@ -1,85 +1,40 @@ -import CopyWebpackPlugin from 'copy-webpack-plugin'; -import { createRequire } from 'module'; -import { dirname, resolve } from 'path'; -import ResolveTypeScriptPlugin from 'resolve-typescript-plugin'; -import { fileURLToPath } from 'url'; -import webpack from 'webpack'; - +import { createRequire } from "module"; +import webpack from "webpack"; +import HtmlWebpackPlugin from "html-webpack-plugin"; const require = createRequire(import.meta.url); export default (_, argv) => ({ - target: 'web', - mode: 'production', - devtool: 'source-map', + target: "web", + mode: "production", + devtool: "source-map", entry: { - main: './src/app/index.tsx', + main: "./src/index.tsx", }, module: { rules: [ { test: /\.tsx?$/, - use: 'ts-loader', + use: "ts-loader", }, { test: /\.css$/i, - use: ['style-loader', 'css-loader', 'postcss-loader'], - }, - { - test: /\.module\.scss$/, - use: [ - 'style-loader', - { - loader: 'css-loader', - options: { - modules: { - localIdentName: '[local]_[hash:base64:5]', - }, - }, - }, - 'sass-loader', - ], - }, - { - test: /\.(woff|woff2|eot|ttf|otf)$/, - type: 'asset/resource', - }, - { - test: /\.scss$/, - exclude: /\.module\.scss$/, - use: ['style-loader', 'css-loader', 'sass-loader'], + use: ["style-loader", "css-loader", "postcss-loader"], }, ], }, - output: { - path: resolve(dirname(fileURLToPath(import.meta.url)), './dest'), - filename: 'index.js', - }, plugins: [ + new HtmlWebpackPlugin({ + template: "./index.html", + }), new webpack.DefinePlugin({ - 'process.env': { - NODE_ENV: JSON.stringify(argv.mode || 'production'), + "process.env": { + NODE_ENV: JSON.stringify(argv.mode || "production"), }, }), - new webpack.ProvidePlugin({ Buffer: ['buffer', 'Buffer'] }), - new CopyWebpackPlugin({ - patterns: [ - { - from: './src/assets', - }, - { - from: './src/app/index.html', - to: 'index.html', - }, - ], - }), + new webpack.ProvidePlugin({ Buffer: ["buffer", "Buffer"] }), ], resolve: { - plugins: [new ResolveTypeScriptPlugin()], - alias: { - // All node specific code, wherever it's located, should be imported as below. - // Provides a clean and simple way to always strip out the node code for the web build. - './node/index.js': false, - }, + extensions: [".tsx", ".ts", ".js"], fallback: { crypto: false, os: false, @@ -87,19 +42,17 @@ export default (_, argv) => ({ path: false, url: false, worker_threads: false, - events: require.resolve('events/'), - buffer: require.resolve('buffer/'), - util: require.resolve('util/'), - stream: require.resolve('stream-browserify'), - string_decoder: require.resolve('string_decoder/'), - tty: require.resolve('tty-browserify'), + events: require.resolve("events/"), + buffer: require.resolve("buffer/"), + util: require.resolve("util/"), + stream: require.resolve("stream-browserify"), + string_decoder: require.resolve("string_decoder/"), + tty: require.resolve("tty-browserify"), }, }, devServer: { port: 5173, historyApiFallback: true, - client: { - overlay: false, - }, + open: true, }, }); diff --git a/boxes/blank/.gitignore b/boxes/blank/.gitignore index 1270997806b..d37f6988611 100644 --- a/boxes/blank/.gitignore +++ b/boxes/blank/.gitignore @@ -3,5 +3,5 @@ node_modules dest -src/artifacts -src/contracts/target \ No newline at end of file +artifacts +src/contracts/target diff --git a/boxes/blank/README.md b/boxes/blank/README.md index 6443e4f34cc..49160e6803d 100644 --- a/boxes/blank/README.md +++ b/boxes/blank/README.md @@ -1,76 +1,67 @@ -This is a minimal [Aztec](https://aztec.network/) Noir smart contract and frontend bootstrapped with [`aztec-cli unbox`](https://github.com/AztecProtocol/aztec-packages/tree/master/yarn-project/cli). It is recommended you use the `aztec-cli unbox blank` command so that the repository is copied with needed modifications from the monorepo subpackage. +# Aztec Box -## Setup +This box is a one-stop-shop for Aztec that will deploy a minimal barebones HTML+JS page. You can use it as a boilerplate to start developing your own Aztec app in seconds! -Dependencies can be installed from the root of the package: +## Prerequisites + +- You should have Docker installed. If you don't, follow [this guide](https://docs.aztec.network/dev_docs/getting_started/quickstart#install-docker). + +## Installation + +To start, run the Aztec install script: ```bash -yarn -yarn install:noir -yarn install:sandbox +bash -i <(curl -s install.aztec.network)` ``` -This sandbox requires [Docker](https://www.docker.com/) to be installed _and running_ locally. In the event the image needs updating, you can run `yarn install:sandbox` (see [sandbox docs](https://docs.aztec.network/developers/cli/main) for more information.) +After a few minutes, you should have all the Aztec CLI commands ready to run. -In addition to the usual javascript dependencies, this project requires `nargo` (package manager) and `noir` (a Domain Specific Language for SNARK proving systems) in addition to `@aztec/aztec-cli`. The former are installed within `yarn install:noir`. +### 1. Launching the sandbox -## Getting started +Run: -After `yarn` has run,`yarn start:sandbox` in one terminal will launch a local instance of the Aztec sandbox via Docker Compose and `yarn start:dev` will launch a frontend app for deploying and interacting with an empty Aztec smart contract. +```bash +aztec-sandbox +``` -At this point, [http://localhost:5173](http://localhost:5173) should provide a minimal smart contract frontend. +This will install all the dependencies and run the sandbox on port 8080 together with a anvil node. -This folder should have the following directory structure: +### 2. Unboxing the box -``` -|— README.md -|— package.json -|— src - index.html - index.ts - |— contracts - |— src - | The Noir smart contract source files are here. - |— main.nr - the cloned noir contract, your starting point - |- interface.nr - autogenerated from main.nr when you compile - |— Nargo.toml [Noir build file, includes Aztec smart contract dependencies] - |— artifacts - | These are both generated from `contracts/` by the compile command - |— blank_contract.json - |— blank.ts - |— tests - | A simple end2end test deploying and testing the minimal contract on a local sandbox - | using the front end helper methods in index.ts - | The test requires the sandbox and anvil to be running (yarn start:sandbox). - |- blank.contract.test.ts -``` +Unbox the box with: -Most relevant to you is likely `src/contracts/main.nr` (and the build config `src/contracts/Nargo.toml`). This contains the example blank contract logic that the frontend interacts with and is a good place to start writing Noir. +```bash +aztec-cli unbox blank +``` -The `src/artifacts` folder can be re-generated from the command line +and install dependencies: ```bash -yarn compile +yarn ``` -This will generate a [contract artifact](src/artifacts/test_contract.json) and TypeScript class for the [Aztec smart contract](src/contracts/main.nr), which the frontend uses to generate the UI. +This sandbox requires [Docker](https://www.docker.com/) to be installed _and running_ locally. In the event the image needs updating, you can run `yarn install:sandbox` (see [sandbox docs](https://docs.aztec.network/developers/cli/main) for more information.) -Note: the `compile` command seems to generate a Typescript file which needs a single change - +Time to build. Run: +```bash +yarn start ``` -import TestContractArtifactJson from 'text_contract.json' assert { type: 'json' }; -// need to update the relative import to -import TestContractArtifactJson from './test_contract.json' assert { type: 'json' }; -``` -After compiling, you can re-deploy the updated noir smart contract from the web UI. The function interaction forms are generated from parsing the contract artifact, so they should update automatically after you recompile. +Your React app is waiting for you on port 5176. Time to make it your own! + +In the `src/contracts` folder, you'll find the default contract being deployed. Don't forget to recompile with `aztec-nargo compile`! Read the [aztec.nr documentation](https://docs.aztec.network/dev_docs/contracts/main) to get started with the `aztec.nr` framework. + +[Read the full Sandbox reference](https://docs.aztec.network/dev_docs/cli/sandbox-reference) for more info on what exactly is happening on your machine! -## Learn More +## More info -To learn more about Noir Smart Contract development, take a look at the following resources: +Here's what is inside your `src` folder: -- [Awesome Noir](https://github.com/noir-lang/awesome-noir) - learn about the Noir programming language. +- `contracts` - The Aztec Contracts you just deployed! +- `config.ts` - A file exporting environment, and other configurations you need +- `index.html` and `.ts` - The actual website you're deploying -## Deploy on Aztec3 +There's also a `test` folder with minimal testing you can expand on, and an `artifacts` folder should pop up once you run your app, these are the artifacts from your contract's compilation. -Coming Soon :) +Visit the [Aztec Docs](https://docs.aztec.network) for more information on how Aztec works, and the [Awesome Aztec Repository](https://github.com/AztecProtocol/awesome-aztec) for more cool projects, boilerplates and tooling. diff --git a/boxes/blank/package.json b/boxes/blank/package.json index f8033cdea46..1af3cbb4c4a 100644 --- a/boxes/blank/package.json +++ b/boxes/blank/package.json @@ -5,14 +5,15 @@ "type": "module", "main": "./dest/index.js", "scripts": { + "compile": "cd src/contracts && ${AZTEC_NARGO:-aztec-nargo} compile", + "codegen": "${AZTEC_CLI:-aztec-cli} codegen src/contracts/target -o artifacts --ts", "build": "yarn clean && yarn compile && yarn codegen && tsc -b && webpack", - "clean": "rm -rf ./dest .tsbuildinfo ./src/artifacts ./src/contracts/target", - "start": "serve -p 3000 ./dest", - "start:dev": "webpack serve --mode=development", + "clean": "rm -rf ./dest .tsbuildinfo ./artifacts ./src/contracts/target", + "prep": "yarn clean && yarn compile && yarn codegen && tsc -b", + "dev": "yarn prep && webpack serve --mode development", + "serve": "serve -p 3000 ./dest", "formatting": "prettier --check ./src && eslint ./src", "formatting:fix": "prettier -w ./src", - "compile": "cd src/contracts && ${AZTEC_NARGO:-aztec-nargo} compile", - "codegen": "${AZTEC_CLI:-aztec-cli} codegen src/contracts/target -o src/artifacts --ts", "test": "NODE_NO_WARNINGS=1 node --experimental-vm-modules $(yarn bin jest) --runInBand" }, "jest": { @@ -28,8 +29,8 @@ "moduleNameMapper": { "^(\\.{1,2}/.*)\\.js$": "$1" }, - "testRegex": "./src/.*\\.test\\.ts$", - "rootDir": "./src" + "testRegex": "tests/.*\\.test\\.ts$", + "rootDir": "./" }, "dependencies": { "@aztec/accounts": "^0.16.9", @@ -62,18 +63,6 @@ "webpack-cli": "^5.1.4", "webpack-dev-server": "^4.15.1" }, - "browserslist": { - "production": [ - ">0.5%", - "not dead", - "not op_mini all" - ], - "development": [ - "last 1 chrome version", - "last 1 firefox version", - "last 1 safari version" - ] - }, "files": [ "dest", "src", diff --git a/boxes/blank/src/config.ts b/boxes/blank/src/config.ts new file mode 100644 index 00000000000..d393763ff1e --- /dev/null +++ b/boxes/blank/src/config.ts @@ -0,0 +1,29 @@ +import { createPXEClient, waitForPXE } from '@aztec/aztec.js'; +import { BlankContractArtifact } from '../artifacts/Blank.js'; + +class PXE { + pxeUrl; + pxe; + + constructor() { + this.pxeUrl = process.env.PXE_URL || 'http://localhost:8080'; + this.pxe = createPXEClient(this.pxeUrl); + } + + async setupPxe() { + await waitForPXE(this.pxe); + return this.pxe; + } + + getPxeUrl() { + return this.pxeUrl; + } + + getPxe() { + return this.pxe; + } +} + +export const pxe = new PXE(); +export const contractArtifact = BlankContractArtifact; +export const CONTRACT_ADDRESS_PARAM_NAMES = ['address']; diff --git a/boxes/blank/src/environment/index.ts b/boxes/blank/src/environment/index.ts deleted file mode 100644 index c64d7f6a2a3..00000000000 --- a/boxes/blank/src/environment/index.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { createPXEClient, waitForPXE } from '@aztec/aztec.js'; - -const { PXE_URL = 'http://localhost:8080' } = process.env; - -// assumes environment is running locally, which this script does not trigger -// as well as anvil. anvil can be started with yarn test:integration -export const setupEnvironment = async () => { - const pxe = createPXEClient(PXE_URL); - await waitForPXE(pxe); - return pxe; - }; \ No newline at end of file diff --git a/boxes/blank/src/index.ts b/boxes/blank/src/index.ts index 6b7cafeac9f..1d0bf66f82d 100644 --- a/boxes/blank/src/index.ts +++ b/boxes/blank/src/index.ts @@ -1,5 +1,5 @@ // docs:start:imports -import { BlankContractArtifact } from './artifacts/Blank.js'; +import { BlankContractArtifact } from '../artifacts/Blank.js'; import { AccountWallet, AztecAddress, diff --git a/boxes/blank/src/tests/blank.contract.test.ts b/boxes/blank/tests/blank.contract.test.ts similarity index 81% rename from boxes/blank/src/tests/blank.contract.test.ts rename to boxes/blank/tests/blank.contract.test.ts index c4e2cb5cdba..6a422177aaf 100644 --- a/boxes/blank/src/tests/blank.contract.test.ts +++ b/boxes/blank/tests/blank.contract.test.ts @@ -1,5 +1,5 @@ import { BlankContract } from '../artifacts/Blank.js'; -import { callContractFunction, deployContract, getWallet } from '../index.js'; +import { callContractFunction, deployContract, getWallet } from '../src/index.js'; import { AccountWallet, AztecAddress, @@ -11,7 +11,7 @@ import { Wallet, createDebugLogger, } from '@aztec/aztec.js'; -import { setupEnvironment } from '../environment/index.js'; +import { pxe } from '../src/config.js'; const logger = createDebugLogger('aztec:blank-box-test'); @@ -30,16 +30,14 @@ describe('ZK Contract Tests', () => { let _account3: CompleteAddress; let contract: Contract; let contractAddress: AztecAddress; - let pxe: PXE; beforeAll(async () => { - pxe = await setupEnvironment(); - const accounts = await pxe.getRegisteredAccounts(); + const accounts = await pxe.getPxe().getRegisteredAccounts(); [owner, _account2, _account3] = accounts; - wallet = await getWallet(owner, pxe); + wallet = await getWallet(owner, pxe.getPxe()); - contract = await deployZKContract(owner, wallet, pxe); + const c = (contract = await deployZKContract(owner, wallet, pxe.getPxe())); contractAddress = contract.address; }, 60000); @@ -49,7 +47,7 @@ describe('ZK Contract Tests', () => { contract.artifact, 'getPublicKey', [owner.address.toField()], - pxe, + pxe.getPxe(), owner, ); expect(callTxReceipt.status).toBe(TxStatus.MINED); diff --git a/boxes/blank/tsconfig.json b/boxes/blank/tsconfig.json index acc585a3b0e..3b4c57677db 100644 --- a/boxes/blank/tsconfig.json +++ b/boxes/blank/tsconfig.json @@ -1,6 +1,5 @@ { "compilerOptions": { - "rootDir": "src", "outDir": "dest", "tsBuildInfoFile": ".tsbuildinfo", "target": "es2020", @@ -21,5 +20,5 @@ "skipLibCheck": true, "jsx": "react-jsx" }, - "include": ["src", "src/contracts/target/*.json"] + "include": ["src", "tests", "src/contracts/target/*.json", "artifacts/*"] } diff --git a/boxes/npx.js b/boxes/npx.js new file mode 100755 index 00000000000..5bdaf3786c9 --- /dev/null +++ b/boxes/npx.js @@ -0,0 +1,167 @@ +#!/usr/bin/env node +import { Command } from "commander"; +import select from "@inquirer/select"; +import input from "@inquirer/input"; +import confirm from "@inquirer/confirm"; +const program = new Command(); +import tiged from "tiged"; +import { exec, execSync } from "child_process"; +import pty from "node-pty"; +import path from "path"; +import os from "os"; +import fs from "fs"; +import chalk from "chalk"; + +const { log, warn, info } = console; +const targetDir = path.join(os.homedir(), ".aztec/bin"); // Use os.homedir() to get $HOME + +function updatePathEnvVar() { + // Detect the user's shell profile file based on common shells and environment variables + const homeDir = os.homedir(); + let shellProfile; + if (process.env.SHELL?.includes("bash")) { + shellProfile = path.join(homeDir, ".bashrc"); + } else if (process.env.SHELL?.includes("zsh")) { + shellProfile = path.join(homeDir, ".zshrc"); + } else { + // Extend with more conditions for other shells if necessary + warn("Unsupported shell or shell not detected."); + return; + } + + // Read the current content of the shell profile to check if the path is already included + const profileContent = fs.readFileSync(shellProfile, "utf8"); + if (profileContent.includes(targetDir)) { + log(`${targetDir} is already in PATH.`); + return; + } + + // Append the export command to the shell profile file + const exportCmd = `\nexport PATH="$PATH:${targetDir}" # Added by Node.js script\n`; + fs.appendFileSync(shellProfile, exportCmd); + + info(`Added ${targetDir} to PATH in ${shellProfile}.`); +} + +program.action(async () => { + const appType = await select({ + message: "Please choose an option:", + choices: [ + { value: "blank-react", name: "Start a barebones React project" }, + ], + }); + + log(chalk.yellow(`You chose: ${appType}`)); + + try { + // STEP 1: Clone the box + const appName = await input({ + message: "Your app name:", + default: "my-aztec-app", + }); + + const emitter = tiged(`AztecProtocol/aztec-packages/boxes/${appType}`); + + chalk.blue("Cloning the boilerplate code..."); + emitter.on("info", (info) => { + log(info.message); + }); + + await emitter.clone(`./${appName}`).then(() => { + log(chalk.bgGreen("Your code is ready!")); + }); + } catch (error) { + log(chalk.bgRed(error.message)); + process.exit(1); + } + + // STEP 2: Checking for docker + try { + execSync("docker info >/dev/null 2>&1"); + } catch (error) { + log( + chalk.bgRed( + "Doesn't seem like Docker is installed. Please visit https://docs.aztec.network", + ), + ); + process.exit(1); + } + + // STEP 2: Checking for the Aztec Sandbox + try { + execSync("docker image inspect aztecprotocol/aztec > /dev/null 2>&1"); + } catch (error) { + const answer = await confirm({ + message: + "Seems like you don't have the Aztec Sandbox installed. Do you want to install it?", + default: true, + }); + + if (answer) { + try { + const ptySession = new Promise((resolve, reject) => { + const ptyProcess = pty.spawn("bash", [], { + name: "xterm-color", + cols: 80, + rows: 30, + cwd: process.cwd(), + env: process.env, + }); + + ptyProcess.on("data", function (data) { + process.stdout.write(data); + }); + + ptyProcess.write( + "echo y | bash -i <(curl -s install.aztec.network); exit\n", + ); + + ptyProcess.on("exit", function (exitCode, signal) { + updatePathEnvVar(); + resolve(); + log(chalk.bgGreen("The Sandbox is installed!")); + }); + }); + + await ptySession; + } catch (error) { + log( + chalk.bgRed( + "Failed to install the Sandbox. Please visit the docs at https://docs.aztec.network", + ), + ); + } + } + } + + // STEP 2: Running the Sandbox + try { + await fetch("http://localhost:8080", { + method: "POST", + headers: { + "Content-Type": "application/json", + }, + body: JSON.stringify({ + jsonrpc: "2.0", + method: "node_getVersion", + id: "null", + }), + }); + } catch (error) { + const answer = await confirm({ + message: + "I can't reach the Sandbox on port 8080. Do you want to start it?", + default: true, + }); + + if (answer) { + log( + chalk.green("Starting the sandbox... This might take a few minutes."), + ); + log(chalk.bgGreen(`Go and explore the boilerplate code while you wait!`)); + execSync(`$HOME/.aztec/bin/aztec sandbox`, { stdio: "inherit" }); + } + } +}); + +program.parse(); diff --git a/boxes/package.json b/boxes/package.json index 9b0417032de..26642817c5c 100644 --- a/boxes/package.json +++ b/boxes/package.json @@ -1,6 +1,7 @@ { "name": "@aztec/boxes", "packageManager": "yarn@4.0.2", + "type": "module", "private": true, "scripts": { "compile": "FORCE_COLOR=true yarn workspaces foreach -A -p -j unlimited -v run compile:local", @@ -11,6 +12,7 @@ "blank-react", "token" ], + "bin": "npx.js", "resolutions": { "@aztec/accounts": "portal:../yarn-project/accounts", "@aztec/aztec.js": "portal:../yarn-project/aztec.js", @@ -20,5 +22,14 @@ "@aztec/circuit-types": "portal:../yarn-project/circuit-types", "@aztec/ethereum": "portal:../yarn-project/ethereum", "@aztec/types": "portal:../yarn-project/types" + }, + "devDependencies": { + "@inquirer/confirm": "^3.0.0", + "@inquirer/input": "^2.0.0", + "@inquirer/select": "^2.0.0", + "chalk": "^5.3.0", + "commander": "^12.0.0", + "node-pty": "^1.0.0", + "tiged": "^2.12.6" } } diff --git a/boxes/token/.eslintrc.cjs b/boxes/token/.eslintrc.cjs deleted file mode 100644 index 1d5617c5bbb..00000000000 --- a/boxes/token/.eslintrc.cjs +++ /dev/null @@ -1,64 +0,0 @@ -module.exports = { - root: true, - env: { browser: true, es2020: true }, - parserOptions: { - project: './tsconfig.json', - }, - extends: [ - 'eslint:recommended', - 'plugin:@typescript-eslint/recommended', - 'plugin:react-hooks/recommended', - 'plugin:import/recommended', - 'plugin:import/typescript', - 'prettier', - ], - settings: { - 'import/resolver': { - typescript: true, - node: true, - }, - }, - ignorePatterns: ['dest', 'webpack.config.js', '.eslintrc.cjs'], - parser: '@typescript-eslint/parser', - plugins: ['react-refresh'], - overrides: [ - { - files: ['*.ts', '*.tsx'], - parserOptions: { - // hacky workaround for CI not having the same tsconfig setup - project: true, - }, - }, - ], - rules: { - 'react-refresh/only-export-components': ['warn', { allowConstantExport: true }], - '@typescript-eslint/explicit-module-boundary-types': 'off', - '@typescript-eslint/no-non-null-assertion': 'off', - '@typescript-eslint/no-explicit-any': 'off', - '@typescript-eslint/no-empty-function': 'off', - '@typescript-eslint/await-thenable': 'error', - '@typescript-eslint/no-floating-promises': 2, - '@typescript-eslint/no-unused-vars': ['error', { argsIgnorePattern: '^_', varsIgnorePattern: '^_' }], - 'require-await': 2, - 'no-console': 'warn', - 'no-constant-condition': 'off', - camelcase: 2, - 'no-restricted-imports': [ - 'error', - { - patterns: [ - { - group: ['client-dest'], - message: "Fix this absolute garbage import. It's your duty to solve it before it spreads.", - }, - { - group: ['dest'], - message: 'You should not be importing from a build directory. Did you accidentally do a relative import?', - }, - ], - }, - ], - 'import/no-unresolved': 'error', - 'import/no-extraneous-dependencies': 'error', - }, -}; diff --git a/boxes/token/.gitignore b/boxes/token/.gitignore deleted file mode 100644 index 1270997806b..00000000000 --- a/boxes/token/.gitignore +++ /dev/null @@ -1,7 +0,0 @@ -.yarn/* -!.yarn/releases - -node_modules -dest -src/artifacts -src/contracts/target \ No newline at end of file diff --git a/boxes/token/.prettierignore b/boxes/token/.prettierignore deleted file mode 100644 index a72dfe54860..00000000000 --- a/boxes/token/.prettierignore +++ /dev/null @@ -1,2 +0,0 @@ -src/artifacts/**/*.json -src/artifacts/**/*.ts \ No newline at end of file diff --git a/boxes/token/.prettierrc.json b/boxes/token/.prettierrc.json deleted file mode 100644 index 7c3bbec6848..00000000000 --- a/boxes/token/.prettierrc.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "singleQuote": true, - "trailingComma": "all", - "printWidth": 120, - "arrowParens": "avoid" -} diff --git a/boxes/token/README.md b/boxes/token/README.md deleted file mode 100644 index 8c9189ca67e..00000000000 --- a/boxes/token/README.md +++ /dev/null @@ -1,75 +0,0 @@ -# Aztec Boxes - -This is a minimal [Aztec](https://aztec.network/) Noir smart contract and frontend bootstrapped with [`aztec-cli unbox`](https://github.com/AztecProtocol/aztec-packages/tree/master/yarn-project/cli). It is recommended you use the `aztec-cli unbox PrivateToken` command so that the repository is copied with needed modifications from the monorepo subpackage. - -Some contract specific settings for `PrivateToken` are in a [config](src/config.ts) will require manual updates depending on your changes to the source code. - -## Setup - -Dependencies can be installed from the root of the package: - -```bash -yarn -yarn install:noir -yarn install:sandbox -``` - -In addition to the usual javascript dependencies, this project requires `nargo` (package manager) and `noir` (a Domain Specific Language for SNARK proving systems) in addition to `@aztec/aztec-cli`. - -The former are installed within `yarn install:noir` which executes - -This sandbox requires [Docker](https://www.docker.com/) to be installed _and running_ locally. In the event the image needs updating, you can run `yarn install:sandbox`. - -## Getting started - -After `yarn` has run,`yarn start:sandbox` in one terminal will launch a local instance of the Aztec sandbox via Docker Compose and `yarn start:dev` will launch a frontend app for deploying and interacting with the PrivateToken contract. - -At this point, [http://localhost:5173](http://localhost:5173) should provide a minimal smart contract frontend. - -This folder should have the following directory structure: - -``` -|— README.md -|— package.json -|— src - |-config.ts - PrivateToken specific configuration for the frontend. - | You may need to update this if you modify the contract functions. - |— app - |— [frontend React .tsx code files] - |- scripts - |- [helpers for frontend to interact with contract on the sandbox] - |— contracts - |— src - | The Noir smart contract source files are here. - |— main.nr - the cloned noir contract, your starting point - |- interface.nr - autogenerated from main.nr when you compile - |— Nargo.toml [Noir build file, includes Aztec smart contract dependencies] - |— artifacts - | These are both generated from `contracts/` by the compile command - |— private_token_contract.json - |— private_token.ts - |— tests - | A simple end2end test deploying and testing the Token on a local sandbox - | using the front end helper methods in app/scripts/ - | The test requires the sandbox and anvil to be running (yarn start:sandbox). - | You can run it via `yarn test:integration`. - |- token.test.ts -``` - -Most relevant to you is likely `src/contracts/main.nr` (and the build config `src/contracts/Nargo.toml`). This contains the example PrivateToken logic that the frontend interacts with and is a good place to start writing Noir. - -The `src/artifacts` folder can be re-generated from the command line with `yarn compile`. - -This will generate a [contract artifact](src/artifacts/test_contract.json) and TypeScript class for the Aztec smart contract in `src/contracts/main.nr`, which the frontend uses to generate the UI. - -After compiling, you can re-deploy the updated noir smart contract from the web UI. The function interaction forms are generated from parsing the contract artifact, so they should update automatically after you recompile. - -## Learn More - -To learn more about Noir Smart Contract development, take a look at the following resources: - -- [Awesome Noir](https://github.com/noir-lang/awesome-noir) - learn about the Noir programming language. - -## Deploy on Aztec3 - -Coming Soon :) diff --git a/boxes/token/package.json b/boxes/token/package.json deleted file mode 100644 index 133a6bb0144..00000000000 --- a/boxes/token/package.json +++ /dev/null @@ -1,102 +0,0 @@ -{ - "name": "@aztec/box-token", - "private": true, - "version": "0.1.0", - "type": "module", - "main": "./dest/index.js", - "scripts": { - "build": "yarn clean && yarn compile && yarn codegen && tsc -b && webpack", - "clean": "rm -rf ./dest .tsbuildinfo ./src/artifacts ./src/contracts/target", - "start": "serve -p 3000 ./dest", - "start:dev": "webpack serve --mode=development", - "formatting": "prettier --check ./src && eslint ./src", - "formatting:fix": "prettier -w ./src", - "compile": "cd src/contracts && ${AZTEC_NARGO:-aztec-nargo} compile", - "codegen": "${AZTEC_CLI:-aztec-cli} codegen src/contracts/target -o src/artifacts --ts", - "test": "NODE_NO_WARNINGS=1 node --experimental-vm-modules $(yarn bin jest) --runInBand" - }, - "jest": { - "preset": "ts-jest/presets/default-esm", - "transform": { - "^.+\\.(ts|tsx)$": [ - "ts-jest", - { - "useESM": true - } - ] - }, - "moduleNameMapper": { - "^(\\.{1,2}/.*)\\.js$": "$1" - }, - "testRegex": "./src/.*\\.test\\.ts$", - "rootDir": "./src" - }, - "dependencies": { - "@aztec/accounts": "^0.16.9", - "@aztec/aztec-ui": "^0.1.14", - "@aztec/aztec.js": "^0.16.9", - "classnames": "^2.3.2", - "formik": "^2.4.3", - "node-sass": "^9.0.0", - "react": "^18.2.0", - "react-dom": "^18.2.0", - "sass-loader": "^13.3.2", - "serve": "^14.2.1", - "yup": "^1.2.0" - }, - "devDependencies": { - "@jest/globals": "^29.6.4", - "@types/jest": "^29.5.0", - "@types/mocha": "^10.0.3", - "@types/node": "^20.5.9", - "@types/react": "^18.2.15", - "@types/react-dom": "^18.2.7", - "@typescript-eslint/eslint-plugin": "^6.0.0", - "@typescript-eslint/parser": "^6.0.0", - "autoprefixer": "^10.4.15", - "copy-webpack-plugin": "^11.0.0", - "css-loader": "^6.8.1", - "eslint": "^8.21.0", - "eslint-config-prettier": "^9.0.0", - "eslint-import-resolver-typescript": "^3.5.5", - "eslint-plugin-import": "^2.27.5", - "eslint-plugin-prettier": "^5.0.1", - "eslint-plugin-react-hooks": "^4.6.0", - "eslint-plugin-react-refresh": "^0.4.3", - "jest": "^29.6.4", - "postcss": "^8.4.29", - "postcss-loader": "^7.3.3", - "prettier": "^3.1.1", - "resolve-typescript-plugin": "^2.0.1", - "stream-browserify": "^3.0.0", - "style-loader": "^3.3.3", - "ts-jest": "^29.1.0", - "ts-loader": "^9.4.4", - "ts-node": "^10.9.1", - "tty-browserify": "^0.0.1", - "typescript": "^5.0.4", - "util": "^0.12.5", - "webpack": "^5.88.2", - "webpack-cli": "^5.1.4", - "webpack-dev-server": "^4.15.1" - }, - "browserslist": { - "production": [ - ">0.5%", - "not dead", - "not op_mini all" - ], - "development": [ - "last 1 chrome version", - "last 1 firefox version", - "last 1 safari version" - ] - }, - "files": [ - "dest", - "src", - "!*.test.*" - ], - "types": "./dest/index.d.ts", - "packageManager": "yarn@4.0.2" -} diff --git a/boxes/token/postcss.config.cjs b/boxes/token/postcss.config.cjs deleted file mode 100644 index d95f27e7959..00000000000 --- a/boxes/token/postcss.config.cjs +++ /dev/null @@ -1,5 +0,0 @@ -const autoprefixer = require('autoprefixer'); - -module.exports = { - plugins: [autoprefixer], -}; diff --git a/boxes/token/src/@types/index.d.ts b/boxes/token/src/@types/index.d.ts deleted file mode 100644 index 091d25e2101..00000000000 --- a/boxes/token/src/@types/index.d.ts +++ /dev/null @@ -1,4 +0,0 @@ -declare module '*.svg' { - const content: any; - export default content; -} diff --git a/boxes/token/src/app/components/contract_function_form.module.scss b/boxes/token/src/app/components/contract_function_form.module.scss deleted file mode 100644 index 056dcc719ff..00000000000 --- a/boxes/token/src/app/components/contract_function_form.module.scss +++ /dev/null @@ -1,66 +0,0 @@ -.input { - border: none; - outline-width: 0; - outline-color: rgba(0, 0, 0, 0); - padding: 2px 20px 0 20px; - width: 100%; - height: 45px; - color: #000; - border: 1px solid rgba(0, 0, 0, 0); - font-size: 16px; - text-align: left; - font-weight: 400; - border-radius: 10px; - text-align: left; - text-overflow: ellipsis; - transition: box-shadow 0.2s; - box-shadow: 0px 4px 10px rgba(0, 0, 0, 0.1); - background-color: white; - -webkit-appearance: none; - - &:disabled { - color: #4a4a4a; - background-color: rgba(239, 239, 239, 0.3); - background: radial-gradient(rgba(239, 239, 239, 0.3), rgba(239, 239, 239, 0.3)); - -webkit-text-fill-color: #4a4a4a; - cursor: not-allowed; - } -} - -.label { - font-weight: 450; - font-size: 18px; - display: flex; - width: 100%; - flex-direction: column; - text-align: left; - margin-bottom: 15px; - justify-content: space-between; -} - -.inputWrapper { - width: 100%; - display: flex; - gap: 15px; -} - -.field { - display: flex; - justify-content: start; - flex-direction: column; - align-items: flex-start; -} - -.content { - display: flex; - justify-content: space-between; - flex-direction: column; - margin: 30px; - width: 450px; - gap: 30px; -} - -.actionButton { - width: 100%; - align-self: center; -} diff --git a/boxes/token/src/app/components/contract_function_form.tsx b/boxes/token/src/app/components/contract_function_form.tsx deleted file mode 100644 index 3f736a4e667..00000000000 --- a/boxes/token/src/app/components/contract_function_form.tsx +++ /dev/null @@ -1,224 +0,0 @@ -import { CONTRACT_ADDRESS_PARAM_NAMES, pxe } from '../../config.js'; -import { callContractFunction, deployContract, viewContractFunction } from '../../scripts/index.js'; -import { convertArgs } from '../../scripts/util.js'; -import styles from './contract_function_form.module.scss'; -import { Button, Loader } from '@aztec/aztec-ui'; -import { AztecAddress, CompleteAddress, ContractArtifact, Fr, FunctionArtifact } from '@aztec/aztec.js'; -import { useFormik } from 'formik'; -import * as Yup from 'yup'; - -const DEFAULT_FIELD_VALUE = 100; -interface BasicParamDef { - name: string; - type: { - kind: string; - path?: string; - }; -} -interface ParamDef { - name: string; - type: { - kind: string; - path?: string; - fields?: BasicParamDef[]; - }; -} - -type NoirFunctionYupSchema = { - // hack: add `any` at the end to get the array schema to typecheck - // eslint-disable-next-line @typescript-eslint/no-explicit-any - [key: string]: Yup.NumberSchema | Yup.ArraySchema | Yup.BooleanSchema | any; -}; - -type NoirFunctionFormValues = { - [key: string]: string | number | number[] | boolean | undefined; -}; - -// returns an object where first value is the yup type, second value is the default value -// this handles "base cases", which can be the parameters directly, or used -// in a recursive manner to handle structs -function generateYupDefaultValue(param: any, defaultAddress: string) { - if (CONTRACT_ADDRESS_PARAM_NAMES.includes(param.name)) { - // these are actually fields, which should be numbers, but yup doesn't support bigint so we convert back to bigint on execution - return { yupType: Yup.string().required(), defaultValue: defaultAddress }; - } else if (param.type.kind === 'field') { - return { yupType: Yup.number().required(), defaultValue: DEFAULT_FIELD_VALUE }; - } else if (param.type.kind === 'array') { - const arrayLength = param.type.length; - return { - yupType: Yup.array() - .of(Yup.number()) - .min(arrayLength) - .max(arrayLength) - .transform(function (value: number[], originalValue: string) { - if (typeof originalValue === 'string') { - return originalValue.split(',').map(Number); - } - return value; - }), - defaultValue: Array(arrayLength).fill(CONTRACT_ADDRESS_PARAM_NAMES.includes(param.name) ? defaultAddress : 200), - }; - } else if (param.type.kind === 'boolean') { - return { yupType: Yup.boolean().required(), defaultValue: false }; - } else { - throw new Error('Unsupported type', param); - } -} - -function generateYupSchema(functionAbi: FunctionArtifact, defaultAddress: string) { - const parameterSchema: NoirFunctionYupSchema = {}; - const initialValues: NoirFunctionFormValues = {}; - for (const param of functionAbi.parameters) { - // use helper function for non struct-types - if (['field', 'array', 'boolean'].includes(param.type.kind)) { - const { yupType, defaultValue } = generateYupDefaultValue(param, defaultAddress); - parameterSchema[param.name] = yupType; - initialValues[param.name] = defaultValue; - continue; - } else if (param.type.kind === 'struct') { - // for type checking, can't annotate left side of "for X of Y" statement - const paramFields: ParamDef[] = param.type.fields!; - const structParamSchema: any = {}; - const structInitialValues: any = {}; - for (const structParam of paramFields) { - const { yupType, defaultValue } = generateYupDefaultValue(structParam, defaultAddress); - structParamSchema[structParam.name] = yupType; - structInitialValues[structParam.name] = defaultValue; - } - parameterSchema[param.name] = Yup.object().shape(structParamSchema); - initialValues[param.name] = structInitialValues; - continue; - } - } - return { validationSchema: Yup.object().shape(parameterSchema), initialValues }; -} - -async function handleFunctionCall( - contractAddress: AztecAddress | undefined, - artifact: ContractArtifact, - functionName: string, - args: any, - wallet: CompleteAddress, -) { - const functionAbi = artifact.functions.find(f => f.name === functionName)!; - const typedArgs: any[] = convertArgs(functionAbi, args); - - if (functionName === 'constructor' && !!wallet) { - if (functionAbi === undefined) { - throw new Error('Cannot find constructor in the ABI.'); - } - // hack: addresses are stored as string in the form to avoid bigint compatibility issues with formik - // convert those back to bigints before sending - - // for now, dont let user change the salt. requires some change to the form generation if we want to let user choose one - // since everything is currently based on parsing the contractABI, and the salt parameter is not present there - const salt = Fr.random(); - return await deployContract(wallet, artifact, typedArgs, salt, pxe); - } - - if (functionAbi.functionType === 'unconstrained') { - return await viewContractFunction(contractAddress!, artifact, functionName, typedArgs, pxe, wallet); - } else { - const txnReceipt = await callContractFunction(contractAddress!, artifact, functionName, typedArgs, pxe, wallet); - return `Transaction ${txnReceipt.status} on block number ${txnReceipt.blockNumber}`; - } -} - -interface ContractFunctionFormProps { - wallet: CompleteAddress; - contractAddress?: AztecAddress; - artifact: ContractArtifact; - functionAbi: FunctionArtifact; - defaultAddress: string; - title?: string; - buttonText?: string; - isLoading: boolean; - disabled: boolean; - onSubmit: () => void; - onSuccess: (result: any) => void; - onError: (msg: string) => void; -} - -export function ContractFunctionForm({ - wallet, - contractAddress, - artifact, - functionAbi, - defaultAddress, - buttonText = 'Submit', - isLoading, - disabled, - onSubmit, - onSuccess, - onError, -}: ContractFunctionFormProps) { - const { validationSchema, initialValues } = generateYupSchema(functionAbi, defaultAddress); - const formik = useFormik({ - initialValues: initialValues, - validationSchema: validationSchema, - onSubmit: async (values: any) => { - onSubmit(); - try { - const result = await handleFunctionCall(contractAddress, artifact, functionAbi.name, values, wallet); - onSuccess(result); - } catch (e: any) { - onError(e.message); - } - }, - }); - return ( -
- {functionAbi.parameters.map(input => ( -
- {input.type.kind !== 'struct' ? ( - <> - - - {formik.touched[input.name] && formik.errors[input.name] && ( -
{formik.errors[input.name]?.toString()}
- )} - - ) : ( - // Rendering object properties if the kind is 'struct' - // find a better way to represent that these are part of the same input - // than the text label `${input.name}.${field.name}` - input.type.fields.map(field => ( -
- - - {/* {formik.touched[input.name] && formik.touched[input.name] && formik.errors[input.name] && formik.errors[input.name][field.name] && ( -
{formik.errors[input.name][field.name]?.toString()}
- )} */} -
- )) - )} -
- ))} - {isLoading ? ( - - ) : ( -