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"
19#include <algorithm>
20#include <stdexcept>
21
22namespace bb {
23namespace { // anonymous namespace
24
34void write_chonk_vk(std::vector<uint8_t> bytecode, const std::filesystem::path& output_path, const API::Flags& flags)
35{
36 auto response =
37 bbapi::ChonkComputeVk{ .circuit = { .bytecode = std::move(bytecode) }, .use_zk_flavor = flags.use_zk_flavor }
38 .execute();
39
40 const bool is_stdout = output_path == "-";
41 if (is_stdout) {
42 write_bytes_to_stdout(response.bytes);
43 } else if (flags.output_format == "json") {
44 // Note: Chonk VK doesn't have a hash, so we pass an empty string
45 std::string json_content = VkJson::build(response.fields, "", flags.scheme);
46 write_file(output_path / "vk.json", std::vector<uint8_t>(json_content.begin(), json_content.end()));
47 info("VK (JSON) saved to ", output_path / "vk.json");
48 } else {
49 write_file(output_path / "vk", response.bytes);
50 }
51}
52} // anonymous namespace
53
54void ChonkAPI::prove(const Flags& flags,
55 const std::filesystem::path& input_path,
56 const std::filesystem::path& output_dir)
57{
58 BB_BENCH_NAME("ChonkAPI::prove");
59 bbapi::BBApiRequest request;
62
63 bbapi::ChonkStart{ .num_circuits = static_cast<uint32_t>(raw_steps.size()) }.execute(request);
64 info("Chonk: starting with ", raw_steps.size(), " circuits");
65 for (size_t i = 0; i < raw_steps.size(); ++i) {
66 const auto& step = raw_steps[i];
68 .circuit = { .name = step.function_name, .bytecode = step.bytecode, .verification_key = step.vk },
69 }
70 .execute(request);
71
72 // NOLINTNEXTLINE(bugprone-unchecked-optional-access): we know the optional has been set here.
73 info("Chonk: accumulating " + step.function_name);
74 bbapi::ChonkAccumulate{ .witness = step.witness }.execute(request);
75 }
76
77 auto proof = bbapi::ChonkProve{}.execute(request).proof;
78
79 const bool output_to_stdout = output_dir == "-";
80
81 const auto write_proof = [&]() {
82 const auto proof_fields = proof.to_field_elements();
83 if (output_to_stdout) {
84 vinfo("writing Chonk proof to stdout");
85 write_bytes_to_stdout(to_buffer(proof_fields));
86 } else if (flags.output_format == "json") {
87 vinfo("writing Chonk proof (JSON) in directory ", output_dir);
88 // Note: Chonk proof doesn't have a vk_hash, so we pass an empty string
89 std::string json_content = ProofJson::build(proof_fields, "", flags.scheme);
90 write_file(output_dir / "proof.json", std::vector<uint8_t>(json_content.begin(), json_content.end()));
91 info("Proof (JSON) saved to ", output_dir / "proof.json");
92 } else {
93 vinfo("writing Chonk proof in directory ", output_dir);
94 write_file(output_dir / "proof", to_buffer(proof_fields));
95 }
96 };
97
98 write_proof();
99
100 if (flags.write_vk) {
101 vinfo("writing Chonk vk in directory ", output_dir);
102 // Write CHONK vk for the hiding kernel (last step) — proven as MegaZK.
103 Flags hiding_flags = flags;
104 hiding_flags.use_zk_flavor = true;
105 write_chonk_vk(raw_steps[raw_steps.size() - 1].bytecode, output_dir, hiding_flags);
106 }
107}
108
109bool ChonkAPI::verify([[maybe_unused]] const Flags& flags,
110 [[maybe_unused]] const std::filesystem::path& public_inputs_path,
111 const std::filesystem::path& proof_path,
112 const std::filesystem::path& vk_path)
113{
114 BB_BENCH_NAME("ChonkAPI::verify");
115 auto proof_fields = many_from_buffer<fr>(read_file(proof_path));
116 auto proof = ChonkProof::from_field_elements(proof_fields);
117
118 auto vk_buffer = read_vk_file(vk_path);
119
120 auto response = bbapi::ChonkVerify{ .proof = std::move(proof), .vk = std::move(vk_buffer) }.execute();
121 return response.valid;
122}
123
124bool ChonkAPI::batch_verify([[maybe_unused]] const Flags& flags, const std::filesystem::path& proofs_dir)
125{
126 BB_BENCH_NAME("ChonkAPI::batch_verify");
127
130
131 for (size_t i = 0;; ++i) {
132 auto proof_file = proofs_dir / ("proof_" + std::to_string(i));
133 auto vk_file = proofs_dir / ("vk_" + std::to_string(i));
134
135 if (!std::filesystem::exists(proof_file) || !std::filesystem::exists(vk_file)) {
136 break;
137 }
138
139 auto proof_fields = many_from_buffer<fr>(read_file(proof_file));
140 proofs.push_back(ChonkProof::from_field_elements(proof_fields));
141 vks.push_back(read_vk_file(vk_file));
142 }
143
144 if (proofs.empty()) {
145 throw_or_abort("batch_verify: no proof_0/vk_0 pairs found in " + proofs_dir.string());
146 }
147
148 info("ChonkAPI::batch_verify - found ", proofs.size(), " proof/vk pairs in ", proofs_dir.string());
149
150 auto response = bbapi::ChonkBatchVerify{ .proofs = std::move(proofs), .vks = std::move(vks) }.execute();
151 return response.valid;
152}
153
154void ChonkAPI::proof_stats(const std::filesystem::path& proof_path, const std::filesystem::path& output_path)
155{
156 auto proof_fields = many_from_buffer<fr>(read_file(proof_path));
157 auto proof = ChonkProof::from_field_elements(proof_fields);
158
159 auto compressed = ProofCompressor::compress_chonk_proof(proof);
160
161 std::string json = "{\n"
162 " \"compressed_proof_size_bytes\": " +
163 std::to_string(compressed.size()) +
164 "\n"
165 "}";
166
167 if (output_path == "-") {
168 std::cout << json << std::endl;
169 } else {
170 write_file(output_path, std::vector<uint8_t>(json.begin(), json.end()));
171 // Write the compressed proof alongside the JSON for further processing (e.g. gzip)
172 auto compressed_proof_path = output_path;
173 compressed_proof_path.replace_extension(".bin");
174 write_file(compressed_proof_path, compressed);
175 info("Proof stats written to ", output_path);
176 }
177}
178
179// WORKTODO(bbapi) remove this
180bool ChonkAPI::prove_and_verify(const std::filesystem::path& input_path)
181{
184
186 // Construct the hiding kernel as the final step of the IVC
187
188 auto proof = ivc->prove();
189 auto vk_and_hash = ivc->get_hiding_kernel_vk_and_hash();
190 ChonkNativeVerifier verifier(vk_and_hash);
191 const bool verified = verifier.verify(proof);
192 return verified;
193}
194
195void ChonkAPI::gates(const Flags& flags, const std::filesystem::path& bytecode_path)
196{
197 BB_BENCH_NAME("ChonkAPI::gates");
198 chonk_gate_count(bytecode_path.string(), flags.include_gates_per_opcode);
199}
200
201void ChonkAPI::write_solidity_verifier([[maybe_unused]] const Flags& flags,
202 [[maybe_unused]] const std::filesystem::path& output_path,
203 [[maybe_unused]] const std::filesystem::path& vk_path)
204{
205 BB_BENCH_NAME("ChonkAPI::write_solidity_verifier");
206 throw_or_abort("API function contract not implemented");
207}
208
209bool ChonkAPI::check_precomputed_vks(const Flags& flags, const std::filesystem::path& input_path)
210{
211 BB_BENCH_NAME("ChonkAPI::check_precomputed_vks");
212 bbapi::BBApiRequest request;
214
216 bool check_failed = false;
217 for (size_t i = 0; i < raw_steps.size(); ++i) {
218 auto& step = raw_steps[i];
219 if (step.vk.empty()) {
220 info("FAIL: Expected precomputed vk for function ", step.function_name);
221 return false;
222 }
223 const bool use_zk_flavor = (i == raw_steps.size() - 1);
224 auto response =
226 .circuit = { .name = step.function_name, .bytecode = step.bytecode, .verification_key = step.vk },
227 .use_zk_flavor = use_zk_flavor,
228 }
229 .execute();
230
231 if (!response.valid) {
232 info("VK mismatch detected for function ", step.function_name);
233 if (vk_policy != bbapi::VkPolicy::REWRITE) {
234 info("Computed VK differs from precomputed VK in ivc-inputs.msgpack");
235 return false;
236 }
237 info("Updating VK in ivc-inputs.msgpack with computed value");
238 step.vk = response.actual_vk;
239 check_failed = true;
240 }
241 }
242 if (check_failed) {
244 return false;
245 }
246 return true;
247}
248
249void ChonkAPI::write_vk(const Flags& flags,
250 const std::filesystem::path& bytecode_path,
251 const std::filesystem::path& output_path)
252{
253 BB_BENCH_NAME("ChonkAPI::write_vk");
254 write_chonk_vk(get_bytecode(bytecode_path), output_path, flags);
255}
256
257bool ChonkAPI::check([[maybe_unused]] const Flags& flags,
258 [[maybe_unused]] const std::filesystem::path& bytecode_path,
259 [[maybe_unused]] const std::filesystem::path& witness_path)
260{
261 throw_or_abort("API function check_witness not implemented");
262 return false;
263}
264
265void chonk_gate_count(const std::string& bytecode_path, bool include_gates_per_opcode)
266{
267 BB_BENCH_NAME("chonk_gate_count");
268 // All circuit reports will be built into the std::string below
269 std::string functions_string = "{\"functions\": [\n ";
270
271 bbapi::BBApiRequest request;
272
273 auto bytecode = get_bytecode(bytecode_path);
274 auto response = bbapi::ChonkStats{ .circuit = { .name = "ivc_circuit", .bytecode = std::move(bytecode) },
275 .include_gates_per_opcode = include_gates_per_opcode }
276 .execute(request);
277
278 // Build the circuit report. It always has one function, corresponding to the ACIR constraint systems.
279 // NOTE: can be reconsidered
280 std::string gates_per_opcode_str;
281 if (include_gates_per_opcode && !response.gates_per_opcode.empty()) {
282 for (size_t j = 0; j < response.gates_per_opcode.size(); j++) {
283 gates_per_opcode_str += std::to_string(response.gates_per_opcode[j]);
284 if (j != response.gates_per_opcode.size() - 1) {
285 gates_per_opcode_str += ",";
286 }
287 }
288 }
289 auto result_string = format(
290 "{\n \"acir_opcodes\": ",
291 response.acir_opcodes,
292 ",\n \"circuit_size\": ",
293 response.circuit_size,
294 (include_gates_per_opcode ? format(",\n \"gates_per_opcode\": [", gates_per_opcode_str, "]") : ""),
295 "\n }");
296 functions_string = format(functions_string, result_string);
297 std::cout << format(functions_string, "\n]}");
298}
299
300} // 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:264
bool prove_and_verify(const std::filesystem::path &input_path)
Test/debug function: prove and verify in one call (bypasses serialization).
void proof_stats(const std::filesystem::path &proof_path, const std::filesystem::path &output_path)
Output proof statistics: compressed proof and its size.
bool batch_verify(const Flags &flags, const std::filesystem::path &proofs_dir)
Batch-verify multiple Chonk proofs from a directory of proof_N/vk_N pairs.
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 MegaHonk verification key for a circuit to be accumulated in Chonk.
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:54
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.
static std::vector< uint8_t > compress_chonk_proof(const ChonkProof &proof)
std::string format(Args... args)
Definition log.hpp:23
#define info(...)
Definition log.hpp:93
#define vinfo(...)
Definition log.hpp:94
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:146
std::vector< uint8_t > read_file(const std::string &filename, size_t bytes=0)
Definition file_io.hpp:31
void write_file(const std::string &filename, std::span< const uint8_t > data)
Definition file_io.hpp:101
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:22
bool write_vk
Definition api.hpp:21
std::string vk_policy
Definition api.hpp:25
bool use_zk_flavor
Definition api.hpp:26
std::string output_format
Definition api.hpp:30
std::string scheme
Definition api.hpp:18
static ChonkProof_ from_field_elements(const std::vector< FF > &fields)
Reconstruct proof from field elements.
std::vector< FF > to_field_elements() const
Serialize proof to field elements (native mode)
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...
static std::string build(const std::vector< T > &fields, const std::string &vk_hash, const std::string &scheme)
static std::string build(const std::vector< T > &fields, const std::string &hash, const std::string &scheme)
Accumulate the previously loaded circuit into the IVC proof.
std::vector< uint8_t > witness
Serialized witness data for the last loaded circuit.
Batch-verify multiple Chonk proofs with a single IPA SRS MSM.
std::vector< ChonkProof > proofs
Verify that a precomputed verification key matches the circuit.
CircuitInput circuit
Circuit with its precomputed verification key.
Compute MegaHonk verification key for a circuit to be accumulated in Chonk.
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)