Barretenberg
The ZK-SNARK library at the core of Aztec
Loading...
Searching...
No Matches
api_chonk.cpp
Go to the documentation of this file.
1#include "api_chonk.hpp"
17#include <algorithm>
18#include <sstream>
19#include <stdexcept>
20
21namespace bb {
22namespace { // anonymous namespace
23
33void write_standalone_vk(std::vector<uint8_t> bytecode, const std::filesystem::path& output_path)
34{
35 auto response = bbapi::ChonkComputeStandaloneVk{
36 .circuit = { .name = "standalone_circuit", .bytecode = std::move(bytecode) }
37 }.execute();
38
39 bool is_stdout = output_path == "-";
40 if (is_stdout) {
41 write_bytes_to_stdout(response.bytes);
42 } else {
43 write_file(output_path / "vk", response.bytes);
44 }
45}
46
57void write_chonk_vk(std::vector<uint8_t> bytecode, const std::filesystem::path& output_dir)
58{
59 info("Chonk: computing IVC vk for hiding kernel circuit");
60 auto response = bbapi::ChonkComputeIvcVk{ .circuit{ .bytecode = std::move(bytecode) } }.execute();
61 const bool output_to_stdout = output_dir == "-";
62 if (output_to_stdout) {
63 write_bytes_to_stdout(response.bytes);
64 } else {
65 write_file(output_dir / "vk", response.bytes);
66 }
67}
68} // anonymous namespace
69
70void ChonkAPI::prove(const Flags& flags,
71 const std::filesystem::path& input_path,
72 const std::filesystem::path& output_dir)
73{
74 BB_BENCH_NAME("ChonkAPI::prove");
75 bbapi::BBApiRequest request;
78
79 bbapi::ChonkStart{ .num_circuits = raw_steps.size() }.execute(request);
80 info("Chonk: starting with ", raw_steps.size(), " circuits");
81 for (const auto& step : raw_steps) {
83 .circuit = { .name = step.function_name, .bytecode = step.bytecode, .verification_key = step.vk }
84 }.execute(request);
85
86 // NOLINTNEXTLINE(bugprone-unchecked-optional-access): we know the optional has been set here.
87 info("Chonk: accumulating " + step.function_name);
88 bbapi::ChonkAccumulate{ .witness = step.witness }.execute(request);
89 }
90
91 auto proof = bbapi::ChonkProve{}.execute(request).proof;
92
93 // We'd like to use the `write` function that UltraHonkAPI uses, but there are missing functions for creating
94 // std::string representations of vks that don't feel worth implementing
95 const bool output_to_stdout = output_dir == "-";
96
97 const auto write_proof = [&]() {
98 const auto buf = to_buffer(proof.to_field_elements());
99 if (output_to_stdout) {
100 vinfo("writing Chonk proof to stdout");
102 } else {
103 vinfo("writing Chonk proof in directory ", output_dir);
104 write_file(output_dir / "proof", buf);
105 }
106 };
107
108 write_proof();
109
110 if (flags.write_vk) {
111 vinfo("writing Chonk vk in directory ", output_dir);
112 // write CHONK vk using the bytecode of the Hiding kernel (the last step of the execution)
113 write_chonk_vk(raw_steps[raw_steps.size() - 1].bytecode, output_dir);
114 }
115}
116
117bool ChonkAPI::verify([[maybe_unused]] const Flags& flags,
118 [[maybe_unused]] const std::filesystem::path& public_inputs_path,
119 const std::filesystem::path& proof_path,
120 const std::filesystem::path& vk_path)
121{
122 BB_BENCH_NAME("ChonkAPI::verify");
123 auto proof_fields = many_from_buffer<fr>(read_file(proof_path));
124 auto proof = ChonkProof::from_field_elements(proof_fields);
125
126 auto vk_buffer = read_vk_file(vk_path);
127
128 auto response = bbapi::ChonkVerify{ .proof = std::move(proof), .vk = std::move(vk_buffer) }.execute();
129 return response.valid;
130}
131
132// WORKTODO(bbapi) remove this
133bool ChonkAPI::prove_and_verify(const std::filesystem::path& input_path)
134{
137
139 // Construct the hiding kernel as the final step of the IVC
140
141 auto proof = ivc->prove();
142 auto vk_and_hash = ivc->get_hiding_kernel_vk_and_hash();
143 ChonkNativeVerifier verifier(vk_and_hash);
144 const bool verified = verifier.verify(proof);
145 return verified;
146}
147
148void ChonkAPI::gates(const Flags& flags, const std::filesystem::path& bytecode_path)
149{
150 BB_BENCH_NAME("ChonkAPI::gates");
151 chonk_gate_count(bytecode_path, flags.include_gates_per_opcode);
152}
153
154void ChonkAPI::write_solidity_verifier([[maybe_unused]] const Flags& flags,
155 [[maybe_unused]] const std::filesystem::path& output_path,
156 [[maybe_unused]] const std::filesystem::path& vk_path)
157{
158 BB_BENCH_NAME("ChonkAPI::write_solidity_verifier");
159 throw_or_abort("API function contract not implemented");
160}
161
162bool ChonkAPI::check_precomputed_vks(const Flags& flags, const std::filesystem::path& input_path)
163{
164 BB_BENCH_NAME("ChonkAPI::check_precomputed_vks");
165 bbapi::BBApiRequest request;
167
169 bool check_failed = false;
170 for (auto& step : raw_steps) {
171 if (step.vk.empty()) {
172 info("FAIL: Expected precomputed vk for function ", step.function_name);
173 return false;
174 }
175 auto response = bbapi::ChonkCheckPrecomputedVk{
176 .circuit = { .name = step.function_name, .bytecode = step.bytecode, .verification_key = step.vk }
177 }.execute();
178
179 if (!response.valid) {
180 info("VK mismatch detected for function ", step.function_name);
181 if (vk_policy != bbapi::VkPolicy::REWRITE) {
182 info("Computed VK differs from precomputed VK in ivc-inputs.msgpack");
183 return false;
184 }
185 info("Updating VK in ivc-inputs.msgpack with computed value");
186 step.vk = response.actual_vk;
187 check_failed = true;
188 }
189 }
190 if (check_failed) {
192 return false;
193 }
194 return true;
195}
196
197void ChonkAPI::write_vk(const Flags& flags,
198 const std::filesystem::path& bytecode_path,
199 const std::filesystem::path& output_path)
200{
201 BB_BENCH_NAME("ChonkAPI::write_vk");
202 auto bytecode = get_bytecode(bytecode_path);
203 if (flags.verifier_type == "ivc") {
204 write_chonk_vk(bytecode, output_path);
205 } else if (flags.verifier_type == "standalone") {
206 write_standalone_vk(bytecode, output_path);
207 } else if (flags.verifier_type == "standalone_hiding") {
208 // write the VK for the hiding kernel which DOES NOT utilize a structured trace
209 write_standalone_vk(bytecode, output_path);
210 } else {
211 const std::string msg = std::string("Can't write vk for verifier type ") + flags.verifier_type;
212 throw_or_abort(msg);
213 }
214}
215
216bool ChonkAPI::check([[maybe_unused]] const Flags& flags,
217 [[maybe_unused]] const std::filesystem::path& bytecode_path,
218 [[maybe_unused]] const std::filesystem::path& witness_path)
219{
220 throw_or_abort("API function check_witness not implemented");
221 return false;
222}
223
224void chonk_gate_count(const std::string& bytecode_path, bool include_gates_per_opcode)
225{
226 BB_BENCH_NAME("chonk_gate_count");
227 // All circuit reports will be built into the std::string below
228 std::string functions_string = "{\"functions\": [\n ";
229
230 bbapi::BBApiRequest request;
231
232 auto bytecode = get_bytecode(bytecode_path);
233 auto response = bbapi::ChonkStats{ .circuit = { .name = "ivc_circuit", .bytecode = std::move(bytecode) },
234 .include_gates_per_opcode = include_gates_per_opcode }
235 .execute(request);
236
237 // Build the circuit report. It always has one function, corresponding to the ACIR constraint systems.
238 // NOTE: can be reconsidered
239 std::string gates_per_opcode_str;
240 if (include_gates_per_opcode && !response.gates_per_opcode.empty()) {
241 for (size_t j = 0; j < response.gates_per_opcode.size(); j++) {
242 gates_per_opcode_str += std::to_string(response.gates_per_opcode[j]);
243 if (j != response.gates_per_opcode.size() - 1) {
244 gates_per_opcode_str += ",";
245 }
246 }
247 }
248 auto result_string = format(
249 "{\n \"acir_opcodes\": ",
250 response.acir_opcodes,
251 ",\n \"circuit_size\": ",
252 response.circuit_size,
253 (include_gates_per_opcode ? format(",\n \"gates_per_opcode\": [", gates_per_opcode_str, "]") : ""),
254 "\n }");
255 functions_string = format(functions_string, result_string);
256 std::cout << format(functions_string, "\n]}");
257}
258
259} // namespace bb
void write_bytes_to_stdout(const std::vector< uint8_t > &data)
Writes raw bytes of the vector to stdout.
Definition log.hpp:21
std::shared_ptr< Napi::ThreadSafeFunction > bytecode
#define BB_BENCH_NAME(name)
Definition bb_bench.hpp:219
bool prove_and_verify(const std::filesystem::path &input_path)
Test/debug function: prove and verify in one call (bypasses serialization).
bool verify(const Flags &flags, const std::filesystem::path &public_inputs_path, const std::filesystem::path &proof_path, const std::filesystem::path &vk_path) override
Verify a Chonk proof against a verification key.
void write_vk(const Flags &flags, const std::filesystem::path &bytecode_path, const std::filesystem::path &output_path) override
Compute and write a verification key.
void prove(const Flags &flags, const std::filesystem::path &input_path, const std::filesystem::path &output_dir)
Main production entry point: generate a Chonk proof from private execution steps.
Definition api_chonk.cpp:70
bool check(const Flags &flags, const std::filesystem::path &bytecode_path, const std::filesystem::path &witness_path) override
void gates(const Flags &flags, const std::filesystem::path &bytecode_path) override
Output gate count statistics for a circuit.
bool check_precomputed_vks(const Flags &flags, const std::filesystem::path &input_path)
Validate that precomputed VKs in ivc-inputs.msgpack match computed VKs.
void write_solidity_verifier(const Flags &flags, const std::filesystem::path &output_path, const std::filesystem::path &vk_path) override
Verifier for Chonk IVC proofs (both native and recursive).
Output verify(const Proof &proof)
Verify a Chonk proof.
std::string format(Args... args)
Definition log.hpp:24
#define vinfo(...)
Definition log.hpp:94
void info(Args... args)
Definition log.hpp:89
uint8_t const * buf
Definition data_store.hpp:9
std::vector< uint8_t > get_bytecode(const std::string &bytecodePath)
VkPolicy
Policy for handling verification keys during IVC accumulation.
VkPolicy parse_vk_policy(const std::string &policy)
Convert VK policy string to enum for internal use.
Entry point for Barretenberg command-line interface.
Definition api.hpp:5
void chonk_gate_count(const std::string &bytecode_path, bool include_gates_per_opcode)
std::vector< uint8_t > read_vk_file(const std::filesystem::path &vk_path)
Read a verification key file with an actionable error message if not found.
Definition file_io.hpp:112
std::vector< uint8_t > read_file(const std::string &filename, size_t bytes=0)
Definition file_io.hpp:30
void write_file(const std::string &filename, std::vector< uint8_t > const &data)
Definition file_io.hpp:59
constexpr decltype(auto) get(::tuplet::tuple< T... > &&t) noexcept
Definition tuple.hpp:13
std::string to_string(bb::avm2::ValueTag tag)
std::vector< uint8_t > to_buffer(T const &value)
bool include_gates_per_opcode
Definition api.hpp:24
bool write_vk
Definition api.hpp:23
std::string verifier_type
Definition api.hpp:21
std::string vk_policy
Definition api.hpp:27
static ChonkProof_ from_field_elements(const std::vector< FF > &fields)
Common logic to reconstruct proof from field elements.
static void compress_and_save(std::vector< PrivateExecutionStepRaw > &&steps, const std::filesystem::path &output_path)
static std::vector< PrivateExecutionStepRaw > load_and_decompress(const std::filesystem::path &input_path)
Parsed private execution steps ready for Chonk accumulation.
std::shared_ptr< Chonk > accumulate()
Creates a Chonk instance and accumulates each circuit in the folding stack. Uses precomputed VKs when...
void parse(std::vector< PrivateExecutionStepRaw > &&steps)
Converts PrivateExecutionStepRaw entries (which contain raw bytecode/witness bytes) into structured A...
Accumulate the previously loaded circuit into the IVC proof.
std::vector< uint8_t > witness
Serialized witness data for the last loaded circuit.
Verify that a precomputed verification key matches the circuit.
CircuitInput circuit
Circuit with its precomputed verification key.
Compute IVC verification key for the complete proof.
Compute standalone verification key for a circuit.
Load a circuit into the Chonk instance for accumulation.
CircuitInput circuit
Circuit to be loaded with its bytecode and verification key.
ChonkProof proof
Complete IVC proof for all accumulated circuits.
Generate a proof for all accumulated circuits.
Response execute(BBApiRequest &request) &&
Initialize a new Chonk instance for incremental proof accumulation.
Get gate counts for a circuit.
CircuitInputNoVK circuit
The circuit to analyze.
Verify a Chonk proof with its verification key.
ChonkProof proof
The Chonk proof to verify.
std::string name
Human-readable name for the circuit.
std::string name
Human-readable name for the circuit.
std::vector< uint8_t > bytecode
Serialized bytecode representation of the circuit.
void throw_or_abort(std::string const &err)