@caatinga/zk 2.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) Caatinga contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/dist/index.cjs ADDED
@@ -0,0 +1,433 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/index.ts
31
+ var index_exports = {};
32
+ __export(index_exports, {
33
+ ZkError: () => ZkError,
34
+ buildCircuit: () => buildCircuit,
35
+ buildStellarVerifyProofArgs: () => buildStellarVerifyProofArgs,
36
+ invokeVerifier: () => invokeVerifier,
37
+ proveCircuit: () => proveCircuit,
38
+ ptauSizeForConstraints: () => ptauSizeForConstraints,
39
+ serializeProof: () => serializeProof,
40
+ serializePublicSignals: () => serializePublicSignals,
41
+ serializeVk: () => serializeVk
42
+ });
43
+ module.exports = __toCommonJS(index_exports);
44
+
45
+ // src/serialization/bigint-helpers.ts
46
+ function decimalToLe32(decimal) {
47
+ let value = BigInt(decimal);
48
+ const out = new Uint8Array(32);
49
+ for (let i = 0; i < 32; i++) {
50
+ out[i] = Number(value & 0xffn);
51
+ value >>= 8n;
52
+ }
53
+ return out;
54
+ }
55
+ function decimalToBe48(decimal) {
56
+ let value = BigInt(decimal);
57
+ const out = new Uint8Array(48);
58
+ for (let i = 47; i >= 0; i--) {
59
+ out[i] = Number(value & 0xffn);
60
+ value >>= 8n;
61
+ }
62
+ return out;
63
+ }
64
+
65
+ // src/serialization/serialize-proof.ts
66
+ function serializeProof(proof) {
67
+ if (proof.curve !== "bls12381") {
68
+ throw new Error(`Expected curve bls12381, got ${proof.curve}`);
69
+ }
70
+ return {
71
+ a: {
72
+ x: decimalToBe48(proof.pi_a[0]),
73
+ y: decimalToBe48(proof.pi_a[1])
74
+ },
75
+ b: {
76
+ x: [decimalToBe48(proof.pi_b[0][1]), decimalToBe48(proof.pi_b[0][0])],
77
+ y: [decimalToBe48(proof.pi_b[1][1]), decimalToBe48(proof.pi_b[1][0])]
78
+ },
79
+ c: {
80
+ x: decimalToBe48(proof.pi_c[0]),
81
+ y: decimalToBe48(proof.pi_c[1])
82
+ }
83
+ };
84
+ }
85
+
86
+ // src/serialization/serialize-vk.ts
87
+ function g2FromSnarkjsExport(rows) {
88
+ return g2FromSnarkjs([rows[0], rows[1]]);
89
+ }
90
+ function g1FromSnarkjs(p) {
91
+ return {
92
+ x: decimalToBe48(p[0]),
93
+ y: decimalToBe48(p[1])
94
+ };
95
+ }
96
+ function g2FromSnarkjs(p) {
97
+ return {
98
+ x: [decimalToBe48(p[0][1]), decimalToBe48(p[0][0])],
99
+ y: [decimalToBe48(p[1][1]), decimalToBe48(p[1][0])]
100
+ };
101
+ }
102
+ function serializeVk(vk) {
103
+ if (vk.curve !== "bls12381") {
104
+ throw new Error(`Expected curve bls12381, got ${vk.curve}`);
105
+ }
106
+ const ic = vk.vk_ic ?? vk.IC;
107
+ if (!ic) {
108
+ throw new Error("Verification key is missing vk_ic/IC entries.");
109
+ }
110
+ return {
111
+ alpha: g1FromSnarkjs(vk.vk_alpha_1),
112
+ beta: g2FromSnarkjsExport(vk.vk_beta_2),
113
+ gamma: g2FromSnarkjsExport(vk.vk_gamma_2),
114
+ delta: g2FromSnarkjsExport(vk.vk_delta_2),
115
+ ic: ic.map(g1FromSnarkjs)
116
+ };
117
+ }
118
+
119
+ // src/serialization/serialize-public-signals.ts
120
+ function serializePublicSignals(signals) {
121
+ return signals.map((s) => decimalToLe32(s));
122
+ }
123
+
124
+ // src/build/build-circuit.ts
125
+ var import_core2 = require("@caatinga/core");
126
+ var import_node_path2 = __toESM(require("path"), 1);
127
+ var import_promises2 = require("fs/promises");
128
+ var import_node_crypto2 = require("crypto");
129
+
130
+ // src/install/lazy-install-zk-tools.ts
131
+ var import_core = require("@caatinga/core");
132
+ var import_promises = require("fs/promises");
133
+ var import_node_path = __toESM(require("path"), 1);
134
+ var import_node_os = __toESM(require("os"), 1);
135
+ var import_node_crypto = require("crypto");
136
+
137
+ // src/errors/ZkError.ts
138
+ var ZkError = class extends Error {
139
+ constructor(message, code, hint) {
140
+ super(message);
141
+ this.code = code;
142
+ this.hint = hint;
143
+ this.name = "ZkError";
144
+ }
145
+ code;
146
+ hint;
147
+ };
148
+
149
+ // src/install/lazy-install-zk-tools.ts
150
+ var ZK_CACHE_DIR = import_node_path.default.join(import_node_os.default.homedir(), ".caatinga", "zk-tools");
151
+ var SNARKJS_VERSION = "0.7.5";
152
+ var CIRCOM_VERSION = "2.1.9";
153
+ function circomAssetName() {
154
+ const platform = process.platform;
155
+ const arch = process.arch === "x64" ? "amd64" : process.arch;
156
+ if (platform === "linux") {
157
+ return `circom-linux-${arch}`;
158
+ }
159
+ if (platform === "darwin") {
160
+ return `circom-macos-${arch}`;
161
+ }
162
+ throw new ZkError(
163
+ `Unsupported platform for automatic circom install: ${platform}`,
164
+ "ZK_UNSUPPORTED_PLATFORM",
165
+ "Install circom 2.x manually and ensure it is on PATH."
166
+ );
167
+ }
168
+ async function ensureCircom() {
169
+ const cached = import_node_path.default.join(ZK_CACHE_DIR, "circom", CIRCOM_VERSION, "circom");
170
+ try {
171
+ await (0, import_promises.access)(cached);
172
+ return cached;
173
+ } catch {
174
+ }
175
+ const asset = circomAssetName();
176
+ const url = `https://github.com/iden3/circom/releases/download/v${CIRCOM_VERSION}/${asset}`;
177
+ const installDir = import_node_path.default.join(ZK_CACHE_DIR, "circom", CIRCOM_VERSION);
178
+ await (0, import_promises.mkdir)(installDir, { recursive: true });
179
+ const archivePath = import_node_path.default.join(installDir, asset);
180
+ await (0, import_core.runCommand)("curl", ["-fsSL", url, "-o", archivePath]);
181
+ await (0, import_promises.chmod)(archivePath, 493);
182
+ return archivePath;
183
+ }
184
+ async function ensureSnarkjs() {
185
+ const installDir = import_node_path.default.join(ZK_CACHE_DIR, `snarkjs-${SNARKJS_VERSION}`);
186
+ const cliPath = import_node_path.default.join(installDir, "node_modules", ".bin", "snarkjs");
187
+ try {
188
+ await (0, import_promises.access)(cliPath);
189
+ return cliPath;
190
+ } catch {
191
+ await (0, import_promises.mkdir)(installDir, { recursive: true });
192
+ await (0, import_promises.writeFile)(
193
+ import_node_path.default.join(installDir, "package.json"),
194
+ JSON.stringify({ name: "caatinga-zk-snarkjs", private: true, version: "0.0.0" }, null, 2),
195
+ "utf8"
196
+ );
197
+ await (0, import_core.runCommand)("npm", ["install", "--no-save", "--legacy-peer-deps", `snarkjs@${SNARKJS_VERSION}`], {
198
+ cwd: installDir
199
+ });
200
+ return cliPath;
201
+ }
202
+ }
203
+ async function ensurePtau(size) {
204
+ const ptauDir = import_node_path.default.join(ZK_CACHE_DIR, "ptau", "bls12-381");
205
+ const finalPath = import_node_path.default.join(ptauDir, `pot${size}_final.ptau`);
206
+ try {
207
+ await (0, import_promises.access)(finalPath);
208
+ return finalPath;
209
+ } catch {
210
+ await (0, import_promises.mkdir)(ptauDir, { recursive: true });
211
+ }
212
+ const snarkjs = await ensureSnarkjs();
213
+ const pot0 = import_node_path.default.join(ptauDir, `pot${size}_0000.ptau`);
214
+ const pot1 = import_node_path.default.join(ptauDir, `pot${size}_0001.ptau`);
215
+ const entropy = (0, import_node_crypto.createHash)("sha256").update((0, import_node_crypto.randomBytes)(32)).digest("hex");
216
+ await (0, import_core.runCommand)(snarkjs, ["powersoftau", "new", "bls12-381", String(size), pot0, "-v"]);
217
+ await (0, import_core.runCommand)(snarkjs, [
218
+ "powersoftau",
219
+ "contribute",
220
+ pot0,
221
+ pot1,
222
+ "-v"
223
+ ], {
224
+ input: `caatinga-dev
225
+ ${entropy}
226
+ `
227
+ });
228
+ await (0, import_core.runCommand)(snarkjs, ["powersoftau", "prepare", "phase2", pot1, finalPath, "-v"]);
229
+ return finalPath;
230
+ }
231
+
232
+ // src/build/detect-ptau-size.ts
233
+ function ptauSizeForConstraints(constraintCount) {
234
+ const needed = Math.ceil(Math.log2(Math.max(constraintCount, 1))) + 1;
235
+ return Math.min(Math.max(needed, 8), 28);
236
+ }
237
+
238
+ // src/build/build-circuit.ts
239
+ function bytesToHex(bytes) {
240
+ return Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join("");
241
+ }
242
+ async function writeEmbeddedVk(vkPath, verifierSrcDir) {
243
+ const raw = JSON.parse(await (0, import_promises2.readFile)(vkPath, "utf8"));
244
+ const vk = serializeVk(raw);
245
+ const lines = [
246
+ "// @generated by caatinga zk build --embed-vk",
247
+ "use soroban_sdk::crypto::bls12_381::{G1Affine, G2Affine};",
248
+ "",
249
+ "pub fn embedded_vk() -> (G1Affine, G2Affine, G2Affine, G2Affine, alloc::vec::Vec<G1Affine>) {",
250
+ ' todo!("Embed VK coordinates from verification_key.json")',
251
+ ` // alpha.x = ${bytesToHex(vk.alpha.x)}`,
252
+ "}",
253
+ ""
254
+ ];
255
+ await (0, import_promises2.writeFile)(import_node_path2.default.join(verifierSrcDir, "vk.rs"), lines.join("\n"), "utf8");
256
+ }
257
+ async function buildCircuit(options) {
258
+ const circom = await ensureCircom();
259
+ const snarkjs = await ensureSnarkjs();
260
+ const circuitDir = import_node_path2.default.resolve(options.circuitPath);
261
+ const outDir = import_node_path2.default.resolve(options.artifactsDir);
262
+ const circuitFile = import_node_path2.default.join(circuitDir, "main.circom");
263
+ const r1csPath = import_node_path2.default.join(outDir, "main.r1cs");
264
+ const zkey0 = import_node_path2.default.join(outDir, "circuit_0000.zkey");
265
+ const zkeyFinal = import_node_path2.default.join(outDir, "circuit_final.zkey");
266
+ const vkPath = import_node_path2.default.join(outDir, "verification_key.json");
267
+ await (0, import_promises2.mkdir)(outDir, { recursive: true });
268
+ await (0, import_core2.runCommand)(circom, [
269
+ circuitFile,
270
+ "--r1cs",
271
+ "--wasm",
272
+ "--sym",
273
+ "-p",
274
+ "bls12381",
275
+ "-o",
276
+ outDir
277
+ ]);
278
+ const r1csInfo = await (0, import_core2.runCommand)(snarkjs, ["r1cs", "info", r1csPath]);
279
+ const constraintMatch = r1csInfo.stdout.match(/# of Constraints:\s+(\d+)/);
280
+ const constraints = constraintMatch ? Number.parseInt(constraintMatch[1], 10) : 1;
281
+ const ptauSize = ptauSizeForConstraints(constraints);
282
+ const ptauPath = await ensurePtau(ptauSize);
283
+ const entropy = (0, import_node_crypto2.createHash)("sha256").update((0, import_node_crypto2.randomBytes)(32)).digest("hex");
284
+ await (0, import_core2.runCommand)(snarkjs, ["groth16", "setup", r1csPath, ptauPath, zkey0]);
285
+ await (0, import_core2.runCommand)(snarkjs, ["zkey", "contribute", zkey0, zkeyFinal, "-v"], {
286
+ input: `caatinga-dev
287
+ ${entropy}
288
+ `
289
+ });
290
+ await (0, import_core2.runCommand)(snarkjs, ["zkey", "export", "verificationkey", zkeyFinal, vkPath]);
291
+ if (options.embedVk) {
292
+ const verifierSrcDir = import_node_path2.default.resolve("contracts", "verifier", "src");
293
+ await writeEmbeddedVk(vkPath, verifierSrcDir);
294
+ }
295
+ }
296
+
297
+ // src/prove/prove-circuit.ts
298
+ var import_core3 = require("@caatinga/core");
299
+ var import_node_path3 = __toESM(require("path"), 1);
300
+ var import_promises3 = require("fs/promises");
301
+ function resolveCircuitWasmPath(artifactsDir) {
302
+ return import_node_path3.default.join(artifactsDir, "main_js", "main.wasm");
303
+ }
304
+ async function proveCircuit(options) {
305
+ const snarkjs = await ensureSnarkjs();
306
+ const artifactsDir = import_node_path3.default.resolve(options.artifactsDir);
307
+ const wasmPath = resolveCircuitWasmPath(artifactsDir);
308
+ const zkeyPath = import_node_path3.default.join(artifactsDir, "circuit_final.zkey");
309
+ const inputPath = import_node_path3.default.resolve(options.inputPath);
310
+ const proofPath = import_node_path3.default.join(artifactsDir, "proof.json");
311
+ const publicPath = import_node_path3.default.join(artifactsDir, "public.json");
312
+ await (0, import_promises3.mkdir)(artifactsDir, { recursive: true });
313
+ if (options.debug) {
314
+ const witnessPath = import_node_path3.default.join(artifactsDir, "witness.wtns");
315
+ await (0, import_core3.runCommand)(snarkjs, ["wtns", "calculate", wasmPath, inputPath, witnessPath, "-v"]);
316
+ await (0, import_core3.runCommand)(snarkjs, ["groth16", "prove", zkeyPath, witnessPath, proofPath, publicPath]);
317
+ return;
318
+ }
319
+ await (0, import_core3.runCommand)(snarkjs, [
320
+ "groth16",
321
+ "fullprove",
322
+ inputPath,
323
+ wasmPath,
324
+ zkeyPath,
325
+ proofPath,
326
+ publicPath
327
+ ]);
328
+ await (0, import_promises3.access)(proofPath);
329
+ await (0, import_promises3.access)(publicPath);
330
+ }
331
+
332
+ // src/invoke/invoke-verifier.ts
333
+ var import_core4 = require("@caatinga/core");
334
+ var import_promises4 = require("fs/promises");
335
+ var import_node_path4 = __toESM(require("path"), 1);
336
+ function concatG1(point) {
337
+ return Buffer.concat([point.x, point.y]).toString("hex");
338
+ }
339
+ function concatG2(point) {
340
+ return Buffer.concat([point.x[0], point.x[1], point.y[0], point.y[1]]).toString("hex");
341
+ }
342
+ function buildStellarVerifyProofArgs(options) {
343
+ const serializedProof = serializeProof(options.proof);
344
+ const args = [];
345
+ if (!options.embedVk) {
346
+ if (!options.vk) {
347
+ throw new ZkError("Verification key is required when embedVk is false.", "ZK_VK_REQUIRED");
348
+ }
349
+ const serializedVk = serializeVk(options.vk);
350
+ args.push(
351
+ "--vk",
352
+ JSON.stringify({
353
+ alpha: concatG1(serializedVk.alpha),
354
+ beta: concatG2(serializedVk.beta),
355
+ gamma: concatG2(serializedVk.gamma),
356
+ delta: concatG2(serializedVk.delta),
357
+ ic: serializedVk.ic.map(concatG1)
358
+ })
359
+ );
360
+ }
361
+ args.push(
362
+ "--proof",
363
+ JSON.stringify({
364
+ a: concatG1(serializedProof.a),
365
+ b: concatG2(serializedProof.b),
366
+ c: concatG1(serializedProof.c)
367
+ })
368
+ );
369
+ args.push("--pub_signals", JSON.stringify(options.publicSignals));
370
+ return args;
371
+ }
372
+ async function invokeVerifier(options) {
373
+ const cwd = options.cwd ?? process.cwd();
374
+ const config = options.config ?? await (0, import_core4.loadConfig)({ cwd });
375
+ const proof = JSON.parse(await (0, import_promises4.readFile)(import_node_path4.default.resolve(cwd, options.proofPath), "utf8"));
376
+ const publicSignals = JSON.parse(
377
+ await (0, import_promises4.readFile)(import_node_path4.default.resolve(cwd, options.publicSignalsPath), "utf8")
378
+ );
379
+ const vk = options.embedVk ? void 0 : JSON.parse(await (0, import_promises4.readFile)(import_node_path4.default.resolve(cwd, options.vkPath), "utf8"));
380
+ const args = buildStellarVerifyProofArgs({
381
+ proof,
382
+ vk,
383
+ publicSignals,
384
+ embedVk: options.embedVk
385
+ });
386
+ const target = `${options.verifierContract}.verify_proof`;
387
+ const result = await (0, import_core4.invokeContract)({
388
+ config,
389
+ target,
390
+ args,
391
+ networkName: options.network,
392
+ source: options.sourceAccount,
393
+ cwd
394
+ });
395
+ if (!result.result) {
396
+ throw new ZkError("Verifier invocation returned no result.", "ZK_INVOKE_FAILED");
397
+ }
398
+ if (result.result.trim().toLowerCase() !== "true") {
399
+ throw new ZkError(
400
+ `Verifier returned ${result.result.trim()}.`,
401
+ "ZK_VERIFY_FAILED"
402
+ );
403
+ }
404
+ const artifacts = await (0, import_core4.readArtifacts)(cwd);
405
+ const contractId = artifacts.networks[options.network]?.contracts[options.verifierContract]?.contractId;
406
+ if (!contractId) {
407
+ throw new ZkError(
408
+ `No deployed artifact found for "${options.verifierContract}" on "${options.network}".`,
409
+ "ZK_INVOKE_FAILED",
410
+ "Run caatinga deploy before invoking the verifier."
411
+ );
412
+ }
413
+ return {
414
+ network: options.network,
415
+ verifierContract: options.verifierContract,
416
+ contractId,
417
+ publicSignals,
418
+ verified: true
419
+ };
420
+ }
421
+ // Annotate the CommonJS export names for ESM import in node:
422
+ 0 && (module.exports = {
423
+ ZkError,
424
+ buildCircuit,
425
+ buildStellarVerifyProofArgs,
426
+ invokeVerifier,
427
+ proveCircuit,
428
+ ptauSizeForConstraints,
429
+ serializeProof,
430
+ serializePublicSignals,
431
+ serializeVk
432
+ });
433
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts","../src/serialization/bigint-helpers.ts","../src/serialization/serialize-proof.ts","../src/serialization/serialize-vk.ts","../src/serialization/serialize-public-signals.ts","../src/build/build-circuit.ts","../src/install/lazy-install-zk-tools.ts","../src/errors/ZkError.ts","../src/build/detect-ptau-size.ts","../src/prove/prove-circuit.ts","../src/invoke/invoke-verifier.ts"],"sourcesContent":["export { serializeProof, type SerializedProof, type SnarkjsProof } from \"./serialization/serialize-proof.js\";\nexport { serializeVk, type SerializedVk, type SnarkjsVk } from \"./serialization/serialize-vk.js\";\nexport { serializePublicSignals } from \"./serialization/serialize-public-signals.js\";\nexport { buildCircuit, type BuildCircuitOptions } from \"./build/build-circuit.js\";\nexport { proveCircuit, type ProveCircuitOptions } from \"./prove/prove-circuit.js\";\nexport { invokeVerifier, buildStellarVerifyProofArgs, type InvokeVerifierOptions, type InvokeVerifierResult } from \"./invoke/invoke-verifier.js\";\nexport { ptauSizeForConstraints } from \"./build/detect-ptau-size.js\";\nexport { ZkError } from \"./errors/ZkError.js\";\n","/**\n * Convert a decimal string to a little-endian unsigned 32-byte array.\n */\nexport function decimalToLe32(decimal: string): Uint8Array {\n let value = BigInt(decimal);\n const out = new Uint8Array(32);\n for (let i = 0; i < 32; i++) {\n out[i] = Number(value & 0xffn);\n value >>= 8n;\n }\n return out;\n}\n\n/**\n * Convert a decimal string to a big-endian unsigned 48-byte array.\n */\nexport function decimalToBe48(decimal: string): Uint8Array {\n let value = BigInt(decimal);\n const out = new Uint8Array(48);\n for (let i = 47; i >= 0; i--) {\n out[i] = Number(value & 0xffn);\n value >>= 8n;\n }\n return out;\n}\n","import { decimalToBe48 } from \"./bigint-helpers.js\";\n\nexport type SerializedG1 = {\n x: Uint8Array;\n y: Uint8Array;\n};\n\nexport type SerializedG2 = {\n x: [Uint8Array, Uint8Array];\n y: [Uint8Array, Uint8Array];\n};\n\nexport type SerializedProof = {\n a: SerializedG1;\n b: SerializedG2;\n c: SerializedG1;\n};\n\nexport type SnarkjsProof = {\n pi_a: [string, string, string];\n pi_b: [[string, string], [string, string]];\n pi_c: [string, string, string];\n protocol: string;\n curve: string;\n};\n\nexport function serializeProof(proof: SnarkjsProof): SerializedProof {\n if (proof.curve !== \"bls12381\") {\n throw new Error(`Expected curve bls12381, got ${proof.curve}`);\n }\n\n return {\n a: {\n x: decimalToBe48(proof.pi_a[0]),\n y: decimalToBe48(proof.pi_a[1]),\n },\n b: {\n x: [decimalToBe48(proof.pi_b[0][1]), decimalToBe48(proof.pi_b[0][0])],\n y: [decimalToBe48(proof.pi_b[1][1]), decimalToBe48(proof.pi_b[1][0])],\n },\n c: {\n x: decimalToBe48(proof.pi_c[0]),\n y: decimalToBe48(proof.pi_c[1]),\n },\n };\n}\n","import { decimalToBe48 } from \"./bigint-helpers.js\";\nimport type { SerializedG1, SerializedG2 } from \"./serialize-proof.js\";\n\nexport type SerializedVk = {\n alpha: SerializedG1;\n beta: SerializedG2;\n gamma: SerializedG2;\n delta: SerializedG2;\n ic: SerializedG1[];\n};\n\nexport type SnarkjsVk = {\n protocol: string;\n curve: string;\n vk_alpha_1: [string, string, string];\n vk_beta_2: [[string, string], [string, string], ...string[][]];\n vk_gamma_2: [[string, string], [string, string], ...string[][]];\n vk_delta_2: [[string, string], [string, string], ...string[][]];\n vk_ic?: Array<[string, string, string]>;\n IC?: Array<[string, string, string]>;\n};\n\nfunction g2FromSnarkjsExport(rows: [[string, string], [string, string], ...string[][]]): SerializedG2 {\n return g2FromSnarkjs([rows[0]!, rows[1]!]);\n}\n\nfunction g1FromSnarkjs(p: [string, string, string]): SerializedG1 {\n return {\n x: decimalToBe48(p[0]),\n y: decimalToBe48(p[1]),\n };\n}\n\nfunction g2FromSnarkjs(p: [[string, string], [string, string]]): SerializedG2 {\n return {\n x: [decimalToBe48(p[0][1]), decimalToBe48(p[0][0])],\n y: [decimalToBe48(p[1][1]), decimalToBe48(p[1][0])],\n };\n}\n\nexport function serializeVk(vk: SnarkjsVk): SerializedVk {\n if (vk.curve !== \"bls12381\") {\n throw new Error(`Expected curve bls12381, got ${vk.curve}`);\n }\n\n const ic = vk.vk_ic ?? vk.IC;\n if (!ic) {\n throw new Error(\"Verification key is missing vk_ic/IC entries.\");\n }\n\n return {\n alpha: g1FromSnarkjs(vk.vk_alpha_1),\n beta: g2FromSnarkjsExport(vk.vk_beta_2),\n gamma: g2FromSnarkjsExport(vk.vk_gamma_2),\n delta: g2FromSnarkjsExport(vk.vk_delta_2),\n ic: ic.map(g1FromSnarkjs),\n };\n}\n","import { decimalToLe32 } from \"./bigint-helpers.js\";\n\nexport function serializePublicSignals(signals: string[]): Uint8Array[] {\n return signals.map((s) => decimalToLe32(s));\n}\n","import { runCommand } from \"@caatinga/core\";\nimport path from \"node:path\";\nimport { mkdir, readFile, writeFile } from \"node:fs/promises\";\nimport { createHash, randomBytes } from \"node:crypto\";\nimport { ensureCircom, ensurePtau, ensureSnarkjs } from \"../install/lazy-install-zk-tools.js\";\nimport { ptauSizeForConstraints } from \"./detect-ptau-size.js\";\nimport { serializeVk, type SnarkjsVk } from \"../serialization/serialize-vk.js\";\n\nexport type BuildCircuitOptions = {\n circuitName: string;\n circuitPath: string;\n artifactsDir: string;\n embedVk: boolean;\n};\n\nfunction bytesToHex(bytes: Uint8Array): string {\n return Array.from(bytes).map((b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\nasync function writeEmbeddedVk(\n vkPath: string,\n verifierSrcDir: string\n): Promise<void> {\n const raw = JSON.parse(await readFile(vkPath, \"utf8\")) as SnarkjsVk;\n const vk = serializeVk(raw);\n const lines = [\n \"// @generated by caatinga zk build --embed-vk\",\n \"use soroban_sdk::crypto::bls12_381::{G1Affine, G2Affine};\",\n \"\",\n \"pub fn embedded_vk() -> (G1Affine, G2Affine, G2Affine, G2Affine, alloc::vec::Vec<G1Affine>) {\",\n \" todo!(\\\"Embed VK coordinates from verification_key.json\\\")\",\n ` // alpha.x = ${bytesToHex(vk.alpha.x)}`,\n \"}\",\n \"\",\n ];\n await writeFile(path.join(verifierSrcDir, \"vk.rs\"), lines.join(\"\\n\"), \"utf8\");\n}\n\nexport async function buildCircuit(options: BuildCircuitOptions): Promise<void> {\n const circom = await ensureCircom();\n const snarkjs = await ensureSnarkjs();\n const circuitDir = path.resolve(options.circuitPath);\n const outDir = path.resolve(options.artifactsDir);\n const circuitFile = path.join(circuitDir, \"main.circom\");\n const r1csPath = path.join(outDir, \"main.r1cs\");\n const zkey0 = path.join(outDir, \"circuit_0000.zkey\");\n const zkeyFinal = path.join(outDir, \"circuit_final.zkey\");\n const vkPath = path.join(outDir, \"verification_key.json\");\n\n await mkdir(outDir, { recursive: true });\n\n await runCommand(circom, [\n circuitFile,\n \"--r1cs\",\n \"--wasm\",\n \"--sym\",\n \"-p\",\n \"bls12381\",\n \"-o\",\n outDir,\n ]);\n\n const r1csInfo = await runCommand(snarkjs, [\"r1cs\", \"info\", r1csPath]);\n const constraintMatch = r1csInfo.stdout.match(/# of Constraints:\\s+(\\d+)/);\n const constraints = constraintMatch ? Number.parseInt(constraintMatch[1]!, 10) : 1;\n const ptauSize = ptauSizeForConstraints(constraints);\n const ptauPath = await ensurePtau(ptauSize);\n const entropy = createHash(\"sha256\").update(randomBytes(32)).digest(\"hex\");\n\n await runCommand(snarkjs, [\"groth16\", \"setup\", r1csPath, ptauPath, zkey0]);\n await runCommand(snarkjs, [\"zkey\", \"contribute\", zkey0, zkeyFinal, \"-v\"], {\n input: `caatinga-dev\\n${entropy}\\n`,\n });\n await runCommand(snarkjs, [\"zkey\", \"export\", \"verificationkey\", zkeyFinal, vkPath]);\n\n if (options.embedVk) {\n const verifierSrcDir = path.resolve(\"contracts\", \"verifier\", \"src\");\n await writeEmbeddedVk(vkPath, verifierSrcDir);\n }\n}\n","import { runCommand } from \"@caatinga/core\";\nimport { access, chmod, mkdir, writeFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport os from \"node:os\";\nimport { createHash, randomBytes } from \"node:crypto\";\nimport { ZkError } from \"../errors/ZkError.js\";\n\nconst ZK_CACHE_DIR = path.join(os.homedir(), \".caatinga\", \"zk-tools\");\nconst SNARKJS_VERSION = \"0.7.5\";\nconst CIRCOM_VERSION = \"2.1.9\";\n\nfunction circomAssetName(): string {\n const platform = process.platform;\n const arch = process.arch === \"x64\" ? \"amd64\" : process.arch;\n if (platform === \"linux\") {\n return `circom-linux-${arch}`;\n }\n if (platform === \"darwin\") {\n return `circom-macos-${arch}`;\n }\n throw new ZkError(\n `Unsupported platform for automatic circom install: ${platform}`,\n \"ZK_UNSUPPORTED_PLATFORM\",\n \"Install circom 2.x manually and ensure it is on PATH.\"\n );\n}\n\nexport async function ensureCircom(): Promise<string> {\n const cached = path.join(ZK_CACHE_DIR, \"circom\", CIRCOM_VERSION, \"circom\");\n try {\n await access(cached);\n return cached;\n } catch {\n // Fall through to download.\n }\n\n const asset = circomAssetName();\n const url = `https://github.com/iden3/circom/releases/download/v${CIRCOM_VERSION}/${asset}`;\n const installDir = path.join(ZK_CACHE_DIR, \"circom\", CIRCOM_VERSION);\n await mkdir(installDir, { recursive: true });\n\n const archivePath = path.join(installDir, asset);\n await runCommand(\"curl\", [\"-fsSL\", url, \"-o\", archivePath]);\n await chmod(archivePath, 0o755);\n\n return archivePath;\n}\n\nexport async function ensureSnarkjs(): Promise<string> {\n const installDir = path.join(ZK_CACHE_DIR, `snarkjs-${SNARKJS_VERSION}`);\n const cliPath = path.join(installDir, \"node_modules\", \".bin\", \"snarkjs\");\n\n try {\n await access(cliPath);\n return cliPath;\n } catch {\n await mkdir(installDir, { recursive: true });\n await writeFile(\n path.join(installDir, \"package.json\"),\n JSON.stringify({ name: \"caatinga-zk-snarkjs\", private: true, version: \"0.0.0\" }, null, 2),\n \"utf8\"\n );\n await runCommand(\"npm\", [\"install\", \"--no-save\", \"--legacy-peer-deps\", `snarkjs@${SNARKJS_VERSION}`], {\n cwd: installDir,\n });\n return cliPath;\n }\n}\n\nexport async function ensurePtau(size: number): Promise<string> {\n const ptauDir = path.join(ZK_CACHE_DIR, \"ptau\", \"bls12-381\");\n const finalPath = path.join(ptauDir, `pot${size}_final.ptau`);\n try {\n await access(finalPath);\n return finalPath;\n } catch {\n await mkdir(ptauDir, { recursive: true });\n }\n\n const snarkjs = await ensureSnarkjs();\n const pot0 = path.join(ptauDir, `pot${size}_0000.ptau`);\n const pot1 = path.join(ptauDir, `pot${size}_0001.ptau`);\n const entropy = createHash(\"sha256\").update(randomBytes(32)).digest(\"hex\");\n\n await runCommand(snarkjs, [\"powersoftau\", \"new\", \"bls12-381\", String(size), pot0, \"-v\"]);\n await runCommand(snarkjs, [\n \"powersoftau\",\n \"contribute\",\n pot0,\n pot1,\n \"-v\",\n ], {\n input: `caatinga-dev\\n${entropy}\\n`,\n });\n await runCommand(snarkjs, [\"powersoftau\", \"prepare\", \"phase2\", pot1, finalPath, \"-v\"]);\n\n return finalPath;\n}\n","export class ZkError extends Error {\n constructor(\n message: string,\n public readonly code: string,\n public readonly hint?: string\n ) {\n super(message);\n this.name = \"ZkError\";\n }\n}\n","export function ptauSizeForConstraints(constraintCount: number): number {\n const needed = Math.ceil(Math.log2(Math.max(constraintCount, 1))) + 1;\n return Math.min(Math.max(needed, 8), 28);\n}\n","import { runCommand } from \"@caatinga/core\";\nimport path from \"node:path\";\nimport { access, mkdir } from \"node:fs/promises\";\nimport { ensureSnarkjs } from \"../install/lazy-install-zk-tools.js\";\n\nexport type ProveCircuitOptions = {\n circuitName: string;\n circuitPath: string;\n artifactsDir: string;\n inputPath: string;\n debug: boolean;\n};\n\nexport function resolveCircuitWasmPath(artifactsDir: string): string {\n return path.join(artifactsDir, \"main_js\", \"main.wasm\");\n}\n\nexport async function proveCircuit(options: ProveCircuitOptions): Promise<void> {\n const snarkjs = await ensureSnarkjs();\n const artifactsDir = path.resolve(options.artifactsDir);\n const wasmPath = resolveCircuitWasmPath(artifactsDir);\n const zkeyPath = path.join(artifactsDir, \"circuit_final.zkey\");\n const inputPath = path.resolve(options.inputPath);\n const proofPath = path.join(artifactsDir, \"proof.json\");\n const publicPath = path.join(artifactsDir, \"public.json\");\n\n await mkdir(artifactsDir, { recursive: true });\n\n if (options.debug) {\n const witnessPath = path.join(artifactsDir, \"witness.wtns\");\n await runCommand(snarkjs, [\"wtns\", \"calculate\", wasmPath, inputPath, witnessPath, \"-v\"]);\n await runCommand(snarkjs, [\"groth16\", \"prove\", zkeyPath, witnessPath, proofPath, publicPath]);\n return;\n }\n\n await runCommand(snarkjs, [\n \"groth16\",\n \"fullprove\",\n inputPath,\n wasmPath,\n zkeyPath,\n proofPath,\n publicPath,\n ]);\n\n await access(proofPath);\n await access(publicPath);\n}\n","import { invokeContract, loadConfig, readArtifacts, type CaatingaConfig } from \"@caatinga/core\";\nimport { readFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { serializeProof, type SnarkjsProof } from \"../serialization/serialize-proof.js\";\nimport { serializeVk, type SnarkjsVk } from \"../serialization/serialize-vk.js\";\nimport { ZkError } from \"../errors/ZkError.js\";\n\nexport type InvokeVerifierOptions = {\n verifierContract: string;\n network: string;\n sourceAccount: string;\n proofPath: string;\n vkPath: string;\n publicSignalsPath: string;\n embedVk: boolean;\n cwd?: string;\n config?: CaatingaConfig;\n};\n\nfunction concatG1(point: { x: Uint8Array; y: Uint8Array }): string {\n return Buffer.concat([point.x, point.y]).toString(\"hex\");\n}\n\nfunction concatG2(point: { x: [Uint8Array, Uint8Array]; y: [Uint8Array, Uint8Array] }): string {\n return Buffer.concat([point.x[0], point.x[1], point.y[0], point.y[1]]).toString(\"hex\");\n}\n\nexport function buildStellarVerifyProofArgs(options: {\n proof: SnarkjsProof;\n vk?: SnarkjsVk;\n publicSignals: string[];\n embedVk: boolean;\n}): string[] {\n const serializedProof = serializeProof(options.proof);\n const args: string[] = [];\n\n if (!options.embedVk) {\n if (!options.vk) {\n throw new ZkError(\"Verification key is required when embedVk is false.\", \"ZK_VK_REQUIRED\");\n }\n\n const serializedVk = serializeVk(options.vk);\n args.push(\n \"--vk\",\n JSON.stringify({\n alpha: concatG1(serializedVk.alpha),\n beta: concatG2(serializedVk.beta),\n gamma: concatG2(serializedVk.gamma),\n delta: concatG2(serializedVk.delta),\n ic: serializedVk.ic.map(concatG1),\n })\n );\n }\n\n args.push(\n \"--proof\",\n JSON.stringify({\n a: concatG1(serializedProof.a),\n b: concatG2(serializedProof.b),\n c: concatG1(serializedProof.c),\n })\n );\n args.push(\"--pub_signals\", JSON.stringify(options.publicSignals));\n\n return args;\n}\n\nexport type InvokeVerifierResult = {\n network: string;\n verifierContract: string;\n contractId: string;\n publicSignals: string[];\n verified: true;\n};\n\nexport async function invokeVerifier(options: InvokeVerifierOptions): Promise<InvokeVerifierResult> {\n const cwd = options.cwd ?? process.cwd();\n const config = options.config ?? await loadConfig({ cwd });\n const proof = JSON.parse(await readFile(path.resolve(cwd, options.proofPath), \"utf8\")) as SnarkjsProof;\n const publicSignals = JSON.parse(\n await readFile(path.resolve(cwd, options.publicSignalsPath), \"utf8\")\n ) as string[];\n\n const vk = options.embedVk\n ? undefined\n : JSON.parse(await readFile(path.resolve(cwd, options.vkPath), \"utf8\")) as SnarkjsVk;\n\n const args = buildStellarVerifyProofArgs({\n proof,\n vk,\n publicSignals,\n embedVk: options.embedVk,\n });\n\n const target = `${options.verifierContract}.verify_proof`;\n const result = await invokeContract({\n config,\n target,\n args,\n networkName: options.network,\n source: options.sourceAccount,\n cwd,\n });\n\n if (!result.result) {\n throw new ZkError(\"Verifier invocation returned no result.\", \"ZK_INVOKE_FAILED\");\n }\n\n if (result.result.trim().toLowerCase() !== \"true\") {\n throw new ZkError(\n `Verifier returned ${result.result.trim()}.`,\n \"ZK_VERIFY_FAILED\"\n );\n }\n\n const artifacts = await readArtifacts(cwd);\n const contractId = artifacts.networks[options.network]?.contracts[options.verifierContract]?.contractId;\n\n if (!contractId) {\n throw new ZkError(\n `No deployed artifact found for \"${options.verifierContract}\" on \"${options.network}\".`,\n \"ZK_INVOKE_FAILED\",\n \"Run caatinga deploy before invoking the verifier.\"\n );\n }\n\n return {\n network: options.network,\n verifierContract: options.verifierContract,\n contractId,\n publicSignals,\n verified: true,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACGO,SAAS,cAAc,SAA6B;AACzD,MAAI,QAAQ,OAAO,OAAO;AAC1B,QAAM,MAAM,IAAI,WAAW,EAAE;AAC7B,WAAS,IAAI,GAAG,IAAI,IAAI,KAAK;AAC3B,QAAI,CAAC,IAAI,OAAO,QAAQ,KAAK;AAC7B,cAAU;AAAA,EACZ;AACA,SAAO;AACT;AAKO,SAAS,cAAc,SAA6B;AACzD,MAAI,QAAQ,OAAO,OAAO;AAC1B,QAAM,MAAM,IAAI,WAAW,EAAE;AAC7B,WAAS,IAAI,IAAI,KAAK,GAAG,KAAK;AAC5B,QAAI,CAAC,IAAI,OAAO,QAAQ,KAAK;AAC7B,cAAU;AAAA,EACZ;AACA,SAAO;AACT;;;ACEO,SAAS,eAAe,OAAsC;AACnE,MAAI,MAAM,UAAU,YAAY;AAC9B,UAAM,IAAI,MAAM,gCAAgC,MAAM,KAAK,EAAE;AAAA,EAC/D;AAEA,SAAO;AAAA,IACL,GAAG;AAAA,MACD,GAAG,cAAc,MAAM,KAAK,CAAC,CAAC;AAAA,MAC9B,GAAG,cAAc,MAAM,KAAK,CAAC,CAAC;AAAA,IAChC;AAAA,IACA,GAAG;AAAA,MACD,GAAG,CAAC,cAAc,MAAM,KAAK,CAAC,EAAE,CAAC,CAAC,GAAG,cAAc,MAAM,KAAK,CAAC,EAA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QAAQ,UACf,SACA,KAAK,MAAM,UAAM,2BAAS,kBAAAA,QAAK,QAAQ,KAAK,QAAQ,MAAM,GAAG,MAAM,CAAC;AAExE,QAAM,OAAO,4BAA4B;AAAA,IACvC;AAAA,IACA;AAAA,IACA;AAAA,IACA,SAAS,QAAQ;AAAA,EACnB,CAAC;AAED,QAAM,SAAS,GAAG,QAAQ,gBAAgB;AAC1C,QAAM,SAAS,UAAM,6BAAe;AAAA,IAClC;AAAA,IACA;AAAA,IACA;AAAA,IACA,aAAa,QAAQ;AAAA,IACrB,QAAQ,QAAQ;AAAA,IAChB;AAAA,EACF,CAAC;AAED,MAAI,CAAC,OAAO,QAAQ;AAClB,UAAM,IAAI,QAAQ,2CAA2C,kBAAkB;AAAA,EACjF;AAEA,MAAI,OAAO,OAAO,KAAK,EAAE,YAAY,MAAM,QAAQ;AACjD,UAAM,IAAI;AAAA,MACR,qBAAqB,OAAO,OAAO,KAAK,CAAC;AAAA,MACzC;AAAA,IACF;AAAA,EACF;AAEA,QAAM,YAAY,UAAM,4BAAc,GAAG;AACzC,QAAM,aAAa,UAAU,SAAS,QAAQ,OAAO,GAAG,UAAU,QAAQ,gBAAgB,GAAG;AAE7F,MAAI,CAAC,YAAY;AACf,UAAM,IAAI;AAAA,MACR,mCAAmC,QAAQ,gBAAgB,SAAS,QAAQ,OAAO;AAAA,MACnF;AAAA,MACA;AAAA,IACF;AAAA,EACF;AAEA,SAAO;AAAA,IACL,SAAS,QAAQ;AAAA,IACjB,kBAAkB,QAAQ;AAAA,IAC1B;AAAA,IACA;AAAA,IACA,UAAU;AAAA,EACZ;AACF;","names":["import_core","import_node_path","import_promises","import_node_crypto","path","os","path","import_core","import_node_path","import_promises","path","import_core","import_promises","import_node_path","path"]}
@@ -0,0 +1,97 @@
1
+ import { CaatingaConfig } from '@caatinga/core';
2
+
3
+ type SerializedG1 = {
4
+ x: Uint8Array;
5
+ y: Uint8Array;
6
+ };
7
+ type SerializedG2 = {
8
+ x: [Uint8Array, Uint8Array];
9
+ y: [Uint8Array, Uint8Array];
10
+ };
11
+ type SerializedProof = {
12
+ a: SerializedG1;
13
+ b: SerializedG2;
14
+ c: SerializedG1;
15
+ };
16
+ type SnarkjsProof = {
17
+ pi_a: [string, string, string];
18
+ pi_b: [[string, string], [string, string]];
19
+ pi_c: [string, string, string];
20
+ protocol: string;
21
+ curve: string;
22
+ };
23
+ declare function serializeProof(proof: SnarkjsProof): SerializedProof;
24
+
25
+ type SerializedVk = {
26
+ alpha: SerializedG1;
27
+ beta: SerializedG2;
28
+ gamma: SerializedG2;
29
+ delta: SerializedG2;
30
+ ic: SerializedG1[];
31
+ };
32
+ type SnarkjsVk = {
33
+ protocol: string;
34
+ curve: string;
35
+ vk_alpha_1: [string, string, string];
36
+ vk_beta_2: [[string, string], [string, string], ...string[][]];
37
+ vk_gamma_2: [[string, string], [string, string], ...string[][]];
38
+ vk_delta_2: [[string, string], [string, string], ...string[][]];
39
+ vk_ic?: Array<[string, string, string]>;
40
+ IC?: Array<[string, string, string]>;
41
+ };
42
+ declare function serializeVk(vk: SnarkjsVk): SerializedVk;
43
+
44
+ declare function serializePublicSignals(signals: string[]): Uint8Array[];
45
+
46
+ type BuildCircuitOptions = {
47
+ circuitName: string;
48
+ circuitPath: string;
49
+ artifactsDir: string;
50
+ embedVk: boolean;
51
+ };
52
+ declare function buildCircuit(options: BuildCircuitOptions): Promise<void>;
53
+
54
+ type ProveCircuitOptions = {
55
+ circuitName: string;
56
+ circuitPath: string;
57
+ artifactsDir: string;
58
+ inputPath: string;
59
+ debug: boolean;
60
+ };
61
+ declare function proveCircuit(options: ProveCircuitOptions): Promise<void>;
62
+
63
+ type InvokeVerifierOptions = {
64
+ verifierContract: string;
65
+ network: string;
66
+ sourceAccount: string;
67
+ proofPath: string;
68
+ vkPath: string;
69
+ publicSignalsPath: string;
70
+ embedVk: boolean;
71
+ cwd?: string;
72
+ config?: CaatingaConfig;
73
+ };
74
+ declare function buildStellarVerifyProofArgs(options: {
75
+ proof: SnarkjsProof;
76
+ vk?: SnarkjsVk;
77
+ publicSignals: string[];
78
+ embedVk: boolean;
79
+ }): string[];
80
+ type InvokeVerifierResult = {
81
+ network: string;
82
+ verifierContract: string;
83
+ contractId: string;
84
+ publicSignals: string[];
85
+ verified: true;
86
+ };
87
+ declare function invokeVerifier(options: InvokeVerifierOptions): Promise<InvokeVerifierResult>;
88
+
89
+ declare function ptauSizeForConstraints(constraintCount: number): number;
90
+
91
+ declare class ZkError extends Error {
92
+ readonly code: string;
93
+ readonly hint?: string | undefined;
94
+ constructor(message: string, code: string, hint?: string | undefined);
95
+ }
96
+
97
+ export { type BuildCircuitOptions, type InvokeVerifierOptions, type InvokeVerifierResult, type ProveCircuitOptions, type SerializedProof, type SerializedVk, type SnarkjsProof, type SnarkjsVk, ZkError, buildCircuit, buildStellarVerifyProofArgs, invokeVerifier, proveCircuit, ptauSizeForConstraints, serializeProof, serializePublicSignals, serializeVk };
@@ -0,0 +1,97 @@
1
+ import { CaatingaConfig } from '@caatinga/core';
2
+
3
+ type SerializedG1 = {
4
+ x: Uint8Array;
5
+ y: Uint8Array;
6
+ };
7
+ type SerializedG2 = {
8
+ x: [Uint8Array, Uint8Array];
9
+ y: [Uint8Array, Uint8Array];
10
+ };
11
+ type SerializedProof = {
12
+ a: SerializedG1;
13
+ b: SerializedG2;
14
+ c: SerializedG1;
15
+ };
16
+ type SnarkjsProof = {
17
+ pi_a: [string, string, string];
18
+ pi_b: [[string, string], [string, string]];
19
+ pi_c: [string, string, string];
20
+ protocol: string;
21
+ curve: string;
22
+ };
23
+ declare function serializeProof(proof: SnarkjsProof): SerializedProof;
24
+
25
+ type SerializedVk = {
26
+ alpha: SerializedG1;
27
+ beta: SerializedG2;
28
+ gamma: SerializedG2;
29
+ delta: SerializedG2;
30
+ ic: SerializedG1[];
31
+ };
32
+ type SnarkjsVk = {
33
+ protocol: string;
34
+ curve: string;
35
+ vk_alpha_1: [string, string, string];
36
+ vk_beta_2: [[string, string], [string, string], ...string[][]];
37
+ vk_gamma_2: [[string, string], [string, string], ...string[][]];
38
+ vk_delta_2: [[string, string], [string, string], ...string[][]];
39
+ vk_ic?: Array<[string, string, string]>;
40
+ IC?: Array<[string, string, string]>;
41
+ };
42
+ declare function serializeVk(vk: SnarkjsVk): SerializedVk;
43
+
44
+ declare function serializePublicSignals(signals: string[]): Uint8Array[];
45
+
46
+ type BuildCircuitOptions = {
47
+ circuitName: string;
48
+ circuitPath: string;
49
+ artifactsDir: string;
50
+ embedVk: boolean;
51
+ };
52
+ declare function buildCircuit(options: BuildCircuitOptions): Promise<void>;
53
+
54
+ type ProveCircuitOptions = {
55
+ circuitName: string;
56
+ circuitPath: string;
57
+ artifactsDir: string;
58
+ inputPath: string;
59
+ debug: boolean;
60
+ };
61
+ declare function proveCircuit(options: ProveCircuitOptions): Promise<void>;
62
+
63
+ type InvokeVerifierOptions = {
64
+ verifierContract: string;
65
+ network: string;
66
+ sourceAccount: string;
67
+ proofPath: string;
68
+ vkPath: string;
69
+ publicSignalsPath: string;
70
+ embedVk: boolean;
71
+ cwd?: string;
72
+ config?: CaatingaConfig;
73
+ };
74
+ declare function buildStellarVerifyProofArgs(options: {
75
+ proof: SnarkjsProof;
76
+ vk?: SnarkjsVk;
77
+ publicSignals: string[];
78
+ embedVk: boolean;
79
+ }): string[];
80
+ type InvokeVerifierResult = {
81
+ network: string;
82
+ verifierContract: string;
83
+ contractId: string;
84
+ publicSignals: string[];
85
+ verified: true;
86
+ };
87
+ declare function invokeVerifier(options: InvokeVerifierOptions): Promise<InvokeVerifierResult>;
88
+
89
+ declare function ptauSizeForConstraints(constraintCount: number): number;
90
+
91
+ declare class ZkError extends Error {
92
+ readonly code: string;
93
+ readonly hint?: string | undefined;
94
+ constructor(message: string, code: string, hint?: string | undefined);
95
+ }
96
+
97
+ export { type BuildCircuitOptions, type InvokeVerifierOptions, type InvokeVerifierResult, type ProveCircuitOptions, type SerializedProof, type SerializedVk, type SnarkjsProof, type SnarkjsVk, ZkError, buildCircuit, buildStellarVerifyProofArgs, invokeVerifier, proveCircuit, ptauSizeForConstraints, serializeProof, serializePublicSignals, serializeVk };
package/dist/index.js ADDED
@@ -0,0 +1,388 @@
1
+ // src/serialization/bigint-helpers.ts
2
+ function decimalToLe32(decimal) {
3
+ let value = BigInt(decimal);
4
+ const out = new Uint8Array(32);
5
+ for (let i = 0; i < 32; i++) {
6
+ out[i] = Number(value & 0xffn);
7
+ value >>= 8n;
8
+ }
9
+ return out;
10
+ }
11
+ function decimalToBe48(decimal) {
12
+ let value = BigInt(decimal);
13
+ const out = new Uint8Array(48);
14
+ for (let i = 47; i >= 0; i--) {
15
+ out[i] = Number(value & 0xffn);
16
+ value >>= 8n;
17
+ }
18
+ return out;
19
+ }
20
+
21
+ // src/serialization/serialize-proof.ts
22
+ function serializeProof(proof) {
23
+ if (proof.curve !== "bls12381") {
24
+ throw new Error(`Expected curve bls12381, got ${proof.curve}`);
25
+ }
26
+ return {
27
+ a: {
28
+ x: decimalToBe48(proof.pi_a[0]),
29
+ y: decimalToBe48(proof.pi_a[1])
30
+ },
31
+ b: {
32
+ x: [decimalToBe48(proof.pi_b[0][1]), decimalToBe48(proof.pi_b[0][0])],
33
+ y: [decimalToBe48(proof.pi_b[1][1]), decimalToBe48(proof.pi_b[1][0])]
34
+ },
35
+ c: {
36
+ x: decimalToBe48(proof.pi_c[0]),
37
+ y: decimalToBe48(proof.pi_c[1])
38
+ }
39
+ };
40
+ }
41
+
42
+ // src/serialization/serialize-vk.ts
43
+ function g2FromSnarkjsExport(rows) {
44
+ return g2FromSnarkjs([rows[0], rows[1]]);
45
+ }
46
+ function g1FromSnarkjs(p) {
47
+ return {
48
+ x: decimalToBe48(p[0]),
49
+ y: decimalToBe48(p[1])
50
+ };
51
+ }
52
+ function g2FromSnarkjs(p) {
53
+ return {
54
+ x: [decimalToBe48(p[0][1]), decimalToBe48(p[0][0])],
55
+ y: [decimalToBe48(p[1][1]), decimalToBe48(p[1][0])]
56
+ };
57
+ }
58
+ function serializeVk(vk) {
59
+ if (vk.curve !== "bls12381") {
60
+ throw new Error(`Expected curve bls12381, got ${vk.curve}`);
61
+ }
62
+ const ic = vk.vk_ic ?? vk.IC;
63
+ if (!ic) {
64
+ throw new Error("Verification key is missing vk_ic/IC entries.");
65
+ }
66
+ return {
67
+ alpha: g1FromSnarkjs(vk.vk_alpha_1),
68
+ beta: g2FromSnarkjsExport(vk.vk_beta_2),
69
+ gamma: g2FromSnarkjsExport(vk.vk_gamma_2),
70
+ delta: g2FromSnarkjsExport(vk.vk_delta_2),
71
+ ic: ic.map(g1FromSnarkjs)
72
+ };
73
+ }
74
+
75
+ // src/serialization/serialize-public-signals.ts
76
+ function serializePublicSignals(signals) {
77
+ return signals.map((s) => decimalToLe32(s));
78
+ }
79
+
80
+ // src/build/build-circuit.ts
81
+ import { runCommand as runCommand2 } from "@caatinga/core";
82
+ import path2 from "path";
83
+ import { mkdir as mkdir2, readFile, writeFile as writeFile2 } from "fs/promises";
84
+ import { createHash as createHash2, randomBytes as randomBytes2 } from "crypto";
85
+
86
+ // src/install/lazy-install-zk-tools.ts
87
+ import { runCommand } from "@caatinga/core";
88
+ import { access, chmod, mkdir, writeFile } from "fs/promises";
89
+ import path from "path";
90
+ import os from "os";
91
+ import { createHash, randomBytes } from "crypto";
92
+
93
+ // src/errors/ZkError.ts
94
+ var ZkError = class extends Error {
95
+ constructor(message, code, hint) {
96
+ super(message);
97
+ this.code = code;
98
+ this.hint = hint;
99
+ this.name = "ZkError";
100
+ }
101
+ code;
102
+ hint;
103
+ };
104
+
105
+ // src/install/lazy-install-zk-tools.ts
106
+ var ZK_CACHE_DIR = path.join(os.homedir(), ".caatinga", "zk-tools");
107
+ var SNARKJS_VERSION = "0.7.5";
108
+ var CIRCOM_VERSION = "2.1.9";
109
+ function circomAssetName() {
110
+ const platform = process.platform;
111
+ const arch = process.arch === "x64" ? "amd64" : process.arch;
112
+ if (platform === "linux") {
113
+ return `circom-linux-${arch}`;
114
+ }
115
+ if (platform === "darwin") {
116
+ return `circom-macos-${arch}`;
117
+ }
118
+ throw new ZkError(
119
+ `Unsupported platform for automatic circom install: ${platform}`,
120
+ "ZK_UNSUPPORTED_PLATFORM",
121
+ "Install circom 2.x manually and ensure it is on PATH."
122
+ );
123
+ }
124
+ async function ensureCircom() {
125
+ const cached = path.join(ZK_CACHE_DIR, "circom", CIRCOM_VERSION, "circom");
126
+ try {
127
+ await access(cached);
128
+ return cached;
129
+ } catch {
130
+ }
131
+ const asset = circomAssetName();
132
+ const url = `https://github.com/iden3/circom/releases/download/v${CIRCOM_VERSION}/${asset}`;
133
+ const installDir = path.join(ZK_CACHE_DIR, "circom", CIRCOM_VERSION);
134
+ await mkdir(installDir, { recursive: true });
135
+ const archivePath = path.join(installDir, asset);
136
+ await runCommand("curl", ["-fsSL", url, "-o", archivePath]);
137
+ await chmod(archivePath, 493);
138
+ return archivePath;
139
+ }
140
+ async function ensureSnarkjs() {
141
+ const installDir = path.join(ZK_CACHE_DIR, `snarkjs-${SNARKJS_VERSION}`);
142
+ const cliPath = path.join(installDir, "node_modules", ".bin", "snarkjs");
143
+ try {
144
+ await access(cliPath);
145
+ return cliPath;
146
+ } catch {
147
+ await mkdir(installDir, { recursive: true });
148
+ await writeFile(
149
+ path.join(installDir, "package.json"),
150
+ JSON.stringify({ name: "caatinga-zk-snarkjs", private: true, version: "0.0.0" }, null, 2),
151
+ "utf8"
152
+ );
153
+ await runCommand("npm", ["install", "--no-save", "--legacy-peer-deps", `snarkjs@${SNARKJS_VERSION}`], {
154
+ cwd: installDir
155
+ });
156
+ return cliPath;
157
+ }
158
+ }
159
+ async function ensurePtau(size) {
160
+ const ptauDir = path.join(ZK_CACHE_DIR, "ptau", "bls12-381");
161
+ const finalPath = path.join(ptauDir, `pot${size}_final.ptau`);
162
+ try {
163
+ await access(finalPath);
164
+ return finalPath;
165
+ } catch {
166
+ await mkdir(ptauDir, { recursive: true });
167
+ }
168
+ const snarkjs = await ensureSnarkjs();
169
+ const pot0 = path.join(ptauDir, `pot${size}_0000.ptau`);
170
+ const pot1 = path.join(ptauDir, `pot${size}_0001.ptau`);
171
+ const entropy = createHash("sha256").update(randomBytes(32)).digest("hex");
172
+ await runCommand(snarkjs, ["powersoftau", "new", "bls12-381", String(size), pot0, "-v"]);
173
+ await runCommand(snarkjs, [
174
+ "powersoftau",
175
+ "contribute",
176
+ pot0,
177
+ pot1,
178
+ "-v"
179
+ ], {
180
+ input: `caatinga-dev
181
+ ${entropy}
182
+ `
183
+ });
184
+ await runCommand(snarkjs, ["powersoftau", "prepare", "phase2", pot1, finalPath, "-v"]);
185
+ return finalPath;
186
+ }
187
+
188
+ // src/build/detect-ptau-size.ts
189
+ function ptauSizeForConstraints(constraintCount) {
190
+ const needed = Math.ceil(Math.log2(Math.max(constraintCount, 1))) + 1;
191
+ return Math.min(Math.max(needed, 8), 28);
192
+ }
193
+
194
+ // src/build/build-circuit.ts
195
+ function bytesToHex(bytes) {
196
+ return Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join("");
197
+ }
198
+ async function writeEmbeddedVk(vkPath, verifierSrcDir) {
199
+ const raw = JSON.parse(await readFile(vkPath, "utf8"));
200
+ const vk = serializeVk(raw);
201
+ const lines = [
202
+ "// @generated by caatinga zk build --embed-vk",
203
+ "use soroban_sdk::crypto::bls12_381::{G1Affine, G2Affine};",
204
+ "",
205
+ "pub fn embedded_vk() -> (G1Affine, G2Affine, G2Affine, G2Affine, alloc::vec::Vec<G1Affine>) {",
206
+ ' todo!("Embed VK coordinates from verification_key.json")',
207
+ ` // alpha.x = ${bytesToHex(vk.alpha.x)}`,
208
+ "}",
209
+ ""
210
+ ];
211
+ await writeFile2(path2.join(verifierSrcDir, "vk.rs"), lines.join("\n"), "utf8");
212
+ }
213
+ async function buildCircuit(options) {
214
+ const circom = await ensureCircom();
215
+ const snarkjs = await ensureSnarkjs();
216
+ const circuitDir = path2.resolve(options.circuitPath);
217
+ const outDir = path2.resolve(options.artifactsDir);
218
+ const circuitFile = path2.join(circuitDir, "main.circom");
219
+ const r1csPath = path2.join(outDir, "main.r1cs");
220
+ const zkey0 = path2.join(outDir, "circuit_0000.zkey");
221
+ const zkeyFinal = path2.join(outDir, "circuit_final.zkey");
222
+ const vkPath = path2.join(outDir, "verification_key.json");
223
+ await mkdir2(outDir, { recursive: true });
224
+ await runCommand2(circom, [
225
+ circuitFile,
226
+ "--r1cs",
227
+ "--wasm",
228
+ "--sym",
229
+ "-p",
230
+ "bls12381",
231
+ "-o",
232
+ outDir
233
+ ]);
234
+ const r1csInfo = await runCommand2(snarkjs, ["r1cs", "info", r1csPath]);
235
+ const constraintMatch = r1csInfo.stdout.match(/# of Constraints:\s+(\d+)/);
236
+ const constraints = constraintMatch ? Number.parseInt(constraintMatch[1], 10) : 1;
237
+ const ptauSize = ptauSizeForConstraints(constraints);
238
+ const ptauPath = await ensurePtau(ptauSize);
239
+ const entropy = createHash2("sha256").update(randomBytes2(32)).digest("hex");
240
+ await runCommand2(snarkjs, ["groth16", "setup", r1csPath, ptauPath, zkey0]);
241
+ await runCommand2(snarkjs, ["zkey", "contribute", zkey0, zkeyFinal, "-v"], {
242
+ input: `caatinga-dev
243
+ ${entropy}
244
+ `
245
+ });
246
+ await runCommand2(snarkjs, ["zkey", "export", "verificationkey", zkeyFinal, vkPath]);
247
+ if (options.embedVk) {
248
+ const verifierSrcDir = path2.resolve("contracts", "verifier", "src");
249
+ await writeEmbeddedVk(vkPath, verifierSrcDir);
250
+ }
251
+ }
252
+
253
+ // src/prove/prove-circuit.ts
254
+ import { runCommand as runCommand3 } from "@caatinga/core";
255
+ import path3 from "path";
256
+ import { access as access2, mkdir as mkdir3 } from "fs/promises";
257
+ function resolveCircuitWasmPath(artifactsDir) {
258
+ return path3.join(artifactsDir, "main_js", "main.wasm");
259
+ }
260
+ async function proveCircuit(options) {
261
+ const snarkjs = await ensureSnarkjs();
262
+ const artifactsDir = path3.resolve(options.artifactsDir);
263
+ const wasmPath = resolveCircuitWasmPath(artifactsDir);
264
+ const zkeyPath = path3.join(artifactsDir, "circuit_final.zkey");
265
+ const inputPath = path3.resolve(options.inputPath);
266
+ const proofPath = path3.join(artifactsDir, "proof.json");
267
+ const publicPath = path3.join(artifactsDir, "public.json");
268
+ await mkdir3(artifactsDir, { recursive: true });
269
+ if (options.debug) {
270
+ const witnessPath = path3.join(artifactsDir, "witness.wtns");
271
+ await runCommand3(snarkjs, ["wtns", "calculate", wasmPath, inputPath, witnessPath, "-v"]);
272
+ await runCommand3(snarkjs, ["groth16", "prove", zkeyPath, witnessPath, proofPath, publicPath]);
273
+ return;
274
+ }
275
+ await runCommand3(snarkjs, [
276
+ "groth16",
277
+ "fullprove",
278
+ inputPath,
279
+ wasmPath,
280
+ zkeyPath,
281
+ proofPath,
282
+ publicPath
283
+ ]);
284
+ await access2(proofPath);
285
+ await access2(publicPath);
286
+ }
287
+
288
+ // src/invoke/invoke-verifier.ts
289
+ import { invokeContract, loadConfig, readArtifacts } from "@caatinga/core";
290
+ import { readFile as readFile2 } from "fs/promises";
291
+ import path4 from "path";
292
+ function concatG1(point) {
293
+ return Buffer.concat([point.x, point.y]).toString("hex");
294
+ }
295
+ function concatG2(point) {
296
+ return Buffer.concat([point.x[0], point.x[1], point.y[0], point.y[1]]).toString("hex");
297
+ }
298
+ function buildStellarVerifyProofArgs(options) {
299
+ const serializedProof = serializeProof(options.proof);
300
+ const args = [];
301
+ if (!options.embedVk) {
302
+ if (!options.vk) {
303
+ throw new ZkError("Verification key is required when embedVk is false.", "ZK_VK_REQUIRED");
304
+ }
305
+ const serializedVk = serializeVk(options.vk);
306
+ args.push(
307
+ "--vk",
308
+ JSON.stringify({
309
+ alpha: concatG1(serializedVk.alpha),
310
+ beta: concatG2(serializedVk.beta),
311
+ gamma: concatG2(serializedVk.gamma),
312
+ delta: concatG2(serializedVk.delta),
313
+ ic: serializedVk.ic.map(concatG1)
314
+ })
315
+ );
316
+ }
317
+ args.push(
318
+ "--proof",
319
+ JSON.stringify({
320
+ a: concatG1(serializedProof.a),
321
+ b: concatG2(serializedProof.b),
322
+ c: concatG1(serializedProof.c)
323
+ })
324
+ );
325
+ args.push("--pub_signals", JSON.stringify(options.publicSignals));
326
+ return args;
327
+ }
328
+ async function invokeVerifier(options) {
329
+ const cwd = options.cwd ?? process.cwd();
330
+ const config = options.config ?? await loadConfig({ cwd });
331
+ const proof = JSON.parse(await readFile2(path4.resolve(cwd, options.proofPath), "utf8"));
332
+ const publicSignals = JSON.parse(
333
+ await readFile2(path4.resolve(cwd, options.publicSignalsPath), "utf8")
334
+ );
335
+ const vk = options.embedVk ? void 0 : JSON.parse(await readFile2(path4.resolve(cwd, options.vkPath), "utf8"));
336
+ const args = buildStellarVerifyProofArgs({
337
+ proof,
338
+ vk,
339
+ publicSignals,
340
+ embedVk: options.embedVk
341
+ });
342
+ const target = `${options.verifierContract}.verify_proof`;
343
+ const result = await invokeContract({
344
+ config,
345
+ target,
346
+ args,
347
+ networkName: options.network,
348
+ source: options.sourceAccount,
349
+ cwd
350
+ });
351
+ if (!result.result) {
352
+ throw new ZkError("Verifier invocation returned no result.", "ZK_INVOKE_FAILED");
353
+ }
354
+ if (result.result.trim().toLowerCase() !== "true") {
355
+ throw new ZkError(
356
+ `Verifier returned ${result.result.trim()}.`,
357
+ "ZK_VERIFY_FAILED"
358
+ );
359
+ }
360
+ const artifacts = await readArtifacts(cwd);
361
+ const contractId = artifacts.networks[options.network]?.contracts[options.verifierContract]?.contractId;
362
+ if (!contractId) {
363
+ throw new ZkError(
364
+ `No deployed artifact found for "${options.verifierContract}" on "${options.network}".`,
365
+ "ZK_INVOKE_FAILED",
366
+ "Run caatinga deploy before invoking the verifier."
367
+ );
368
+ }
369
+ return {
370
+ network: options.network,
371
+ verifierContract: options.verifierContract,
372
+ contractId,
373
+ publicSignals,
374
+ verified: true
375
+ };
376
+ }
377
+ export {
378
+ ZkError,
379
+ buildCircuit,
380
+ buildStellarVerifyProofArgs,
381
+ invokeVerifier,
382
+ proveCircuit,
383
+ ptauSizeForConstraints,
384
+ serializeProof,
385
+ serializePublicSignals,
386
+ serializeVk
387
+ };
388
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/serialization/bigint-helpers.ts","../src/serialization/serialize-proof.ts","../src/serialization/serialize-vk.ts","../src/serialization/serialize-public-signals.ts","../src/build/build-circuit.ts","../src/install/lazy-install-zk-tools.ts","../src/errors/ZkError.ts","../src/build/detect-ptau-size.ts","../src/prove/prove-circuit.ts","../src/invoke/invoke-verifier.ts"],"sourcesContent":["/**\n * Convert a decimal string to a little-endian unsigned 32-byte array.\n */\nexport function decimalToLe32(decimal: string): Uint8Array {\n let value = BigInt(decimal);\n const out = new Uint8Array(32);\n for (let i = 0; i < 32; i++) {\n out[i] = Number(value & 0xffn);\n value >>= 8n;\n }\n return out;\n}\n\n/**\n * Convert a decimal string to a big-endian unsigned 48-byte array.\n */\nexport function decimalToBe48(decimal: string): Uint8Array {\n let value = BigInt(decimal);\n const out = new Uint8Array(48);\n for (let i = 47; i >= 0; i--) {\n out[i] = Number(value & 0xffn);\n value >>= 8n;\n }\n return out;\n}\n","import { decimalToBe48 } from \"./bigint-helpers.js\";\n\nexport type SerializedG1 = {\n x: Uint8Array;\n y: Uint8Array;\n};\n\nexport type SerializedG2 = {\n x: [Uint8Array, Uint8Array];\n y: [Uint8Array, Uint8Array];\n};\n\nexport type SerializedProof = {\n a: SerializedG1;\n b: SerializedG2;\n c: SerializedG1;\n};\n\nexport type SnarkjsProof = {\n pi_a: [string, string, string];\n pi_b: [[string, string], [string, string]];\n pi_c: [string, string, string];\n protocol: string;\n curve: string;\n};\n\nexport function serializeProof(proof: SnarkjsProof): SerializedProof {\n if (proof.curve !== \"bls12381\") {\n throw new Error(`Expected curve bls12381, got ${proof.curve}`);\n }\n\n return {\n a: {\n x: decimalToBe48(proof.pi_a[0]),\n y: decimalToBe48(proof.pi_a[1]),\n },\n b: {\n x: [decimalToBe48(proof.pi_b[0][1]), decimalToBe48(proof.pi_b[0][0])],\n y: [decimalToBe48(proof.pi_b[1][1]), decimalToBe48(proof.pi_b[1][0])],\n },\n c: {\n x: decimalToBe48(proof.pi_c[0]),\n y: decimalToBe48(proof.pi_c[1]),\n },\n };\n}\n","import { decimalToBe48 } from \"./bigint-helpers.js\";\nimport type { SerializedG1, SerializedG2 } from \"./serialize-proof.js\";\n\nexport type SerializedVk = {\n alpha: SerializedG1;\n beta: SerializedG2;\n gamma: SerializedG2;\n delta: SerializedG2;\n ic: SerializedG1[];\n};\n\nexport type SnarkjsVk = {\n protocol: string;\n curve: string;\n vk_alpha_1: [string, string, string];\n vk_beta_2: [[string, string], [string, string], ...string[][]];\n vk_gamma_2: [[string, string], [string, string], ...string[][]];\n vk_delta_2: [[string, string], [string, string], ...string[][]];\n vk_ic?: Array<[string, string, string]>;\n IC?: Array<[string, string, string]>;\n};\n\nfunction g2FromSnarkjsExport(rows: [[string, string], [string, string], ...string[][]]): SerializedG2 {\n return g2FromSnarkjs([rows[0]!, rows[1]!]);\n}\n\nfunction g1FromSnarkjs(p: [string, string, string]): SerializedG1 {\n return {\n x: decimalToBe48(p[0]),\n y: decimalToBe48(p[1]),\n };\n}\n\nfunction g2FromSnarkjs(p: [[string, string], [string, string]]): SerializedG2 {\n return {\n x: [decimalToBe48(p[0][1]), decimalToBe48(p[0][0])],\n y: [decimalToBe48(p[1][1]), decimalToBe48(p[1][0])],\n };\n}\n\nexport function serializeVk(vk: SnarkjsVk): SerializedVk {\n if (vk.curve !== \"bls12381\") {\n throw new Error(`Expected curve bls12381, got ${vk.curve}`);\n }\n\n const ic = vk.vk_ic ?? vk.IC;\n if (!ic) {\n throw new Error(\"Verification key is missing vk_ic/IC entries.\");\n }\n\n return {\n alpha: g1FromSnarkjs(vk.vk_alpha_1),\n beta: g2FromSnarkjsExport(vk.vk_beta_2),\n gamma: g2FromSnarkjsExport(vk.vk_gamma_2),\n delta: g2FromSnarkjsExport(vk.vk_delta_2),\n ic: ic.map(g1FromSnarkjs),\n };\n}\n","import { decimalToLe32 } from \"./bigint-helpers.js\";\n\nexport function serializePublicSignals(signals: string[]): Uint8Array[] {\n return signals.map((s) => decimalToLe32(s));\n}\n","import { runCommand } from \"@caatinga/core\";\nimport path from \"node:path\";\nimport { mkdir, readFile, writeFile } from \"node:fs/promises\";\nimport { createHash, randomBytes } from \"node:crypto\";\nimport { ensureCircom, ensurePtau, ensureSnarkjs } from \"../install/lazy-install-zk-tools.js\";\nimport { ptauSizeForConstraints } from \"./detect-ptau-size.js\";\nimport { serializeVk, type SnarkjsVk } from \"../serialization/serialize-vk.js\";\n\nexport type BuildCircuitOptions = {\n circuitName: string;\n circuitPath: string;\n artifactsDir: string;\n embedVk: boolean;\n};\n\nfunction bytesToHex(bytes: Uint8Array): string {\n return Array.from(bytes).map((b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\nasync function writeEmbeddedVk(\n vkPath: string,\n verifierSrcDir: string\n): Promise<void> {\n const raw = JSON.parse(await readFile(vkPath, \"utf8\")) as SnarkjsVk;\n const vk = serializeVk(raw);\n const lines = [\n \"// @generated by caatinga zk build --embed-vk\",\n \"use soroban_sdk::crypto::bls12_381::{G1Affine, G2Affine};\",\n \"\",\n \"pub fn embedded_vk() -> (G1Affine, G2Affine, G2Affine, G2Affine, alloc::vec::Vec<G1Affine>) {\",\n \" todo!(\\\"Embed VK coordinates from verification_key.json\\\")\",\n ` // alpha.x = ${bytesToHex(vk.alpha.x)}`,\n \"}\",\n \"\",\n ];\n await writeFile(path.join(verifierSrcDir, \"vk.rs\"), lines.join(\"\\n\"), \"utf8\");\n}\n\nexport async function buildCircuit(options: BuildCircuitOptions): Promise<void> {\n const circom = await ensureCircom();\n const snarkjs = await ensureSnarkjs();\n const circuitDir = path.resolve(options.circuitPath);\n const outDir = path.resolve(options.artifactsDir);\n const circuitFile = path.join(circuitDir, \"main.circom\");\n const r1csPath = path.join(outDir, \"main.r1cs\");\n const zkey0 = path.join(outDir, \"circuit_0000.zkey\");\n const zkeyFinal = path.join(outDir, \"circuit_final.zkey\");\n const vkPath = path.join(outDir, \"verification_key.json\");\n\n await mkdir(outDir, { recursive: true });\n\n await runCommand(circom, [\n circuitFile,\n \"--r1cs\",\n \"--wasm\",\n \"--sym\",\n \"-p\",\n \"bls12381\",\n \"-o\",\n outDir,\n ]);\n\n const r1csInfo = await runCommand(snarkjs, [\"r1cs\", \"info\", r1csPath]);\n const constraintMatch = r1csInfo.stdout.match(/# of Constraints:\\s+(\\d+)/);\n const constraints = constraintMatch ? Number.parseInt(constraintMatch[1]!, 10) : 1;\n const ptauSize = ptauSizeForConstraints(constraints);\n const ptauPath = await ensurePtau(ptauSize);\n const entropy = createHash(\"sha256\").update(randomBytes(32)).digest(\"hex\");\n\n await runCommand(snarkjs, [\"groth16\", \"setup\", r1csPath, ptauPath, zkey0]);\n await runCommand(snarkjs, [\"zkey\", \"contribute\", zkey0, zkeyFinal, \"-v\"], {\n input: `caatinga-dev\\n${entropy}\\n`,\n });\n await runCommand(snarkjs, [\"zkey\", \"export\", \"verificationkey\", zkeyFinal, vkPath]);\n\n if (options.embedVk) {\n const verifierSrcDir = path.resolve(\"contracts\", \"verifier\", \"src\");\n await writeEmbeddedVk(vkPath, verifierSrcDir);\n }\n}\n","import { runCommand } from \"@caatinga/core\";\nimport { access, chmod, mkdir, writeFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport os from \"node:os\";\nimport { createHash, randomBytes } from \"node:crypto\";\nimport { ZkError } from \"../errors/ZkError.js\";\n\nconst ZK_CACHE_DIR = path.join(os.homedir(), \".caatinga\", \"zk-tools\");\nconst SNARKJS_VERSION = \"0.7.5\";\nconst CIRCOM_VERSION = \"2.1.9\";\n\nfunction circomAssetName(): string {\n const platform = process.platform;\n const arch = process.arch === \"x64\" ? \"amd64\" : process.arch;\n if (platform === \"linux\") {\n return `circom-linux-${arch}`;\n }\n if (platform === \"darwin\") {\n return `circom-macos-${arch}`;\n }\n throw new ZkError(\n `Unsupported platform for automatic circom install: ${platform}`,\n \"ZK_UNSUPPORTED_PLATFORM\",\n \"Install circom 2.x manually and ensure it is on PATH.\"\n );\n}\n\nexport async function ensureCircom(): Promise<string> {\n const cached = path.join(ZK_CACHE_DIR, \"circom\", CIRCOM_VERSION, \"circom\");\n try {\n await access(cached);\n return cached;\n } catch {\n // Fall through to download.\n }\n\n const asset = circomAssetName();\n const url = `https://github.com/iden3/circom/releases/download/v${CIRCOM_VERSION}/${asset}`;\n const installDir = path.join(ZK_CACHE_DIR, \"circom\", CIRCOM_VERSION);\n await mkdir(installDir, { recursive: true });\n\n const archivePath = path.join(installDir, asset);\n await runCommand(\"curl\", [\"-fsSL\", url, \"-o\", archivePath]);\n await chmod(archivePath, 0o755);\n\n return archivePath;\n}\n\nexport async function ensureSnarkjs(): Promise<string> {\n const installDir = path.join(ZK_CACHE_DIR, `snarkjs-${SNARKJS_VERSION}`);\n const cliPath = path.join(installDir, \"node_modules\", \".bin\", \"snarkjs\");\n\n try {\n await access(cliPath);\n return cliPath;\n } catch {\n await mkdir(installDir, { recursive: true });\n await writeFile(\n path.join(installDir, \"package.json\"),\n JSON.stringify({ name: \"caatinga-zk-snarkjs\", private: true, version: \"0.0.0\" }, null, 2),\n \"utf8\"\n );\n await runCommand(\"npm\", [\"install\", \"--no-save\", \"--legacy-peer-deps\", `snarkjs@${SNARKJS_VERSION}`], {\n cwd: installDir,\n });\n return cliPath;\n }\n}\n\nexport async function ensurePtau(size: number): Promise<string> {\n const ptauDir = path.join(ZK_CACHE_DIR, \"ptau\", \"bls12-381\");\n const finalPath = path.join(ptauDir, `pot${size}_final.ptau`);\n try {\n await access(finalPath);\n return finalPath;\n } catch {\n await mkdir(ptauDir, { recursive: true });\n }\n\n const snarkjs = await ensureSnarkjs();\n const pot0 = path.join(ptauDir, `pot${size}_0000.ptau`);\n const pot1 = path.join(ptauDir, `pot${size}_0001.ptau`);\n const entropy = createHash(\"sha256\").update(randomBytes(32)).digest(\"hex\");\n\n await runCommand(snarkjs, [\"powersoftau\", \"new\", \"bls12-381\", String(size), pot0, \"-v\"]);\n await runCommand(snarkjs, [\n \"powersoftau\",\n \"contribute\",\n pot0,\n pot1,\n \"-v\",\n ], {\n input: `caatinga-dev\\n${entropy}\\n`,\n });\n await runCommand(snarkjs, [\"powersoftau\", \"prepare\", \"phase2\", pot1, finalPath, \"-v\"]);\n\n return finalPath;\n}\n","export class ZkError extends Error {\n constructor(\n message: string,\n public readonly code: string,\n public readonly hint?: string\n ) {\n super(message);\n this.name = \"ZkError\";\n }\n}\n","export function ptauSizeForConstraints(constraintCount: number): number {\n const needed = Math.ceil(Math.log2(Math.max(constraintCount, 1))) + 1;\n return Math.min(Math.max(needed, 8), 28);\n}\n","import { runCommand } from \"@caatinga/core\";\nimport path from \"node:path\";\nimport { access, mkdir } from \"node:fs/promises\";\nimport { ensureSnarkjs } from \"../install/lazy-install-zk-tools.js\";\n\nexport type ProveCircuitOptions = {\n circuitName: string;\n circuitPath: string;\n artifactsDir: string;\n inputPath: string;\n debug: boolean;\n};\n\nexport function resolveCircuitWasmPath(artifactsDir: string): string {\n return path.join(artifactsDir, \"main_js\", \"main.wasm\");\n}\n\nexport async function proveCircuit(options: ProveCircuitOptions): Promise<void> {\n const snarkjs = await ensureSnarkjs();\n const artifactsDir = path.resolve(options.artifactsDir);\n const wasmPath = resolveCircuitWasmPath(artifactsDir);\n const zkeyPath = path.join(artifactsDir, \"circuit_final.zkey\");\n const inputPath = path.resolve(options.inputPath);\n const proofPath = path.join(artifactsDir, \"proof.json\");\n const publicPath = path.join(artifactsDir, \"public.json\");\n\n await mkdir(artifactsDir, { recursive: true });\n\n if (options.debug) {\n const witnessPath = path.join(artifactsDir, \"witness.wtns\");\n await runCommand(snarkjs, [\"wtns\", \"calculate\", wasmPath, inputPath, witnessPath, \"-v\"]);\n await runCommand(snarkjs, [\"groth16\", \"prove\", zkeyPath, witnessPath, proofPath, publicPath]);\n return;\n }\n\n await runCommand(snarkjs, [\n \"groth16\",\n \"fullprove\",\n inputPath,\n wasmPath,\n zkeyPath,\n proofPath,\n publicPath,\n ]);\n\n await access(proofPath);\n await access(publicPath);\n}\n","import { invokeContract, loadConfig, readArtifacts, type CaatingaConfig } from \"@caatinga/core\";\nimport { readFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { serializeProof, type SnarkjsProof } from \"../serialization/serialize-proof.js\";\nimport { serializeVk, type SnarkjsVk } from \"../serialization/serialize-vk.js\";\nimport { ZkError } from \"../errors/ZkError.js\";\n\nexport type InvokeVerifierOptions = {\n verifierContract: string;\n network: string;\n sourceAccount: string;\n proofPath: string;\n vkPath: string;\n publicSignalsPath: string;\n embedVk: boolean;\n cwd?: string;\n config?: CaatingaConfig;\n};\n\nfunction concatG1(point: { x: Uint8Array; y: Uint8Array }): string {\n return Buffer.concat([point.x, point.y]).toString(\"hex\");\n}\n\nfunction concatG2(point: { x: [Uint8Array, Uint8Array]; y: [Uint8Array, Uint8Array] }): string {\n return Buffer.concat([point.x[0], point.x[1], point.y[0], point.y[1]]).toString(\"hex\");\n}\n\nexport function buildStellarVerifyProofArgs(options: {\n proof: SnarkjsProof;\n vk?: SnarkjsVk;\n publicSignals: string[];\n embedVk: boolean;\n}): string[] {\n const serializedProof = serializeProof(options.proof);\n const args: string[] = [];\n\n if (!options.embedVk) {\n if (!options.vk) {\n throw new ZkError(\"Verification key is required when embedVk is false.\", \"ZK_VK_REQUIRED\");\n }\n\n const serializedVk = serializeVk(options.vk);\n args.push(\n \"--vk\",\n JSON.stringify({\n alpha: concatG1(serializedVk.alpha),\n beta: concatG2(serializedVk.beta),\n gamma: concatG2(serializedVk.gamma),\n delta: concatG2(serializedVk.delta),\n ic: serializedVk.ic.map(concatG1),\n })\n );\n }\n\n args.push(\n \"--proof\",\n JSON.stringify({\n a: concatG1(serializedProof.a),\n b: concatG2(serializedProof.b),\n c: concatG1(serializedProof.c),\n })\n );\n args.push(\"--pub_signals\", JSON.stringify(options.publicSignals));\n\n return args;\n}\n\nexport type InvokeVerifierResult = {\n network: string;\n verifierContract: string;\n contractId: string;\n publicSignals: string[];\n verified: true;\n};\n\nexport async function invokeVerifier(options: InvokeVerifierOptions): Promise<InvokeVerifierResult> {\n const cwd = options.cwd ?? process.cwd();\n const config = options.config ?? await loadConfig({ cwd });\n const proof = JSON.parse(await readFile(path.resolve(cwd, options.proofPath), \"utf8\")) as SnarkjsProof;\n const publicSignals = JSON.parse(\n await readFile(path.resolve(cwd, options.publicSignalsPath), \"utf8\")\n ) as string[];\n\n const vk = options.embedVk\n ? undefined\n : JSON.parse(await readFile(path.resolve(cwd, options.vkPath), \"utf8\")) as SnarkjsVk;\n\n const args = buildStellarVerifyProofArgs({\n proof,\n vk,\n publicSignals,\n embedVk: options.embedVk,\n });\n\n const target = `${options.verifierContract}.verify_proof`;\n const result = await invokeContract({\n config,\n target,\n args,\n networkName: options.network,\n source: options.sourceAccount,\n cwd,\n });\n\n if (!result.result) {\n throw new ZkError(\"Verifier invocation returned no result.\", \"ZK_INVOKE_FAILED\");\n }\n\n if (result.result.trim().toLowerCase() !== \"true\") {\n throw new ZkError(\n `Verifier returned ${result.result.trim()}.`,\n \"ZK_VERIFY_FAILED\"\n );\n }\n\n const artifacts = await readArtifacts(cwd);\n const contractId = artifacts.networks[options.network]?.contracts[options.verifierContract]?.contractId;\n\n if (!contractId) {\n throw new ZkError(\n `No deployed artifact found for \"${options.verifierContract}\" on \"${options.network}\".`,\n \"ZK_INVOKE_FAILED\",\n \"Run caatinga deploy before invoking the verifier.\"\n );\n }\n\n return {\n network: options.network,\n verifierContract: options.verifierContract,\n contractId,\n publicSignals,\n verified: true,\n };\n}\n"],"mappings":";AAGO,SAAS,cAAc,SAA6B;AACzD,MAAI,QAAQ,OAAO,OAAO;AAC1B,QAAM,MAAM,IAAI,WAAW,EAAE;AAC7B,WAAS,IAAI,GAAG,IAAI,IAAI,KAAK;AAC3B,QAAI,CAAC,IAAI,OAAO,QAAQ,KAAK;AAC7B,cAAU;AAAA,EACZ;AACA,SAAO;AACT;AAKO,SAAS,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M,IAAI;AAAA,MACR,mCAAmC,QAAQ,gBAAgB,SAAS,QAAQ,OAAO;AAAA,MACnF;AAAA,MACA;AAAA,IACF;AAAA,EACF;AAEA,SAAO;AAAA,IACL,SAAS,QAAQ;AAAA,IACjB,kBAAkB,QAAQ;AAAA,IAC1B;AAAA,IACA;AAAA,IACA,UAAU;AAAA,EACZ;AACF;","names":["runCommand","path","mkdir","writeFile","createHash","randomBytes","writeFile","path","mkdir","runCommand","createHash","randomBytes","runCommand","path","access","mkdir","path","mkdir","runCommand","access","readFile","path","readFile","path"]}
package/package.json ADDED
@@ -0,0 +1,37 @@
1
+ {
2
+ "name": "@caatinga/zk",
3
+ "version": "2.3.0",
4
+ "description": "Zero-knowledge proof serialization bridge for Stellar/Soroban",
5
+ "type": "module",
6
+ "engines": {
7
+ "node": ">=20"
8
+ },
9
+ "main": "./dist/index.cjs",
10
+ "module": "./dist/index.js",
11
+ "types": "./dist/index.d.ts",
12
+ "exports": {
13
+ ".": {
14
+ "types": "./dist/index.d.ts",
15
+ "import": "./dist/index.js",
16
+ "require": "./dist/index.cjs"
17
+ }
18
+ },
19
+ "files": [
20
+ "dist",
21
+ "README.md",
22
+ "LICENSE"
23
+ ],
24
+ "dependencies": {
25
+ "@caatinga/core": "^2.3.0"
26
+ },
27
+ "devDependencies": {
28
+ "tsup": "^8.3.5",
29
+ "typescript": "^5.7.2",
30
+ "vitest": "^2.1.8"
31
+ },
32
+ "scripts": {
33
+ "build": "tsup",
34
+ "test": "vitest run --pool=threads",
35
+ "typecheck": "tsc --noEmit"
36
+ }
37
+ }