Barretenberg
The ZK-SNARK library at the core of Aztec
Loading...
Searching...
No Matches
aztec_process.cpp
Go to the documentation of this file.
1#ifndef __wasm__
2#include "aztec_process.hpp"
11#include <filesystem>
12#include <fstream>
13#include <iomanip>
14#include <nlohmann/json.hpp>
15#include <sstream>
16#include <thread>
17
18#ifdef ENABLE_AVM_TRANSPILER
19// Include avm_transpiler header
20#include <avm_transpiler.h>
21#endif
22
23namespace bb {
24
25namespace {
26
30std::vector<uint8_t> extract_bytecode(const nlohmann::json& function)
31{
32 if (!function.contains("bytecode")) {
33 throw_or_abort("Function missing bytecode field");
34 }
35
36 const auto& base64_bytecode = function["bytecode"].get<std::string>();
37 return decode_bytecode(base64_bytecode);
38}
39
43std::string compute_bytecode_hash(const std::vector<uint8_t>& bytecode)
44{
45 auto hash = crypto::sha256(bytecode);
46 std::ostringstream oss;
47 for (auto byte : hash) {
48 oss << std::hex << std::setw(2) << std::setfill('0') << static_cast<int>(byte);
49 }
50 return oss.str();
51}
52
56std::filesystem::path get_cache_dir()
57{
58 const char* home = std::getenv("HOME");
59 if (!home) {
60 home = ".";
61 }
62 std::filesystem::path cache_dir = std::filesystem::path(home) / ".bb" / BB_VERSION / "vk_cache";
63 std::filesystem::create_directories(cache_dir);
64 return cache_dir;
65}
66
70bool is_private_constrained_function(const nlohmann::json& function)
71{
72 bool is_public = false;
73 bool is_unconstrained = false;
74
75 // Check custom_attributes for "public"
76 if (function.contains("custom_attributes") && function["custom_attributes"].is_array()) {
77 for (const auto& attr : function["custom_attributes"]) {
78 if (attr.is_string() && attr.get<std::string>() == "public") {
79 is_public = true;
80 break;
81 }
82 }
83 }
84
85 // Check is_unconstrained
86 if (function.contains("is_unconstrained") && function["is_unconstrained"].is_boolean()) {
87 is_unconstrained = function["is_unconstrained"].get<bool>();
88 }
89
90 return !is_public && !is_unconstrained;
91}
92
96std::vector<uint8_t> get_or_generate_cached_vk(const std::filesystem::path& cache_dir,
97 const std::string& circuit_name,
98 const std::vector<uint8_t>& bytecode,
99 bool force)
100{
101 std::string hash_str = compute_bytecode_hash(bytecode);
102 std::filesystem::path vk_cache_path = cache_dir / (hash_str + ".vk");
103
104 // Check cache unless force is true
105 if (!force && std::filesystem::exists(vk_cache_path)) {
106 info("Verification key already in cache: ", hash_str);
107 return read_file(vk_cache_path);
108 }
109
110 // Generate new VK
111 info("Generating verification key: ", hash_str);
112 auto response = bbapi::ChonkComputeVk{ .circuit = { .name = circuit_name, .bytecode = bytecode } }.execute();
113
114 // Cache the VK
115 write_file(vk_cache_path, response.bytes);
116
117 return response.bytes;
118}
119
123void generate_vks_for_functions(const std::filesystem::path& cache_dir,
125 bool force)
126{
127#ifdef __wasm__
128 throw_or_abort("VK generation not supported in WASM");
129#endif
130
131 const size_t total_cpus = get_num_cpus();
132 const size_t num_functions = functions.size();
133
134 // Heuristic for nested parallelism:
135 // - actual_tasks = min(num_functions, total_cpus)
136 // - threads_per_task = min(total_cpus, max(2, total_cpus / actual_tasks * 2))
137 size_t actual_tasks = std::min(num_functions, total_cpus);
138 size_t threads_per_task = std::min(total_cpus, std::max(size_t{ 2 }, total_cpus / actual_tasks * 2));
139
140 // Track work distribution
141 std::atomic<size_t> current_function{ 0 };
142
143 // Worker function
144 auto worker = [&]() {
145 // Set thread-local concurrency for this worker
146 set_parallel_for_concurrency(threads_per_task);
147
148 // Process functions
149 size_t func_idx;
150 while ((func_idx = current_function.fetch_add(1)) < num_functions) {
151 auto* function = functions[func_idx];
152 std::string fn_name = (*function)["name"].get<std::string>();
153
154 // Get bytecode from function
155 auto bytecode = extract_bytecode(*function);
156
157 // Generate and cache VK (can use parallel_for internally)
158 get_or_generate_cached_vk(cache_dir, fn_name, bytecode, force);
159 }
160 };
161
162 // Spawn threads
163 std::vector<std::thread> threads;
164 threads.reserve(actual_tasks);
165
166 for (size_t i = 0; i < actual_tasks; ++i) {
167 threads.emplace_back(worker);
168 }
169
170 // Wait for completion
171 for (auto& t : threads) {
172 t.join();
173 }
174
175 // Update JSON with VKs from cache (sequential is fine here, it's fast)
176 for (auto* function : functions) {
177 std::string fn_name = (*function)["name"].get<std::string>();
178
179 // Get bytecode to compute hash
180 auto bytecode = extract_bytecode(*function);
181
182 // Read VK from cache
183 std::string hash_str = compute_bytecode_hash(bytecode);
184 std::filesystem::path vk_cache_path = cache_dir / (hash_str + ".vk");
185 auto vk_data = read_file(vk_cache_path);
186
187 // Encode to base64 and store in JSON
188 std::string encoded_vk = base64_encode(vk_data.data(), vk_data.size(), false);
189 (*function)["verification_key"] = encoded_vk;
190 }
191}
192
193} // anonymous namespace
194
198bool transpile_artifact([[maybe_unused]] const std::string& input_path, [[maybe_unused]] const std::string& output_path)
199{
200#ifdef ENABLE_AVM_TRANSPILER
201 info("Transpiling: ", input_path, " -> ", output_path);
202
203 auto result = avm_transpile_file(input_path.c_str(), output_path.c_str());
204
205 if (result.success == 0) {
206 if (result.error_message) {
207 std::string error_msg(result.error_message);
208 if (error_msg == "Contract already transpiled") {
209 // Already transpiled, copy if different paths
210 if (input_path != output_path) {
211 std::filesystem::copy_file(
212 input_path, output_path, std::filesystem::copy_options::overwrite_existing);
213 }
214 } else {
215 info("Transpilation failed: ", error_msg);
216 avm_free_result(&result);
217 return false;
218 }
219 } else {
220 info("Transpilation failed");
221 avm_free_result(&result);
222 return false;
223 }
224 }
225
226 avm_free_result(&result);
227
228 info("Transpiled: ", input_path, " -> ", output_path);
229#else
230 throw_or_abort("AVM Transpiler is not enabled. Please enable it to use bb aztec_process.");
231#endif
232 return true;
233}
234
235bool process_aztec_artifact(const std::string& input_path, const std::string& output_path, bool force)
236{
237 if (!transpile_artifact(input_path, output_path)) {
238 return false;
239 }
240
241 // Verify output exists
242 if (!std::filesystem::exists(output_path)) {
243 throw_or_abort("Output file does not exist after transpilation");
244 }
245
246 // Step 2: Generate verification keys
247 auto cache_dir = get_cache_dir();
248 info("Generating verification keys for functions in ", std::filesystem::path(output_path).filename().string());
249 info("Cache directory: ", cache_dir.string());
250
251 // Read and parse artifact JSON
252 auto artifact_content = read_file(output_path);
253 std::string artifact_str(artifact_content.begin(), artifact_content.end());
254 auto artifact_json = nlohmann::json::parse(artifact_str);
255
256 if (!artifact_json.contains("functions")) {
257 info("Warning: No functions found in artifact");
258 return true;
259 }
260
261 // Strip __aztec_nr_internals__ prefix from function names.
262 // The #[aztec] macro generates wrapper functions with this prefix; we strip it so
263 // the exported ABI exposes the original developer-written names.
264 const std::string internal_prefix = "__aztec_nr_internals__";
265 for (auto& function : artifact_json["functions"]) {
266 auto& name = function["name"];
267 if (name.is_string()) {
268 std::string fn_name = name.get<std::string>();
269 if (fn_name.size() >= internal_prefix.size() &&
270 fn_name.compare(0, internal_prefix.size(), internal_prefix) == 0) {
271 name = fn_name.substr(internal_prefix.size());
272 }
273 }
274 }
275
276 // Filter to private constrained functions
277 std::vector<nlohmann::json*> private_functions;
278 for (auto& function : artifact_json["functions"]) {
279 if (is_private_constrained_function(function)) {
280 private_functions.push_back(&function);
281 }
282 }
283
284 if (!private_functions.empty()) {
285 // Generate VKs
286 generate_vks_for_functions(cache_dir, private_functions, force);
287 } else {
288 info("No private constrained functions found");
289 }
290
291 // Write updated JSON back to file
292 std::ofstream out_file(output_path);
293 out_file << artifact_json.dump(2) << std::endl;
294 out_file.close();
295
296 info("Successfully processed: ", input_path, " -> ", output_path);
297 return true;
298}
299
300std::vector<std::string> find_contract_artifacts(const std::string& search_path)
301{
302 std::vector<std::string> artifacts;
303
304 // Recursively search for .json files in target/ directories, excluding cache/
305 for (const auto& entry : std::filesystem::recursive_directory_iterator(search_path)) {
306 if (!entry.is_regular_file()) {
307 continue;
308 }
309
310 const auto& path = entry.path();
311
312 // Must be a .json file
313 if (path.extension() != ".json") {
314 continue;
315 }
316
317 // Must be in a target/ directory
318 std::string path_str = path.string();
319 if (path_str.find("/target/") == std::string::npos && path_str.find("\\target\\") == std::string::npos) {
320 continue;
321 }
322
323 // Exclude cache directories and function artifact temporaries
324 if (path_str.find("/cache/") != std::string::npos || path_str.find("\\cache\\") != std::string::npos ||
325 path_str.find(".function_artifact_") != std::string::npos) {
326 continue;
327 }
328
329 artifacts.push_back(path.string());
330 }
331
332 return artifacts;
333}
334
335bool process_all_artifacts(const std::string& search_path, bool force)
336{
337 auto artifacts = find_contract_artifacts(search_path);
338
339 if (artifacts.empty()) {
340 info("No contract artifacts found in '", search_path, "'.");
341 return false;
342 }
343
344 info("Found ", artifacts.size(), " contract artifact(s) to process");
345
346 bool all_success = true;
347 for (const auto& artifact : artifacts) {
348 // Process in-place (input == output)
349 if (!process_aztec_artifact(artifact, artifact, force)) {
350 all_success = false;
351 }
352 }
353
354 if (all_success) {
355 info("Contract postprocessing complete!");
356 }
357
358 return all_success;
359}
360
361bool get_cache_paths(const std::string& input_path)
362{
363 try {
364 // Verify input exists
365 if (!std::filesystem::exists(input_path)) {
366 throw_or_abort("Input file does not exist: " + input_path);
367 }
368
369 // Read and parse artifact JSON
370 auto artifact_content = read_file(input_path);
371 std::string artifact_str(artifact_content.begin(), artifact_content.end());
372 auto artifact_json = nlohmann::json::parse(artifact_str);
373
374 if (!artifact_json.contains("functions")) {
375 // No functions, but not an error
376 return true;
377 }
378
379 // Get cache directory
380 auto cache_dir = get_cache_dir();
381
382 // Find all private constrained functions and output their cache paths
383 for (const auto& function : artifact_json["functions"]) {
384 if (!is_private_constrained_function(function)) {
385 continue;
386 }
387
388 std::string fn_name = function["name"].get<std::string>();
389 auto bytecode = extract_bytecode(function);
390 std::string hash_str = compute_bytecode_hash(bytecode);
391 std::filesystem::path vk_cache_path = cache_dir / (hash_str + ".vk");
392
393 // Output format: hash:cache_path:function_name
394 std::cout << hash_str << ":" << vk_cache_path.string() << ":" << fn_name << std::endl;
395 }
396
397 return true;
398 } catch (const std::exception& e) {
399 info("Error getting cache paths: ", e.what());
400 return false;
401 }
402}
403
404} // namespace bb
405#endif
std::shared_ptr< Napi::ThreadSafeFunction > bytecode
std::string base64_encode(unsigned char const *bytes_to_encode, size_t in_len, bool url)
Definition base64.cpp:117
Chonk-specific command definitions for the Barretenberg RPC API.
#define info(...)
Definition log.hpp:93
std::vector< uint8_t > decode_bytecode(const std::string &base64_bytecode)
Sha256Hash sha256(const ByteContainer &input)
SHA-256 hash function (FIPS 180-4)
Definition sha256.cpp:150
Entry point for Barretenberg command-line interface.
Definition api.hpp:5
bool transpile_artifact(const std::string &input_path, const std::string &output_path)
Transpile the artifact file (or copy if transpiler not enabled)
bool process_all_artifacts(const std::string &search_path, bool force)
Process all discovered contract artifacts in a directory tree.
bool get_cache_paths(const std::string &input_path)
Get cache paths for all verification keys in an artifact.
bool process_aztec_artifact(const std::string &input_path, const std::string &output_path, bool force)
Process Aztec contract artifacts: transpile and generate verification keys.
size_t get_num_cpus()
Definition thread.cpp:33
std::vector< std::string > find_contract_artifacts(const std::string &search_path)
Find all contract artifacts in target/ directories.
const char * BB_VERSION
Definition version.hpp:14
std::vector< uint8_t > read_file(const std::string &filename, size_t bytes=0)
Definition file_io.hpp:31
void set_parallel_for_concurrency(size_t num_cores)
Definition thread.cpp:23
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
void throw_or_abort(std::string const &err)