From d655ceb4397e7ab974c6dc5ce5355c7f2caf6003 Mon Sep 17 00:00:00 2001
From: Satya
Date: Fri, 20 Nov 2026 23:55:47 +0800
Subject: [PATCH 1/2] Harden ZkeyContributor pre-secret validation,
ctScalarMul, and CI snarkjs interop (ADR-0031)
---
.github/workflows/assurance.yml | 17 +-
...0031-groth16-mpc-trusted-setup-ceremony.md | 152 +++-
docs/ceremony/USER-GUIDE.md | 10 +-
zeroj-crypto/build.gradle | 7 +
.../R1csSnarkjsCeremonyRoundTripTest.java | 19 +-
.../groth16/ZkeyPkStoreImporterTest.java | 19 +-
.../crypto/testsupport/SnarkjsCliLocator.java | 165 +++++
zeroj-integration-tests/build.gradle | 3 +
.../examples/dsl/common/SnarkjsProver.java | 11 +-
zeroj-tools/build.gradle | 8 +
.../java/org/zeroj/ceremony/CeremonyCli.java | 16 +-
.../org/zeroj/tools/zkey/ZkeyContributor.java | 688 ++++++++++++++----
.../org/zeroj/ceremony/CeremonyCliTest.java | 44 +-
.../ceremony/ZkeyContributorInteropTest.java | 32 +-
.../zeroj/tools/zkey/ZkeyContributorTest.java | 670 +++++++++++++++++
15 files changed, 1685 insertions(+), 176 deletions(-)
create mode 100644 zeroj-crypto/src/testFixtures/java/org/zeroj/crypto/testsupport/SnarkjsCliLocator.java
create mode 100644 zeroj-tools/src/test/java/org/zeroj/tools/zkey/ZkeyContributorTest.java
diff --git a/.github/workflows/assurance.yml b/.github/workflows/assurance.yml
index 3cbdb2e5..457b6228 100644
--- a/.github/workflows/assurance.yml
+++ b/.github/workflows/assurance.yml
@@ -101,12 +101,18 @@ jobs:
# Both directions, with negatives: ZeroJ Groth16/PlonK proofs and ZeroJ-native verification
# keys are checked by `snarkjs groth16 verify` / `snarkjs plonk verify` (tampered proofs and
- # public inputs must be rejected), and live `snarkjs ... prove` output is checked by the
- # pure-Java and blst ZeroJ verifiers. -PrequireSnarkjs makes a missing oracle a failure.
- - name: Run the bidirectional interop suites
+ # public inputs must be rejected), live `snarkjs ... prove` output is checked by the
+ # pure-Java and blst ZeroJ verifiers, and the ADR-0031 ceremony / streaming .zkey interop
+ # suites exercise export-r1cs, contribute, snarkjs zkey verify, and finalize end to end.
+ # -PrequireSnarkjs makes a missing or wrong-version oracle a hard failure across all modules.
+ - name: Run the bidirectional and ceremony interop suites
run: |
./gradlew -PrequireSnarkjs \
:zeroj-integration-tests:test --tests 'org.zeroj.it.snarkjs.*' \
+ :zeroj-crypto:test --tests 'org.zeroj.crypto.groth16.R1csSnarkjsCeremonyRoundTripTest' \
+ --tests 'org.zeroj.crypto.groth16.ZkeyPkStoreImporterTest' \
+ :zeroj-tools:test --tests 'org.zeroj.ceremony.ZkeyContributorInteropTest' \
+ --tests 'org.zeroj.ceremony.CeremonyCliTest' \
--stacktrace
- name: Upload test reports
@@ -114,7 +120,10 @@ jobs:
uses: actions/upload-artifact@v4
with:
name: snarkjs-interop-test-reports
- path: 'zeroj-integration-tests/build/reports/tests/'
+ path: |
+ zeroj-integration-tests/build/reports/tests/
+ zeroj-crypto/build/reports/tests/
+ zeroj-tools/build/reports/tests/
retention-days: 14
gnark-fixtures:
diff --git a/docs/adr/0031-groth16-mpc-trusted-setup-ceremony.md b/docs/adr/0031-groth16-mpc-trusted-setup-ceremony.md
index b12832c0..38fc6f8c 100644
--- a/docs/adr/0031-groth16-mpc-trusted-setup-ceremony.md
+++ b/docs/adr/0031-groth16-mpc-trusted-setup-ceremony.md
@@ -2,8 +2,9 @@
## Status
-Proposed (2026-07-08) — planned on `feat/adr_0031_mpc_ceremony`. The **CLI
-artifact boundary** is superseded by
+Proposed (2026-07-08; amended 2026-11-20 for R3 contributor input validation, secret-scalar
+routing, atomic writes, and fail-closed CI interop) — planned on `feat/adr_0031_mpc_ceremony`. The
+**CLI artifact boundary** is superseded by
[ADR-0044](0044-focused-module-surface-and-optional-provider-isolation.md).
ADR-0044 merged the `zeroj-ceremony` Gradle module into `zeroj-tools`. This is a
@@ -198,3 +199,150 @@ proceed in parallel with the audit; only the production ceremony itself must wai
`.zkey` by SHA-256.
- The dev single-party path stays flag-gated (`zeroj.allowInsecureTrustedSetup`) and prints its
warning; production docs must point exclusively at the ceremony flow.
+
+---
+
+## 2026-11-20 Amendment — R3 Contributor Hardening & Fail-Closed CI Interop
+
+### Risk classification
+
+- **R3:** `ZkeyContributor` (`zeroj-tools`) applies contributor secret scalars (`k`, `k⁻¹`, `s`) to
+ untrusted elliptic-curve points read from an input `.zkey` file.
+- **R1 / Process:** Fail-closed CI execution of the four ceremony and streaming `.zkey`
+ interoperability suites against pinned `snarkjs@0.7.6`.
+
+### Threat model & trust assumptions
+
+1. **Untrusted input `.zkey`:** The input `.zkey` file supplied to `zeroj-ceremony contribute` is
+ treated as untrusted (for example, a compromised coordinator or malicious prior participant). An
+ attacker may inject off-curve points, small-subgroup (cofactor) points, non-canonical field
+ coordinates (`>= p`), identity `delta1`/`delta2`, mismatched `delta1`/`delta2` pairings, a broken
+ prior-contribution chain, malformed/overlapping section tables, or invalid TLV parameters.
+ Because short-Weierstrass Jacobian formulas do not depend on `b`, multiplying thousands of
+ unvalidated `L`/`H` points by the same secret `k⁻¹` via variable-time `scalarMul` creates an
+ invalid-curve and small-subgroup leakage surface against the contributor's secret.
+2. **Secret values & ADR-0062 I3 contract:** The freshly sampled scalars `k`, `k⁻¹ mod r`, and `s`
+ are secret. Routing all secret multiplications through `JacobianG1BLS381.ctScalarMul` /
+ `JacobianG2BLS381.ctScalarMul` ([ADR-0062](0062-bls12381-independent-review-and-remediation.md)
+ D1: Clavier–Joye additive scalar splitting + fixed-schedule Montgomery ladder + built-in on-curve
+ and prime-order subgroup check) removes variable-time bit-length/operation-schedule leakage and
+ blocks invalid-curve/subgroup inputs. Per **ADR-0062 I3**, this is **not** a JVM constant-time
+ guarantee (`BigInteger`, field reductions, Java branches, JIT, and GC remain variable-time);
+ production ceremony contributions MUST still run on an **offline, isolated host**.
+3. **Independent verification unchanged:** `snarkjs zkey verify` (`0.7.6`) remains the independent
+ verifier of the complete ceremony transcript. `zeroj-ceremony` implements `export-r1cs`,
+ `contribute`, and `finalize`; `verify` and `beacon` remain executed directly with `snarkjs`.
+
+### Pinned normative references
+
+- `snarkjs@0.7.6`: `src/zkey_contribute.js`, `src/zkey_utils.js`, `src/zkey_new.js`,
+ `src/zkey_verify_frominit.js`, `src/mpc_applykey.js`, `src/misc.js`.
+- `ffjavascript@0.3.1`: `src/wasm_curve.js` (LEM affine zero encoding `0^96` for G1 and `0^192` for
+ G2; `batchApplyKey` preserves infinity).
+- [ADR-0062](0062-bls12381-independent-review-and-remediation.md) (D1 `ctScalarMul`, I3 honest
+ secret-path contract, D7 raw pairing validation).
+- [ADR-0047](0047-snarkjs-bidirectional-interop-export-and-ci.md) (pinned `snarkjs@0.7.6` CI oracle
+ and `-PrequireSnarkjs`).
+
+### Exact security invariants (`S1`–`S7`)
+
+- **S1 — File & section table framing:** Require `inSize >= 12`, magic `0x79656b7a` (`"zkey"` LE),
+ version `∈ {1, 2}`, exactly 10 unique sections (`1..10`), no negative/out-of-bounds sizes, no
+ duplicate or unsupported section types, exact consumption (`pos == inSize`, zero trailing bytes),
+ section 1 size `== 4` with protocol `== 1` (Groth16), and section 2 size `== 964`.
+- **S2 — Exact BLS12-381 primes & section dimensions:** Require `n8q == 48`, exact unsigned LE
+ `q == MontFp381.modulus()`, `n8r == 32`, exact unsigned LE `r == MontFr381.modulus()`. Validate
+ `nVars >= 1`, `nVars >= nPublic + 1`, `domainSize` positive power of 2, exact section sizes for
+ sections 3 (`(nPublic + 1) * 96`), 4 (`4 + nCoeffs * 44`), 5 (`nVars * 96`), 6 (`nVars * 96`),
+ 7 (`nVars * 192`), 8 (`(nVars - nPublic - 1) * 96`), and 9 (`domainSize * 96`).
+- **S3 — Canonical Montgomery decoding & G2 infinity sentinel:** Decode every 48-byte LEM coordinate
+ via `MontFp381.fromMontLimbs(...)`, which rejects raw values `>= p` without silent modular
+ reduction. `g2FromLem` explicitly detects the 192-byte all-zero infinity sentinel and returns
+ `AffineG2.INFINITY`.
+- **S4 — Pre-secret header, pairing, and contribution chain validation:** Before sampling `k` or `s`:
+ - All six header points (`alpha1`, `beta1`, `beta2`, `gamma2`, `delta1`, `delta2`) and every prior
+ contribution's `deltaAfter`, `g1_s`, `g1_sx`, `g2_spx` MUST be canonical (`< p`), non-infinity,
+ on-curve, and in the prime-order subgroup (`[r]P = O`).
+ - Header deltas MUST satisfy `e(delta1, G2) == e(G1, delta2)`.
+ - Section 10 MUST be structurally exact (`size >= 68`, bounded `nContrib`, `type ∈ {0, 1}`,
+ strictly ascending TLV parameter tags `{1, 2, 3}` matching `snarkjs zkey_utils.js`, zero
+ trailing bytes).
+ - Chain continuity: `delta1` MUST equal `G1` when `nContrib == 0`, and MUST equal
+ `priors[nContrib - 1].deltaAfter` when `nContrib > 0` (matching
+ `snarkjs zkey_verify_frominit.js:48,141`).
+- **S5 — Pinned `snarkjs 0.7.6` infinity semantics for `L` and `H`:** Per `snarkjs@0.7.6`
+ (`zkey_new.js:460-466`, `mpc_applykey.js:44`) and `ffjavascript@0.3.1` (`wasm_curve.js`), the
+ all-zero 96-byte LEM infinity sentinel is legal in `L` (e.g. private wires unused in constraints)
+ and preserved unchanged (`k⁻¹ · O = O`, leaking zero bits of `k⁻¹`). Every non-infinity point in
+ `L` (section 8) and `H` (section 9) MUST have canonical `< p` coordinates, lie on BLS12-381 G1,
+ and lie in the prime-order subgroup. Any violation aborts the contribution with `IOException`.
+- **S6 — Secret-scalar routing (`ctScalarMul`):** Every multiplication by `s`, `k`, or `k⁻¹`
+ (`g1_s`, `g1_sx`, `g2_spx`, `delta1New`, `delta2New`, and every non-infinity `L`/`H` point) is
+ routed through `JacobianG1BLS381.ctScalarMul` / `JacobianG2BLS381.ctScalarMul`. For `L`/`H`,
+ validation relies on `ctScalarMul`'s built-in on-curve + prime-order subgroup check (avoiding a
+ duplicate subgroup check per point) and maps `IllegalArgumentException` across parallel worker
+ threads into a deterministic `IOException`.
+- **S7 — Atomic output writes, overwrite guard, and UTF-8 `--name` safety:**
+ - In-place overwrite (`in` and `out` resolving to the same file, including symlinks via
+ `Files.isSameFile`) is unconditionally rejected, even when overwrite is requested.
+ - Existing `out` is rejected by default (`ZkeyContributor.contribute(in, out, name)` and CLI
+ `contribute`) unless explicit `overwrite = true` / `--overwrite` is supplied.
+ - Output is written to a sibling temp file in `out`'s parent directory, forced to storage
+ (`FileChannel.force(true)`), unmapped/closed, and published atomically (`Files.createLink` for
+ non-clobbering publish when `!overwrite`, or `Files.move(..., ATOMIC_MOVE, REPLACE_EXISTING)`
+ when `overwrite`). On any error, the temp file is deleted and any existing `out` remains
+ untouched.
+ - `--name` truncates up to 64 code points and `<= 255` UTF-8 bytes on code-point boundaries,
+ matching `snarkjs 0.7.6` while preventing surrogate splits and 1-byte TLV length overflow.
+
+### Alternatives considered & measured performance trade-off
+
+- **Measured throughput (16-core Apple Silicon, Java 25, 4,096 affine G1 points after warmup):**
+ - Previous unvalidated variable-time `scalarMul`: **19,006 muls/s** (`0.216 s`).
+ - Hardened ADR-0062 `ctScalarMul` (includes single on-curve + subgroup check + additive scalar
+ splitting + 2×255 Montgomery ladder): **5,326 muls/s** (`0.769 s`), a **`3.57×`** factor.
+ - Extrapolated to a 19M-constraint circuit (~77M L+H points): ~**4.0 h** on 16 cores (vs ~1.1 h
+ unvalidated variable-time).
+- **Alternative rejected:** Inventing an unpinned batched subgroup test to skip per-point subgroup
+ checks in `L`/`H`. Rejected under `AGENTS.md` (do not invent cryptography; never trade
+ cryptographic soundness/secret safety for performance without an explicit reviewed design).
+
+### Compatibility & breaking notes
+
+- **Behavioral change:** `ZkeyContributor.contribute(Path, Path, String)` now throws `IOException`
+ if `out` already exists (previously it deleted `out` first). Callers intending replacement must
+ call `contribute(in, out, name, true)` or pass `--overwrite` to `zeroj-ceremony contribute`.
+ In-place `--in == --out` is always rejected.
+- **Stricter input validation:** Malformed or synthetic `.zkey` files with wrong primes, non-canonical
+ coordinates, invalid points, mismatched `delta1`/`delta2` pairings, or broken `deltaAfter` chains
+ are now rejected before secret generation.
+- **Wire compatibility:** Produced `.zkey` files remain 100% bit-compatible with `snarkjs@0.7.6`.
+
+### CI interop wiring
+
+- Shared test-fixture locator `SnarkjsCliLocator` (`zeroj-crypto` `testFixtures`, excluded from
+ published artifacts per ADR-0046) resolves `snarkjs@0.7.6` via `-Dzeroj.snarkjs`, `SNARKJS_BIN`,
+ `PATH`, and common npm directories.
+- `zeroj-crypto/build.gradle`, `zeroj-tools/build.gradle`, and `zeroj-integration-tests/build.gradle`
+ forward `-Dzeroj.snarkjs` and honor `-PrequireSnarkjs` (`zeroj.assurance.requireSnarkjs=true`,
+ disabling up-to-date caching).
+- `.github/workflows/assurance.yml` (`snarkjs-interop` job) runs all four ceremony / `.zkey` interop
+ suites (`R1csSnarkjsCeremonyRoundTripTest`, `ZkeyPkStoreImporterTest`,
+ `ZkeyContributorInteropTest`, `CeremonyCliTest`) fail-closed under `-PrequireSnarkjs`.
+
+### Amendment milestones & audit gates
+
+| Milestone | Scope | Status |
+|---|---|---|
+| M7 | Implement S1–S7 in `ZkeyContributor` and `CeremonyCli` (`--overwrite`) | Implemented |
+| M8 | Offline unit/negative test suite (`ZkeyContributorTest`) covering framing, primes, canonical `< p`, infinity, off-curve, small-subgroup, pairing mismatch, chain break, TLV, overwrite/atomic rollback | Implemented |
+| M9 | `SnarkjsCliLocator` + `-PrequireSnarkjs` + `assurance.yml` wiring for all 4 ceremony/streaming `.zkey` suites | Implemented |
+| M10 | External cryptographic review & ceremony rehearsal sign-off before production value-bearing ceremony | Open (mandatory gate) |
+
+### Revision history
+
+- **2026-07-08:** Initial `Proposed` ADR covering Option A/B ceremony architecture and M1–M6 results.
+- **2026-08-31:** CLI artifact boundary superseded by ADR-0044 (`zeroj-ceremony` merged into `zeroj-tools`).
+- **2026-11-20:** Added R3 contributor hardening amendment (`S1`–`S7`), measured `ctScalarMul`
+ throughput trade-off (`3.57×`), pinned `snarkjs@0.7.6` `L`/`H` infinity semantics, and fail-closed
+ CI interop wiring (`SnarkjsCliLocator` + `assurance.yml`). Status remains `Proposed` pending review.
diff --git a/docs/ceremony/USER-GUIDE.md b/docs/ceremony/USER-GUIDE.md
index 67783cd8..b5b72097 100644
--- a/docs/ceremony/USER-GUIDE.md
+++ b/docs/ceremony/USER-GUIDE.md
@@ -41,7 +41,8 @@ You received `key_N.zkey` from the ceremony coordinator, plus the published hash
# 1. check what you received matches what the coordinator published
shasum -a 256 key_N.zkey
-# 2. contribute (seconds for small circuits; ~1 h for a 19M-constraint circuit — multi-core)
+# 2. contribute (seconds for small circuits; ~4 h for a 19M-constraint circuit on 16 cores with
+# per-point subgroup validation and ADR-0062 ctScalarMul)
zeroj-ceremony contribute --in key_N.zkey --out key_N+1.zkey --name "your name / org"
# 3. record the Contribution Hash the tool prints — it goes in your attestation
@@ -54,10 +55,13 @@ zeroj-ceremony contribute --in key_N.zkey --out key_N+1.zkey --name "your name /
| option | required | meaning |
|---|---|---|
| `--in ` | yes | the `.zkey` you received |
-| `--out ` | yes | the `.zkey` you send back |
+| `--out ` | yes | the `.zkey` you send back (must not equal `--in`, and must not already exist unless `--overwrite` is passed) |
| `--name ` | no | recorded in the public transcript (default: "zeroj contributor") |
+| `--overwrite` | no | atomically replace an existing `--out` file (in-place `--in == --out` is always rejected) |
-Your randomness is drawn from the OS secure random source, used once, and never written anywhere.
+Your randomness is drawn from the OS secure random source, applied via ADR-0062 `ctScalarMul` after
+validating the input `.zkey`, used once, and never written anywhere. Run contributions on a
+dedicated, offline/isolated machine (pure-Java `ctScalarMul` is not a JVM constant-time guarantee).
The output is byte-compatible with snarkjs: anyone can independently check the whole ceremony with
`snarkjs zkey verify key_N+1.zkey` — the verifying tool is *not* ZeroJ.
diff --git a/zeroj-crypto/build.gradle b/zeroj-crypto/build.gradle
index d4870e25..6e87a5a6 100644
--- a/zeroj-crypto/build.gradle
+++ b/zeroj-crypto/build.gradle
@@ -30,6 +30,13 @@ test {
// zeroj-crypto still exercises legacy BN254 arithmetic/prover regression
// coverage. Runtime users must opt in explicitly to BN254.
systemProperty 'zeroj.allowLegacyBn254', 'true'
+ if (System.getProperty('zeroj.snarkjs') != null) {
+ systemProperty 'zeroj.snarkjs', System.getProperty('zeroj.snarkjs')
+ }
+ if (project.hasProperty('requireSnarkjs')) {
+ systemProperty 'zeroj.assurance.requireSnarkjs', 'true'
+ outputs.upToDateWhen { false }
+ }
}
// ADR-0027 M7: opt-in prover-scale benchmark. Heavy (minutes, multi-GB); never part of
diff --git a/zeroj-crypto/src/test/java/org/zeroj/crypto/groth16/R1csSnarkjsCeremonyRoundTripTest.java b/zeroj-crypto/src/test/java/org/zeroj/crypto/groth16/R1csSnarkjsCeremonyRoundTripTest.java
index bc6b8ec2..1f2e4942 100644
--- a/zeroj-crypto/src/test/java/org/zeroj/crypto/groth16/R1csSnarkjsCeremonyRoundTripTest.java
+++ b/zeroj-crypto/src/test/java/org/zeroj/crypto/groth16/R1csSnarkjsCeremonyRoundTripTest.java
@@ -10,6 +10,7 @@
import org.zeroj.bls12381.field.MontFr381;
import org.zeroj.bls12381.pairing.BLS12381Pairing;
import org.zeroj.codec.SnarkjsJsonCodec;
+import org.zeroj.crypto.testsupport.SnarkjsCliLocator;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
@@ -44,8 +45,7 @@ class R1csSnarkjsCeremonyRoundTripTest {
@Test
void zerojR1cs_snarkjsCeremony_zerojProve_verifies(@TempDir Path dir) throws Exception {
- String snarkjs = findSnarkjs();
- assumeTrue(snarkjs != null, "snarkjs not found (install snarkjs or set -Dzeroj.snarkjs)");
+ String snarkjs = requireSnarkjs();
// 1. a ZeroJ R1CS: squaring chain, 1 public input (wire 1 = final value)
int n = 64, numWires = n + 2, numPublic = 1;
@@ -116,14 +116,15 @@ private static BigInteger[] witness(int n) {
// ---- snarkjs exec ----
- private static String findSnarkjs() {
- String prop = System.getProperty("zeroj.snarkjs");
- for (String cand : new String[]{prop,
- System.getProperty("user.home") + "/.npm-global/bin/snarkjs",
- "/usr/local/bin/snarkjs", "/opt/homebrew/bin/snarkjs"}) {
- if (cand != null && Files.isExecutable(Path.of(cand))) return cand;
+ private static String requireSnarkjs() {
+ var res = SnarkjsCliLocator.resolvePinned();
+ if (!res.isReady()) {
+ if (SnarkjsCliLocator.isRequired()) {
+ fail(res.reason() + " — required by -PrequireSnarkjs");
+ }
+ assumeTrue(false, res.reason() + " — skipping");
}
- return null;
+ return res.binary();
}
private static void run(Path dir, String... cmd) throws IOException, InterruptedException {
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 93a082f2..aba41753 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
@@ -10,6 +10,7 @@
import org.zeroj.bls12381.field.MontFr381;
import org.zeroj.bls12381.pairing.BLS12381Pairing;
import org.zeroj.codec.SnarkjsJsonCodec;
+import org.zeroj.crypto.testsupport.SnarkjsCliLocator;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
@@ -38,8 +39,7 @@ class ZkeyPkStoreImporterTest {
@Test
void ceremonyZkey_streamImport_provesFromStore(@TempDir Path dir) throws Exception {
- String snarkjs = findSnarkjs();
- assumeTrue(snarkjs != null, "snarkjs not found");
+ String snarkjs = requireSnarkjs();
// snarkjs ceremony over an exported ZeroJ circuit (M1 flow)
int n = 64, numWires = n + 2, numPublic = 1;
@@ -126,14 +126,15 @@ private static BigInteger[] witness(int n) {
return w;
}
- private static String findSnarkjs() {
- String prop = System.getProperty("zeroj.snarkjs");
- for (String cand : new String[]{prop,
- System.getProperty("user.home") + "/.npm-global/bin/snarkjs",
- "/usr/local/bin/snarkjs", "/opt/homebrew/bin/snarkjs"}) {
- if (cand != null && Files.isExecutable(Path.of(cand))) return cand;
+ private static String requireSnarkjs() {
+ var res = SnarkjsCliLocator.resolvePinned();
+ if (!res.isReady()) {
+ if (SnarkjsCliLocator.isRequired()) {
+ fail(res.reason() + " — required by -PrequireSnarkjs");
+ }
+ assumeTrue(false, res.reason() + " — skipping");
}
- return null;
+ return res.binary();
}
private static void run(Path dir, String... cmd) throws IOException, InterruptedException {
diff --git a/zeroj-crypto/src/testFixtures/java/org/zeroj/crypto/testsupport/SnarkjsCliLocator.java b/zeroj-crypto/src/testFixtures/java/org/zeroj/crypto/testsupport/SnarkjsCliLocator.java
new file mode 100644
index 00000000..0e45e278
--- /dev/null
+++ b/zeroj-crypto/src/testFixtures/java/org/zeroj/crypto/testsupport/SnarkjsCliLocator.java
@@ -0,0 +1,165 @@
+package org.zeroj.crypto.testsupport;
+
+import java.io.File;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Locale;
+import java.util.Set;
+import java.util.concurrent.TimeUnit;
+import java.util.regex.Pattern;
+
+/**
+ * Discovers and version-checks the pinned {@code snarkjs} CLI for ceremony and {@code .zkey}
+ * interop tests (ADR-0031 / ADR-0047).
+ *
+ *
Discovery order:
+ *
+ *
{@code -Dzeroj.snarkjs} system property
+ *
{@code SNARKJS_BIN} environment variable
+ *
{@code PATH} entries
+ *
common global npm install directories ({@code ~/.npm-global/bin}, {@code /usr/local/bin},
+ * {@code /opt/homebrew/bin}, {@code ~/.nvm/versions/node/current/bin})
+ *
+ *
+ *
Locally, an absent binary or a version other than {@value #PINNED_VERSION} skips the suite;
+ * under {@code -PrequireSnarkjs} ({@value #REQUIRE_PROPERTY}={@code true}), both fail closed.
+ */
+public final class SnarkjsCliLocator {
+
+ private SnarkjsCliLocator() {}
+
+ /** Normative snarkjs version pinned by ADR-0047 and ADR-0031. */
+ public static final String PINNED_VERSION = "0.7.6";
+
+ /** System property set by Gradle {@code -PrequireSnarkjs}. */
+ public static final String REQUIRE_PROPERTY = "zeroj.assurance.requireSnarkjs";
+
+ /** Optional explicit binary override via system property. */
+ public static final String BIN_PROPERTY = "zeroj.snarkjs";
+
+ /** Optional explicit binary override via environment variable. */
+ public static final String BIN_ENV = "SNARKJS_BIN";
+
+ /** Resolution outcome: {@code binary != null} iff pinned snarkjs is ready to execute. */
+ public record Resolution(String binary, String version, String reason) {
+ public boolean isReady() {
+ return binary != null;
+ }
+ }
+
+ public static boolean isRequired() {
+ return Boolean.getBoolean(REQUIRE_PROPERTY);
+ }
+
+ /**
+ * Locate {@code snarkjs} and verify that {@code snarkjs --version} reports
+ * {@code snarkjs@0.7.6}.
+ */
+ public static Resolution resolvePinned() {
+ String expected = "snarkjs@" + PINNED_VERSION;
+ String wrongVersionFound = null;
+ String wrongVersionBin = null;
+
+ for (String candidate : candidateBinaries()) {
+ String detected = probeVersion(candidate);
+ if (expected.equals(detected)) {
+ return new Resolution(candidate, detected, null);
+ }
+ if (detected != null && wrongVersionFound == null) {
+ wrongVersionFound = detected;
+ wrongVersionBin = candidate;
+ }
+ }
+
+ if (wrongVersionFound != null) {
+ return new Resolution(null, wrongVersionFound,
+ "ADR-0047/ADR-0031 pin " + expected + " as the interop oracle, found "
+ + wrongVersionFound + " at " + wrongVersionBin);
+ }
+ return new Resolution(null, null,
+ "snarkjs " + PINNED_VERSION + " not found or not answering `--version` within 10 s "
+ + "(checked -D" + BIN_PROPERTY + ", " + BIN_ENV + ", PATH, and common npm bin dirs)");
+ }
+
+ private static List candidateBinaries() {
+ Set candidates = new LinkedHashSet<>();
+
+ String prop = System.getProperty(BIN_PROPERTY);
+ if (prop != null && !prop.isBlank()) {
+ candidates.add(prop.trim());
+ }
+ String envBin = System.getenv(BIN_ENV);
+ if (envBin != null && !envBin.isBlank()) {
+ candidates.add(envBin.trim());
+ }
+
+ boolean isWindows = System.getProperty("os.name", "").toLowerCase(Locale.ROOT).contains("win");
+ String[] exeNames = isWindows ? new String[]{"snarkjs.cmd", "snarkjs.exe", "snarkjs"} : new String[]{"snarkjs"};
+
+ String pathEnv = System.getenv("PATH");
+ if (pathEnv != null && !pathEnv.isBlank()) {
+ for (String dir : pathEnv.split(Pattern.quote(File.pathSeparator))) {
+ if (dir.isBlank()) continue;
+ for (String name : exeNames) {
+ Path p = Path.of(dir, name);
+ if (Files.isRegularFile(p) && Files.isExecutable(p)) {
+ candidates.add(p.toAbsolutePath().normalize().toString());
+ }
+ }
+ }
+ }
+
+ String home = System.getProperty("user.home", "");
+ String[] common = {
+ home + "/.npm-global/bin/snarkjs",
+ "/usr/local/bin/snarkjs",
+ "/opt/homebrew/bin/snarkjs",
+ home + "/.nvm/versions/node/current/bin/snarkjs"
+ };
+ for (String c : common) {
+ Path p = Path.of(c);
+ if (Files.isRegularFile(p) && Files.isExecutable(p)) {
+ candidates.add(p.toAbsolutePath().normalize().toString());
+ }
+ }
+
+ // Final fallback letting OS PATH resolution run directly if PATH scan missed a wrapper
+ candidates.add(isWindows ? "snarkjs.cmd" : "snarkjs");
+ return new ArrayList<>(candidates);
+ }
+
+ /**
+ * Runs {@code --version} (snarkjs exits 99 by design after printing its banner) and
+ * extracts the {@code snarkjs@} line, or returns {@code null} on failure/timeout.
+ */
+ static String probeVersion(String bin) {
+ try {
+ Path out = Files.createTempFile("snarkjs-version", ".txt");
+ try {
+ Process p = new ProcessBuilder(bin, "--version")
+ .redirectErrorStream(true)
+ .redirectOutput(out.toFile())
+ .start();
+ if (!p.waitFor(10, TimeUnit.SECONDS)) {
+ p.destroyForcibly();
+ return null;
+ }
+ for (String line : Files.readAllLines(out, StandardCharsets.UTF_8)) {
+ String trimmed = line.trim();
+ if (trimmed.startsWith("snarkjs@")) {
+ return trimmed;
+ }
+ }
+ return null;
+ } finally {
+ Files.deleteIfExists(out);
+ }
+ } catch (Exception e) {
+ return null;
+ }
+ }
+}
diff --git a/zeroj-integration-tests/build.gradle b/zeroj-integration-tests/build.gradle
index 3fd17e50..77dd1281 100644
--- a/zeroj-integration-tests/build.gradle
+++ b/zeroj-integration-tests/build.gradle
@@ -70,6 +70,9 @@ test {
// ADR-0047: the snarkjs interop suites (it.snarkjs.*) skip when snarkjs is absent locally. The
// assurance workflow passes -PrequireSnarkjs so that absence, or a snarkjs other than the pinned
// 0.7.6, fails the job instead of silently reducing the suite to its offline half.
+ if (System.getProperty('zeroj.snarkjs') != null) {
+ systemProperty 'zeroj.snarkjs', System.getProperty('zeroj.snarkjs')
+ }
if (project.hasProperty('requireSnarkjs')) {
systemProperty 'zeroj.assurance.requireSnarkjs', 'true'
// The oracle is an external binary Gradle cannot fingerprint: never report the interop run
diff --git a/zeroj-integration-tests/src/test/java/org/zeroj/examples/dsl/common/SnarkjsProver.java b/zeroj-integration-tests/src/test/java/org/zeroj/examples/dsl/common/SnarkjsProver.java
index 9e1f71e7..5648b4a7 100644
--- a/zeroj-integration-tests/src/test/java/org/zeroj/examples/dsl/common/SnarkjsProver.java
+++ b/zeroj-integration-tests/src/test/java/org/zeroj/examples/dsl/common/SnarkjsProver.java
@@ -43,16 +43,21 @@ public SnarkjsProver() {
* Find snarkjs binary by checking common locations.
*/
public static String findSnarkjs() {
- // 1. Environment variable
+ // 1. Explicit system property override
+ String propBin = System.getProperty("zeroj.snarkjs");
+ if (propBin != null && !propBin.isBlank()) return propBin.trim();
+
+ // 2. Environment variable
String envBin = System.getenv("SNARKJS_BIN");
- if (envBin != null && !envBin.isBlank()) return envBin;
+ if (envBin != null && !envBin.isBlank()) return envBin.trim();
- // 2. Common npm global install locations
+ // 3. Common npm global install locations
String home = System.getProperty("user.home");
String[] candidates = {
"snarkjs",
home + "/.npm-global/bin/snarkjs",
"/usr/local/bin/snarkjs",
+ "/opt/homebrew/bin/snarkjs",
home + "/.nvm/versions/node/current/bin/snarkjs",
};
for (String candidate : candidates) {
diff --git a/zeroj-tools/build.gradle b/zeroj-tools/build.gradle
index 9f3b1e0c..de14d39a 100644
--- a/zeroj-tools/build.gradle
+++ b/zeroj-tools/build.gradle
@@ -26,6 +26,7 @@ dependencies {
annotationProcessor 'info.picocli:picocli-codegen:4.7.6' // emits GraalVM reflection configs at compile time
testImplementation project(':zeroj-codec') // SnarkjsJsonCodec (VK parsing in the E2E test)
+ testImplementation testFixtures(project(':zeroj-crypto')) // SnarkjsCliLocator (ADR-0031/0047)
}
publishing {
@@ -131,4 +132,11 @@ tasks.register('nativeDistZip', Zip) {
test {
useJUnitPlatform()
systemProperty 'zeroj.allowInsecureTrustedSetup', 'true'
+ if (System.getProperty('zeroj.snarkjs') != null) {
+ systemProperty 'zeroj.snarkjs', System.getProperty('zeroj.snarkjs')
+ }
+ if (project.hasProperty('requireSnarkjs')) {
+ systemProperty 'zeroj.assurance.requireSnarkjs', 'true'
+ outputs.upToDateWhen { false }
+ }
}
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 5854c297..3b951a43 100644
--- a/zeroj-tools/src/main/java/org/zeroj/ceremony/CeremonyCli.java
+++ b/zeroj-tools/src/main/java/org/zeroj/ceremony/CeremonyCli.java
@@ -15,6 +15,7 @@
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Files;
+import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.util.concurrent.Callable;
@@ -117,13 +118,26 @@ static class Contribute implements Callable {
@Option(names = "--out", required = true, description = "Output .zkey") Path out;
@Option(names = "--name", defaultValue = "zeroj contributor", description = "Contributor name (in the transcript)")
String name;
+ @Option(names = "--overwrite", description = "Replace --out if it already exists (in-place --in == --out is always rejected)")
+ boolean overwrite;
@Override
public Integer call() throws Exception {
if (!Files.isReadable(in)) { System.err.println("Cannot read .zkey: " + in); return 2; }
+ Path inAbs = in.toAbsolutePath().normalize();
+ Path outAbs = out.toAbsolutePath().normalize();
+ boolean outExists = Files.exists(outAbs, LinkOption.NOFOLLOW_LINKS);
+ if ((outExists && Files.isSameFile(inAbs, outAbs)) || inAbs.equals(outAbs)) {
+ System.err.println("Refusing in-place overwrite: --in and --out refer to the same file: " + out);
+ return 2;
+ }
+ if (outExists && !overwrite) {
+ System.err.println("Output file already exists (pass --overwrite to replace): " + out);
+ return 2;
+ }
System.out.printf("Contributing to %s (%,d bytes) -> %s ...%n", in, Files.size(in), out);
long t0 = System.nanoTime();
- byte[] hash = ZkeyContributor.contribute(in, out, name);
+ byte[] hash = ZkeyContributor.contribute(in, out, name, overwrite);
System.out.printf("Done in %.1fs.%n", (System.nanoTime() - t0) / 1e9);
StringBuilder hex = new StringBuilder("Contribution Hash:\n\t\t");
for (int i = 0; i < hash.length; i++) {
diff --git a/zeroj-tools/src/main/java/org/zeroj/tools/zkey/ZkeyContributor.java b/zeroj-tools/src/main/java/org/zeroj/tools/zkey/ZkeyContributor.java
index e70ac1c1..bd12fdee 100644
--- a/zeroj-tools/src/main/java/org/zeroj/tools/zkey/ZkeyContributor.java
+++ b/zeroj-tools/src/main/java/org/zeroj/tools/zkey/ZkeyContributor.java
@@ -1,14 +1,19 @@
package org.zeroj.tools.zkey;
+import org.bouncycastle.crypto.digests.Blake2bDigest;
+import org.zeroj.bls12381.ec.G1Point;
+import org.zeroj.bls12381.ec.G2Point;
import org.zeroj.bls12381.ec.JacobianG1BLS381;
import org.zeroj.bls12381.ec.JacobianG1BLS381.AffineG1;
import org.zeroj.bls12381.ec.JacobianG2BLS381;
import org.zeroj.bls12381.ec.JacobianG2BLS381.AffineG2;
+import org.zeroj.bls12381.field.Fp;
+import org.zeroj.bls12381.field.Fp2;
import org.zeroj.bls12381.field.MontFp2_381;
import org.zeroj.bls12381.field.MontFp381;
import org.zeroj.bls12381.field.MontFr381;
+import org.zeroj.bls12381.pairing.BLS12381Pairing;
import org.zeroj.crypto.poly.FrFFTFlat;
-import org.bouncycastle.crypto.digests.Blake2bDigest;
import java.io.IOException;
import java.lang.foreign.Arena;
@@ -18,27 +23,40 @@
import java.nio.ByteOrder;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;
+import java.nio.file.AtomicMoveNotSupportedException;
+import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
+import java.nio.file.LinkOption;
import java.nio.file.Path;
+import java.nio.file.StandardCopyOption;
import java.nio.file.StandardOpenOption;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
+import java.util.Objects;
+import java.util.concurrent.atomic.AtomicReference;
/**
- * ZeroJ-native Groth16 phase-2 contributor (ADR-0031 M5, Option B) — a bit-compatible
- * reimplementation of {@code snarkjs zkey contribute}: reads a ceremony {@code .zkey}, applies a
- * fresh secret {@code k} (delta ← k·delta in the header; every L- and H-section point ← k⁻¹·point,
- * multi-core), and appends the BGM17 proof-of-knowledge record to the contributions section — in
- * the exact snarkjs byte format, so the resulting transcript still verifies with stock
- * {@code snarkjs zkey verify} and further snarkjs contributions can stack on top.
+ * ZeroJ-native Groth16 phase-2 contributor (ADR-0031 M5 & 2026-11-20 R3 hardening amendment) —
+ * a bit-compatible reimplementation of {@code snarkjs zkey contribute}: validates untrusted input
+ * {@code .zkey} structure and group elements, applies a fresh secret {@code k} via ADR-0062
+ * {@code ctScalarMul} (delta ← k·delta in the header; every non-infinity L- and
+ * H-section point ← k&supmin;¹·point, multi-core), and appends the BGM17
+ * proof-of-knowledge record to the contributions section — in the exact snarkjs 0.7.6 byte format,
+ * so the resulting transcript still verifies with stock {@code snarkjs zkey verify} and further
+ * snarkjs contributions can stack on top.
+ *
+ *
Side-channel contract (ADR-0062 I3): All multiplications by secret scalars ({@code k},
+ * {@code k⁻¹}, {@code s}) use {@link JacobianG1BLS381#ctScalarMul} /
+ * {@link JacobianG2BLS381#ctScalarMul} (additive scalar splitting + fixed-schedule Montgomery
+ * ladder). This is not a JVM constant-time guarantee; ceremony contributions must still run
+ * on an offline, isolated host.
*
*
The challenge point is derived via {@link SnarkjsHashToG2} over the blake2b-512 transcript
- * (csHash ‖ prior contributions ‖ s-pair), mirroring snarkjs exactly. The contributor's secret
- * {@code k} and the s-pair base come from {@link SecureRandom} (no compatibility requirement —
- * only the challenge derivation must match).
+ * ({@code csHash ‖ prior contributions ‖ s-pair}), mirroring snarkjs 0.7.6 exactly. The
+ * contributor's secret {@code k} and the s-pair base come from {@link SecureRandom}.
*/
public final class ZkeyContributor {
@@ -47,136 +65,343 @@ private ZkeyContributor() {}
private static final ValueLayout.OfInt U32 = ValueLayout.JAVA_INT_UNALIGNED.withOrder(ByteOrder.LITTLE_ENDIAN);
private static final ValueLayout.OfLong U64 = ValueLayout.JAVA_LONG_UNALIGNED.withOrder(ByteOrder.LITTLE_ENDIAN);
+ private static final int ZKEY_MAGIC = 0x79656b7a; // "zkey" little-endian
+ private static final int GROTH16_PROTOCOL = 1;
+ private static final int REQUIRED_SECTIONS = 10;
+ private static final long MIN_CONTRIBUTION_BYTES = 96 + 96 + 96 + 192 + 64 + 4 + 4; // 552
+
private static final BigInteger P = MontFp381.modulus();
private static final BigInteger R_FR = MontFr381.modulus();
- private static final BigInteger MONT_R = BigInteger.ONE.shiftLeft(384).mod(P);
- private static final BigInteger MONT_R_INV = MONT_R.modInverse(P);
+ private static final G1Point G1_GENERATOR = toG1Point(JacobianG1BLS381.GENERATOR.toAffine());
+ private static final G2Point G2_GENERATOR = toG2Point(JacobianG2BLS381.GENERATOR.toAffine());
+
+ // Section-2 Groth16 BLS12-381 header offsets (fixed layout, validated on read)
+ private static final long H_N8Q = 0;
+ private static final long H_Q = 4;
+ private static final long H_N8R = 52;
+ private static final long H_R = 56;
+ private static final long H_NVARS = 88;
+ private static final long H_NPUBLIC = 92;
+ private static final long H_DOMAIN_SIZE = 96;
+ private static final long H_ALPHA1 = 100;
+ private static final long H_BETA1 = 196;
+ private static final long H_BETA2 = 292;
+ private static final long H_GAMMA2 = 484;
+ private static final long H_DELTA1 = 676;
+ private static final long H_DELTA2 = 772;
+ private static final long HEADER_LEN = 964;
+
+ private record PriorContribution(
+ AffineG1 deltaAfter,
+ AffineG1 g1s,
+ AffineG1 g1sx,
+ AffineG2 g2spx,
+ byte[] transcript,
+ byte[] rawBytes) {}
+
+ /**
+ * Contribute to {@code in} and atomically write the updated {@code .zkey} to {@code out}.
+ * Fails if {@code out} already exists or resolves to {@code in}.
+ *
+ * @return the contribution hash (blake2b-512 of the new record's public key) — publish it.
+ */
+ public static byte[] contribute(Path in, Path out, String name) throws IOException {
+ return contribute(in, out, name, false);
+ }
- // section-2 offsets (fixed layout, validated on read)
- private static final long H_DELTA1 = 676, H_DELTA2 = 772, HEADER_LEN = 964;
+ /**
+ * Contribute to {@code in} and atomically write the updated {@code .zkey} to {@code out}.
+ *
+ * @param overwrite if {@code false}, fails when {@code out} already exists. In-place overwrite
+ * ({@code in} and {@code out} resolving to the same file) is always rejected.
+ * @return the contribution hash (blake2b-512 of the new record's public key) — publish it.
+ */
+ public static byte[] contribute(Path in, Path out, String name, boolean overwrite) throws IOException {
+ Objects.requireNonNull(in, "in");
+ Objects.requireNonNull(out, "out");
+
+ Path inAbs = in.toAbsolutePath().normalize();
+ Path outAbs = out.toAbsolutePath().normalize();
+ Path outDir = outAbs.getParent();
+ if (outDir == null || !Files.isDirectory(outDir)) {
+ throw new IOException("Output parent directory does not exist: " + outDir);
+ }
+ if (Files.isDirectory(outAbs)) {
+ throw new IOException("Output path is a directory: " + out);
+ }
+ boolean outExists = Files.exists(outAbs, LinkOption.NOFOLLOW_LINKS);
+ if (outExists) {
+ if (Files.exists(inAbs) && Files.isSameFile(inAbs, outAbs)) {
+ throw new IOException("Refusing in-place overwrite: --in and --out refer to the same file: " + out);
+ }
+ if (!overwrite) {
+ throw new IOException("Output file already exists (pass --overwrite / overwrite=true to replace): " + out);
+ }
+ } else if (inAbs.equals(outAbs)) {
+ throw new IOException("Refusing in-place overwrite: --in and --out refer to the same path: " + out);
+ }
- /** @return the contribution hash (blake2b-512 of the new record's public key) — publish it. */
- public static byte[] contribute(Path in, Path out, String name) throws IOException {
- try (FileChannel inCh = FileChannel.open(in, StandardOpenOption.READ);
- Arena arena = Arena.ofShared()) {
+ try (FileChannel inCh = FileChannel.open(inAbs, StandardOpenOption.READ);
+ Arena inArena = Arena.ofShared()) {
long inSize = inCh.size();
- MemorySegment z = inCh.map(FileChannel.MapMode.READ_ONLY, 0, inSize, arena);
+ if (inSize < 12) {
+ throw new IOException("Truncated .zkey file: " + inSize + " bytes");
+ }
+ MemorySegment z = inCh.map(FileChannel.MapMode.READ_ONLY, 0, inSize, inArena);
+
+ // ---- S1: file header and section table framing ----
+ if (z.get(U32, 0) != ZKEY_MAGIC) {
+ throw new IOException("Invalid .zkey magic");
+ }
+ int version = z.get(U32, 4);
+ if (version != 1 && version != 2) {
+ throw new IOException("Unsupported .zkey version: " + version);
+ }
+ long nSectionsLong = Integer.toUnsignedLong(z.get(U32, 8));
+ if (nSectionsLong != REQUIRED_SECTIONS) {
+ throw new IOException("Expected " + REQUIRED_SECTIONS + " Groth16 .zkey sections, got " + nSectionsLong);
+ }
- if (z.get(U32, 0) != 0x79656b7a) throw new IOException("Invalid .zkey magic");
- int nSections = z.get(U32, 8);
Map sec = new HashMap<>();
long pos = 12;
- for (int i = 0; i < nSections; i++) {
+ for (int i = 0; i < REQUIRED_SECTIONS; i++) {
+ if (pos > inSize - 12) {
+ throw new IOException("Truncated .zkey section header at index " + i);
+ }
int type = z.get(U32, pos);
long size = z.get(U64, pos + 4);
pos += 12;
- sec.put(type, new long[]{pos, size});
+ if (size < 0 || size > inSize - pos) {
+ throw new IOException("Out-of-bounds .zkey section " + type + " size: " + size);
+ }
+ if (type < 1 || type > REQUIRED_SECTIONS) {
+ throw new IOException("Unsupported .zkey section type: " + type);
+ }
+ if (sec.put(type, new long[]{pos, size}) != null) {
+ throw new IOException("Duplicate .zkey section " + type);
+ }
pos += size;
}
- for (int s : new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10})
- if (!sec.containsKey(s)) throw new IOException("Missing .zkey section " + s);
- if (z.get(U32, sec.get(1)[0]) != 1) throw new IOException("Not a Groth16 .zkey");
- if (sec.get(2)[1] != HEADER_LEN) throw new IOException("Unexpected Groth16 header length");
+ if (pos != inSize) {
+ throw new IOException("Trailing bytes after .zkey sections: " + (inSize - pos) + " extra bytes");
+ }
+ for (int s = 1; s <= REQUIRED_SECTIONS; s++) {
+ if (!sec.containsKey(s)) {
+ throw new IOException("Missing .zkey section " + s);
+ }
+ }
+ if (sec.get(1)[1] != 4 || z.get(U32, sec.get(1)[0]) != GROTH16_PROTOCOL) {
+ throw new IOException("Not a Groth16 .zkey");
+ }
+ if (sec.get(2)[1] != HEADER_LEN) {
+ throw new IOException("Unexpected Groth16 header length: " + sec.get(2)[1]);
+ }
+
+ // ---- S2: exact BLS12-381 primes and section dimensions ----
long h = sec.get(2)[0];
- if (z.get(U32, h) != 48 || z.get(U32, h + 52) != 32)
- throw new IOException("Not a BLS12-381 .zkey");
+ if (z.get(U32, h + H_N8Q) != 48 || z.get(U32, h + H_N8R) != 32) {
+ throw new IOException("Not a BLS12-381 .zkey (unexpected prime byte lengths)");
+ }
+ if (!P.equals(readUnsignedLE(z, h + H_Q, 48))) {
+ throw new IOException("Not a BLS12-381 .zkey (base field prime q mismatch)");
+ }
+ if (!R_FR.equals(readUnsignedLE(z, h + H_R, 32))) {
+ throw new IOException("Not a BLS12-381 .zkey (scalar field prime r mismatch)");
+ }
+
+ long nVars = Integer.toUnsignedLong(z.get(U32, h + H_NVARS));
+ long nPublic = Integer.toUnsignedLong(z.get(U32, h + H_NPUBLIC));
+ long domainSize = Integer.toUnsignedLong(z.get(U32, h + H_DOMAIN_SIZE));
+ if (nVars < 1 || nVars < nPublic + 1) {
+ throw new IOException("Invalid Groth16 header dimensions: nVars=" + nVars + ", nPublic=" + nPublic);
+ }
+ if (domainSize == 0 || (domainSize & (domainSize - 1)) != 0 || domainSize > Integer.MAX_VALUE) {
+ throw new IOException("Invalid Groth16 domainSize: " + domainSize);
+ }
+ long nL = nVars - nPublic - 1;
+ if (nL > Integer.MAX_VALUE) {
+ throw new IOException("L section point count exceeds int range: " + nL);
+ }
- AffineG1 delta1 = g1FromLem(z, h + H_DELTA1);
- AffineG2 delta2 = g2FromLem(z, h + H_DELTA2);
+ validateSectionSize(sec, 3, (nPublic + 1L) * 96L, "IC");
+ validateCoeffsSection(z, sec.get(4));
+ validateSectionSize(sec, 5, nVars * 96L, "A");
+ validateSectionSize(sec, 6, nVars * 96L, "B1");
+ validateSectionSize(sec, 7, nVars * 192L, "B2");
+ validateSectionSize(sec, 8, nL * 96L, "L");
+ validateSectionSize(sec, 9, domainSize * 96L, "H");
+
+ // ---- S3 & S4: pre-secret header, delta pairing, and contribution chain validation ----
+ requireNonIdentitySubgroupG1(z, h + H_ALPHA1, "header.alpha1");
+ requireNonIdentitySubgroupG1(z, h + H_BETA1, "header.beta1");
+ requireNonIdentitySubgroupG2(z, h + H_BETA2, "header.beta2");
+ requireNonIdentitySubgroupG2(z, h + H_GAMMA2, "header.gamma2");
+ AffineG1 delta1 = requireNonIdentitySubgroupG1(z, h + H_DELTA1, "header.delta1");
+ AffineG2 delta2 = requireNonIdentitySubgroupG2(z, h + H_DELTA2, "header.delta2");
+
+ if (!BLS12381Pairing.pairingCheck(
+ new G1Point[]{toG1Point(delta1), G1_GENERATOR.negate()},
+ new G2Point[]{G2_GENERATOR, toG2Point(delta2)})) {
+ throw new IOException("Header delta1 and delta2 fail pairing check e(delta1, G2) == e(G1, delta2)");
+ }
- // section 10: csHash + prior contribution records (raw for copy, parsed for hashing)
long s10 = sec.get(10)[0];
+ long s10Size = sec.get(10)[1];
+ long s10End = s10 + s10Size;
+ if (s10Size < 68) {
+ throw new IOException("Truncated .zkey contributions section: " + s10Size + " bytes");
+ }
byte[] csHash = bytes(z, s10, 64);
- int nContrib = z.get(U32, s10 + 64);
+ long nContribLong = Integer.toUnsignedLong(z.get(U32, s10 + 64));
+ long maxContribs = (s10Size - 68) / MIN_CONTRIBUTION_BYTES;
+ if (nContribLong > maxContribs) {
+ throw new IOException("Invalid prior contribution count " + nContribLong
+ + " for section size " + s10Size);
+ }
+ int nContrib = (int) nContribLong;
long rp = s10 + 68;
- List priorRaw = new ArrayList<>();
- List