Barretenberg
The ZK-SNARK library at the core of Aztec
Loading...
Searching...
No Matches
bbapi_ultra_honk.cpp
Go to the documentation of this file.
12
13namespace bb::bbapi {
14
16{
17 return acir_format::ProgramMetadata{ .has_ipa_claim = IO::HasIPA };
18}
19
20template <typename Flavor, typename IO, typename Circuit = typename Flavor::CircuitBuilder>
21Circuit _compute_circuit(std::vector<uint8_t>&& bytecode, std::vector<uint8_t>&& witness)
22{
23 const acir_format::ProgramMetadata metadata = _create_program_metadata<IO>();
25
26 if (!witness.empty()) {
27 program.witness = acir_format::witness_buf_to_witness_vector(std::move(witness));
28 }
29 return acir_format::create_circuit<Circuit>(program, metadata);
30}
31
32template <typename Flavor, typename IO>
34 std::vector<uint8_t>&& witness)
35{
36 // Measure function time and debug print
37 auto initial_time = std::chrono::high_resolution_clock::now();
38 typename Flavor::CircuitBuilder builder = _compute_circuit<Flavor, IO>(std::move(bytecode), std::move(witness));
40 auto final_time = std::chrono::high_resolution_clock::now();
41 auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(final_time - initial_time);
42 info("CircuitProve: Proving key computed in ", duration.count(), " ms");
43
44 // Validate consistency between IO type and IPA proof presence
45 // IO::HasIPA indicates the circuit type requires IPA accumulation (rollup circuits)
46 // prover_instance->ipa_proof contains the actual IPA proof data from the circuit
47 if constexpr (IO::HasIPA) {
48 BB_ASSERT(!prover_instance->ipa_proof.empty(),
49 "RollupIO circuit expected IPA proof but none was provided. "
50 "Ensure the circuit includes IPA accumulation data.");
51 } else {
52 BB_ASSERT(prover_instance->ipa_proof.empty(),
53 "Non-rollup circuit should not have IPA proof. "
54 "Use ipa_accumulation=true in settings for rollup circuits.");
55 }
56
57 return prover_instance;
58}
59template <typename Flavor, typename IO>
60CircuitProve::Response _prove(std::vector<uint8_t>&& bytecode,
61 std::vector<uint8_t>&& witness,
62 std::vector<uint8_t>&& vk_bytes)
63{
64 using Proof = typename Flavor::Transcript::Proof;
66
67 auto prover_instance = _compute_prover_instance<Flavor, IO>(std::move(bytecode), std::move(witness));
68
69 // Create or deserialize VK
70 std::shared_ptr<VerificationKey> vk;
71 if (vk_bytes.empty()) {
72 info("WARNING: computing verification key while proving. Pass in a precomputed vk for better performance.");
73 vk = std::make_shared<VerificationKey>(prover_instance->get_precomputed());
74 } else {
75 vk = std::make_shared<VerificationKey>(from_buffer<VerificationKey>(vk_bytes));
76 }
77
78 // Construct proof
79 UltraProver_<Flavor> prover{ prover_instance, vk };
80 Proof full_proof = prover.construct_proof();
81
82 // Compute where to split (inner public inputs vs everything else)
83 size_t num_public_inputs = prover.num_public_inputs();
84 BB_ASSERT_GTE(num_public_inputs, IO::PUBLIC_INPUTS_SIZE, "Public inputs should contain the expected IO structure.");
85 size_t num_inner_public_inputs = num_public_inputs - IO::PUBLIC_INPUTS_SIZE;
86
87 // Optimization: if vk not provided, include it in response
89 if (vk_bytes.empty()) {
90 vk_response = { .bytes = to_buffer(*vk), .fields = vk_to_uint256_fields(*vk), .hash = to_buffer(vk->hash()) };
91 }
92
93 // Split proof: inner public inputs at front, rest is the "proof"
94 return { .public_inputs =
95 std::vector<uint256_t>{ full_proof.begin(),
96 full_proof.begin() + static_cast<std::ptrdiff_t>(num_inner_public_inputs) },
97 .proof = std::vector<uint256_t>{ full_proof.begin() + static_cast<std::ptrdiff_t>(num_inner_public_inputs),
98 full_proof.end() },
99 .vk = std::move(vk_response) };
100}
101
102template <typename Flavor, typename IO>
103bool _verify(const std::vector<uint8_t>& vk_bytes,
104 const std::vector<uint256_t>& public_inputs,
105 const std::vector<uint256_t>& proof)
106{
108 using VKAndHash = typename Flavor::VKAndHash;
109 using Verifier = UltraVerifier_<Flavor, IO>;
110
111 // Validate VK size upfront before deserialization
112 const size_t expected_vk_size = VerificationKey::calc_num_data_types() * sizeof(bb::fr);
113 if (vk_bytes.size() != expected_vk_size) {
114 info(
115 "Proof verification failed: invalid VK size. Expected ", expected_vk_size, " bytes, got ", vk_bytes.size());
116 return false;
117 }
118
119 std::shared_ptr<VerificationKey> vk = std::make_shared<VerificationKey>(from_buffer<VerificationKey>(vk_bytes));
120 auto vk_and_hash = std::make_shared<VKAndHash>(vk);
121 Verifier verifier{ vk_and_hash };
122
123 // Validate proof size
124 const size_t log_n = verifier.compute_log_n();
125 const size_t expected_size = ProofLength::Honk<Flavor>::template expected_proof_size<IO>(log_n);
126 if (proof.size() != expected_size) {
127 info("Proof verification failed: invalid proof size. Expected ", expected_size, ", got ", proof.size());
128 return false;
129 }
130
131 auto complete_proof = concatenate_proof<Flavor>(public_inputs, proof);
132 bool verified = verifier.verify_proof(complete_proof).result;
133
134 if (verified) {
135 info("Proof verified successfully");
136 } else {
137 info("Proof verification failed");
138 }
139
140 return verified;
141}
142
144{
145 BB_BENCH_NAME(MSGPACK_SCHEMA_NAME);
146 return dispatch_by_settings(settings, [&]<typename Flavor, typename IO>() {
147 return _prove<Flavor, IO>(std::move(circuit.bytecode), std::move(witness), std::move(circuit.verification_key));
148 });
149}
150
152{
153 BB_BENCH_NAME(MSGPACK_SCHEMA_NAME);
154 return dispatch_by_settings(settings, [&]<typename Flavor, typename IO>() {
155 auto prover_instance = _compute_prover_instance<Flavor, IO>(std::move(circuit.bytecode), {});
156 auto vk = std::make_shared<typename Flavor::VerificationKey>(prover_instance->get_precomputed());
158 .fields = vk_to_uint256_fields(*vk),
159 .hash = to_buffer(vk->hash()) };
160 });
161}
162
163template <typename Flavor, typename IO>
164CircuitStats::Response _stats(std::vector<uint8_t>&& bytecode, bool include_gates_per_opcode)
165{
166 using Circuit = typename Flavor::CircuitBuilder;
167 // Parse the circuit to get gate count information
169
170 acir_format::ProgramMetadata metadata = _create_program_metadata<IO>();
171 metadata.collect_gates_per_opcode = include_gates_per_opcode;
172 CircuitStats::Response response;
173 response.num_acir_opcodes = static_cast<uint32_t>(constraint_system.num_acir_opcodes);
174
175 acir_format::AcirProgram program{ std::move(constraint_system), {} };
176 auto builder = acir_format::create_circuit<Circuit>(program, metadata);
177 builder.finalize_circuit(/*ensure_nonzero=*/true);
178
179 response.num_gates = static_cast<uint32_t>(builder.get_finalized_total_circuit_size());
180 response.num_gates_dyadic = static_cast<uint32_t>(builder.get_circuit_subgroup_size(response.num_gates));
181 // note: will be empty if collect_gates_per_opcode is false
182 response.gates_per_opcode =
183 std::vector<uint32_t>(program.constraints.gates_per_opcode.begin(), program.constraints.gates_per_opcode.end());
184
185 return response;
186}
187
189{
190 BB_BENCH_NAME(MSGPACK_SCHEMA_NAME);
191 return dispatch_by_settings(settings, [&]<typename Flavor, typename IO>() {
192 return _stats<Flavor, IO>(std::move(circuit.bytecode), include_gates_per_opcode);
193 });
194}
195
197{
198 BB_BENCH_NAME(MSGPACK_SCHEMA_NAME);
199 bool verified = dispatch_by_settings(settings, [&]<typename Flavor, typename IO>() {
200 return _verify<Flavor, IO>(verification_key, public_inputs, proof);
201 });
202 return { verified };
203}
204
206{
207 BB_BENCH_NAME(MSGPACK_SCHEMA_NAME);
208
210 validate_vk_size<VK>(verification_key);
211
212 // Standard UltraHonk flavors
213 auto vk = from_buffer<VK>(verification_key);
214 std::vector<bb::fr> fields;
215 fields = vk.to_field_elements();
216
217 return { std::move(fields) };
218}
219
221{
222 BB_BENCH_NAME(MSGPACK_SCHEMA_NAME);
223
225 validate_vk_size<VK>(verification_key);
226
227 // MegaFlavor for private function verification keys
228 auto vk = from_buffer<VK>(verification_key);
229 std::vector<bb::fr> fields;
230 fields = vk.to_field_elements();
231
232 return { std::move(fields) };
233}
234
236{
237 BB_BENCH_NAME(MSGPACK_SCHEMA_NAME);
239 validate_vk_size<VK>(verification_key);
240
241 auto vk = std::make_shared<VK>(from_buffer<VK>(verification_key));
242
243 std::string contract = settings.disable_zk ? get_honk_solidity_verifier(vk) : get_honk_zk_solidity_verifier(vk);
244
245// If in wasm, we dont include the optimized solidity verifier - due to its large bundle size
246// This will run generate twice, but this should only be run before deployment and not frequently
247#ifndef __wasm__
248 if (settings.disable_zk && settings.optimized_solidity_verifier) {
250 }
251#endif
252
253 return { std::move(contract) };
254}
255
256} // namespace bb::bbapi
#define BB_ASSERT(expression,...)
Definition assert.hpp:70
#define BB_ASSERT_GTE(left, right,...)
Definition assert.hpp:128
std::shared_ptr< Napi::ThreadSafeFunction > bytecode
#define BB_BENCH_NAME(name)
Definition bb_bench.hpp:225
Shared type definitions for the Barretenberg RPC API.
UltraHonk-specific command definitions for the Barretenberg RPC API.
ECCVMCircuitBuilder CircuitBuilder
FixedVKAndHash_< PrecomputedEntities< Commitment >, BF, ECCVMHardcodedVKAndHash > VerificationKey
The verification key stores commitments to the precomputed polynomials used by the verifier.
NativeVerificationKey_< PrecomputedEntities< Commitment >, Codec, HashFunction, CommitmentKey > VerificationKey
The verification key stores commitments to the precomputed (non-witness) polynomials used by the veri...
Base Native verification key class.
Definition flavor.hpp:135
static size_t calc_num_data_types()
Calculate the number of field elements needed for serialization.
Definition flavor.hpp:200
NativeVerificationKey_< PrecomputedEntities< Commitment >, Codec, HashFunction, CommitmentKey > VerificationKey
The verification key stores commitments to the precomputed (non-witness) polynomials used by the veri...
NativeVerificationKey_< PrecomputedEntities< Commitment >, Codec, HashFunction, CommitmentKey > VerificationKey
#define info(...)
Definition log.hpp:93
#define BB_UNUSED
AluTraceBuilder builder
Definition alu.test.cpp:124
std::string get_honk_solidity_verifier(auto const &verification_key)
std::string get_optimized_honk_solidity_verifier(auto const &verification_key)
std::string get_honk_zk_solidity_verifier(auto const &verification_key)
WitnessVector witness_buf_to_witness_vector(std::vector< uint8_t > &&buf)
Convert a buffer representing a witness vector into Barretenberg's internal WitnessVector format.
AcirFormat circuit_buf_to_acir_format(std::vector< uint8_t > &&buf)
Convert a buffer representing a circuit into Barretenberg's internal AcirFormat representation.
std::shared_ptr< ProverInstance_< Flavor > > _compute_prover_instance(std::vector< uint8_t > &&bytecode, std::vector< uint8_t > &&witness)
bool _verify(const std::vector< uint8_t > &vk_bytes, const std::vector< uint256_t > &public_inputs, const std::vector< uint256_t > &proof)
acir_format::ProgramMetadata _create_program_metadata()
Circuit _compute_circuit(std::vector< uint8_t > &&bytecode, std::vector< uint8_t > &&witness)
CircuitStats::Response _stats(std::vector< uint8_t > &&bytecode, bool include_gates_per_opcode)
std::vector< uint256_t > vk_to_uint256_fields(const VK &vk)
Convert VK to uint256 field elements, handling flavor-specific return types.
CircuitProve::Response _prove(std::vector< uint8_t > &&bytecode, std::vector< uint8_t > &&witness, std::vector< uint8_t > &&vk_bytes)
auto dispatch_by_settings(const ProofSystemSettings &settings, Operation &&operation)
Dispatch to the correct Flavor and IO type based on proof system settings.
field< Bn254FrParams > fr
Definition fr.hpp:155
VerifierCommitmentKey< Curve > vk
constexpr decltype(auto) get(::tuplet::tuple< T... > &&t) noexcept
Definition tuple.hpp:13
std::vector< uint8_t > to_buffer(T const &value)
Struct containing both the constraints to be added to the circuit and the witness vector.
Metadata required to create a circuit.
Full Honk proof layout (used by UltraVerifier).
Response execute(const BBApiRequest &request={}) &&
Contains proof and public inputs. Both are given as vectors of fields. To be used for verification....
Response execute(const BBApiRequest &request={}) &&
std::vector< uint32_t > gates_per_opcode
Response execute(const BBApiRequest &request={}) &&
Response execute(const BBApiRequest &request={}) &&
Response execute(const BBApiRequest &request={}) &&
Response execute(const BBApiRequest &request={}) &&
Response execute(const BBApiRequest &request={}) &&