From 167bc8d1c85469075fa9c1745b7897abf28df238 Mon Sep 17 00:00:00 2001
From: Satya
Date: Sat, 26 Sep 2026 23:38:51 +0800
Subject: [PATCH 1/2] fix(groth16): validate and pin streaming proving-key
imports
---
...rity-audit-and-public-testnet-readiness.md | 36 ++++
docs/ceremony/OPTION-A-RUNBOOK.md | 10 +-
docs/ceremony/USER-GUIDE.md | 12 +-
docs/ceremony/rehearsal.sh | 2 +-
docs/groth16-dev-guide.md | 9 +-
.../org/zeroj/crypto/groth16/Groth16Keys.java | 7 +-
.../zeroj/crypto/groth16/Groth16PkStore.java | 16 +-
.../crypto/groth16/Groth16StoreIntegrity.java | 79 ++++++++
.../crypto/groth16/ZkeyPkStoreImporter.java | 168 ++++++++++++++----
.../Groth16PipelineCeremonyKeyTest.java | 2 +-
.../groth16/Groth16ProverApiSurfaceTest.java | 1 +
.../ZkeyPkStoreImporterProfileTest.java | 6 +-
.../groth16/ZkeyPkStoreImporterTest.java | 2 +-
.../groth16/ZkeyStreamingBoundaryTest.java | 151 ++++++++++++++++
.../java/org/zeroj/ceremony/CeremonyCli.java | 16 +-
.../org/zeroj/ceremony/CeremonyCliTest.java | 11 +-
.../ceremony/ZkeyContributorInteropTest.java | 2 +-
17 files changed, 481 insertions(+), 49 deletions(-)
create mode 100644 zeroj-crypto/src/main/java/org/zeroj/crypto/groth16/Groth16StoreIntegrity.java
create mode 100644 zeroj-crypto/src/test/java/org/zeroj/crypto/groth16/ZkeyStreamingBoundaryTest.java
diff --git a/docs/adr/0025-end-to-end-security-audit-and-public-testnet-readiness.md b/docs/adr/0025-end-to-end-security-audit-and-public-testnet-readiness.md
index 86791fc7..afdbf998 100644
--- a/docs/adr/0025-end-to-end-security-audit-and-public-testnet-readiness.md
+++ b/docs/adr/0025-end-to-end-security-audit-and-public-testnet-readiness.md
@@ -366,3 +366,39 @@ rationale.
- `docs/beta-release-readiness.md`
- CIP-0381 (Plutus BLS12-381 builtins):
- RFC 9380 hash-to-curve:
+
+## Implementation contract — streaming Groth16 import (issues #48/#47, 2026-09-26)
+
+This bounded milestone applies accepted Decisions 5–6 to the later streaming importer;
+it does not introduce a new proof-system profile. Risk: R2 validation with R3 confidentiality
+impact if untrusted query points reach a private-witness MSM. The input file is untrusted;
+no private witness or ceremony contribution secret is processed during import.
+
+Invariants: canonical Montgomery residues before reduction; on-curve and prime-order checks
+on every imported G1/G2 point; infinity permitted only in query arrays, never header/IC;
+bounded, exact section reads and dimensions; no returned/published store after a failed check.
+Use the existing Jacobian multiply-by-r predicate already used by SetupCacheIO, not a new
+endomorphism implementation. The format reference is snarkjs **v0.7.6** `src/zkey_utils.js`
+(writeHeader, writeZKey, readHeaderGroth16), plus ADR-0045's stricter infinity profile.
+
+A pinned import checks an externally trusted SHA-256. An explicitly named unpinned import
+exists for fixtures/local experiments and still performs all mathematical validation. Stage
+a private copy while hashing and parse that same copy, so source-file replacement cannot
+switch the bytes after the hash check. Build a fresh sibling directory and publish only after
+validation; never overwrite an existing destination. This costs temporary disk space, not
+key-sized Java heap. Correctness takes precedence over import throughput.
+
+The manifest records the source identity and hashes of all store payload files. A caller can
+pin the returned manifest digest when subsequently loading the bundle. Self-contained hashes
+without an externally trusted pin detect corruption, not malicious replacement. The caller
+must control the directory and exclude concurrent file mutation throughout an mmap handle's
+lifetime; this API does not defend against a hostile same-user process rewriting mapped files.
+Legacy locally generated stores remain a trusted-local-directory API. No hash or subgroup
+check substitutes for independently verifying the MPC transcript and its exact circuit.
+
+Verification: checked-in snarkjs fixture import/prove; in-memory/streaming point differentials;
+wrong-subgroup G1/G2, noncanonical residues, infinity policy, malformed/truncated sections,
+hash mismatch and late-failure/no-publication tests; persisted-file mutation rejection.
+Production Filecoin conversion, circuit freeze, contributor ceremony, public artifact manifest,
+independent review and live deployment evidence remain open under #48. This milestone must
+not close that issue or change maturity claims.
diff --git a/docs/ceremony/OPTION-A-RUNBOOK.md b/docs/ceremony/OPTION-A-RUNBOOK.md
index 196a29cc..ac792110 100644
--- a/docs/ceremony/OPTION-A-RUNBOOK.md
+++ b/docs/ceremony/OPTION-A-RUNBOOK.md
@@ -80,7 +80,7 @@ snarkjs zkey export verificationkey key_final.zkey verification_key.json
# Into ZeroJ (streaming; handles multi-GB keys):
java -cp zeroj-ceremony.jar org.zeroj.ceremony.CeremonyCli \
- finalize --zkey key_final.zkey --pk-store ./ownership-pk
+ finalize --sha256 "$VERIFIED_ZKEY_SHA256" --zkey key_final.zkey --pk-store ./ownership-pk
```
Proving afterwards: `Groth16PkStore.load(dir)` + `ZkeyPkStoreImporter.snarkjsConstraints(compiled, numPublic)`
@@ -105,3 +105,11 @@ from source to confirm the key binds to the claimed circuit.
- [ ] beacon source pre-announced, applied, published
- [ ] `zkey verify` green; final key + VK hashes published
- [ ] `finalize` run; a test proof generated and verified off-chain and on-chain
+
+Finalization requires `--sha256` from an independently verified ceremony manifest, or an
+explicit `--allow-unpinned` for local experiments. These options are mutually exclusive.
+The output directory must not exist. Retain the printed manifest SHA-256 through a trusted
+channel and pass it to `Groth16PkStore.load(dir, expectedManifestSha256)` when reopening.
+The expected hash authenticates bytes only relative to its trusted source; independent
+`snarkjs zkey verify` and circuit/ceremony provenance remain mandatory. Protect the local
+store from mutation for the entire mmap lifetime.
diff --git a/docs/ceremony/USER-GUIDE.md b/docs/ceremony/USER-GUIDE.md
index 4e1d4079..69e0db08 100644
--- a/docs/ceremony/USER-GUIDE.md
+++ b/docs/ceremony/USER-GUIDE.md
@@ -89,7 +89,7 @@ Then key genesis with snarkjs: `snarkjs groth16 setup ownership.r1cs 10 -n="final beacon"
snarkjs zkey verify my.r1cs prepared.ptau key_final.zkey # anyone can re-run this
-zeroj-ceremony finalize --zkey key_final.zkey --pk-store ./pk
+zeroj-ceremony finalize --sha256 "$VERIFIED_ZKEY_SHA256" --zkey key_final.zkey --pk-store ./pk
```
A runnable rehearsal of exactly this flow: [`rehearsal.sh`](rehearsal.sh). Full coordinator
@@ -161,3 +161,11 @@ I confirm the entropy was generated fresh and destroyed after use.
- **What must I keep secret?** Nothing after you finish — your randomness is used and discarded.
What you must *do* is not let anyone observe the machine during the contribution, and publish
your attestation.
+
+Finalization requires `--sha256` from an independently verified ceremony manifest, or an
+explicit `--allow-unpinned` for local experiments. These options are mutually exclusive.
+The output directory must not exist. Retain the printed manifest SHA-256 through a trusted
+channel and pass it to `Groth16PkStore.load(dir, expectedManifestSha256)` when reopening.
+The expected hash authenticates bytes only relative to its trusted source; independent
+`snarkjs zkey verify` and circuit/ceremony provenance remain mandatory. Protect the local
+store from mutation for the entire mmap lifetime.
diff --git a/docs/ceremony/rehearsal.sh b/docs/ceremony/rehearsal.sh
index 2ff13234..e359c3cb 100755
--- a/docs/ceremony/rehearsal.sh
+++ b/docs/ceremony/rehearsal.sh
@@ -50,7 +50,7 @@ echo ">> [coordinator] beacon (pre-announced public randomness) + independent ve
echo ">> [coordinator] finalize into a ZeroJ proving-key store + export VK"
"$SNARKJS" zkey export verificationkey key_final.zkey verification_key.json
-$CLI finalize --zkey key_final.zkey --pk-store ./pk-store
+$CLI finalize --allow-unpinned --zkey key_final.zkey --pk-store ./pk-store
echo ""
echo ">> REHEARSAL COMPLETE. Artifacts in $WORK (transcript.txt = the publishable record)."
diff --git a/docs/groth16-dev-guide.md b/docs/groth16-dev-guide.md
index 44480a15..1e4a0097 100644
--- a/docs/groth16-dev-guide.md
+++ b/docs/groth16-dev-guide.md
@@ -82,7 +82,7 @@ Run the multi-party ceremony externally (snarkjs), then import the `.zkey` once
store layout; from there it's Flow 2's load-and-prove:
```java
-ZkeyPkStoreImporter.importToPkStore(zkeyPath, keysDir); // one-time; writes the dense store
+var imported = ZkeyPkStoreImporter.importToPkStore(zkeyPath, keysDir, expectedSourceSha256); // one-time; writes the dense store
try (var keys = Groth16Keys.load(keysDir)) {
// a snarkjs setup appends numPublic+1 public-input binding rows after the circuit rows —
@@ -208,3 +208,10 @@ to reproduce the blinders.
Memory numbers, formats, and the full optimization history: ADR-0033 (prove memory),
ADR-0034 (frontend + prove speed), ADR-0035 (setup memory/time + sparse store).
+
+The expected source SHA-256 must come from independently verified ceremony provenance, not
+from an untrusted download itself. Retain `imported.manifestSha256()` via a trusted channel
+and reopen with `Groth16Keys.load(keysDir, expectedManifestSha256)`. Imports require a new
+destination directory and stage a temporary source copy (extra disk space, bounded heap).
+Keep the entire directory protected from concurrent modification while mapped. Legacy local
+stores and the explicitly named `importUnpinnedToPkStore` API do not authenticate provenance.
diff --git a/zeroj-crypto/src/main/java/org/zeroj/crypto/groth16/Groth16Keys.java b/zeroj-crypto/src/main/java/org/zeroj/crypto/groth16/Groth16Keys.java
index c912cae6..06d1378c 100644
--- a/zeroj-crypto/src/main/java/org/zeroj/crypto/groth16/Groth16Keys.java
+++ b/zeroj-crypto/src/main/java/org/zeroj/crypto/groth16/Groth16Keys.java
@@ -117,7 +117,12 @@ public static Groth16Keys setupToStore(R1CSFlat flat, int numWires, int numPubli
* manifest. The key files are memory-mapped; close the handle to unmap.
*/
public static Groth16Keys load(Path dir) throws IOException {
- var loaded = Groth16PkStore.load(dir);
+ return load(dir, null);
+ }
+
+ /** Load a validated import using its externally trusted manifest identity. */
+ public static Groth16Keys load(Path dir, String expectedManifestSha256) throws IOException {
+ var loaded = Groth16PkStore.load(dir, expectedManifestSha256);
return new Groth16Keys(loaded.pk(), loaded.readers(), loaded.gammaG2(), loaded.ic(),
loaded.domain(), loaded.readers().b2().count(), loaded.circuitFingerprint(), loaded.arena());
}
diff --git a/zeroj-crypto/src/main/java/org/zeroj/crypto/groth16/Groth16PkStore.java b/zeroj-crypto/src/main/java/org/zeroj/crypto/groth16/Groth16PkStore.java
index da5a3581..4ef14675 100644
--- a/zeroj-crypto/src/main/java/org/zeroj/crypto/groth16/Groth16PkStore.java
+++ b/zeroj-crypto/src/main/java/org/zeroj/crypto/groth16/Groth16PkStore.java
@@ -134,8 +134,22 @@ public static void writeAuxAndManifest(Path dir, AffineG1 alphaG1, AffineG1 beta
}
}
- /** Load a saved key from {@code dir}, memory-mapping the G1 arrays into a fresh shared arena. */
+ /**
+ * Load a trusted local store, memory-mapping its G1 arrays. Self-contained hashes detect
+ * corruption but do not authenticate a store; use the pinned overload for imported keys.
+ * The directory must remain protected from concurrent mutation for the handle's lifetime.
+ */
public static Loaded load(Path dir) throws IOException {
+ return load(dir, null);
+ }
+
+ /**
+ * Load an imported store against the manifest hash returned by the validated importer.
+ * The pin must come from a trusted channel. Exclude concurrent mutations for the handle's
+ * entire lifetime; mmap does not isolate reads from a hostile local writer.
+ */
+ public static Loaded load(Path dir, String expectedManifestSha256) throws IOException {
+ Groth16StoreIntegrity.verify(dir, expectedManifestSha256);
var m = new Properties();
try (var in = Files.newInputStream(dir.resolve(MANIFEST))) { m.load(in); }
String circuitFingerprint = m.getProperty("circuitFingerprint");
diff --git a/zeroj-crypto/src/main/java/org/zeroj/crypto/groth16/Groth16StoreIntegrity.java b/zeroj-crypto/src/main/java/org/zeroj/crypto/groth16/Groth16StoreIntegrity.java
new file mode 100644
index 00000000..3c60852f
--- /dev/null
+++ b/zeroj-crypto/src/main/java/org/zeroj/crypto/groth16/Groth16StoreIntegrity.java
@@ -0,0 +1,79 @@
+package org.zeroj.crypto.groth16;
+
+import java.io.IOException;
+import java.io.StringWriter;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+import java.util.HexFormat;
+import java.util.Properties;
+import java.util.TreeSet;
+
+/** Content identities for validated streaming imports; not a ceremony transcript verifier. */
+final class Groth16StoreIntegrity {
+ private static final String[] PAYLOADS = {"aux.bin", "pointsA.bin", "pointsB1.bin",
+ "pointsB2.bin", "pointsH.bin", "pointsL.bin"};
+
+ private Groth16StoreIntegrity() {}
+
+ static void requireDigest(String digest) {
+ if (digest == null || !digest.matches("[0-9a-fA-F]{64}"))
+ throw new IllegalArgumentException("Expected SHA-256 must be 64 hexadecimal characters");
+ }
+
+ static String digest(Path file) throws IOException {
+ MessageDigest hash;
+ try { hash = MessageDigest.getInstance("SHA-256"); }
+ catch (NoSuchAlgorithmException impossible) { throw new IllegalStateException(impossible); }
+ try (var in = Files.newInputStream(file)) {
+ byte[] buffer = new byte[1 << 20];
+ int count;
+ while ((count = in.read(buffer)) != -1) hash.update(buffer, 0, count);
+ }
+ return HexFormat.of().formatHex(hash.digest());
+ }
+
+ static String seal(Path dir, String sourceSha256) throws IOException {
+ Path manifest = dir.resolve("manifest.properties");
+ Properties values = new Properties();
+ try (var in = Files.newInputStream(manifest)) { values.load(in); }
+ values.setProperty("integrityProfile", "validated-zkey-v1");
+ values.setProperty("sourceSha256", sourceSha256);
+ for (String payload : PAYLOADS) values.setProperty("sha256." + payload, digest(dir.resolve(payload)));
+ // Stable key order and no timestamp: identical imports have identical content identities.
+ try (var out = Files.newBufferedWriter(manifest)) {
+ for (String key : new TreeSet<>(values.stringPropertyNames())) {
+ Properties entry = new Properties();
+ entry.setProperty(key, values.getProperty(key));
+ StringWriter encoded = new StringWriter();
+ entry.store(encoded, null);
+ for (String line : encoded.toString().split("\\R")) {
+ if (!line.startsWith("#")) { out.write(line); out.write('\n'); }
+ }
+ }
+ }
+ return digest(manifest);
+ }
+
+ static void verify(Path dir, String expectedManifestSha256) throws IOException {
+ Path manifest = dir.resolve("manifest.properties");
+ if (expectedManifestSha256 != null) {
+ requireDigest(expectedManifestSha256);
+ if (!digest(manifest).equalsIgnoreCase(expectedManifestSha256))
+ throw new IOException("Groth16 manifest SHA-256 mismatch");
+ }
+ Properties values = new Properties();
+ try (var in = Files.newInputStream(manifest)) { values.load(in); }
+ String profile = values.getProperty("integrityProfile");
+ if (profile == null && expectedManifestSha256 == null) return; // trusted legacy local store
+ if (!"validated-zkey-v1".equals(profile)) throw new IOException("Missing/unsupported integrity profile");
+ try { requireDigest(values.getProperty("sourceSha256")); }
+ catch (IllegalArgumentException bad) { throw new IOException("Missing/invalid source identity", bad); }
+ for (String payload : PAYLOADS) {
+ String expected = values.getProperty("sha256." + payload);
+ if (expected == null || !digest(dir.resolve(payload)).equals(expected))
+ throw new IOException("Groth16 store SHA-256 mismatch: " + payload);
+ }
+ }
+}
diff --git a/zeroj-crypto/src/main/java/org/zeroj/crypto/groth16/ZkeyPkStoreImporter.java b/zeroj-crypto/src/main/java/org/zeroj/crypto/groth16/ZkeyPkStoreImporter.java
index a8cb5630..997ac876 100644
--- a/zeroj-crypto/src/main/java/org/zeroj/crypto/groth16/ZkeyPkStoreImporter.java
+++ b/zeroj-crypto/src/main/java/org/zeroj/crypto/groth16/ZkeyPkStoreImporter.java
@@ -1,5 +1,7 @@
package org.zeroj.crypto.groth16;
+import org.zeroj.bls12381.ec.JacobianG1BLS381;
+import org.zeroj.bls12381.ec.JacobianG2BLS381;
import org.zeroj.bls12381.ec.JacobianG1BLS381.AffineG1;
import org.zeroj.bls12381.ec.JacobianG2BLS381.AffineG2;
import org.zeroj.bls12381.field.MontFp2_381;
@@ -16,6 +18,10 @@
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.HashMap;
+import java.util.Comparator;
+import java.util.HexFormat;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.IntStream;
@@ -28,7 +34,7 @@
*
* The {@code .zkey} stores points as little-endian Montgomery residues — byte-identical
* to the flat-limb layout of the ZeroJ proving-key store on little-endian platforms — so the four
- * G1 sections (A, B1, L, H) are raw-copied and then curve-validated in parallel. The G2
+ * G1 sections (A, B1, L, H) are raw-copied and then curve/subgroup-validated in parallel. The G2
* section is converted (Montgomery → canonical big-endian, the store's G2 encoding) and validated
* in the same parallel pass. VK parts (alpha/beta/gamma/delta, IC) land in the store's
* {@code aux.bin}/manifest via the shared {@link Groth16PkStore} writer.
@@ -53,38 +59,110 @@ private ZkeyPkStoreImporter() {}
private static final BigInteger FP_R_INV = BigInteger.ONE.shiftLeft(384).mod(FP).modInverse(FP);
/** Parsed dimensions, for logging/validation by the caller. */
- public record Imported(int numWires, int numPublic, int domainSize) {}
+ public record Imported(int numWires, int numPublic, int domainSize,
+ String sourceSha256, String manifestSha256) {}
- /** Convert {@code zkeyFile} into a {@link Groth16PkStore} directory at {@code dir}. */
+ /**
+ * @deprecated Select a trusted expected SHA-256 or explicitly use the unpinned test API.
+ */
+ @Deprecated
public static Imported importToPkStore(Path zkeyFile, Path dir) throws IOException {
- long fileSize = Files.size(zkeyFile);
- if (fileSize > MAX_ZKEY_FILE) throw new IOException(".zkey exceeds " + (MAX_ZKEY_FILE >> 30) + " GB limit");
- Files.createDirectories(dir);
+ throw new IOException("Expected .zkey SHA-256 required; use the pinned overload or "
+ + "importUnpinnedToPkStore for explicitly unpinned local/test artifacts");
+ }
+
+ /** Import a mathematically validated key whose bytes match a trusted external hash. */
+ public static Imported importToPkStore(Path zkeyFile, Path dir, String expectedSha256) throws IOException {
+ Groth16StoreIntegrity.requireDigest(expectedSha256);
+ return stageImport(zkeyFile, dir, expectedSha256);
+ }
+
+ /**
+ * Explicit local/test opt-in: validates the key but cannot authenticate its ceremony origin.
+ * This never bypasses curve, subgroup, canonicality or structural checks.
+ */
+ public static Imported importUnpinnedToPkStore(Path zkeyFile, Path dir) throws IOException {
+ return stageImport(zkeyFile, dir, null);
+ }
+
+ private static Imported stageImport(Path source, Path destination, String expectedHash) throws IOException {
+ Path target = destination.toAbsolutePath();
+ if (Files.exists(target)) throw new IOException("Output directory already exists: " + target);
+ Files.createDirectories(target.getParent());
+ Path staging = Files.createTempDirectory(target.getParent(), ".zeroj-import-");
+ try {
+ Path snapshot = staging.resolve("source.zkey");
+ MessageDigest hash;
+ try { hash = MessageDigest.getInstance("SHA-256"); }
+ catch (NoSuchAlgorithmException impossible) { throw new IllegalStateException(impossible); }
+ long total = 0;
+ try (var in = Files.newInputStream(source); var out = Files.newOutputStream(snapshot)) {
+ byte[] buffer = new byte[1 << 20];
+ int count;
+ while ((count = in.read(buffer)) != -1) {
+ total += count;
+ if (total > MAX_ZKEY_FILE) throw new IOException(".zkey exceeds 64 GB limit");
+ hash.update(buffer, 0, count);
+ out.write(buffer, 0, count);
+ }
+ }
+ String sourceHash = HexFormat.of().formatHex(hash.digest());
+ if (expectedHash != null && !sourceHash.equalsIgnoreCase(expectedHash))
+ throw new IOException(".zkey SHA-256 mismatch");
+ Imported dimensions;
+ try {
+ dimensions = importSnapshot(snapshot, staging);
+ } catch (IllegalArgumentException | IndexOutOfBoundsException malformed) {
+ throw new IOException("Malformed .zkey", malformed);
+ }
+ Files.delete(snapshot);
+ String manifestHash = Groth16StoreIntegrity.seal(staging, sourceHash);
+ // No REPLACE_EXISTING: an existing store is never partially overwritten.
+ Files.move(staging, target);
+ return new Imported(dimensions.numWires(), dimensions.numPublic(), dimensions.domainSize(),
+ sourceHash, manifestHash);
+ } finally {
+ if (Files.exists(staging)) {
+ try (var files = Files.walk(staging)) {
+ for (Path path : files.sorted(Comparator.reverseOrder()).toList()) Files.delete(path);
+ }
+ }
+ }
+ }
+ private static Imported importSnapshot(Path zkeyFile, Path dir) throws IOException {
+ long fileSize = Files.size(zkeyFile);
+ if (fileSize < 12) throw new IOException("Truncated .zkey header");
try (FileChannel ch = FileChannel.open(zkeyFile, StandardOpenOption.READ);
Arena arena = Arena.ofShared()) {
MemorySegment z = ch.map(FileChannel.MapMode.READ_ONLY, 0, fileSize, arena);
// global header
if (z.get(U32, 0) != 0x79656b7a) throw new IOException("Invalid .zkey magic"); // "zkey" LE
+ int version = z.get(U32, 4);
+ if (version != 1 && version != 2) throw new IOException("Unsupported .zkey version: " + version);
int nSections = z.get(U32, 8);
if (nSections <= 0 || nSections > 64) throw new IOException("Invalid .zkey section count");
Map sections = new HashMap<>();
long pos = 12;
for (int i = 0; i < nSections; i++) {
+ if (fileSize - pos < 12) throw new IOException("Truncated .zkey section header");
int type = z.get(U32, pos);
long size = z.get(U64, pos + 4);
pos += 12;
- if (size < 0 || pos + size > fileSize) throw new IOException("Invalid .zkey section " + type);
+ if (size < 0 || size > fileSize - pos) throw new IOException("Invalid .zkey section " + type);
if (sections.put(type, new long[]{pos, size}) != null)
throw new IOException("Duplicate .zkey section " + type);
pos += size;
}
- for (int s : new int[]{1, 2, 3, 5, 6, 7, 8, 9}) {
+ if (pos != fileSize) throw new IOException("Trailing bytes after .zkey sections");
+ for (int s : new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9}) {
if (!sections.containsKey(s)) throw new IOException("Missing .zkey section " + s);
}
+ requireSize(sections.get(1), 4, "protocol");
+ requireSize(sections.get(2), 964, "Groth16 header");
if (z.get(U32, sections.get(1)[0]) != 1) throw new IOException("Not a Groth16 .zkey");
// section 2: Groth16 header
@@ -97,6 +175,7 @@ public static Imported importToPkStore(Path zkeyFile, Path dir) throws IOExcepti
int nPublic = z.get(U32, h + 92);
int domainSize = z.get(U32, h + 96);
validateDims(nVars, nPublic, domainSize);
+ validateCoefficients(z, sections.get(4), nVars, domainSize);
long p = h + 100;
AffineG1 alphaG1 = g1(z, p); p += 96;
@@ -107,12 +186,12 @@ public static Imported importToPkStore(Path zkeyFile, Path dir) throws IOExcepti
AffineG2 deltaG2 = g2(z, p);
// ADR-0025/ADR-0045 profile: single VK points and every IC entry must be on-curve and
// not the point at infinity; an infinity IC[i] would leave public input i unbound.
- requireNonInfinityOnCurve(alphaG1.isOnCurve(), alphaG1.isInfinity(), "alphaG1");
- requireNonInfinityOnCurve(betaG1.isOnCurve(), betaG1.isInfinity(), "betaG1");
- requireNonInfinityOnCurve(betaG2.isOnCurve(), betaG2.isInfinity(), "betaG2");
- requireNonInfinityOnCurve(gammaG2.isOnCurve(), gammaG2.isInfinity(), "gammaG2");
- requireNonInfinityOnCurve(deltaG1.isOnCurve(), deltaG1.isInfinity(), "deltaG1");
- requireNonInfinityOnCurve(deltaG2.isOnCurve(), deltaG2.isInfinity(), "deltaG2");
+ requireValid(alphaG1, false, "alphaG1");
+ requireValid(betaG1, false, "betaG1");
+ requireValid(betaG2, false, "betaG2");
+ requireValid(gammaG2, false, "gammaG2");
+ requireValid(deltaG1, false, "deltaG1");
+ requireValid(deltaG2, false, "deltaG2");
// section 3: IC (nPublic + 1 points)
long[] ic3 = sections.get(3)[0] == 0 ? null : sections.get(3);
@@ -120,7 +199,7 @@ public static Imported importToPkStore(Path zkeyFile, Path dir) throws IOExcepti
AffineG1[] ic = new AffineG1[nPublic + 1];
for (int i = 0; i <= nPublic; i++) {
ic[i] = g1(z, ic3[0] + i * 96L);
- requireNonInfinityOnCurve(ic[i].isOnCurve(), ic[i].isInfinity(), "IC[" + i + "]");
+ requireValid(ic[i], false, "IC[" + i + "]");
}
int nPrivate = nVars - nPublic - 1;
@@ -135,7 +214,7 @@ public static Imported importToPkStore(Path zkeyFile, Path dir) throws IOExcepti
Groth16PkStore.writeAuxAndManifest(dir, alphaG1, betaG1, deltaG1,
betaG2, deltaG2, gammaG2, ic, nPublic, nVars, domainSize);
- return new Imported(nVars, nPublic, domainSize);
+ return new Imported(nVars, nPublic, domainSize, null, null);
}
}
@@ -168,7 +247,7 @@ private static void copyAndValidateG1(MemorySegment z, long[] sec, int count, Pa
MemorySegment dst = out.map(FileChannel.MapMode.READ_WRITE, 0, bytes, a);
dst.copyFrom(src);
- // parallel on-curve validation (reads the Montgomery limbs straight from the copy)
+ // parallel canonicality, curve and subgroup validation (reads the Montgomery limbs straight from the copy)
AtomicInteger bad = new AtomicInteger(-1);
int t = Math.max(1, Math.min(Runtime.getRuntime().availableProcessors(), count));
int per = (count + t - 1) / t;
@@ -183,11 +262,12 @@ private static void copyAndValidateG1(MemorySegment z, long[] sec, int count, Pa
var pt = new AffineG1(
MontFp381.fromMontLimbs(buf[0], buf[1], buf[2], buf[3], buf[4], buf[5]),
MontFp381.fromMontLimbs(buf[6], buf[7], buf[8], buf[9], buf[10], buf[11]));
- if (!pt.isOnCurve()) bad.compareAndSet(-1, i);
+ if (!pt.isOnCurve() || !JacobianG1BLS381.fromAffine(pt.x(), pt.y())
+ .scalarMul(FR).isInfinity()) bad.compareAndSet(-1, i);
}
});
if (bad.get() >= 0)
- throw new IOException(".zkey " + label + "[" + bad.get() + "] is not on the curve");
+ throw new IOException(".zkey " + label + "[" + bad.get() + "] is not on the curve or in the prime-order subgroup");
}
}
@@ -213,14 +293,15 @@ private static void convertG2Section(MemorySegment z, long[] sec, int count, Pat
BigInteger yr = mont(z, in + 96, coord), yi = mont(z, in + 144, coord);
var pt = new AffineG2(MontFp2_381.of(xr, xi), MontFp2_381.of(yr, yi));
boolean inf = xr.signum() == 0 && xi.signum() == 0 && yr.signum() == 0 && yi.signum() == 0;
- if (!inf && !pt.isOnCurve()) { bad.compareAndSet(-1, i); return; }
+ if (!inf && (!pt.isOnCurve() || !JacobianG2BLS381.fromAffine(pt.x(), pt.y())
+ .scalarMul(FR).isInfinity())) { bad.compareAndSet(-1, i); return; }
long o = i * 192L;
putBE(dst, o, xr, coord); putBE(dst, o + 48, xi, coord);
putBE(dst, o + 96, yr, coord); putBE(dst, o + 144, yi, coord);
}
});
if (bad.get() >= 0)
- throw new IOException(".zkey pointsB2[" + bad.get() + "] is not on the curve");
+ throw new IOException(".zkey pointsB2[" + bad.get() + "] is not on the curve or in the prime-order subgroup");
}
}
@@ -231,7 +312,9 @@ private static BigInteger mont(MemorySegment z, long off, byte[] scratch48) {
MemorySegment.copy(z, off, MemorySegment.ofArray(scratch48), 0, 48);
byte[] be = new byte[48];
for (int i = 0; i < 48; i++) be[i] = scratch48[47 - i];
- return new BigInteger(1, be).multiply(FP_R_INV).mod(FP);
+ BigInteger raw = new BigInteger(1, be);
+ if (raw.compareTo(FP) >= 0) throw new IllegalArgumentException("Noncanonical Montgomery residue");
+ return raw.multiply(FP_R_INV).mod(FP);
}
/** canonical BigInteger → 48-byte BE at {@code off} (the PkStore G2 coordinate encoding). */
@@ -267,26 +350,47 @@ private static AffineG2 g2(MemorySegment z, long off) {
private static void validateDims(int nVars, int nPublic, int domainSize) throws IOException {
if (nVars <= 1 || nVars > MAX_WIRES) throw new IOException("Invalid .zkey nVars: " + nVars);
- if (nPublic < 0 || nPublic >= nVars) throw new IOException("Invalid .zkey nPublic: " + nPublic);
+ if (nPublic < 0 || nPublic > (1 << 20) || nPublic >= nVars) throw new IOException("Invalid .zkey nPublic: " + nPublic);
if (domainSize < 4 || Integer.bitCount(domainSize) != 1
|| Integer.numberOfTrailingZeros(domainSize) > MAX_DOMAIN_POWER)
throw new IOException("Invalid .zkey domainSize: " + domainSize);
}
private static void requireSize(long[] sec, long needed, String label) throws IOException {
- if (sec == null || sec[1] < needed) throw new IOException(".zkey section too small for " + label);
+ if (sec == null || sec[1] != needed) throw new IOException(".zkey section has incorrect size for " + label);
+ }
+
+ private static void requireValid(AffineG1 point, boolean allowInfinity, String label) throws IOException {
+ if (point.isInfinity()) {
+ if (allowInfinity) return;
+ throw new IOException(label + " must not be infinity");
+ }
+ if (!point.isOnCurve() || !JacobianG1BLS381.fromAffine(point.x(), point.y()).scalarMul(FR).isInfinity())
+ throw new IOException(label + " is not on curve and in the prime-order subgroup");
}
- private static void requireOnCurve(boolean ok, String label) throws IOException {
- if (!ok) throw new IOException(".zkey " + label + " is not on the curve");
+ private static void requireValid(AffineG2 point, boolean allowInfinity, String label) throws IOException {
+ if (point.isInfinity()) {
+ if (allowInfinity) return;
+ throw new IOException(label + " must not be infinity");
+ }
+ if (!point.isOnCurve() || !JacobianG2BLS381.fromAffine(point.x(), point.y()).scalarMul(FR).isInfinity())
+ throw new IOException(label + " is not on curve and in the prime-order subgroup");
}
- /** ADR-0045 I1: a VK point that is off-curve or the point at infinity is rejected at import. */
- private static void requireNonInfinityOnCurve(boolean onCurve, boolean infinity, String label) throws IOException {
- if (infinity) {
- throw new IOException(".zkey " + label + " is the point at infinity, which the Groth16 verifier"
- + " profile rejects (ADR-0045)");
+ private static void validateCoefficients(MemorySegment z, long[] section, int wires, int domain)
+ throws IOException {
+ if (section[1] < 4) throw new IOException("Truncated coefficient section");
+ int count = z.get(U32, section[0]);
+ if (count < 0) throw new IOException("Invalid coefficient count");
+ requireSize(section, 4L + count * 44L, "coefficients");
+ for (int i = 0; i < count; i++) {
+ long offset = section[0] + 4L + i * 44L;
+ int matrix = z.get(U32, offset), row = z.get(U32, offset + 4), wire = z.get(U32, offset + 8);
+ if (matrix < 0 || matrix > 2 || row < 0 || row >= domain || wire < 0 || wire >= wires)
+ throw new IOException("Invalid coefficient index");
+ if (fieldLE(z, offset + 12, 32).compareTo(FR) >= 0)
+ throw new IOException("Noncanonical coefficient");
}
- requireOnCurve(onCurve, label);
}
}
diff --git a/zeroj-crypto/src/test/java/org/zeroj/crypto/groth16/Groth16PipelineCeremonyKeyTest.java b/zeroj-crypto/src/test/java/org/zeroj/crypto/groth16/Groth16PipelineCeremonyKeyTest.java
index 9a6fa569..63cee1a6 100644
--- a/zeroj-crypto/src/test/java/org/zeroj/crypto/groth16/Groth16PipelineCeremonyKeyTest.java
+++ b/zeroj-crypto/src/test/java/org/zeroj/crypto/groth16/Groth16PipelineCeremonyKeyTest.java
@@ -71,7 +71,7 @@ void importedCeremonyKey_provesThroughPipeline_withoutCache_onMiss_andOnHit(@Tem
Path zkeyFile = tmp.resolve("key.zkey");
Files.write(zkeyFile, zkeyBytes);
Path store = tmp.resolve("store");
- ZkeyPkStoreImporter.importToPkStore(zkeyFile, store);
+ ZkeyPkStoreImporter.importUnpinnedToPkStore(zkeyFile, store);
// Compiled must accept the original relation as-is (no S1 here).
var cc = new Groth16Pipeline.Compiled(flatOf(original), circuitRows, numWires, numPublic);
diff --git a/zeroj-crypto/src/test/java/org/zeroj/crypto/groth16/Groth16ProverApiSurfaceTest.java b/zeroj-crypto/src/test/java/org/zeroj/crypto/groth16/Groth16ProverApiSurfaceTest.java
index 6a414d83..11c5a550 100644
--- a/zeroj-crypto/src/test/java/org/zeroj/crypto/groth16/Groth16ProverApiSurfaceTest.java
+++ b/zeroj-crypto/src/test/java/org/zeroj/crypto/groth16/Groth16ProverApiSurfaceTest.java
@@ -91,6 +91,7 @@ class Groth16ProverApiSurfaceTest {
"setupInMemory(List,int,int,BigInteger)",
"setupToStore(R1CSFlat,int,int,BigInteger,Path,boolean)",
"load(Path)",
+ "load(Path,String)",
"of(Loaded)",
"of(SetupResult)",
"prove(BigInteger[],List)",
diff --git a/zeroj-crypto/src/test/java/org/zeroj/crypto/groth16/ZkeyPkStoreImporterProfileTest.java b/zeroj-crypto/src/test/java/org/zeroj/crypto/groth16/ZkeyPkStoreImporterProfileTest.java
index 14d87467..c5ad4937 100644
--- a/zeroj-crypto/src/test/java/org/zeroj/crypto/groth16/ZkeyPkStoreImporterProfileTest.java
+++ b/zeroj-crypto/src/test/java/org/zeroj/crypto/groth16/ZkeyPkStoreImporterProfileTest.java
@@ -28,7 +28,7 @@ class ZkeyPkStoreImporterProfileTest {
@Test
void unmodifiedCeremonyZkey_importsAndHasFiniteIc(@TempDir Path tmp) throws IOException {
Path zkey = copyZkey(tmp);
- var dims = ZkeyPkStoreImporter.importToPkStore(zkey, tmp.resolve("store"));
+ var dims = ZkeyPkStoreImporter.importUnpinnedToPkStore(zkey, tmp.resolve("store"));
assertTrue(dims.numPublic() >= 1);
try (var loaded = Groth16PkStore.load(tmp.resolve("store"))) {
for (var ic : loaded.ic()) assertFalse(ic.isInfinity());
@@ -42,7 +42,7 @@ void zkeyWithInfinityIcEntry_isRejectedAtImport(@TempDir Path tmp) throws IOExce
long icSection = sectionOffset(zkey, 3);
zero(zkey, icSection + entry * 96L, 96);
Path store = tmp.resolve("store-" + entry);
- var ex = assertThrows(IOException.class, () -> ZkeyPkStoreImporter.importToPkStore(zkey, store));
+ var ex = assertThrows(IOException.class, () -> ZkeyPkStoreImporter.importUnpinnedToPkStore(zkey, store));
assertTrue(ex.getMessage().contains("IC[" + entry + "]"), ex.getMessage());
assertTrue(ex.getMessage().contains("infinity"), ex.getMessage());
}
@@ -53,7 +53,7 @@ void zkeyWithInfinityAlpha_isRejectedAtImport(@TempDir Path tmp) throws IOExcept
Path zkey = copyZkey(tmp);
long header = sectionOffset(zkey, 2);
zero(zkey, header + 100, 96); // alphaG1 sits right after the two field primes and dims
- var ex = assertThrows(IOException.class, () -> ZkeyPkStoreImporter.importToPkStore(zkey, tmp.resolve("s")));
+ var ex = assertThrows(IOException.class, () -> ZkeyPkStoreImporter.importUnpinnedToPkStore(zkey, tmp.resolve("s")));
assertTrue(ex.getMessage().contains("alphaG1"), ex.getMessage());
assertTrue(ex.getMessage().contains("infinity"), ex.getMessage());
}
diff --git a/zeroj-crypto/src/test/java/org/zeroj/crypto/groth16/ZkeyPkStoreImporterTest.java b/zeroj-crypto/src/test/java/org/zeroj/crypto/groth16/ZkeyPkStoreImporterTest.java
index 412dac24..93a082f2 100644
--- a/zeroj-crypto/src/test/java/org/zeroj/crypto/groth16/ZkeyPkStoreImporterTest.java
+++ b/zeroj-crypto/src/test/java/org/zeroj/crypto/groth16/ZkeyPkStoreImporterTest.java
@@ -56,7 +56,7 @@ void ceremonyZkey_streamImport_provesFromStore(@TempDir Path dir) throws Excepti
// 1. streaming import → PkStore
Path store = dir.resolve("pk-store");
- var dims = ZkeyPkStoreImporter.importToPkStore(dir.resolve("key1.zkey"), store);
+ var dims = ZkeyPkStoreImporter.importUnpinnedToPkStore(dir.resolve("key1.zkey"), store);
assertEquals(numWires, dims.numWires());
assertEquals(numPublic, dims.numPublic());
diff --git a/zeroj-crypto/src/test/java/org/zeroj/crypto/groth16/ZkeyStreamingBoundaryTest.java b/zeroj-crypto/src/test/java/org/zeroj/crypto/groth16/ZkeyStreamingBoundaryTest.java
new file mode 100644
index 00000000..a9b1851f
--- /dev/null
+++ b/zeroj-crypto/src/test/java/org/zeroj/crypto/groth16/ZkeyStreamingBoundaryTest.java
@@ -0,0 +1,151 @@
+package org.zeroj.crypto.groth16;
+
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+import org.zeroj.bls12381.ec.G1Point;
+import org.zeroj.bls12381.ec.G2Point;
+import org.zeroj.bls12381.field.Fp;
+import org.zeroj.bls12381.field.Fp2;
+
+import java.io.IOException;
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.Arrays;
+import java.util.HexFormat;
+import java.security.MessageDigest;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+class ZkeyStreamingBoundaryTest {
+ @TempDir Path tmp;
+ static byte[] fixture() throws IOException {
+ try (var in = ZkeyStreamingBoundaryTest.class.getResourceAsStream(
+ "/test-circuits/multiplier-bls381/multiplier.zkey")) {
+ return in.readAllBytes();
+ }
+ }
+ static int section(byte[] bytes, int wanted) {
+ var b = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN);
+ int offset = 12;
+ for (int i = 0; i < b.getInt(8); i++) {
+ int type = b.getInt(offset);
+ int size = Math.toIntExact(b.getLong(offset + 4));
+ if (type == wanted) return offset + 12;
+ offset += 12 + size;
+ }
+ throw new AssertionError("Missing section " + wanted);
+ }
+ static void put(byte[] bytes, int offset, BigInteger value) {
+ Arrays.fill(bytes, offset, offset + 48, (byte) 0);
+ byte[] be = value.toByteArray();
+ for (int i = 0; i < Math.min(48, be.length); i++) bytes[offset + i] = be[be.length - 1 - i];
+ }
+ static void point(byte[] bytes, int offset, BigInteger... values) {
+ for (int i = 0; i < values.length; i++)
+ put(bytes, offset + i * 48, values[i].shiftLeft(384).mod(Fp.P));
+ }
+ void rejected(byte[] bytes) throws IOException {
+ Path input = Files.createTempFile(tmp, "mutated", ".zkey");
+ Files.write(input, bytes);
+ Path out = tmp.resolve(input.getFileName() + "-store");
+ assertThrows(IOException.class, () -> ZkeyPkStoreImporter.importUnpinnedToPkStore(input, out));
+ assertFalse(Files.exists(out), "failed import must not publish any store");
+ }
+ @Test void rejectsG1TorsionInEveryPointSection() throws IOException {
+ var torsion = new G1Point(Fp.ZERO, Fp.of(2));
+ assertTrue(torsion.isOnCurve());
+ assertFalse(torsion.isInSubgroup());
+ byte[] original = fixture();
+ int h = section(original, 2);
+ int[] offsets = {h + 100, h + 196, h + 676, section(original, 3),
+ section(original, 5), section(original, 6), section(original, 8), section(original, 9)};
+ for (int offset : offsets) {
+ byte[] b = original.clone();
+ point(b, offset, BigInteger.ZERO, BigInteger.TWO);
+ rejected(b);
+ }
+ }
+ @Test void rejectsG2TorsionInEveryPointSection() throws IOException {
+ Fp2 x = Fp2.of(Fp.ZERO, Fp.ONE);
+ Fp2 y = x.square().mul(x).add(Fp2.of(Fp.of(4), Fp.of(4))).sqrt().orElseThrow();
+ var torsion = new G2Point(x, y);
+ assertTrue(torsion.isOnCurve());
+ assertFalse(torsion.isInSubgroup());
+ byte[] original = fixture();
+ int h = section(original, 2);
+ for (int offset : new int[]{h + 292, h + 484, h + 772, section(original, 7)}) {
+ byte[] b = original.clone();
+ point(b, offset, x.c0().value(), x.c1().value(), y.c0().value(), y.c1().value());
+ rejected(b);
+ }
+ }
+ @Test void rejectsNoncanonicalResiduesAndMalformedStructure() throws IOException {
+ byte[] original = fixture();
+ for (int sec : new int[]{2, 3, 5, 6, 7, 8, 9}) {
+ byte[] b = original.clone();
+ put(b, section(b, sec) + (sec == 2 ? 100 : 0), Fp.P);
+ rejected(b);
+ }
+ for (int length : new int[]{0, 4, 11, 15, original.length - 1})
+ rejected(Arrays.copyOf(original, length));
+ byte[] b = original.clone();
+ ByteBuffer.wrap(b).order(ByteOrder.LITTLE_ENDIAN).putInt(4, 0);
+ rejected(b);
+ b = Arrays.copyOf(original, original.length + 1);
+ rejected(b);
+ b = original.clone();
+ ByteBuffer.wrap(b).order(ByteOrder.LITTLE_ENDIAN).putLong(16, Long.MAX_VALUE);
+ rejected(b);
+ }
+
+ @Test void pinsSourceAndStoreAndRejectsTampering() throws Exception {
+ byte[] bytes = fixture();
+ Path input = tmp.resolve("key.zkey");
+ Files.write(input, bytes);
+ String expected = HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes));
+ Path store = tmp.resolve("pinned");
+ assertThrows(IOException.class, () -> ZkeyPkStoreImporter.importToPkStore(input, store, "00".repeat(32)));
+ assertFalse(Files.exists(store));
+ var imported = ZkeyPkStoreImporter.importToPkStore(input, store, expected);
+ assertEquals(expected, imported.sourceSha256());
+ var repeat = ZkeyPkStoreImporter.importToPkStore(input, tmp.resolve("repeat"), expected);
+ assertEquals(imported.manifestSha256(), repeat.manifestSha256(), "deterministic manifest");
+ try (var keys = Groth16Keys.load(store, imported.manifestSha256())) {
+ assertEquals(imported.numWires(), keys.numWires());
+ }
+ assertThrows(IOException.class, () -> Groth16Keys.load(store, "00".repeat(32)));
+ for (String payload : new String[]{"aux.bin", "pointsA.bin", "pointsB1.bin", "pointsB2.bin", "pointsH.bin", "pointsL.bin"}) {
+ Path file = store.resolve(payload);
+ byte[] valid = Files.readAllBytes(file);
+ byte[] changed = valid.clone();
+ changed[0] ^= 1;
+ Files.write(file, changed);
+ assertThrows(IOException.class, () -> Groth16Keys.load(store, imported.manifestSha256()), payload);
+ Files.write(file, valid);
+ }
+ // Refuse overwrite before touching an existing valid bundle.
+ byte[] manifest = Files.readAllBytes(store.resolve("manifest.properties"));
+ assertThrows(IOException.class, () -> ZkeyPkStoreImporter.importToPkStore(input, store, expected));
+ assertArrayEquals(manifest, Files.readAllBytes(store.resolve("manifest.properties")));
+ assertThrows(IOException.class, () -> ZkeyPkStoreImporter.importToPkStore(input, tmp.resolve("implicit")));
+ }
+
+ @Test void rejectsDuplicateSectionsAndBadCoefficients() throws IOException {
+ byte[] original = fixture();
+ byte[] b = original.clone();
+ ByteBuffer.wrap(b).order(ByteOrder.LITTLE_ENDIAN).putInt(section(b, 2) - 12, 1);
+ rejected(b);
+ b = original.clone();
+ ByteBuffer.wrap(b).order(ByteOrder.LITTLE_ENDIAN).putInt(section(b, 4) + 4, 3);
+ rejected(b);
+ b = original.clone();
+ ByteBuffer.wrap(b).order(ByteOrder.LITTLE_ENDIAN).putInt(section(b, 4) + 8, Integer.MAX_VALUE);
+ rejected(b);
+ b = original.clone();
+ ByteBuffer.wrap(b).order(ByteOrder.LITTLE_ENDIAN).putInt(section(b, 4) + 12, Integer.MAX_VALUE);
+ rejected(b);
+ }
+}
diff --git a/zeroj-tools/src/main/java/org/zeroj/ceremony/CeremonyCli.java b/zeroj-tools/src/main/java/org/zeroj/ceremony/CeremonyCli.java
index 68a5bde0..b8c9f183 100644
--- a/zeroj-tools/src/main/java/org/zeroj/ceremony/CeremonyCli.java
+++ b/zeroj-tools/src/main/java/org/zeroj/ceremony/CeremonyCli.java
@@ -153,17 +153,27 @@ public String[] getVersion() {
static class Finalize implements Callable {
@Option(names = "--zkey", required = true, description = "Final ceremony .zkey") Path zkey;
- @Option(names = "--pk-store", required = true, description = "Output proving-key store directory") Path pkStore;
+ @Option(names = "--pk-store", required = true, description = "New output proving-key store directory") Path pkStore;
+ @Option(names = "--sha256", description = "Expected SHA-256 from a trusted ceremony manifest") String sha256;
+ @Option(names = "--allow-unpinned", description = "Explicit local/test import without source authentication") boolean allowUnpinned;
@Override
public Integer call() throws Exception {
if (!Files.isReadable(zkey)) { System.err.println("Cannot read .zkey: " + zkey); return 2; }
System.out.printf("Importing %s (%,d bytes) -> %s ...%n", zkey, Files.size(zkey), pkStore);
long t0 = System.nanoTime();
- var dims = ZkeyPkStoreImporter.importToPkStore(zkey, pkStore);
+ if ((sha256 == null) == !allowUnpinned) {
+ System.err.println("Choose exactly one of --sha256 or --allow-unpinned");
+ return 2;
+ }
+ var dims = allowUnpinned
+ ? ZkeyPkStoreImporter.importUnpinnedToPkStore(zkey, pkStore)
+ : ZkeyPkStoreImporter.importToPkStore(zkey, pkStore, sha256);
+ System.out.println("Source SHA-256: " + dims.sourceSha256());
+ System.out.println("Manifest SHA-256 (retain via a trusted channel): " + dims.manifestSha256());
System.out.printf("Done in %.1fs: %,d wires | %d public | domain %,d%n",
(System.nanoTime() - t0) / 1e9, dims.numWires(), dims.numPublic(), dims.domainSize());
- System.out.println("Prove with Groth16PkStore.load(\"" + pkStore + "\") and "
+ System.out.println("Prove with Groth16PkStore.load(\"" + pkStore + "\", \"" + dims.manifestSha256() + "\") and "
+ "ZkeyPkStoreImporter.snarkjsConstraints(yourConstraints, " + dims.numPublic() + ").");
return 0;
}
diff --git a/zeroj-tools/src/test/java/org/zeroj/ceremony/CeremonyCliTest.java b/zeroj-tools/src/test/java/org/zeroj/ceremony/CeremonyCliTest.java
index 5af0dacf..d8f9c2cc 100644
--- a/zeroj-tools/src/test/java/org/zeroj/ceremony/CeremonyCliTest.java
+++ b/zeroj-tools/src/test/java/org/zeroj/ceremony/CeremonyCliTest.java
@@ -20,6 +20,8 @@
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.math.BigInteger;
+import java.security.MessageDigest;
+import java.util.HexFormat;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
@@ -78,7 +80,14 @@ void fullOptionA_ceremonyViaCli_provesAndVerifies(@TempDir Path dir) throws Exce
// 3. finalize via CLI
Path store = dir.resolve("pk-store");
- assertEquals(0, CeremonyCli.run(new String[]{"finalize",
+ String sourceHash = HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256")
+ .digest(Files.readAllBytes(dir.resolve("key1.zkey"))));
+ assertEquals(2, CeremonyCli.run(new String[]{"finalize", "--zkey", dir.resolve("key1.zkey").toString(),
+ "--pk-store", store.toString()}));
+ assertEquals(2, CeremonyCli.run(new String[]{"finalize", "--allow-unpinned", "--sha256", sourceHash,
+ "--zkey", dir.resolve("key1.zkey").toString(), "--pk-store", store.toString()}));
+ assertFalse(Files.exists(store));
+ assertEquals(0, CeremonyCli.run(new String[]{"finalize", "--sha256", sourceHash,
"--zkey", dir.resolve("key1.zkey").toString(), "--pk-store", store.toString()}));
// 4. prove from the store; verify against the snarkjs VK
diff --git a/zeroj-tools/src/test/java/org/zeroj/ceremony/ZkeyContributorInteropTest.java b/zeroj-tools/src/test/java/org/zeroj/ceremony/ZkeyContributorInteropTest.java
index c7be8a6c..28a1a2fd 100644
--- a/zeroj-tools/src/test/java/org/zeroj/ceremony/ZkeyContributorInteropTest.java
+++ b/zeroj-tools/src/test/java/org/zeroj/ceremony/ZkeyContributorInteropTest.java
@@ -61,7 +61,7 @@ void zerojContribution_verifiedBySnarkjs_mixedTranscript(@TempDir Path dir) thro
// (c) the final key proves (via the in-memory importer for brevity) — full-circle sanity
run(dir, snarkjs, "zkey", "export", "verificationkey", "key3.zkey", "vk.json");
Path store = dir.resolve("pk");
- assertEquals(0, CeremonyCli.run(new String[]{"finalize",
+ assertEquals(0, CeremonyCli.run(new String[]{"finalize", "--allow-unpinned",
"--zkey", dir.resolve("key3.zkey").toString(), "--pk-store", store.toString()}));
var builder = MulFixtureCircuit.build();
var compiled = builder.compileR1CS(CurveId.BLS12_381);
From e29cc3d214bfbd6dc493d074303d1cf53f09b8ed Mon Sep 17 00:00:00 2001
From: Satya
Date: Sun, 27 Sep 2026 14:13:28 +0800
Subject: [PATCH 2/2] fix(groth16): seal circuit metadata before pinning
imported keys
---
...rity-audit-and-public-testnet-readiness.md | 42 +++++++++-
docs/benchmarks/SubgroupImportTiming.java | 59 +++++++++++++
.../streaming-zkey-import-2026-09-27.md | 83 +++++++++++++++++++
docs/ceremony/OPTION-A-RUNBOOK.md | 12 ++-
docs/ceremony/USER-GUIDE.md | 20 +++--
docs/ceremony/rehearsal.sh | 5 +-
docs/groth16-dev-guide.md | 14 +++-
.../zeroj/crypto/groth16/Groth16PkStore.java | 7 +-
.../crypto/groth16/ZkeyPkStoreImporter.java | 47 +++++++++--
.../Groth16PipelineCeremonyKeyTest.java | 30 +++++--
.../groth16/ZkeyStreamingBoundaryTest.java | 79 ++++++++++++++----
.../java/org/zeroj/ceremony/CeremonyCli.java | 29 +++++--
.../org/zeroj/ceremony/CeremonyCliTest.java | 68 +++++++++++++--
13 files changed, 439 insertions(+), 56 deletions(-)
create mode 100644 docs/benchmarks/SubgroupImportTiming.java
create mode 100644 docs/benchmarks/streaming-zkey-import-2026-09-27.md
diff --git a/docs/adr/0025-end-to-end-security-audit-and-public-testnet-readiness.md b/docs/adr/0025-end-to-end-security-audit-and-public-testnet-readiness.md
index afdbf998..eddd08ab 100644
--- a/docs/adr/0025-end-to-end-security-audit-and-public-testnet-readiness.md
+++ b/docs/adr/0025-end-to-end-security-audit-and-public-testnet-readiness.md
@@ -376,13 +376,14 @@ no private witness or ceremony contribution secret is processed during import.
Invariants: canonical Montgomery residues before reduction; on-curve and prime-order checks
on every imported G1/G2 point; infinity permitted only in query arrays, never header/IC;
-bounded, exact section reads and dimensions; no returned/published store after a failed check.
+bounded, exact section reads and dimensions (only snarkjs section types 1–10); no
+returned/published store after a failed check.
Use the existing Jacobian multiply-by-r predicate already used by SetupCacheIO, not a new
endomorphism implementation. The format reference is snarkjs **v0.7.6** `src/zkey_utils.js`
(writeHeader, writeZKey, readHeaderGroth16), plus ADR-0045's stricter infinity profile.
A pinned import checks an externally trusted SHA-256. An explicitly named unpinned import
-exists for fixtures/local experiments and still performs all mathematical validation. Stage
+exists for fixtures/local experiments and still performs all structural and point validation. Stage
a private copy while hashing and parse that same copy, so source-file replacement cannot
switch the bytes after the hash check. Build a fresh sibling directory and publish only after
validation; never overwrite an existing destination. This costs temporary disk space, not
@@ -402,3 +403,40 @@ hash mismatch and late-failure/no-publication tests; persisted-file mutation rej
Production Filecoin conversion, circuit freeze, contributor ceremony, public artifact manifest,
independent review and live deployment evidence remain open under #48. This milestone must
not close that issue or change maturity claims.
+
+### PR #61 review amendment — seal circuit metadata before returning the pin
+
+The importer accepts an optional, externally trusted exact circuit fingerprint (ADR-0042)
+and checks its dimensions against the imported key before sealing the manifest. The returned
+manifest SHA-256 covers this fingerprint along with source and payload hashes. Supplying the
+fingerprint is a caller assertion about the verified circuit, not a key/R1CS consistency check.
+Imports without it remain unbound. `bindCircuitFingerprint` is only for unsealed local stores;
+it must reject sealed imports without changing any bytes, even if the fingerprint is identical.
+To add or change metadata, re-import into a new directory and explicitly retain the new pin.
+This preserves pinned loads and cache hits without silently invalidating an existing pin.
+Tests cover pinned import/binding/load/prove/cache-hit, rejected late binding, and incompatible
+circuit dimensions. Legacy unsealed development-store binding remains supported.
+
+**Residual witness-confidentiality risk:** valid subgroup points alone do not make a proving
+key safe. A malicious author can shift a private wire's L query by a known multiple of G;
+the pairing residual of a resulting proof then permits guesses of that witness value (including
+individual secret bits). This matters for account-ownership root-key witnesses. Before using
+private witnesses, independently verify the key against the exact R1CS and trusted `.ptau`
+with `snarkjs zkey verify`, or pin a key hash supplied by someone trusted who performed that
+verification. Hashing an arbitrary downloaded key, binding a circuit fingerprint, or merely
+checking its points does not establish this property. See snarkjs **v0.7.6**
+[`zkey_verify_fromr1cs.js`](https://github.com/iden3/snarkjs/blob/v0.7.6/src/zkey_verify_fromr1cs.js)
+and [`zkey_verify_frominit.js`](https://github.com/iden3/snarkjs/blob/v0.7.6/src/zkey_verify_frominit.js).
+An internal key-consistency verifier is tracked in [#67](https://github.com/bloxbean/zeroj/issues/67).
+It requires a separate reviewed design and independent positive/negative reference vectors;
+it is outside this import-hardening milestone.
+
+Subgroup validation keeps the existing multiply-by-r predicate. Future throughput work must
+preserve that predicate (for example flat-limb arithmetic or a qualified blst implementation)
+and add differential tests; this milestone does not introduce an endomorphism-based check.
+
+Local measurements and reproduction commands are recorded in
+[the PR #61 timing report](../benchmarks/streaming-zkey-import-2026-09-27.md): median single-thread
+CPU cost was 0.5113 ms/G1 and 1.4840 ms/G2 point. The 19M-constraint ownership artifact was not
+available, so full-scale finalize timing remains pending under #48. The report labels its
+point-count extrapolation explicitly; it is not a measured 19M result.
diff --git a/docs/benchmarks/SubgroupImportTiming.java b/docs/benchmarks/SubgroupImportTiming.java
new file mode 100644
index 00000000..083e2ac0
--- /dev/null
+++ b/docs/benchmarks/SubgroupImportTiming.java
@@ -0,0 +1,59 @@
+package org.zeroj.benchmarks;
+
+import org.zeroj.bls12381.ec.JacobianG1BLS381;
+import org.zeroj.bls12381.ec.JacobianG2BLS381;
+import org.zeroj.bls12381.ec.JacobianG1BLS381.AffineG1;
+import org.zeroj.bls12381.ec.JacobianG2BLS381.AffineG2;
+import org.zeroj.bls12381.field.MontFr381;
+
+import java.lang.management.ManagementFactory;
+import java.lang.management.ThreadMXBean;
+import java.math.BigInteger;
+import java.util.Locale;
+
+/** Single-thread cost sample of the importer's existing predicates, not a full-import benchmark. */
+public final class SubgroupImportTiming {
+ private static final BigInteger R = MontFr381.modulus();
+ private static final int POINTS = 512;
+ private static final ThreadMXBean THREADS = ManagementFactory.getThreadMXBean();
+
+ public static void main(String[] args) {
+ if (!THREADS.isCurrentThreadCpuTimeSupported()) throw new IllegalStateException("CPU timing unavailable");
+ THREADS.setThreadCpuTimeEnabled(true);
+ var g1 = new AffineG1[POINTS];
+ var g2 = new AffineG2[POINTS];
+ for (int i = 0; i < POINTS; i++) {
+ // Distinct non-infinity public points; construction excluded from timings.
+ var scalar = BigInteger.valueOf(i + 1L);
+ g1[i] = JacobianG1BLS381.GENERATOR.scalarMul(scalar).toAffine();
+ g2[i] = JacobianG2BLS381.GENERATOR.scalarMul(scalar).toAffine();
+ }
+ System.out.printf("Java %s; %s %s; %d processors; %d points/group; 3 warmup + 5 measured passes%n",
+ System.getProperty("java.runtime.version"), System.getProperty("os.name"),
+ System.getProperty("os.arch"), Runtime.getRuntime().availableProcessors(), POINTS);
+ for (int pass = -3; pass < 5; pass++) {
+ measure("G1", pass, () -> {
+ for (var p : g1) {
+ if (!p.isOnCurve() || !JacobianG1BLS381.fromAffine(p.x(), p.y()).scalarMul(R).isInfinity())
+ throw new AssertionError("G1 predicate failed");
+ }
+ });
+ measure("G2", pass, () -> {
+ for (var p : g2) {
+ if (!p.isOnCurve() || !JacobianG2BLS381.fromAffine(p.x(), p.y()).scalarMul(R).isInfinity())
+ throw new AssertionError("G2 predicate failed");
+ }
+ });
+ }
+ }
+
+ private static void measure(String group, int pass, Runnable predicate) {
+ long cpu = THREADS.getCurrentThreadCpuTime();
+ long wall = System.nanoTime();
+ predicate.run();
+ double wallMs = (System.nanoTime() - wall) / 1e6 / POINTS;
+ double cpuMs = (THREADS.getCurrentThreadCpuTime() - cpu) / 1e6 / POINTS;
+ if (pass >= 0) System.out.printf(Locale.ROOT, "%s pass %d: wall %.4f ms/point; CPU %.4f ms/point%n",
+ group, pass + 1, wallMs, cpuMs);
+ }
+}
diff --git a/docs/benchmarks/streaming-zkey-import-2026-09-27.md b/docs/benchmarks/streaming-zkey-import-2026-09-27.md
new file mode 100644
index 00000000..a5d6f82a
--- /dev/null
+++ b/docs/benchmarks/streaming-zkey-import-2026-09-27.md
@@ -0,0 +1,83 @@
+# Streaming Groth16 import timing — PR #61 review
+
+Measured on 2026-09-27 on an Apple M4 Max (16 available processors, 128 GiB RAM),
+macOS/aarch64, Liberica OpenJDK 25.0.2+12-LTS, `-Xms1g -Xmx1g`. These measurements use
+PR #61's review changes based on `167bc8d`; the subgroup predicate is unchanged from that
+commit. Other development jobs were active on the host. These are local observations, not
+release performance guarantees.
+
+**The 19M-constraint ownership import has not been measured.** No such `.zkey` was available
+in the inspected checkout, and its path and trusted hash have been requested. Do not report
+the extrapolation below as an actual finalize run. Full-scale wall time, CPU time, peak RSS,
+temporary disk use and storage throughput remain evidence to collect under #48.
+
+## Predicate measurement
+
+[SubgroupImportTiming.java](SubgroupImportTiming.java) checks 512 distinct non-infinity public
+points per group using the same on-curve plus Jacobian multiply-by-r predicate as the importer.
+Point construction is excluded. One thread executes three warmup passes followed by five
+measured passes. CPU time is current-thread CPU time; wall time includes scheduling and GC.
+
+| Pass | G1 wall ms/point | G1 CPU ms/point | G2 wall ms/point | G2 CPU ms/point |
+|---|---:|---:|---:|---:|
+| 1 | 0.5051 | 0.5044 | 1.4732 | 1.4684 |
+| 2 | 0.5121 | 0.5113 | 1.4955 | 1.4840 |
+| 3 | 0.5143 | 0.5121 | 1.4902 | 1.4867 |
+| 4 | 0.5111 | 0.5091 | 1.4760 | 1.4715 |
+| 5 | 0.5225 | 0.5221 | 1.4956 | 1.4908 |
+| Median | 0.5121 | 0.5113 | 1.4902 | 1.4840 |
+
+Using the reviewer's **assumed** 70–90 million non-infinity G1 points and 19 million G2 points,
+these median CPU costs imply about **64–74 thousand core-seconds** for point validation alone.
+Dividing by 16 gives an idealized **1.1–1.3 hours**; this is not a wall-time prediction. It assumes
+perfect scaling across heterogeneous cores and excludes decoding, copies, hashing, I/O,
+allocation/GC interference and other import work. Actual point counts have not been measured
+from the ownership key. An import that skips subgroup validation is not an acceptable faster
+alternative. Future optimization must preserve the predicate and be independently qualified.
+
+Reproduce from the repository root (set `CEREMONY_JAR` to the fat jar produced by the build):
+
+```bash
+./gradlew :zeroj-tools:fatJar
+export CEREMONY_JAR=zeroj-tools/build/libs/zeroj-ceremony--all.jar
+TIMING_CLASSES=$(mktemp -d)
+javac -cp "$CEREMONY_JAR" -d "$TIMING_CLASSES" docs/benchmarks/SubgroupImportTiming.java
+java -Xms1g -Xmx1g -cp "$TIMING_CLASSES:$CEREMONY_JAR" org.zeroj.benchmarks.SubgroupImportTiming
+```
+
+## Small complete import
+
+The checked-in `zeroj-crypto/src/test/resources/test-circuits/multiplier-bls381/multiplier.zkey`
+is 3,652 bytes (4 wires, 1 public input, domain 4), SHA-256
+`9839919f7951828d2c4ac8af231ab640ca2ade07fa9b834c872cc36512dc6252`.
+Three fresh JVM CLI runs with `-Djava.util.concurrent.ForkJoinPool.common.parallelism=15`
+and a new output directory each completed with:
+
+| Run | Process wall s | User CPU s | System CPU s | Peak RSS bytes |
+|---|---:|---:|---:|---:|
+| 1 | 0.16 | 0.27 | 0.03 | 107757568 |
+| 2 | 0.16 | 0.27 | 0.03 | 108625920 |
+| 3 | 0.16 | 0.27 | 0.03 | 108199936 |
+
+The CLI rounded import time to 0.1 s in each run. All returned manifest SHA-256
+`96d4a699cfadbc7407d56a7b39cc44cad76ce4f0a9e7d5a4d943f6cc939dc8b8` (unbound circuit metadata).
+This tiny, cached-input experiment mostly measures startup; it cannot establish large-key
+throughput or memory use. The fixture is test material, not a production ceremony artifact.
+
+For a full-size run, obtain `VERIFIED_ZKEY_SHA256` through a trusted verification process,
+provide the matching key path as `VERIFIED_ZKEY`, and use a **new** `NEW_PK_STORE` directory:
+
+```bash
+# macOS time; on Linux use /usr/bin/time -v instead of -lp.
+/usr/bin/time -lp java -Xms1g -Xmx1g \
+ -Djava.util.concurrent.ForkJoinPool.common.parallelism=15 \
+ -jar "$CEREMONY_JAR" finalize --sha256 "$VERIFIED_ZKEY_SHA256" \
+ --zkey "$VERIFIED_ZKEY" --pk-store "$NEW_PK_STORE"
+```
+
+Record the revision, JDK/OS/CPU, heap and worker settings, source hash/size, exact circuit
+fingerprint, counts of non-infinity points, output manifest pin, disk configuration, peak
+space, process CPU/wall time and peak RSS. Include `--circuit-fingerprint` when that verified
+metadata is available. Keep source and mapped store directories protected from concurrent
+mutation throughout verification/import/proving. Performance evidence does not establish
+ceremony trust or production readiness.
diff --git a/docs/ceremony/OPTION-A-RUNBOOK.md b/docs/ceremony/OPTION-A-RUNBOOK.md
index ac792110..fef72335 100644
--- a/docs/ceremony/OPTION-A-RUNBOOK.md
+++ b/docs/ceremony/OPTION-A-RUNBOOK.md
@@ -74,7 +74,9 @@ entropy was destroyed.
snarkjs zkey beacon key_.zkey key_final.zkey 10 -n="final beacon"
# The independent check anyone can re-run:
-snarkjs zkey verify ownership.r1cs pot25_final.ptau key_final.zkey
+snarkjs zkey verify ownership.r1cs pot25_final.ptau key_final.zkey || exit 1
+# Hash only the independently verified artifact, kept in a controlled directory:
+VERIFIED_ZKEY_SHA256=$(shasum -a 256 key_final.zkey | awk '{print $1}')
snarkjs zkey export verificationkey key_final.zkey verification_key.json
@@ -83,10 +85,14 @@ java -cp zeroj-ceremony.jar org.zeroj.ceremony.CeremonyCli \
finalize --sha256 "$VERIFIED_ZKEY_SHA256" --zkey key_final.zkey --pk-store ./ownership-pk
```
-Proving afterwards: `Groth16PkStore.load(dir)` + `ZkeyPkStoreImporter.snarkjsConstraints(compiled, numPublic)`
+Proving afterwards: `Groth16PkStore.load(dir, expectedManifestSha256)` + `ZkeyPkStoreImporter.snarkjsConstraints(compiled, numPublic)`
(snarkjs appends one public-input binding row per public signal — the helper synthesizes them; it is
asserted against real zkeys in `ZkeyPkStoreImporterTest`). The VK for the on-chain validator comes
-from the same store (`loaded.gammaG2()`, `loaded.ic()`).
+from the same store (`loaded.gammaG2()`, `loaded.ic()`). Retain the manifest SHA-256 printed by
+`finalize` through a trusted channel, outside the store. For circuit-aware cache hits, pass
+`--circuit-fingerprint "$VERIFIED_CIRCUIT_FINGERPRINT"` at finalize time; sealed stores cannot
+be bound afterwards. This fingerprint must come from the verified exact R1CS and is metadata,
+not a substitute for `zkey verify`.
## Transcript publication (what makes it trustworthy)
diff --git a/docs/ceremony/USER-GUIDE.md b/docs/ceremony/USER-GUIDE.md
index 69e0db08..67783cd8 100644
--- a/docs/ceremony/USER-GUIDE.md
+++ b/docs/ceremony/USER-GUIDE.md
@@ -95,11 +95,18 @@ zeroj-ceremony finalize --sha256 "$VERIFIED_ZKEY_SHA256" --zkey key_final.zkey -
| option | required | meaning |
|---|---|---|
| `--zkey ` | yes | the final (post-beacon, verified) ceremony `.zkey` — streaming import, multi-GB safe |
-| `--pk-store ` | yes | output directory (loadable with `Groth16PkStore.load(dir)`) |
+| `--pk-store ` | yes | new output directory (must not already exist) |
+| `--sha256 ` | yes, except explicit local/test mode | trusted SHA-256 of the independently verified final key |
+| `--allow-unpinned` | local/test only | alternative to `--sha256`; does not authenticate the source |
+| `--circuit-fingerprint ` | for circuit-aware cache hits | trusted exact R1CS fingerprint included before sealing |
-Applications then prove with `Groth16PkStore.load(dir)` +
+Applications then prove with `Groth16PkStore.load(dir, expectedManifestSha256)` +
`ZkeyPkStoreImporter.snarkjsConstraints(compiledConstraints, numPublic)` (snarkjs setup appends one
-binding row per public input — the helper synthesizes them).
+binding row per public input — the helper synthesizes them). Retain the manifest SHA-256
+printed by `finalize` outside the store through a trusted channel and use it for subsequent
+loads. Set the optional fingerprint to the verified R1CS's `Groth16Pipeline.Compiled.fingerprint()`;
+this records the caller's circuit association, not a key-consistency verification. Sealed
+imports reject later `bindCircuitFingerprint` calls; re-import to add metadata.
## 4. A complete ceremony at a glance
@@ -115,11 +122,14 @@ zeroj-ceremony contribute --in key_0002.zkey --out key_0003.zkey --name "carol"
# coordinator: pre-announced public beacon, independent verification, finalize
snarkjs zkey beacon key_0003.zkey key_final.zkey 10 -n="final beacon"
-snarkjs zkey verify my.r1cs prepared.ptau key_final.zkey # anyone can re-run this
+snarkjs zkey verify my.r1cs prepared.ptau key_final.zkey || exit 1 # anyone can re-run this
+# Hash only after verification succeeds; keep these artifacts in a controlled directory.
+VERIFIED_ZKEY_SHA256=$(shasum -a 256 key_final.zkey | awk '{print $1}')
zeroj-ceremony finalize --sha256 "$VERIFIED_ZKEY_SHA256" --zkey key_final.zkey --pk-store ./pk
```
-A runnable rehearsal of exactly this flow: [`rehearsal.sh`](rehearsal.sh). Full coordinator
+A small development rehearsal of these steps (its fixed entropy/beacon are not production-safe):
+[`rehearsal.sh`](rehearsal.sh). Full coordinator
procedure (attestations, transcript publication, checklist): [OPTION-A-RUNBOOK.md](OPTION-A-RUNBOOK.md).
## 5. Contributor attestation (publish after contributing)
diff --git a/docs/ceremony/rehearsal.sh b/docs/ceremony/rehearsal.sh
index e359c3cb..a1947c9a 100755
--- a/docs/ceremony/rehearsal.sh
+++ b/docs/ceremony/rehearsal.sh
@@ -47,10 +47,13 @@ $CLI contribute --in key_0002.zkey --out key_0003.zkey --name "carol (zeroj)" |
echo ">> [coordinator] beacon (pre-announced public randomness) + independent verification"
"$SNARKJS" zkey beacon key_0003.zkey key_final.zkey 0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f 10 -n="rehearsal beacon"
"$SNARKJS" zkey verify mul.r1cs pot.ptau key_final.zkey | tee -a transcript.txt
+# pipefail above ensures a failed verification stops before hashing/finalize.
+VERIFIED_ZKEY_SHA256=$(shasum -a 256 key_final.zkey | awk '{print $1}')
+printf '%s key_final.zkey\n' "$VERIFIED_ZKEY_SHA256" | tee -a transcript.txt
echo ">> [coordinator] finalize into a ZeroJ proving-key store + export VK"
"$SNARKJS" zkey export verificationkey key_final.zkey verification_key.json
-$CLI finalize --allow-unpinned --zkey key_final.zkey --pk-store ./pk-store
+$CLI finalize --sha256 "$VERIFIED_ZKEY_SHA256" --zkey key_final.zkey --pk-store ./pk-store | tee -a transcript.txt
echo ""
echo ">> REHEARSAL COMPLETE. Artifacts in $WORK (transcript.txt = the publishable record)."
diff --git a/docs/groth16-dev-guide.md b/docs/groth16-dev-guide.md
index 1e4a0097..0239627b 100644
--- a/docs/groth16-dev-guide.md
+++ b/docs/groth16-dev-guide.md
@@ -82,15 +82,25 @@ Run the multi-party ceremony externally (snarkjs), then import the `.zkey` once
store layout; from there it's Flow 2's load-and-prove:
```java
-var imported = ZkeyPkStoreImporter.importToPkStore(zkeyPath, keysDir, expectedSourceSha256); // one-time; writes the dense store
+var imported = ZkeyPkStoreImporter.importToPkStore(
+ zkeyPath, keysDir, expectedSourceSha256, expectedCircuitFingerprint);
-try (var keys = Groth16Keys.load(keysDir)) {
+try (var keys = Groth16Keys.load(keysDir, imported.manifestSha256())) {
// a snarkjs setup appends numPublic+1 public-input binding rows after the circuit rows —
// tell the H computation about them (0 for locally-generated bundles):
Groth16ProofBLS381 proof = keys.prove(ProverBackend.PURE_JAVA, w, flat, numPublic + 1);
}
```
+Supply the exact fingerprint of the independently verified R1CS (for example,
+`Groth16Pipeline.Compiled.fingerprint()`). It is included before sealing, so pinned loads and
+circuit-aware cache hits work together. Binding a sealed store later is rejected; re-import
+into a new directory to add metadata. The three-argument import remains available for an
+unbound store. A supplied fingerprint asserts circuit identity; it does not verify that the
+key is consistent with that relation. Independently verify the key against the R1CS and trusted
+`.ptau`, or use a trusted hash from someone who did. Retain the returned manifest hash outside
+the store through a trusted channel and supply it on every later load.
+
The importer always writes the dense format, and dense stays readable forever — ceremony
bundles are never affected by the sparse default.
diff --git a/zeroj-crypto/src/main/java/org/zeroj/crypto/groth16/Groth16PkStore.java b/zeroj-crypto/src/main/java/org/zeroj/crypto/groth16/Groth16PkStore.java
index 4ef14675..f2fdba5f 100644
--- a/zeroj-crypto/src/main/java/org/zeroj/crypto/groth16/Groth16PkStore.java
+++ b/zeroj-crypto/src/main/java/org/zeroj/crypto/groth16/Groth16PkStore.java
@@ -59,7 +59,10 @@ public static boolean exists(Path dir) {
return Files.isRegularFile(dir.resolve(MANIFEST));
}
- /** Bind an already-created local or imported key bundle to one exact circuit relation. */
+ /**
+ * Bind an unsealed local key bundle to one exact circuit relation.
+ * Sealed imports must receive their fingerprint during import, before computing the pin.
+ */
public static void bindCircuitFingerprint(Path dir, String fingerprint) throws IOException {
if (!Groth16Pipeline.isExactFingerprint(fingerprint)) {
throw new IllegalArgumentException("exact circuit fingerprint is required");
@@ -67,6 +70,8 @@ public static void bindCircuitFingerprint(Path dir, String fingerprint) throws I
Path manifest = dir.resolve(MANIFEST);
var properties = new Properties();
try (var in = Files.newInputStream(manifest)) { properties.load(in); }
+ if (properties.containsKey("integrityProfile"))
+ throw new IOException("Cannot bind a sealed store; supply the circuit fingerprint during import");
validateManifestDimensions(properties, fingerprint);
String existing = properties.getProperty("circuitFingerprint");
if (existing != null && !existing.equals(fingerprint)) {
diff --git a/zeroj-crypto/src/main/java/org/zeroj/crypto/groth16/ZkeyPkStoreImporter.java b/zeroj-crypto/src/main/java/org/zeroj/crypto/groth16/ZkeyPkStoreImporter.java
index 997ac876..ee064e4c 100644
--- a/zeroj-crypto/src/main/java/org/zeroj/crypto/groth16/ZkeyPkStoreImporter.java
+++ b/zeroj-crypto/src/main/java/org/zeroj/crypto/groth16/ZkeyPkStoreImporter.java
@@ -39,7 +39,8 @@
* in the same parallel pass. VK parts (alpha/beta/gamma/delta, IC) land in the store's
* {@code aux.bin}/manifest via the shared {@link Groth16PkStore} writer.
*
- * After import: {@code Groth16PkStore.load(dir)} + prove exactly as with a ZeroJ-generated key.
+ *
After import: {@code Groth16PkStore.load(dir, imported.manifestSha256())}, then prove
+ * as with a ZeroJ-generated key.
* Note snarkjs setup appends public-input binding rows to the constraint list — use
* {@link #snarkjsConstraints(java.util.List, int)} when proving under a ceremony key.
*/
@@ -65,27 +66,56 @@ public record Imported(int numWires, int numPublic, int domainSize,
/**
* @deprecated Select a trusted expected SHA-256 or explicitly use the unpinned test API.
*/
- @Deprecated
+ @Deprecated(forRemoval = true)
public static Imported importToPkStore(Path zkeyFile, Path dir) throws IOException {
throw new IOException("Expected .zkey SHA-256 required; use the pinned overload or "
+ "importUnpinnedToPkStore for explicitly unpinned local/test artifacts");
}
- /** Import a mathematically validated key whose bytes match a trusted external hash. */
+ /**
+ * Import structurally and point-validated bytes matching a trusted external hash.
+ * The sealed store is unbound; use the fingerprint overload for circuit-aware cache hits.
+ * This does not verify key consistency with the R1CS or ceremony transcript.
+ */
public static Imported importToPkStore(Path zkeyFile, Path dir, String expectedSha256) throws IOException {
Groth16StoreIntegrity.requireDigest(expectedSha256);
- return stageImport(zkeyFile, dir, expectedSha256);
+ return stageImport(zkeyFile, dir, expectedSha256, null);
}
/**
- * Explicit local/test opt-in: validates the key but cannot authenticate its ceremony origin.
+ * Import with an exact circuit fingerprint included before the manifest is sealed.
+ * The caller must independently establish the key/circuit association; this checks only
+ * fingerprint syntax and dimensions, not the relation or ceremony transcript.
+ */
+ public static Imported importToPkStore(Path zkeyFile, Path dir, String expectedSha256,
+ String expectedCircuitFingerprint) throws IOException {
+ Groth16StoreIntegrity.requireDigest(expectedSha256);
+ requireFingerprint(expectedCircuitFingerprint);
+ return stageImport(zkeyFile, dir, expectedSha256, expectedCircuitFingerprint);
+ }
+
+ /**
+ * Explicit local/test opt-in: validates structure and points but cannot authenticate ceremony origin.
* This never bypasses curve, subgroup, canonicality or structural checks.
*/
public static Imported importUnpinnedToPkStore(Path zkeyFile, Path dir) throws IOException {
- return stageImport(zkeyFile, dir, null);
+ return stageImport(zkeyFile, dir, null, null);
+ }
+
+ /** Explicit local/test import with caller-asserted circuit metadata sealed into the manifest. */
+ public static Imported importUnpinnedToPkStore(Path zkeyFile, Path dir,
+ String expectedCircuitFingerprint) throws IOException {
+ requireFingerprint(expectedCircuitFingerprint);
+ return stageImport(zkeyFile, dir, null, expectedCircuitFingerprint);
+ }
+
+ private static void requireFingerprint(String fingerprint) {
+ if (!Groth16Pipeline.isExactFingerprint(fingerprint))
+ throw new IllegalArgumentException("exact circuit fingerprint is required");
}
- private static Imported stageImport(Path source, Path destination, String expectedHash) throws IOException {
+ private static Imported stageImport(Path source, Path destination, String expectedHash,
+ String circuitFingerprint) throws IOException {
Path target = destination.toAbsolutePath();
if (Files.exists(target)) throw new IOException("Output directory already exists: " + target);
Files.createDirectories(target.getParent());
@@ -116,6 +146,8 @@ private static Imported stageImport(Path source, Path destination, String expect
throw new IOException("Malformed .zkey", malformed);
}
Files.delete(snapshot);
+ if (circuitFingerprint != null)
+ Groth16PkStore.bindCircuitFingerprint(staging, circuitFingerprint);
String manifestHash = Groth16StoreIntegrity.seal(staging, sourceHash);
// No REPLACE_EXISTING: an existing store is never partially overwritten.
Files.move(staging, target);
@@ -149,6 +181,7 @@ private static Imported importSnapshot(Path zkeyFile, Path dir) throws IOExcepti
for (int i = 0; i < nSections; i++) {
if (fileSize - pos < 12) throw new IOException("Truncated .zkey section header");
int type = z.get(U32, pos);
+ if (type < 1 || type > 10) throw new IOException("Unknown .zkey section " + type);
long size = z.get(U64, pos + 4);
pos += 12;
if (size < 0 || size > fileSize - pos) throw new IOException("Invalid .zkey section " + type);
diff --git a/zeroj-crypto/src/test/java/org/zeroj/crypto/groth16/Groth16PipelineCeremonyKeyTest.java b/zeroj-crypto/src/test/java/org/zeroj/crypto/groth16/Groth16PipelineCeremonyKeyTest.java
index 63cee1a6..8bb85d85 100644
--- a/zeroj-crypto/src/test/java/org/zeroj/crypto/groth16/Groth16PipelineCeremonyKeyTest.java
+++ b/zeroj-crypto/src/test/java/org/zeroj/crypto/groth16/Groth16PipelineCeremonyKeyTest.java
@@ -20,11 +20,14 @@
import java.math.BigInteger;
import java.nio.file.Files;
import java.nio.file.Path;
+import java.security.MessageDigest;
+import java.util.HexFormat;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -71,24 +74,40 @@ void importedCeremonyKey_provesThroughPipeline_withoutCache_onMiss_andOnHit(@Tem
Path zkeyFile = tmp.resolve("key.zkey");
Files.write(zkeyFile, zkeyBytes);
Path store = tmp.resolve("store");
- ZkeyPkStoreImporter.importUnpinnedToPkStore(zkeyFile, store);
// Compiled must accept the original relation as-is (no S1 here).
var cc = new Groth16Pipeline.Compiled(flatOf(original), circuitRows, numWires, numPublic);
+ String sourceHash = HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(zkeyBytes));
+ var imported = ZkeyPkStoreImporter.importToPkStore(zkeyFile, store, sourceHash, cc.fingerprint());
+ var repeated = ZkeyPkStoreImporter.importToPkStore(zkeyFile, tmp.resolve("repeat"), sourceHash, cc.fingerprint());
+ assertEquals(imported.manifestSha256(), repeated.manifestSha256());
+ byte[] sealed = Files.readAllBytes(store.resolve("manifest.properties"));
+ var failure = assertThrows(IOException.class, () -> Groth16PkStore.bindCircuitFingerprint(store, cc.fingerprint()));
+ assertTrue(failure.getMessage().contains("sealed"));
+ assertArrayEquals(sealed, Files.readAllBytes(store.resolve("manifest.properties")));
+ String incompatible = cc.fingerprint().replace("-w" + numWires + "-", "-w" + (numWires + 1) + "-");
+ Path badStore = tmp.resolve("incompatible");
+ var mismatch = assertThrows(IOException.class,
+ () -> ZkeyPkStoreImporter.importToPkStore(zkeyFile, badStore, sourceHash, incompatible));
+ assertTrue(mismatch.getMessage().contains("dimensions"), mismatch.getMessage());
+ assertFalse(Files.exists(badStore));
+ assertThrows(IllegalArgumentException.class,
+ () -> ZkeyPkStoreImporter.importToPkStore(zkeyFile, badStore, sourceHash, "not-exact"));
+ assertFalse(Files.exists(badStore));
BigInteger[] witness = ZkeyImporterBLS381.importWtns(new ByteArrayInputStream(resource(WTNS)));
assertEquals(numWires, witness.length);
FlatScalars w = FlatScalars.pack(witness, witness.length);
BigInteger[] pub = Arrays.copyOfRange(witness, 1, 1 + numPublic);
- // (a) cache disabled, unbound key
- try (var keys = Groth16Keys.load(store)) {
+ // (a) cache disabled, pinned and circuit-bound key
+ try (var keys = Groth16Keys.load(store, imported.manifestSha256())) {
var proof = Groth16Pipeline.prove(keys, null, null, () -> cc, () -> w, bindingRows, ProverBackend.PURE_JAVA);
assertTrue(pairingVerify(keys, proof, pub), "cache disabled");
}
// (b) cache miss: the pipeline compiles, writes r1cs.bin, and proves
Path cache = tmp.resolve(Groth16Pipeline.R1CS_CACHE);
- try (var keys = Groth16Keys.load(store)) {
+ try (var keys = Groth16Keys.load(store, imported.manifestSha256())) {
var proof = Groth16Pipeline.prove(keys, cache, null, () -> cc, () -> w, bindingRows, ProverBackend.PURE_JAVA);
assertTrue(pairingVerify(keys, proof, pub), "cache miss");
}
@@ -96,8 +115,7 @@ void importedCeremonyKey_provesThroughPipeline_withoutCache_onMiss_andOnHit(@Tem
assertTrue(Groth16Pipeline.cacheMatches(cache, cc.fingerprint()));
// (c) cache hit on a bundle bound to the exact fingerprint: no recompilation
- Groth16PkStore.bindCircuitFingerprint(store, cc.fingerprint());
- try (var keys = Groth16Keys.load(store)) {
+ try (var keys = Groth16Keys.load(store, imported.manifestSha256())) {
assertEquals(cc.fingerprint(), keys.circuitFingerprint());
var proof = Groth16Pipeline.prove(keys, cache, cc.fingerprint(),
() -> { throw new AssertionError("a cache hit must not recompile"); },
diff --git a/zeroj-crypto/src/test/java/org/zeroj/crypto/groth16/ZkeyStreamingBoundaryTest.java b/zeroj-crypto/src/test/java/org/zeroj/crypto/groth16/ZkeyStreamingBoundaryTest.java
index a9b1851f..dabeeb43 100644
--- a/zeroj-crypto/src/test/java/org/zeroj/crypto/groth16/ZkeyStreamingBoundaryTest.java
+++ b/zeroj-crypto/src/test/java/org/zeroj/crypto/groth16/ZkeyStreamingBoundaryTest.java
@@ -6,6 +6,7 @@
import org.zeroj.bls12381.ec.G2Point;
import org.zeroj.bls12381.field.Fp;
import org.zeroj.bls12381.field.Fp2;
+import org.zeroj.bls12381.field.MontFr381;
import java.io.IOException;
import java.math.BigInteger;
@@ -15,6 +16,7 @@
import java.nio.file.Path;
import java.util.Arrays;
import java.util.HexFormat;
+import java.util.Locale;
import java.security.MessageDigest;
import static org.junit.jupiter.api.Assertions.*;
@@ -47,11 +49,17 @@ static void point(byte[] bytes, int offset, BigInteger... values) {
for (int i = 0; i < values.length; i++)
put(bytes, offset + i * 48, values[i].shiftLeft(384).mod(Fp.P));
}
- void rejected(byte[] bytes) throws IOException {
+ void rejected(byte[] bytes, String reason) throws IOException {
Path input = Files.createTempFile(tmp, "mutated", ".zkey");
Files.write(input, bytes);
Path out = tmp.resolve(input.getFileName() + "-store");
- assertThrows(IOException.class, () -> ZkeyPkStoreImporter.importUnpinnedToPkStore(input, out));
+ var failure = assertThrows(IOException.class,
+ () -> ZkeyPkStoreImporter.importUnpinnedToPkStore(input, out));
+ StringBuilder messages = new StringBuilder();
+ for (Throwable cause = failure; cause != null; cause = cause.getCause())
+ messages.append(cause.getMessage()).append('\n');
+ assertTrue(messages.toString().toLowerCase(Locale.ROOT).contains(reason.toLowerCase(Locale.ROOT)),
+ "expected " + reason + " rejection, got: " + messages);
assertFalse(Files.exists(out), "failed import must not publish any store");
}
@Test void rejectsG1TorsionInEveryPointSection() throws IOException {
@@ -65,7 +73,7 @@ void rejected(byte[] bytes) throws IOException {
for (int offset : offsets) {
byte[] b = original.clone();
point(b, offset, BigInteger.ZERO, BigInteger.TWO);
- rejected(b);
+ rejected(b, "subgroup");
}
}
@Test void rejectsG2TorsionInEveryPointSection() throws IOException {
@@ -79,26 +87,47 @@ void rejected(byte[] bytes) throws IOException {
for (int offset : new int[]{h + 292, h + 484, h + 772, section(original, 7)}) {
byte[] b = original.clone();
point(b, offset, x.c0().value(), x.c1().value(), y.c0().value(), y.c1().value());
- rejected(b);
+ rejected(b, "subgroup");
}
}
- @Test void rejectsNoncanonicalResiduesAndMalformedStructure() throws IOException {
+ @Test void rejectsNoncanonicalResiduesOfOtherwiseValidPoints() throws IOException {
byte[] original = fixture();
- for (int sec : new int[]{2, 3, 5, 6, 7, 8, 9}) {
+ int h = section(original, 2);
+ // Include header G1/G2, IC and all query paths. The old reducing decoder would see
+ // exactly the same valid point; raw p alone would instead create an off-curve point.
+ for (int offset : new int[]{h + 100, h + 292, h + 484, h + 772, section(original, 3),
+ section(original, 5), section(original, 6), section(original, 7),
+ section(original, 8), section(original, 9)}) {
byte[] b = original.clone();
- put(b, section(b, sec) + (sec == 2 ? 100 : 0), Fp.P);
- rejected(b);
+ byte[] be = new byte[48];
+ for (int i = 0; i < 48; i++) be[47 - i] = b[offset + i];
+ BigInteger canonical = new BigInteger(1, be);
+ assertTrue(canonical.compareTo(Fp.P) < 0);
+ BigInteger alias = canonical.add(Fp.P);
+ assertTrue(alias.bitLength() <= 384);
+ assertEquals(canonical, alias.mod(Fp.P));
+ put(b, offset, alias);
+ rejected(b, "canonical");
}
- for (int length : new int[]{0, 4, 11, 15, original.length - 1})
- rejected(Arrays.copyOf(original, length));
+ }
+
+ @Test void rejectsMalformedStructure() throws IOException {
+ byte[] original = fixture();
+ for (int length : new int[]{0, 4, 11, 15})
+ rejected(Arrays.copyOf(original, length), "Truncated .zkey");
+ rejected(Arrays.copyOf(original, original.length - 1), "Invalid .zkey section");
byte[] b = original.clone();
ByteBuffer.wrap(b).order(ByteOrder.LITTLE_ENDIAN).putInt(4, 0);
- rejected(b);
- b = Arrays.copyOf(original, original.length + 1);
- rejected(b);
+ rejected(b, "version");
+ rejected(Arrays.copyOf(original, original.length + 1), "Trailing bytes");
b = original.clone();
ByteBuffer.wrap(b).order(ByteOrder.LITTLE_ENDIAN).putLong(16, Long.MAX_VALUE);
- rejected(b);
+ rejected(b, "Invalid .zkey section");
+ for (int type : new int[]{0, 11, Integer.MAX_VALUE}) {
+ b = original.clone();
+ ByteBuffer.wrap(b).order(ByteOrder.LITTLE_ENDIAN).putInt(section(b, 2) - 12, type);
+ rejected(b, "Unknown .zkey section");
+ }
}
@Test void pinsSourceAndStoreAndRejectsTampering() throws Exception {
@@ -113,6 +142,12 @@ void rejected(byte[] bytes) throws IOException {
assertEquals(expected, imported.sourceSha256());
var repeat = ZkeyPkStoreImporter.importToPkStore(input, tmp.resolve("repeat"), expected);
assertEquals(imported.manifestSha256(), repeat.manifestSha256(), "deterministic manifest");
+ byte[] sealed = Files.readAllBytes(store.resolve("manifest.properties"));
+ String fingerprint = "c1-w" + imported.numWires() + "-p" + imported.numPublic() + "-r" + "ab".repeat(32);
+ var sealedFailure = assertThrows(IOException.class,
+ () -> Groth16PkStore.bindCircuitFingerprint(store, fingerprint));
+ assertTrue(sealedFailure.getMessage().contains("sealed"));
+ assertArrayEquals(sealed, Files.readAllBytes(store.resolve("manifest.properties")));
try (var keys = Groth16Keys.load(store, imported.manifestSha256())) {
assertEquals(imported.numWires(), keys.numWires());
}
@@ -137,15 +172,23 @@ void rejected(byte[] bytes) throws IOException {
byte[] original = fixture();
byte[] b = original.clone();
ByteBuffer.wrap(b).order(ByteOrder.LITTLE_ENDIAN).putInt(section(b, 2) - 12, 1);
- rejected(b);
+ rejected(b, "Duplicate .zkey section");
b = original.clone();
ByteBuffer.wrap(b).order(ByteOrder.LITTLE_ENDIAN).putInt(section(b, 4) + 4, 3);
- rejected(b);
+ rejected(b, "Invalid coefficient index");
b = original.clone();
ByteBuffer.wrap(b).order(ByteOrder.LITTLE_ENDIAN).putInt(section(b, 4) + 8, Integer.MAX_VALUE);
- rejected(b);
+ rejected(b, "Invalid coefficient index");
b = original.clone();
ByteBuffer.wrap(b).order(ByteOrder.LITTLE_ENDIAN).putInt(section(b, 4) + 12, Integer.MAX_VALUE);
- rejected(b);
+ rejected(b, "Invalid coefficient index");
+ for (BigInteger value : new BigInteger[]{MontFr381.modulus(), MontFr381.modulus().add(BigInteger.ONE)}) {
+ b = original.clone();
+ int offset = section(b, 4) + 16; // count + first coefficient's three indices
+ byte[] be = value.toByteArray();
+ Arrays.fill(b, offset, offset + 32, (byte) 0);
+ for (int i = 0; i < Math.min(32, be.length); i++) b[offset + i] = be[be.length - 1 - i];
+ rejected(b, "Noncanonical coefficient");
+ }
}
}
diff --git a/zeroj-tools/src/main/java/org/zeroj/ceremony/CeremonyCli.java b/zeroj-tools/src/main/java/org/zeroj/ceremony/CeremonyCli.java
index b8c9f183..5854c297 100644
--- a/zeroj-tools/src/main/java/org/zeroj/ceremony/CeremonyCli.java
+++ b/zeroj-tools/src/main/java/org/zeroj/ceremony/CeremonyCli.java
@@ -4,6 +4,7 @@
import org.zeroj.circuit.CircuitBuilder;
import org.zeroj.circuit.r1cs.R1CSConstraintSystem;
import org.zeroj.crypto.groth16.R1csExporter;
+import org.zeroj.crypto.groth16.Groth16Pipeline;
import org.zeroj.crypto.groth16.ZkeyPkStoreImporter;
import org.zeroj.tools.zkey.ZkeyContributor;
import picocli.CommandLine;
@@ -157,18 +158,34 @@ static class Finalize implements Callable {
@Option(names = "--sha256", description = "Expected SHA-256 from a trusted ceremony manifest") String sha256;
@Option(names = "--allow-unpinned", description = "Explicit local/test import without source authentication") boolean allowUnpinned;
+ @Option(names = "--circuit-fingerprint", description = "Trusted exact R1CS fingerprint to bind before sealing (optional)")
+ String circuitFingerprint;
+
@Override
public Integer call() throws Exception {
+ if ((sha256 != null) == allowUnpinned) {
+ System.err.println("Choose exactly one of --sha256 or --allow-unpinned");
+ return 2;
+ }
+ if (sha256 != null && !sha256.matches("[0-9a-fA-F]{64}")) {
+ System.err.println("--sha256 must be exactly 64 hexadecimal characters");
+ return 2;
+ }
+ if (circuitFingerprint != null && !Groth16Pipeline.isExactFingerprint(circuitFingerprint)) {
+ System.err.println("--circuit-fingerprint must be an exact R1CS fingerprint");
+ return 2;
+ }
if (!Files.isReadable(zkey)) { System.err.println("Cannot read .zkey: " + zkey); return 2; }
System.out.printf("Importing %s (%,d bytes) -> %s ...%n", zkey, Files.size(zkey), pkStore);
long t0 = System.nanoTime();
- if ((sha256 == null) == !allowUnpinned) {
- System.err.println("Choose exactly one of --sha256 or --allow-unpinned");
- return 2;
+ ZkeyPkStoreImporter.Imported dims;
+ if (circuitFingerprint == null) {
+ dims = allowUnpinned ? ZkeyPkStoreImporter.importUnpinnedToPkStore(zkey, pkStore)
+ : ZkeyPkStoreImporter.importToPkStore(zkey, pkStore, sha256);
+ } else {
+ dims = allowUnpinned ? ZkeyPkStoreImporter.importUnpinnedToPkStore(zkey, pkStore, circuitFingerprint)
+ : ZkeyPkStoreImporter.importToPkStore(zkey, pkStore, sha256, circuitFingerprint);
}
- var dims = allowUnpinned
- ? ZkeyPkStoreImporter.importUnpinnedToPkStore(zkey, pkStore)
- : ZkeyPkStoreImporter.importToPkStore(zkey, pkStore, sha256);
System.out.println("Source SHA-256: " + dims.sourceSha256());
System.out.println("Manifest SHA-256 (retain via a trusted channel): " + dims.manifestSha256());
System.out.printf("Done in %.1fs: %,d wires | %d public | domain %,d%n",
diff --git a/zeroj-tools/src/test/java/org/zeroj/ceremony/CeremonyCliTest.java b/zeroj-tools/src/test/java/org/zeroj/ceremony/CeremonyCliTest.java
index d8f9c2cc..0edb100b 100644
--- a/zeroj-tools/src/test/java/org/zeroj/ceremony/CeremonyCliTest.java
+++ b/zeroj-tools/src/test/java/org/zeroj/ceremony/CeremonyCliTest.java
@@ -10,6 +10,7 @@
import org.zeroj.bls12381.pairing.BLS12381Pairing;
import org.zeroj.codec.SnarkjsJsonCodec;
import org.zeroj.crypto.groth16.Groth16PkStore;
+import org.zeroj.crypto.groth16.Groth16Pipeline;
import org.zeroj.crypto.groth16.Groth16ProverBLS381;
import org.zeroj.crypto.groth16.ProverBackend;
import org.zeroj.crypto.groth16.R1CSImporter;
@@ -19,12 +20,16 @@
import java.io.ByteArrayInputStream;
import java.io.IOException;
+import java.io.ByteArrayOutputStream;
+import java.io.PrintStream;
+import java.nio.charset.StandardCharsets;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.util.HexFormat;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
+import java.util.ArrayList;
import java.util.Map;
import java.util.concurrent.TimeUnit;
@@ -59,6 +64,31 @@ void missingArgs_failCleanly() {
assertEquals(2, CeremonyCli.run(new String[]{"export-r1cs", "--out", "x.r1cs"}));
}
+ @Test
+ void finalizeInvalidPolicyArguments_failBeforeImport(@TempDir Path dir) throws Exception {
+ Path input = dir.resolve("readable.zkey");
+ Files.write(input, new byte[]{0}); // must not reach the parser
+ Path store = dir.resolve("store");
+ for (List options : List.of(
+ List.of(),
+ List.of("--sha256", "00".repeat(32), "--allow-unpinned"),
+ List.of("--sha256", ""),
+ List.of("--sha256", "0".repeat(63)),
+ List.of("--sha256", "0".repeat(65)),
+ List.of("--sha256", "gg".repeat(32)),
+ List.of("--allow-unpinned", "--circuit-fingerprint", "c1-w4-p1"))) {
+ var args = new ArrayList<>(List.of("finalize", "--zkey", input.toString(), "--pk-store", store.toString()));
+ args.addAll(options);
+ var result = capture(args.toArray(String[]::new));
+ assertEquals(2, result.exitCode(), result.stderr());
+ assertEquals("", result.stdout(), "argument errors must precede Importing output");
+ assertFalse(result.stderr().contains("Exception"), result.stderr());
+ assertTrue(result.stderr().contains(options.contains("--circuit-fingerprint")
+ ? "exact R1CS" : options.size() == 2 ? "64 hexadecimal" : "Choose exactly one"), result.stderr());
+ assertFalse(Files.exists(store));
+ }
+ }
+
@Test
void fullOptionA_ceremonyViaCli_provesAndVerifies(@TempDir Path dir) throws Exception {
String snarkjs = findSnarkjs();
@@ -87,18 +117,27 @@ void fullOptionA_ceremonyViaCli_provesAndVerifies(@TempDir Path dir) throws Exce
assertEquals(2, CeremonyCli.run(new String[]{"finalize", "--allow-unpinned", "--sha256", sourceHash,
"--zkey", dir.resolve("key1.zkey").toString(), "--pk-store", store.toString()}));
assertFalse(Files.exists(store));
- assertEquals(0, CeremonyCli.run(new String[]{"finalize", "--sha256", sourceHash,
- "--zkey", dir.resolve("key1.zkey").toString(), "--pk-store", store.toString()}));
-
- // 4. prove from the store; verify against the snarkjs VK
var builder = MulFixtureCircuit.build();
var compiled = builder.compileR1CS(CurveId.BLS12_381);
+ String fingerprint = new Groth16Pipeline.Compiled(compiled.flat(), compiled.numConstraints(),
+ compiled.numWires(), compiled.numPublicInputs()).fingerprint();
+ var result = capture("finalize", "--sha256", sourceHash.toUpperCase(),
+ "--circuit-fingerprint", fingerprint,
+ "--zkey", dir.resolve("key1.zkey").toString(), "--pk-store", store.toString());
+ assertEquals(0, result.exitCode(), result.stderr());
+ String manifestPin = result.stdout().lines()
+ .filter(line -> line.startsWith("Manifest SHA-256 (retain via a trusted channel): "))
+ .map(line -> line.substring(line.lastIndexOf(' ') + 1)).findFirst().orElseThrow();
+ assertTrue(manifestPin.matches("[0-9a-f]{64}"));
+
+ // 4. prove from the store loaded with the exact pin returned by the CLI; verify snarkjs VK
BigInteger[] witness = builder.calculateWitness(Map.of(
"out", List.of(BigInteger.valueOf(33)),
"a", List.of(BigInteger.valueOf(3)),
"b", List.of(BigInteger.valueOf(11))), CurveId.BLS12_381);
- try (var loaded = Groth16PkStore.load(store)) {
+ try (var loaded = Groth16PkStore.load(store, manifestPin)) {
+ assertEquals(fingerprint, loaded.circuitFingerprint());
var cons = ZkeyPkStoreImporter.snarkjsConstraints(compiled.constraints(), compiled.numPublicInputs());
var proof = Groth16ProverBLS381.proveWithReaders(loaded.pk(), loaded.readers(),
ProverBackend.PURE_JAVA, witness, cons, compiled.numWires(), loaded.domain());
@@ -115,6 +154,25 @@ void fullOptionA_ceremonyViaCli_provesAndVerifies(@TempDir Path dir) throws Exce
// ---- helpers ----
+ private record CliResult(int exitCode, String stdout, String stderr) {}
+
+ private static CliResult capture(String... args) {
+ var stdout = new ByteArrayOutputStream();
+ var stderr = new ByteArrayOutputStream();
+ PrintStream previousOut = System.out;
+ PrintStream previousErr = System.err;
+ try (var out = new PrintStream(stdout, true, StandardCharsets.UTF_8);
+ var err = new PrintStream(stderr, true, StandardCharsets.UTF_8)) {
+ System.setOut(out);
+ System.setErr(err);
+ int exitCode = CeremonyCli.run(args);
+ return new CliResult(exitCode, stdout.toString(StandardCharsets.UTF_8), stderr.toString(StandardCharsets.UTF_8));
+ } finally {
+ System.setOut(previousOut);
+ System.setErr(previousErr);
+ }
+ }
+
private static String findSnarkjs() {
String prop = System.getProperty("zeroj.snarkjs");
for (String cand : new String[]{prop,