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..9daf76ee 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 @@ -166,7 +167,7 @@ that stays with the circuit's ceremony (minimum viable: coordinator contribution | M2 | `ZkeyPkStoreImporter` — streaming (mmap) ceremony-`.zkey` → `Groth16PkStore`; bit-identical to the strict importer; `snarkjsConstraints()` binding-row synthesis asserted against real zkeys (which store only the A/B matrices — provers derive C=A·B) | | M3 | phase-1 decision: **Filecoin PoT primary**, own-ptau fallback (measured table above) | | M4 | `zeroj-ceremony` CLI (picocli; GraalVM configs auto-emitted; `contribute`/`finalize` native-friendly) + Option-A runbook; full ceremony driven through the CLI **green** | -| M5 | **ZeroJ-native contributor, snarkjs-verified**: `contribute` writes snarkjs-format `.zkey`; interop test: zeroj → `snarkjs zkey verify` OK → snarkjs stacks on top → second zeroj contribution → verify OK → proves. Measured **23.3k parallel G1 muls/s → a 19M-circuit contribution ≈ 0.9 h** (vs ~2.5–3 h Node) | +| M5 | **ZeroJ-native contributor, snarkjs-verified**: `contribute` writes snarkjs-format `.zkey`; interop test: zeroj → `snarkjs zkey verify` OK → snarkjs stacks on top → second zeroj contribution → verify OK → proves. Initial unvalidated variable-time measurement: **23.3k parallel G1 muls/s → ≈ 0.9 h** (vs ~2.5–3 h Node) — *superseded by the 2026-11-20 R3 hardening amendment measurement below (~4.0 h on 16 cores with per-point subgroup validation and `ctScalarMul`)* | | M6 | **rehearsal ceremony green** (`docs/ceremony/rehearsal.sh`): mixed tooling (2 ZeroJ + 1 snarkjs), beacon, independent `zkey verify`, finalize → PkStore | **Bug-compatibility findings** (the two subtleties that make Option B possible, documented in code): @@ -198,3 +199,166 @@ 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`, `nContrib < 2³² − 1` so `nContrib + 1` + fits uint32, bounded against section size, `type ∈ {0, 1}`, strictly ascending TLV parameter + tags `{1, 2, 3}` matching `snarkjs zkey_utils.js`, zero trailing bytes). Section 10 transcript + hashing is streamed in `O(1)` heap memory (no per-record `ArrayList` or `byte[]` buffering), + and the validated prior-record byte range is copied directly from the input mapping into the + output mapping. + - 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. These per-point `L`/`H` checks run during rescaling right + before each secret multiplication (`ctScalarMul`); any violation aborts with `IOException` and + deletes the staging temp file without touching `out`. +- **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, POSIX permissions, and UTF-16 `--name` parity:** + - 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, mapped content is forced + (`MemorySegment.force()`), the channel is forced (`FileChannel.force(true)`), POSIX mode bits + are copied from `in` on POSIX filesystems (so public `.zkey` files are not restricted to + `0600`), and publication fails closed if the filesystem cannot honor the requested guarantee: + - `!overwrite`: publishes via `Files.createLink(out, tmp)` (atomic non-clobbering; fails closed + if `out` already exists or hard links are unsupported — never degrades to check-then-move), + then unlinks `tmp` in a separate post-publish step. + - `overwrite`: publishes via `Files.move(tmp, out, ATOMIC_MOVE, REPLACE_EXISTING)` (fails closed + if atomic move is unsupported — never degrades to non-atomic move). + - On any error before publish succeeds, `tmp` is deleted and any existing `out` stays untouched. + - `--name` matches `snarkjs@0.7.6` (`new TextEncoder("utf-8").encode(c.name.substring(0, 64))`) + bit-for-bit: truncates at 64 UTF-16 code units and replaces any unpaired surrogate (including + one produced at index 64) with `U+FFFD` (`EF BF BD`) before UTF-8 encoding (max 192 bytes, so + the 1-byte TLV length cannot 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:** Header framing, primes, header VK points, `delta1`/`delta2` + pairing, and Section 10 prior records/chains are validated and fail closed **before** secret + generation (`k`/`s`); `L` and `H` points are validated per point (canonical `< p`, on-curve, + prime-order subgroup inside `ctScalarMul`) during rescaling before each secret multiplication. +- **Wire compatibility:** Produced `.zkey` files (including UTF-16 `--name` truncation with + `U+FFFD` replacement) 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` across `zeroj-crypto`, `zeroj-tools`, + and `zeroj-integration-tests`. Explicit `-Dzeroj.snarkjs` and `SNARKJS_BIN` overrides are + authoritative (failing closed if missing or wrong version rather than falling through to `PATH`); + otherwise discovery searches `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..aa5b6e0d 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. @@ -164,8 +168,10 @@ I confirm the entropy was generated fresh and destroyed after use. - **Do I have to trust this tool?** No — verification is always done with *snarkjs* (`zkey verify`), which independently re-checks every contribution including ZeroJ-made ones. -- **zeroj-ceremony or snarkjs for contributing?** Identical result; ZeroJ is ~3× faster on large - circuits (measured: ~0.9 h vs ~2.5–3 h for a 19M-constraint key) and ships as a single binary. +- **zeroj-ceremony or snarkjs for contributing?** Bit-compatible result; `zeroj-ceremony` ships as + a single native/JVM binary with pre-secret validation and per-point subgroup checks via ADR-0062 + `ctScalarMul` (~4.0 h extrapolated on 16 cores for a 19M-constraint key, vs ~2.5–3 h for + `snarkjs` on Node). Use whichever fits your contributor environment. - **How much machine do I need?** Contributing needs modest memory (the tool streams the file); disk = ~2× the `.zkey` size. A 19M-constraint key is ~30 GB. - **What must I keep secret?** Nothing after you finish — your randomness is used and discarded. diff --git a/www/src/content/docs/guides/proving/trusted-setup-ceremony.mdx b/www/src/content/docs/guides/proving/trusted-setup-ceremony.mdx index 04954388..9af79141 100644 --- a/www/src/content/docs/guides/proving/trusted-setup-ceremony.mdx +++ b/www/src/content/docs/guides/proving/trusted-setup-ceremony.mdx @@ -140,14 +140,18 @@ shasum -a 256 key_0008.zkey | 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 | Your name in the public transcript (default `zeroj contributor`) | +| `--overwrite` | no | Atomically replace an existing `--out` file (in-place `--in == --out` is always rejected) | -The tool draws your secret from the OS secure random source, uses it once, and never writes it -anywhere. It prints a **Contribution Hash**; copy it into your attestation. The equivalent snarkjs -command is `snarkjs zkey contribute key_0007.zkey key_0008.zkey --name="..."`. ZeroJ's -documentation reports its contributor at roughly 0.9 hours versus 2.5 to 3 hours for snarkjs on a -19M-constraint key (about 30 GB); budget about twice the `.zkey` size in free disk. +The tool validates the input `.zkey`, draws your secret from the OS secure random source, applies +it via ADR-0062 `ctScalarMul`, uses it once, and never writes it anywhere. Run contributions on an +**offline, isolated machine** (pure-Java `ctScalarMul` is not a JVM constant-time guarantee). It +prints a **Contribution Hash**; copy it into your attestation. The equivalent snarkjs command is +`snarkjs zkey contribute key_0007.zkey key_0008.zkey --name="..."`. With per-point subgroup +validation and `ctScalarMul`, ZeroJ's contributor extrapolates to roughly 4.0 hours on 16 cores +(versus roughly 2.5 to 3 hours for snarkjs) on a 19M-constraint key (about 30 GB); budget about +twice the `.zkey` size in free disk. **Publish an attestation**, for example as a gist or a pull request to the ceremony's transcript repository: @@ -166,7 +170,9 @@ After contributing there's nothing left to keep secret. What matters is that nob machine during the contribution. To embed contributions in your own service or wallet, `zeroj-tools` exposes the same step as a -library call: `ZkeyContributor.contribute(in, out, name)` returns the contribution hash. +library call: `ZkeyContributor.contribute(in, out, name)` fails if `out` already exists (or +resolves to `in`) and returns the contribution hash; pass `ZkeyContributor.contribute(in, out, name, true)` +to atomically replace an existing `out` file (in-place overwrite is still rejected). ## Close the ceremony (coordinator) 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/test/java/org/zeroj/crypto/testsupport/SnarkjsCliLocatorTest.java b/zeroj-crypto/src/test/java/org/zeroj/crypto/testsupport/SnarkjsCliLocatorTest.java new file mode 100644 index 00000000..df6eba92 --- /dev/null +++ b/zeroj-crypto/src/test/java/org/zeroj/crypto/testsupport/SnarkjsCliLocatorTest.java @@ -0,0 +1,48 @@ +package org.zeroj.crypto.testsupport; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import java.nio.file.Files; +import java.nio.file.Path; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class SnarkjsCliLocatorTest { + + @Test + void explicitPropertyMissing_doesNotFallThroughToPath(@TempDir Path dir) { + Path missing = dir.resolve("does-not-exist-snarkjs"); + var res = SnarkjsCliLocator.resolvePinned(missing.toString(), null); + assertFalse(res.isReady(), "explicit -Dzeroj.snarkjs must be authoritative"); + assertNull(res.binary()); + assertTrue(res.reason().contains("-Dzeroj.snarkjs"), res.reason()); + } + + @Test + void explicitEnvWrongVersion_doesNotFallThroughToPath(@TempDir Path dir) throws Exception { + Path fake = dir.resolve("fake-snarkjs.sh"); + Files.writeString(fake, "#!/bin/sh\necho 'snarkjs@0.9.9'\nexit 99\n"); + fake.toFile().setExecutable(true); + + var res = SnarkjsCliLocator.resolvePinned(null, fake.toString()); + assertFalse(res.isReady(), "explicit SNARKJS_BIN wrong version must fail closed"); + assertEquals("snarkjs@0.9.9", res.version()); + assertTrue(res.reason().contains("SNARKJS_BIN") && res.reason().contains("0.7.6"), res.reason()); + } + + @Test + void explicitPropertyPinnedVersion_succeeds(@TempDir Path dir) throws Exception { + Path fake = dir.resolve("pinned-snarkjs.sh"); + Files.writeString(fake, "#!/bin/sh\necho 'snarkjs@0.7.6'\nexit 99\n"); + fake.toFile().setExecutable(true); + + var res = SnarkjsCliLocator.resolvePinned(fake.toString(), null); + assertTrue(res.isReady(), res.reason()); + assertEquals(fake.toString(), res.binary()); + assertEquals("snarkjs@0.7.6", res.version()); + } +} 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..109f2568 --- /dev/null +++ b/zeroj-crypto/src/testFixtures/java/org/zeroj/crypto/testsupport/SnarkjsCliLocator.java @@ -0,0 +1,181 @@ +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; + +/** + * Shared locator and version validator for the pinned {@code snarkjs} CLI used across ceremony, + * streaming {@code .zkey}, and bidirectional interop tests (ADR-0031 / ADR-0047). + * + *

Discovery order: + *

    + *
  1. {@code -Dzeroj.snarkjs} system property (authoritative if set — never falls through)
  2. + *
  3. {@code SNARKJS_BIN} environment variable (authoritative if set — never falls through)
  4. + *
  5. {@code PATH} entries
  6. + *
  7. common global npm install directories ({@code ~/.npm-global/bin}, {@code /usr/local/bin}, + * {@code /opt/homebrew/bin}, {@code ~/.nvm/versions/node/current/bin})
  8. + *
+ * + *

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}. Explicit overrides ({@code -Dzeroj.snarkjs} or {@code SNARKJS_BIN}) + * are authoritative and do not fall through to {@code PATH} if missing or wrong-version. + */ + public static Resolution resolvePinned() { + return resolvePinned(System.getProperty(BIN_PROPERTY), System.getenv(BIN_ENV)); + } + + static Resolution resolvePinned(String explicitProp, String explicitEnv) { + String expected = "snarkjs@" + PINNED_VERSION; + + if (explicitProp != null && !explicitProp.isBlank()) { + return resolveAuthoritative(explicitProp.trim(), "-D" + BIN_PROPERTY, expected); + } + if (explicitEnv != null && !explicitEnv.isBlank()) { + return resolveAuthoritative(explicitEnv.trim(), BIN_ENV, expected); + } + + String wrongVersionFound = null; + String wrongVersionBin = null; + for (String candidate : discoverFallbackBinaries()) { + 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 Resolution resolveAuthoritative(String bin, String source, String expected) { + String detected = probeVersion(bin); + if (expected.equals(detected)) { + return new Resolution(bin, detected, null); + } + if (detected != null) { + return new Resolution(null, detected, + "Explicit " + source + "=" + bin + " reported " + detected + + ", but ADR-0047/ADR-0031 pin " + expected); + } + return new Resolution(null, null, + "Explicit " + source + "=" + bin + " is missing or did not answer `--version` within 10 s"); + } + + private static List discoverFallbackBinaries() { + Set candidates = new LinkedHashSet<>(); + + 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()); + } + } + + 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..60cb9774 100644 --- a/zeroj-integration-tests/build.gradle +++ b/zeroj-integration-tests/build.gradle @@ -39,6 +39,7 @@ dependencies { testImplementation project(':zeroj-circuit-annotation-api') testImplementation project(':zeroj-mpf-poseidon') testImplementation project(':zeroj-crypto') + testImplementation testFixtures(project(':zeroj-crypto')) testImplementation project(':zeroj-bls12381') testImplementation project(':zeroj-blst') testImplementation project(':zeroj-test-vectors') @@ -70,6 +71,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..a8c30a87 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 @@ -1,5 +1,7 @@ package org.zeroj.examples.dsl.common; +import org.zeroj.crypto.testsupport.SnarkjsCliLocator; + import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; @@ -43,23 +45,17 @@ 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; - - // 2. Common npm global install locations - String home = System.getProperty("user.home"); - String[] candidates = { - "snarkjs", - home + "/.npm-global/bin/snarkjs", - "/usr/local/bin/snarkjs", - home + "/.nvm/versions/node/current/bin/snarkjs", - }; - for (String candidate : candidates) { - if (Files.isExecutable(Path.of(candidate))) { - return candidate; - } - } + if (envBin != null && !envBin.isBlank()) return envBin.trim(); + + // 3. Shared PATH + common npm global install discovery + var res = SnarkjsCliLocator.resolvePinned(); + if (res.isReady()) return res.binary(); return "snarkjs"; // fallback to PATH } diff --git a/zeroj-integration-tests/src/test/java/org/zeroj/it/snarkjs/SnarkjsInteropSupport.java b/zeroj-integration-tests/src/test/java/org/zeroj/it/snarkjs/SnarkjsInteropSupport.java index b186d744..6fba3b0f 100644 --- a/zeroj-integration-tests/src/test/java/org/zeroj/it/snarkjs/SnarkjsInteropSupport.java +++ b/zeroj-integration-tests/src/test/java/org/zeroj/it/snarkjs/SnarkjsInteropSupport.java @@ -5,6 +5,7 @@ import org.zeroj.circuit.CircuitBuilder; import org.zeroj.circuit.r1cs.R1CSConstraintSystem; import org.zeroj.crypto.groth16.R1csExporter; +import org.zeroj.crypto.testsupport.SnarkjsCliLocator; import org.zeroj.examples.dsl.common.SnarkjsProver; import org.zeroj.examples.dsl.common.WitnessExporter; @@ -24,21 +25,22 @@ /** * Shared plumbing for the ADR-0047 bidirectional snarkjs interop suites. * - *

snarkjs is discovered by {@link SnarkjsProver#findSnarkjs()} ({@code SNARKJS_BIN}, then common - * npm locations, then {@code PATH}). Locally, an absent snarkjs — or one other than the pinned - * {@value #PINNED_VERSION} — skips the suites; in the assurance workflow the build passes - * {@code -PrequireSnarkjs}, which sets {@code zeroj.assurance.requireSnarkjs=true} and turns both - * into a failure, so the oracle can never silently vanish or drift. Verdicts come from - * {@link #verify}, which distinguishes a rejection from a crash.

+ *

snarkjs is discovered and version-checked by {@link SnarkjsCliLocator#resolvePinned()} + * ({@code -Dzeroj.snarkjs}, then {@code SNARKJS_BIN} — both authoritative if set — then + * {@code PATH}, then common global npm locations). Locally, an absent snarkjs — or one other than + * the pinned {@value #PINNED_VERSION} — skips the suites; in the assurance workflow the + * build passes {@code -PrequireSnarkjs}, which sets {@code zeroj.assurance.requireSnarkjs=true} + * and turns both into a failure, so the oracle can never silently vanish or drift. Verdicts come + * from {@link #verify}, which distinguishes a rejection from a crash.

*/ final class SnarkjsInteropSupport { private SnarkjsInteropSupport() {} /** The snarkjs release ADR-0047 pins as the normative reference for the JSON formats. */ - static final String PINNED_VERSION = "0.7.6"; + static final String PINNED_VERSION = SnarkjsCliLocator.PINNED_VERSION; - static final String REQUIRE_PROPERTY = "zeroj.assurance.requireSnarkjs"; + static final String REQUIRE_PROPERTY = SnarkjsCliLocator.REQUIRE_PROPERTY; static final BigInteger FR = MontFr381.modulus(); @@ -48,26 +50,23 @@ private SnarkjsInteropSupport() {} /** How long a single snarkjs invocation may take before it is killed and reported as an error. */ static final long SNARKJS_TIMEOUT_SECONDS = 300; + private static volatile String resolvedBin; + /** * Returns a ready snarkjs driver. Absent snarkjs: skip locally, fail under {@link #REQUIRE_PROPERTY}. * A snarkjs other than {@value #PINNED_VERSION}: skip locally (the byte-for-byte assertions are * only meaningful against the pinned oracle), fail under {@link #REQUIRE_PROPERTY}. */ static SnarkjsProver requireSnarkjs() { - boolean required = Boolean.getBoolean(REQUIRE_PROPERTY); - String bin = SnarkjsProver.findSnarkjs(); - String version = version(bin); - if (version == null) { - String msg = "snarkjs not found or not answering `--version` within 10 s (SNARKJS_BIN / PATH; see SnarkjsProver.findSnarkjs())"; - if (required) fail(msg + " — required by -PrequireSnarkjs"); - assumeTrue(false, msg + " — skipping"); - } - if (!("snarkjs@" + PINNED_VERSION).equals(version)) { - String msg = "ADR-0047 pins snarkjs " + PINNED_VERSION + " as the interop oracle, found " + version; - if (required) fail(msg + " — required by -PrequireSnarkjs"); - assumeTrue(false, msg + " — skipping"); + var res = SnarkjsCliLocator.resolvePinned(); + if (!res.isReady()) { + if (SnarkjsCliLocator.isRequired()) { + fail(res.reason() + " — required by -PrequireSnarkjs"); + } + assumeTrue(false, res.reason() + " — skipping"); } - return new SnarkjsProver(bin, SNARKJS_TIMEOUT_SECONDS); + resolvedBin = res.binary(); + return new SnarkjsProver(res.binary(), SNARKJS_TIMEOUT_SECONDS); } /** @@ -111,8 +110,9 @@ enum Verdict { VALID, INVALID } * test can only pass on a genuine {@code INVALID}. */ static Verdict verify(String protocol, Path dir) throws IOException, InterruptedException { + String bin = resolvedBin != null ? resolvedBin : SnarkjsProver.findSnarkjs(); var out = dir.resolve("verify-" + protocol + "-" + System.nanoTime() + ".log"); - var pb = new ProcessBuilder(SnarkjsProver.findSnarkjs(), protocol, "verify", + var pb = new ProcessBuilder(bin, protocol, "verify", "verification_key.json", "public.json", "proof.json") .directory(dir.toFile()).redirectErrorStream(true).redirectOutput(out.toFile()); var p = pb.start(); 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..37492f63 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.nio.file.attribute.PosixFilePermission; 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.Set; +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,366 @@ 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 long MAX_U32 = 0xFFFF_FFFFL; + 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; + + /** Package-private seam for testing atomic publish behavior under contention and unsupported filesystems. */ + interface FilePublisher { + void createHardLink(Path target, Path existing) throws IOException; + void atomicReplace(Path source, Path target) throws IOException; + } - // section-2 offsets (fixed layout, validated on read) - private static final long H_DELTA1 = 676, H_DELTA2 = 772, HEADER_LEN = 964; + static final FilePublisher DEFAULT_PUBLISHER = new FilePublisher() { + @Override + public void createHardLink(Path target, Path existing) throws IOException { + Files.createLink(target, existing); + } - /** @return the contribution hash (blake2b-512 of the new record's public key) — publish it. */ + @Override + public void atomicReplace(Path source, Path target) throws IOException { + Files.move(source, target, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); + } + }; + + /** + * 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 { - try (FileChannel inCh = FileChannel.open(in, StandardOpenOption.READ); - Arena arena = Arena.ofShared()) { + return contribute(in, out, name, false); + } + + /** + * 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 { + return contribute(in, out, name, overwrite, DEFAULT_PUBLISHER); + } + + static byte[] contribute(Path in, Path out, String name, boolean overwrite, FilePublisher publisher) + throws IOException { + Objects.requireNonNull(in, "in"); + Objects.requireNonNull(out, "out"); + Objects.requireNonNull(publisher, "publisher"); + + 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); + } + + 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)"); + } - AffineG1 delta1 = g1FromLem(z, h + H_DELTA1); - AffineG2 delta2 = g2FromLem(z, h + H_DELTA2); + 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); + } + + 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 streamed Section 10 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 rp = s10 + 68; - List priorRaw = new ArrayList<>(); - List priors = new ArrayList<>(); // [deltaAfter, g1s, g1sx, g2spx, transcript] - for (int i = 0; i < nContrib; i++) { - long start = rp; - AffineG1 deltaAfter = g1FromLem(z, rp); - AffineG1 g1s = g1FromLem(z, rp + 96); - AffineG1 g1sx = g1FromLem(z, rp + 192); - AffineG2 g2spx = g2FromLem(z, rp + 288); - byte[] transcript = bytes(z, rp + 480, 64); - rp += 480 + 64 + 4; // + type - long paramLen = Integer.toUnsignedLong(z.get(U32, rp)); - rp += 4 + paramLen; - priorRaw.add(bytes(z, start, rp - start)); - priors.add(new Object[]{deltaAfter, g1s, g1sx, g2spx, transcript}); - } - - // fresh secret + s-pair + long nContribLong = Integer.toUnsignedLong(z.get(U32, s10 + 64)); + if (nContribLong >= MAX_U32) { + throw new IOException("Prior contribution count " + nContribLong + " would overflow uint32"); + } + long maxContribs = (s10Size - 68) / MIN_CONTRIBUTION_BYTES; + if (nContribLong > maxContribs) { + throw new IOException("Invalid prior contribution count " + nContribLong + + " for section size " + s10Size); + } + + // Stream transcript hashing in O(1) heap (no per-record ArrayList or byte[] copies). + // snarkjs streams each prior's components into ONE running blake2b-512 hasher + // (hashPubKey(hasher, c)), NOT the priors' sub-hashes. + Blake2bDigest th = new Blake2bDigest(512); + update(th, csHash); + + long priorRecordsStart = s10 + 68; + long rp = priorRecordsStart; + AffineG1 lastDeltaAfter = null; + for (long i = 0; i < nContribLong; i++) { + if (rp > s10End - MIN_CONTRIBUTION_BYTES) { + throw new IOException("Truncated contribution record at index " + i); + } + String prefix = "contributions[" + i + "]"; + AffineG1 deltaAfter = requireNonIdentitySubgroupG1(z, rp, prefix + ".deltaAfter"); + AffineG1 pG1s = requireNonIdentitySubgroupG1(z, rp + 96, prefix + ".g1_s"); + AffineG1 pG1sx = requireNonIdentitySubgroupG1(z, rp + 192, prefix + ".g1_sx"); + AffineG2 pG2spx = requireNonIdentitySubgroupG2(z, rp + 288, prefix + ".g2_spx"); + byte[] pTranscript = bytes(z, rp + 480, 64); + int type = z.get(U32, rp + 544); + if (type != 0 && type != 1) { + throw new IOException("Unsupported contribution type " + type + " at index " + i); + } + long paramLen = Integer.toUnsignedLong(z.get(U32, rp + 548)); + long paramStart = rp + 552; + if (paramLen > s10End - paramStart) { + throw new IOException("Out-of-bounds contribution params length " + paramLen + " at index " + i); + } + validateContributionParams(z, paramStart, paramLen); + hashPubKeyInto(th, deltaAfter, pG1s, pG1sx, pG2spx, pTranscript); + lastDeltaAfter = deltaAfter; + rp = paramStart + paramLen; + } + if (rp != s10End) { + throw new IOException("Trailing bytes in .zkey contributions section: " + (s10End - rp)); + } + long priorRawLen = rp - priorRecordsStart; + + AffineG1 expectedDelta1 = lastDeltaAfter == null + ? JacobianG1BLS381.GENERATOR.toAffine() + : lastDeltaAfter; + if (!delta1.equals(expectedDelta1)) { + throw new IOException("Header delta1 does not match " + + (lastDeltaAfter == null ? "G1 generator (0 prior contributions)" : "last contribution deltaAfter")); + } + + // ---- S6: draw fresh secrets ONLY after all pre-secret header & prior checks succeed ---- SecureRandom rnd = new SecureRandom(); BigInteger k = randScalar(rnd); BigInteger s = randScalar(rnd); - AffineG1 g1s = JacobianG1BLS381.GENERATOR.scalarMul(s).toAffine(); - AffineG1 g1sx = JacobianG1BLS381.fromAffine(g1s.xBigInt(), g1s.yBigInt()).scalarMul(k).toAffine(); + AffineG1 g1s = JacobianG1BLS381.GENERATOR.ctScalarMul(s).toAffine(); + AffineG1 g1sx = JacobianG1BLS381.fromAffine(g1s.x(), g1s.y()).ctScalarMul(k).toAffine(); - // transcript = blake2b512(csHash ‖ RAW fields of every prior record ‖ unc(g1_s) ‖ unc(g1_sx)) - // — snarkjs streams each prior's components into ONE running hasher (hashPubKey(hasher, c)), - // NOT the priors' sub-hashes. (The two coincide only with zero priors.) - Blake2bDigest th = new Blake2bDigest(512); - update(th, csHash); - for (Object[] c : priors) - hashPubKeyInto(th, (AffineG1) c[0], (AffineG1) c[1], (AffineG1) c[2], (AffineG2) c[3], (byte[]) c[4]); update(th, g1Unc(g1s)); update(th, g1Unc(g1sx)); byte[] transcript = digest(th); AffineG2 g2sp = SnarkjsHashToG2.hashToG2(transcript); - AffineG2 g2spx = JacobianG2BLS381.fromAffine(g2sp.x(), g2sp.y()).scalarMul(k).toAffine(); + if (g2sp.isInfinity()) { + throw new IOException("Hash-to-G2 challenge unexpectedly produced identity point"); + } + AffineG2 g2spx = JacobianG2BLS381.fromAffine(g2sp.x(), g2sp.y()).ctScalarMul(k).toAffine(); - AffineG1 delta1New = JacobianG1BLS381.fromAffine(delta1.xBigInt(), delta1.yBigInt()).scalarMul(k).toAffine(); - AffineG2 delta2New = JacobianG2BLS381.fromAffine(delta2.x(), delta2.y()).scalarMul(k).toAffine(); + AffineG1 delta1New = JacobianG1BLS381.fromAffine(delta1.x(), delta1.y()).ctScalarMul(k).toAffine(); + AffineG2 delta2New = JacobianG2BLS381.fromAffine(delta2.x(), delta2.y()).ctScalarMul(k).toAffine(); BigInteger kInv = k.modInverse(R_FR); - // new contribution record - byte[] nameBytes = name == null ? new byte[0] - : name.substring(0, Math.min(name.length(), 64)).getBytes(StandardCharsets.UTF_8); - byte[] params = nameBytes.length == 0 ? new byte[0] : concat(new byte[]{1, (byte) nameBytes.length}, nameBytes); + // new contribution record (UTF-16 truncation + U+FFFD matches snarkjs 0.7.6 TextEncoder) + byte[] nameBytes = encodeName(name); + byte[] params = nameBytes.length == 0 + ? new byte[0] + : concat(new byte[]{1, (byte) nameBytes.length}, nameBytes); byte[] record = concat( g1Lem(delta1New), g1Lem(g1s), g1Lem(g1sx), g2Lem(g2spx), transcript, u32(0), u32(params.length), params); - // ---- write the new zkey ---- - long s10NewSize = 64 + 4 + priorRaw.stream().mapToLong(b -> b.length).sum() + record.length; - long total = 12 - + 12 + sec.get(1)[1] + 12 + sec.get(2)[1] - + 12 + sec.get(3)[1] + 12 + sec.get(4)[1] + 12 + sec.get(5)[1] - + 12 + sec.get(6)[1] + 12 + sec.get(7)[1] + 12 + sec.get(8)[1] - + 12 + sec.get(9)[1] + 12 + s10NewSize; - - Files.deleteIfExists(out); - try (FileChannel outCh = FileChannel.open(out, StandardOpenOption.CREATE_NEW, - StandardOpenOption.READ, StandardOpenOption.WRITE)) { - MemorySegment o = outCh.map(FileChannel.MapMode.READ_WRITE, 0, total, arena); - long w = 0; - o.set(U32, 0, 0x79656b7a); o.set(U32, 4, 1); o.set(U32, 8, 10); - w = 12; - w = section(o, w, 1, sec.get(1)[1]); - o.set(U32, w, 1); w += sec.get(1)[1]; // protocol groth16 - w = section(o, w, 2, sec.get(2)[1]); - MemorySegment.copy(z, sec.get(2)[0], o, w, sec.get(2)[1]); // header, then patch deltas - put(o, w + H_DELTA1, g1Lem(delta1New)); - put(o, w + H_DELTA2, g2Lem(delta2New)); - w += sec.get(2)[1]; - for (int t : new int[]{3, 4, 5, 6, 7}) { // unchanged sections - w = section(o, w, t, sec.get(t)[1]); - MemorySegment.copy(z, sec.get(t)[0], o, w, sec.get(t)[1]); - w += sec.get(t)[1]; + // ---- S7: write the new .zkey into a sibling temp file, flush, then publish atomically ---- + long s10NewSize = 64L + 4L + priorRawLen + record.length; + long total = 12L + + 12L + sec.get(1)[1] + 12L + sec.get(2)[1] + + 12L + sec.get(3)[1] + 12L + sec.get(4)[1] + 12L + sec.get(5)[1] + + 12L + sec.get(6)[1] + 12L + sec.get(7)[1] + 12L + sec.get(8)[1] + + 12L + sec.get(9)[1] + 12L + s10NewSize; + + Path tmp = Files.createTempFile(outDir, ".zeroj-zkey-", ".tmp"); + boolean published = false; + try { + try (FileChannel outCh = FileChannel.open(tmp, + StandardOpenOption.READ, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING)) { + try (Arena outArena = Arena.ofShared()) { + MemorySegment o = outCh.map(FileChannel.MapMode.READ_WRITE, 0, total, outArena); + o.set(U32, 0, ZKEY_MAGIC); + o.set(U32, 4, 1); + o.set(U32, 8, REQUIRED_SECTIONS); + long w = 12; + + w = section(o, w, 1, sec.get(1)[1]); + o.set(U32, w, GROTH16_PROTOCOL); + w += sec.get(1)[1]; + + w = section(o, w, 2, sec.get(2)[1]); + MemorySegment.copy(z, sec.get(2)[0], o, w, sec.get(2)[1]); + put(o, w + H_DELTA1, g1Lem(delta1New)); + put(o, w + H_DELTA2, g2Lem(delta2New)); + w += sec.get(2)[1]; + + for (int t : new int[]{3, 4, 5, 6, 7}) { + w = section(o, w, t, sec.get(t)[1]); + MemorySegment.copy(z, sec.get(t)[0], o, w, sec.get(t)[1]); + w += sec.get(t)[1]; + } + + w = section(o, w, 8, sec.get(8)[1]); + rescaleG1Section(z, sec.get(8)[0], o, w, (int) nL, kInv, "L (section 8)"); + w += sec.get(8)[1]; + + w = section(o, w, 9, sec.get(9)[1]); + rescaleG1Section(z, sec.get(9)[0], o, w, (int) domainSize, kInv, "H (section 9)"); + w += sec.get(9)[1]; + + w = section(o, w, 10, s10NewSize); + put(o, w, csHash); + o.set(U32, w + 64, (int) (nContribLong + 1L)); + if (priorRawLen > 0) { + MemorySegment.copy(z, priorRecordsStart, o, w + 68, priorRawLen); + } + put(o, w + 68 + priorRawLen, record); + + o.force(); + } + outCh.force(true); } - for (int t : new int[]{8, 9}) { // L, H ← kInv·point - w = section(o, w, t, sec.get(t)[1]); - rescaleG1Section(z, sec.get(t)[0], o, w, (int) (sec.get(t)[1] / 96), kInv); - w += sec.get(t)[1]; + + copyPosixPermissionsBestEffort(inAbs, tmp); + publishTempFile(tmp, inAbs, outAbs, overwrite, publisher); + published = true; + } finally { + if (!published) { + Files.deleteIfExists(tmp); } - w = section(o, w, 10, s10NewSize); - put(o, w, csHash); - o.set(U32, w + 64, nContrib + 1); - long q = w + 68; - for (byte[] raw : priorRaw) { put(o, q, raw); q += raw.length; } - put(o, q, record); + } + + // Temp unlink is separate from link publication: outAbs is already committed. + if (!overwrite) { + Files.deleteIfExists(tmp); } Blake2bDigest ch = new Blake2bDigest(512); @@ -185,49 +433,232 @@ public static byte[] contribute(Path in, Path out, String name) throws IOExcepti } } - // ---- L/H rescale (multi-core) ---- + private static void copyPosixPermissionsBestEffort(Path inAbs, Path tmp) { + try { + Set perms = Files.getPosixFilePermissions(inAbs); + Files.setPosixFilePermissions(tmp, perms); + } catch (UnsupportedOperationException | IOException ignored) { + // Non-POSIX filesystems (e.g. Windows) do not expose POSIX mode bits. + } + } + static void publishTempFile(Path tmp, Path inAbs, Path outAbs, boolean overwrite, FilePublisher publisher) + throws IOException { + if (Files.exists(outAbs, LinkOption.NOFOLLOW_LINKS) + && Files.exists(inAbs) + && Files.isSameFile(inAbs, outAbs)) { + throw new IOException("Refusing in-place overwrite: --in and --out refer to the same file: " + outAbs); + } + if (!overwrite) { + try { + // Atomic non-clobbering publish: fails with FileAlreadyExistsException if outAbs exists. + publisher.createHardLink(outAbs, tmp); + return; + } catch (FileAlreadyExistsException e) { + throw new IOException( + "Output file already exists (pass --overwrite / overwrite=true to replace): " + outAbs, e); + } catch (UnsupportedOperationException | IOException e) { + throw new IOException( + "Atomic non-clobbering publish failed (filesystem must support hard links for safe " + + "no-overwrite publication): " + outAbs, e); + } + } + try { + publisher.atomicReplace(tmp, outAbs); + } catch (AtomicMoveNotSupportedException | UnsupportedOperationException e) { + throw new IOException( + "Atomic overwrite failed (filesystem does not support atomic move for target): " + outAbs, e); + } + } + + // ---- L/H rescale (multi-core, ADR-0062 ctScalarMul) ---- + + /** + * Rescales every point in section 8 (L) or section 9 (H) by {@code kInv}. + * + *

Per snarkjs 0.7.6 ({@code zkey_new.js:460-466}, {@code mpc_applykey.js:44}, + * {@code ffjavascript} 0.3.1 {@code wasm_curve.js}), infinity (96 zero bytes) is legal in L + * (e.g. unused private wires) and preserved unchanged ({@code kInv · O = O}, leaking zero bits + * of {@code kInv}). Every non-infinity point is canonical-checked ({@code < p}) in + * {@link #g1FromLem} and on-curve + prime-order subgroup validated inside + * {@link JacobianG1BLS381#ctScalarMul} (checked once per point).

+ */ private static void rescaleG1Section(MemorySegment in, long inOff, MemorySegment out, long outOff, - int count, BigInteger kInv) { + int count, BigInteger kInv, String sectionName) throws IOException { + if (count == 0) return; + AtomicReference failure = new AtomicReference<>(); FrFFTFlat.parallelRange(count, (lo, hi) -> { for (int i = lo; i < hi; i++) { - AffineG1 p = g1FromLem(in, inOff + i * 96L); - AffineG1 r = p.isInfinity() ? p - : JacobianG1BLS381.fromAffine(p.xBigInt(), p.yBigInt()).scalarMul(kInv).toAffine(); - put(out, outOff + i * 96L, g1Lem(r)); + if (failure.get() != null) return; + try { + AffineG1 p = g1FromLem(in, inOff + i * 96L); + AffineG1 r = p.isInfinity() + ? AffineG1.INFINITY + : JacobianG1BLS381.fromAffine(p.x(), p.y()).ctScalarMul(kInv).toAffine(); + put(out, outOff + i * 96L, g1Lem(r)); + } catch (IllegalArgumentException e) { + failure.compareAndSet(null, new IOException( + "Invalid G1 point in " + sectionName + " at index " + i + ": " + e.getMessage(), e)); + return; + } } }); + IOException err = failure.get(); + if (err != null) throw err; + } + + // ---- validation helpers ---- + + private static void validateSectionSize(Map sec, int type, long expected, String label) + throws IOException { + long actual = sec.get(type)[1]; + if (actual != expected) { + throw new IOException("Section " + type + " (" + label + ") size mismatch: expected " + + expected + " bytes, got " + actual); + } + } + + private static void validateCoeffsSection(MemorySegment z, long[] sec4) throws IOException { + long off = sec4[0]; + long size = sec4[1]; + if (size < 4) { + throw new IOException("Truncated .zkey coefficients section (section 4): " + size + " bytes"); + } + long nCoeffs = Integer.toUnsignedLong(z.get(U32, off)); + long expected = 4L + nCoeffs * 44L; + if (size != expected) { + throw new IOException("Section 4 (coeffs) size mismatch: header declares " + nCoeffs + + " entries (" + expected + " bytes), got " + size); + } + } + + private static void validateContributionParams(MemorySegment z, long paramStart, long paramLen) throws IOException { + long pos = paramStart; + long end = paramStart + paramLen; + int lastTag = 0; + while (pos < end) { + int tag = z.get(ValueLayout.JAVA_BYTE, pos++) & 0xFF; + if (tag <= lastTag) { + throw new IOException("Contribution parameters must be strictly sorted by tag"); + } + lastTag = tag; + if (tag == 1 || tag == 3) { + if (pos >= end) { + throw new IOException("Truncated contribution parameter length for tag " + tag); + } + int len = z.get(ValueLayout.JAVA_BYTE, pos++) & 0xFF; + if (len > end - pos) { + throw new IOException("Truncated contribution parameter payload for tag " + tag); + } + pos += len; + } else if (tag == 2) { + if (pos >= end) { + throw new IOException("Truncated contribution parameter payload for tag 2"); + } + pos += 1; + } else { + throw new IOException("Unrecognized contribution parameter tag: " + tag); + } + } + if (pos != end) { + throw new IOException("Contribution parameter length mismatch"); + } + } + + private static AffineG1 requireNonIdentitySubgroupG1(MemorySegment z, long off, String label) throws IOException { + AffineG1 p; + try { + p = g1FromLem(z, off); + } catch (IllegalArgumentException e) { + throw new IOException("Non-canonical G1 coordinate in " + label + ": " + e.getMessage(), e); + } + if (p.isInfinity()) { + throw new IOException("Identity G1 point is forbidden for " + label); + } + if (!p.isOnCurve()) { + throw new IOException("Off-curve G1 point for " + label); + } + if (!JacobianG1BLS381.fromAffine(p.x(), p.y()).scalarMul(R_FR).isInfinity()) { + throw new IOException("Non-subgroup G1 point for " + label); + } + return p; + } + + private static AffineG2 requireNonIdentitySubgroupG2(MemorySegment z, long off, String label) throws IOException { + AffineG2 p; + try { + p = g2FromLem(z, off); + } catch (IllegalArgumentException e) { + throw new IOException("Non-canonical G2 coordinate in " + label + ": " + e.getMessage(), e); + } + if (p.isInfinity()) { + throw new IOException("Identity G2 point is forbidden for " + label); + } + if (!p.isOnCurve()) { + throw new IOException("Off-curve G2 point for " + label); + } + if (!JacobianG2BLS381.fromAffine(p.x(), p.y()).scalarMul(R_FR).isInfinity()) { + throw new IOException("Non-subgroup G2 point for " + label); + } + return p; + } + + private static G1Point toG1Point(AffineG1 p) { + return p.isInfinity() ? G1Point.INFINITY : new G1Point(Fp.of(p.xBigInt()), Fp.of(p.yBigInt())); + } + + private static G2Point toG2Point(AffineG2 p) { + if (p.isInfinity()) return G2Point.INFINITY; + return new G2Point( + Fp2.of(Fp.of(p.x().reBigInt()), Fp.of(p.x().imBigInt())), + Fp2.of(Fp.of(p.y().reBigInt()), Fp.of(p.y().imBigInt()))); } // ---- point codecs (LEM = little-endian Montgomery; Unc = canonical big-endian) ---- + private static MontFp381 montFpFromLem(MemorySegment z, long off) { + return MontFp381.fromMontLimbs( + z.get(U64, off), + z.get(U64, off + 8), + z.get(U64, off + 16), + z.get(U64, off + 24), + z.get(U64, off + 32), + z.get(U64, off + 40)); + } + private static AffineG1 g1FromLem(MemorySegment z, long off) { - BigInteger x = fromMontLE(z, off), y = fromMontLE(z, off + 48); - if (x.signum() == 0 && y.signum() == 0) return AffineG1.INFINITY; - return new AffineG1(MontFp381.fromBigInteger(x), MontFp381.fromBigInteger(y)); + MontFp381 x = montFpFromLem(z, off); + MontFp381 y = montFpFromLem(z, off + 48); + if (x.isZero() && y.isZero()) return AffineG1.INFINITY; + return new AffineG1(x, y); } private static AffineG2 g2FromLem(MemorySegment z, long off) { - return new AffineG2( - MontFp2_381.of(fromMontLE(z, off), fromMontLE(z, off + 48)), - MontFp2_381.of(fromMontLE(z, off + 96), fromMontLE(z, off + 144))); + MontFp381 x0 = montFpFromLem(z, off); + MontFp381 x1 = montFpFromLem(z, off + 48); + MontFp381 y0 = montFpFromLem(z, off + 96); + MontFp381 y1 = montFpFromLem(z, off + 144); + if (x0.isZero() && x1.isZero() && y0.isZero() && y1.isZero()) { + return AffineG2.INFINITY; + } + return new AffineG2(MontFp2_381.of(x0, x1), MontFp2_381.of(y0, y1)); } private static byte[] g1Lem(AffineG1 p) { byte[] b = new byte[96]; if (p.isInfinity()) return b; - montLE(p.xBigInt(), b, 0); - montLE(p.yBigInt(), b, 48); + putMontFpLE(p.x(), b, 0); + putMontFpLE(p.y(), b, 48); return b; } private static byte[] g2Lem(AffineG2 p) { byte[] b = new byte[192]; if (p.isInfinity()) return b; - montLE(p.x().reBigInt(), b, 0); - montLE(p.x().imBigInt(), b, 48); - montLE(p.y().reBigInt(), b, 96); - montLE(p.y().imBigInt(), b, 144); + putMontFpLE(p.x().re(), b, 0); + putMontFpLE(p.x().im(), b, 48); + putMontFpLE(p.y().re(), b, 96); + putMontFpLE(p.y().im(), b, 144); return b; } @@ -261,17 +692,28 @@ private static void hashPubKeyInto(Blake2bDigest d, AffineG1 deltaAfter, AffineG // ---- low-level helpers ---- - private static BigInteger fromMontLE(MemorySegment z, long off) { - byte[] le = bytes(z, off, 48); - byte[] be = new byte[48]; - for (int i = 0; i < 48; i++) be[i] = le[47 - i]; - return new BigInteger(1, be).multiply(MONT_R_INV).mod(P); + private static BigInteger readUnsignedLE(MemorySegment z, long off, int len) { + byte[] be = new byte[len]; + for (int i = 0; i < len; i++) { + be[len - 1 - i] = z.get(ValueLayout.JAVA_BYTE, off + i); + } + return new BigInteger(1, be); } - private static void montLE(BigInteger v, byte[] out, int off) { - byte[] be = v.multiply(MONT_R).mod(P).toByteArray(); - int s = Math.max(0, be.length - 48), len = be.length - s; - for (int i = 0; i < len; i++) out[off + i] = be[be.length - 1 - i]; + private static void putMontFpLE(MontFp381 v, byte[] out, int off) { + long[] limbs = v.toLimbs(); + for (int i = 0; i < 6; i++) { + long limb = limbs[i]; + int base = off + i * 8; + out[base] = (byte) limb; + out[base + 1] = (byte) (limb >>> 8); + out[base + 2] = (byte) (limb >>> 16); + out[base + 3] = (byte) (limb >>> 24); + out[base + 4] = (byte) (limb >>> 32); + out[base + 5] = (byte) (limb >>> 40); + out[base + 6] = (byte) (limb >>> 48); + out[base + 7] = (byte) (limb >>> 56); + } } private static void be48(BigInteger v, byte[] out, int off) { @@ -280,9 +722,39 @@ private static void be48(BigInteger v, byte[] out, int off) { System.arraycopy(be, s, out, off + 48 - len, len); } + /** + * Bit-exact port of snarkjs 0.7.6 ({@code new TextEncoder("utf-8").encode(c.name.substring(0, 64))}): + * truncates at 64 UTF-16 code units, then replaces any unpaired surrogate (including one created + * by slicing a surrogate pair at index 64) with {@code U+FFFD} ({@code EF BF BD}) per WHATWG + * {@code toUSVString} before UTF-8 encoding. Maximum output length is 192 bytes ({@code <= 255}), + * so the 1-byte TLV length field can never overflow. + */ + static byte[] encodeName(String name) { + if (name == null || name.isEmpty()) return new byte[0]; + int limit = Math.min(name.length(), 64); + StringBuilder usv = new StringBuilder(limit); + for (int i = 0; i < limit; i++) { + char c = name.charAt(i); + if (Character.isHighSurrogate(c)) { + if (i + 1 < limit && Character.isLowSurrogate(name.charAt(i + 1))) { + usv.append(c).append(name.charAt(++i)); + } else { + usv.append('\uFFFD'); + } + } else if (Character.isLowSurrogate(c)) { + usv.append('\uFFFD'); + } else { + usv.append(c); + } + } + return usv.toString().getBytes(StandardCharsets.UTF_8); + } + private static BigInteger randScalar(SecureRandom rnd) { BigInteger v; - do { v = new BigInteger(512, rnd).mod(R_FR); } while (v.signum() == 0); + do { + v = new BigInteger(512, rnd).mod(R_FR); + } while (v.signum() == 0); return v; } @@ -311,11 +783,16 @@ private static byte[] concat(byte[]... parts) { for (byte[] p : parts) len += p.length; byte[] r = new byte[len]; int o = 0; - for (byte[] p : parts) { System.arraycopy(p, 0, r, o, p.length); o += p.length; } + for (byte[] p : parts) { + System.arraycopy(p, 0, r, o, p.length); + o += p.length; + } return r; } - private static void update(Blake2bDigest d, byte[] b) { d.update(b, 0, b.length); } + private static void update(Blake2bDigest d, byte[] b) { + d.update(b, 0, b.length); + } private static byte[] digest(Blake2bDigest d) { byte[] out = new byte[64]; 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 0edb100b..cbce032f 100644 --- a/zeroj-tools/src/test/java/org/zeroj/ceremony/CeremonyCliTest.java +++ b/zeroj-tools/src/test/java/org/zeroj/ceremony/CeremonyCliTest.java @@ -15,6 +15,7 @@ import org.zeroj.crypto.groth16.ProverBackend; import org.zeroj.crypto.groth16.R1CSImporter; import org.zeroj.crypto.groth16.ZkeyPkStoreImporter; +import org.zeroj.crypto.testsupport.SnarkjsCliLocator; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; @@ -89,10 +90,34 @@ void finalizeInvalidPolicyArguments_failBeforeImport(@TempDir Path dir) throws E } } + @Test + void contributeOverwriteAndSamePath_rejectedBeforeParsing(@TempDir Path dir) throws Exception { + Path input = dir.resolve("input.zkey"); + Path existing = dir.resolve("existing.zkey"); + byte[] sentinelIn = new byte[]{1, 2, 3, 4}; + byte[] sentinelOut = new byte[]{5, 6, 7, 8}; + Files.write(input, sentinelIn); + Files.write(existing, sentinelOut); + + var samePath = capture("contribute", "--in", input.toString(), "--out", input.toString()); + assertEquals(2, samePath.exitCode(), samePath.stderr()); + assertTrue(samePath.stderr().contains("in-place overwrite"), samePath.stderr()); + assertArrayEquals(sentinelIn, Files.readAllBytes(input), "input must remain untouched"); + + var samePathForced = capture("contribute", "--overwrite", "--in", input.toString(), "--out", input.toString()); + assertEquals(2, samePathForced.exitCode(), samePathForced.stderr()); + assertTrue(samePathForced.stderr().contains("in-place overwrite"), samePathForced.stderr()); + assertArrayEquals(sentinelIn, Files.readAllBytes(input), "input must remain untouched even with --overwrite"); + + var existsNoFlag = capture("contribute", "--in", input.toString(), "--out", existing.toString()); + assertEquals(2, existsNoFlag.exitCode(), existsNoFlag.stderr()); + assertTrue(existsNoFlag.stderr().contains("--overwrite"), existsNoFlag.stderr()); + assertArrayEquals(sentinelOut, Files.readAllBytes(existing), "existing output must remain untouched"); + } + @Test void fullOptionA_ceremonyViaCli_provesAndVerifies(@TempDir Path dir) throws Exception { - String snarkjs = findSnarkjs(); - assumeTrue(snarkjs != null, "snarkjs not found"); + String snarkjs = requireSnarkjs(); // 1. export via CLI Path r1cs = dir.resolve("mul.r1cs"); @@ -173,14 +198,15 @@ private static CliResult capture(String... args) { } } - 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-tools/src/test/java/org/zeroj/ceremony/ZkeyContributorInteropTest.java b/zeroj-tools/src/test/java/org/zeroj/ceremony/ZkeyContributorInteropTest.java index 28a1a2fd..a0040d30 100644 --- a/zeroj-tools/src/test/java/org/zeroj/ceremony/ZkeyContributorInteropTest.java +++ b/zeroj-tools/src/test/java/org/zeroj/ceremony/ZkeyContributorInteropTest.java @@ -1,6 +1,19 @@ package org.zeroj.ceremony; import org.zeroj.api.CurveId; +import org.zeroj.bls12381.ec.G1Point; +import org.zeroj.bls12381.ec.G2Point; +import org.zeroj.bls12381.ec.JacobianG1BLS381; +import org.zeroj.bls12381.ec.JacobianG2BLS381; +import org.zeroj.bls12381.field.Fp; +import org.zeroj.bls12381.field.Fp2; +import org.zeroj.bls12381.pairing.BLS12381Pairing; +import org.zeroj.codec.SnarkjsJsonCodec; +import org.zeroj.crypto.groth16.Groth16PkStore; +import org.zeroj.crypto.groth16.Groth16ProverBLS381; +import org.zeroj.crypto.groth16.ProverBackend; +import org.zeroj.crypto.groth16.ZkeyPkStoreImporter; +import org.zeroj.crypto.testsupport.SnarkjsCliLocator; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; @@ -26,8 +39,7 @@ class ZkeyContributorInteropTest { @Test void zerojContribution_verifiedBySnarkjs_mixedTranscript(@TempDir Path dir) throws Exception { - String snarkjs = findSnarkjs(); - assumeTrue(snarkjs != null, "snarkjs not found"); + String snarkjs = requireSnarkjs(); // ceremony genesis (snarkjs) Path r1cs = dir.resolve("mul.r1cs"); @@ -38,13 +50,14 @@ void zerojContribution_verifiedBySnarkjs_mixedTranscript(@TempDir Path dir) thro run(dir, snarkjs, "powersoftau", "prepare", "phase2", "pot1.ptau", "pot.ptau"); run(dir, snarkjs, "groth16", "setup", r1cs.toString(), "pot.ptau", "key0.zkey"); - // contribution #1: ZeroJ-native (via the CLI) + // contribution #1: ZeroJ-native (via the CLI) with a UTF-16 boundary name matching snarkjs 0.7.6 + String boundaryName = "a".repeat(63) + "\uD83D\uDE00"; assertEquals(0, CeremonyCli.run(new String[]{"contribute", "--in", dir.resolve("key0.zkey").toString(), "--out", dir.resolve("key1.zkey").toString(), - "--name", "zeroj-native-1"})); + "--name", boundaryName})); - // (a) snarkjs must accept the ZeroJ contribution's transcript + PoK + L/H rescale + // (a) snarkjs must accept the ZeroJ contribution's transcript + PoK + L/H rescale + UTF-8 name run(dir, snarkjs, "zkey", "verify", r1cs.toString(), "pot.ptau", "key1.zkey"); // (b) a snarkjs contribution must stack on top of ours (mixed-tool chain), then verify @@ -58,7 +71,7 @@ void zerojContribution_verifiedBySnarkjs_mixedTranscript(@TempDir Path dir) thro "--name", "zeroj-native-3"})); run(dir, snarkjs, "zkey", "verify", r1cs.toString(), "pot.ptau", "key3.zkey"); - // (c) the final key proves (via the in-memory importer for brevity) — full-circle sanity + // (c) the final key proves and pairing-verifies against the snarkjs-exported VK run(dir, snarkjs, "zkey", "export", "verificationkey", "key3.zkey", "vk.json"); Path store = dir.resolve("pk"); assertEquals(0, CeremonyCli.run(new String[]{"finalize", "--allow-unpinned", @@ -69,26 +82,53 @@ void zerojContribution_verifiedBySnarkjs_mixedTranscript(@TempDir Path dir) thro "out", List.of(BigInteger.valueOf(391)), "a", List.of(BigInteger.valueOf(17)), "b", List.of(BigInteger.valueOf(23))), CurveId.BLS12_381); - try (var loaded = org.zeroj.crypto.groth16.Groth16PkStore.load(store)) { - var cons = org.zeroj.crypto.groth16.ZkeyPkStoreImporter + try (var loaded = Groth16PkStore.load(store)) { + var cons = ZkeyPkStoreImporter .snarkjsConstraints(compiled.constraints(), compiled.numPublicInputs()); - var proof = org.zeroj.crypto.groth16.Groth16ProverBLS381.proveWithReaders( + var proof = Groth16ProverBLS381.proveWithReaders( loaded.pk(), loaded.readers(), - org.zeroj.crypto.groth16.ProverBackend.PURE_JAVA, + ProverBackend.PURE_JAVA, witness, cons, compiled.numWires(), loaded.domain()); assertTrue(proof.a().isOnCurve() && proof.b().isOnCurve() && proof.c().isOnCurve()); + + var vk = SnarkjsJsonCodec.parseVerificationKey(Files.readString(dir.resolve("vk.json"))); + G1Point vkX = parseG1(vk.ic().get(0)).add(parseG1(vk.ic().get(1)).scalarMul(witness[1])); + boolean ok = BLS12381Pairing.pairingCheck( + new G1Point[]{toG1(proof.a()), parseG1(vk.vkAlpha1()).negate(), vkX.negate(), toG1(proof.c()).negate()}, + new G2Point[]{toG2(proof.b()), parseG2(vk.vkBeta2()), parseG2(vk.vkGamma2()), parseG2(vk.vkDelta2())}); + assertTrue(ok, "Mixed-tool ceremony proof MUST pairing-verify against final snarkjs VK"); } - System.out.println("[M5] ZeroJ contribute -> snarkjs verify OK -> mixed-tool chain verify OK -> proves PASSED"); + System.out.println("[M5] ZeroJ contribute -> snarkjs verify OK -> mixed-tool chain verify OK -> proves & verifies PASSED"); + } + + private static G1Point toG1(JacobianG1BLS381.AffineG1 p) { + return p.isInfinity() ? G1Point.INFINITY : new G1Point(Fp.of(p.xBigInt()), Fp.of(p.yBigInt())); + } + + private static G2Point toG2(JacobianG2BLS381.AffineG2 p) { + if (p.isInfinity()) return G2Point.INFINITY; + return new G2Point( + Fp2.of(Fp.of(p.x().reBigInt()), Fp.of(p.x().imBigInt())), + Fp2.of(Fp.of(p.y().reBigInt()), Fp.of(p.y().imBigInt()))); + } + + private static G1Point parseG1(List c) { return new G1Point(Fp.of(c.get(0)), Fp.of(c.get(1))); } + + private static G2Point parseG2(List> c) { + return new G2Point( + Fp2.of(Fp.of(c.get(0).get(0)), Fp.of(c.get(0).get(1))), + Fp2.of(Fp.of(c.get(1).get(0)), Fp.of(c.get(1).get(1)))); } - 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-tools/src/test/java/org/zeroj/tools/zkey/ZkeyContributorTest.java b/zeroj-tools/src/test/java/org/zeroj/tools/zkey/ZkeyContributorTest.java new file mode 100644 index 00000000..d12f8c31 --- /dev/null +++ b/zeroj-tools/src/test/java/org/zeroj/tools/zkey/ZkeyContributorTest.java @@ -0,0 +1,795 @@ +package org.zeroj.tools.zkey; + +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.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 java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.math.BigInteger; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.charset.StandardCharsets; +import java.nio.file.AtomicMoveNotSupportedException; +import java.nio.file.FileAlreadyExistsException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.attribute.PosixFilePermission; +import java.nio.file.attribute.PosixFilePermissions; +import java.util.Arrays; +import java.util.List; +import java.util.Set; +import java.util.stream.Stream; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Offline unit and adversarial-input tests for {@link ZkeyContributor} (ADR-0031 R3 hardening + * amendment). + */ +class ZkeyContributorTest { + + private static final BigInteger P = MontFp381.modulus(); + private static final BigInteger R = MontFr381.modulus(); + + private static final AffineG1 G1 = JacobianG1BLS381.GENERATOR.toAffine(); + private static final AffineG2 G2 = JacobianG2BLS381.GENERATOR.toAffine(); + private static final G1Point G1_GEN = toG1(G1); + private static final G2Point G2_GEN = toG2(G2); + + // (0, 2) satisfies y^2 = x^3 + 4 over Fp, has order 3 (not in the r-order subgroup). + private static final AffineG1 SMALL_SUBGROUP_G1 = new AffineG1(MontFp381.ZERO, MontFp381.TWO); + + // Off-curve G1 point: (G1.x, G1.y + 1). + private static final AffineG1 OFF_CURVE_G1 = new AffineG1(G1.x(), G1.y().add(MontFp381.ONE)); + + // Off-curve G2 point: (G2.x, G2.y + (1, 0)). + private static final AffineG2 OFF_CURVE_G2 = new AffineG2(G2.x(), G2.y().add(MontFp2_381.ONE)); + + // On-curve non-subgroup G2 point: (0, sqrt(4*(1+u))) on y^2 = x^3 + 4*(1+u). + private static final AffineG2 SMALL_SUBGROUP_G2 = buildSmallSubgroupG2(); + + // ---- Positive controls ---- + + @Test + void validGenesisAndChainedContribution_preservesInfinityInLAndH_andUpdatesPairings(@TempDir Path dir) + throws Exception { + // Verify our adversarial test points have the exact algebraic properties we assert. + assertTrue(SMALL_SUBGROUP_G1.isOnCurve()); + assertFalse(JacobianG1BLS381.fromAffine(SMALL_SUBGROUP_G1.x(), SMALL_SUBGROUP_G1.y()).scalarMul(R).isInfinity()); + assertFalse(OFF_CURVE_G1.isOnCurve()); + assertTrue(SMALL_SUBGROUP_G2.isOnCurve()); + assertFalse(JacobianG2BLS381.fromAffine(SMALL_SUBGROUP_G2.x(), SMALL_SUBGROUP_G2.y()).scalarMul(R).isInfinity()); + assertFalse(OFF_CURVE_G2.isOnCurve()); + + // nVars = 4, nPublic = 1 => nL = 2; domainSize = 4 => nH = 4. + // Include AffineG1.INFINITY in both L[1] and H[3] (snarkjs 0.7.6 infinity semantics). + AffineG1 l0 = JacobianG1BLS381.GENERATOR.scalarMul(BigInteger.valueOf(7)).toAffine(); + AffineG1[] lPoints = {l0, AffineG1.INFINITY}; + AffineG1[] hPoints = { + JacobianG1BLS381.GENERATOR.scalarMul(BigInteger.valueOf(11)).toAffine(), + JacobianG1BLS381.GENERATOR.scalarMul(BigInteger.valueOf(13)).toAffine(), + JacobianG1BLS381.GENERATOR.scalarMul(BigInteger.valueOf(17)).toAffine(), + AffineG1.INFINITY + }; + + Path z0 = dir.resolve("key0.zkey"); + Files.write(z0, buildSyntheticZkey(G1, G2, lPoints, hPoints, null)); + + Path z1 = dir.resolve("key1.zkey"); + byte[] hash1 = ZkeyContributor.contribute(z0, z1, "alice"); + assertEquals(64, hash1.length); + assertTrue(Files.exists(z1)); + assertNoTempFiles(dir); + + // Verify key1: delta1New != G1, e(delta1New, G2) == e(G1, delta2New), + // e(L_new[0], delta2New) == e(L_old[0], G2), L_new[1] == INFINITY, H_new[3] == INFINITY. + byte[] z1Bytes = Files.readAllBytes(z1); + long s2Off = findSectionOffset(z1Bytes, 2); + AffineG1 d1New = readG1(z1Bytes, (int) (s2Off + 676)); + AffineG2 d2New = readG2(z1Bytes, (int) (s2Off + 772)); + assertFalse(d1New.equals(G1)); + assertTrue(BLS12381Pairing.pairingCheck( + new G1Point[]{toG1(d1New), G1_GEN.negate()}, + new G2Point[]{G2_GEN, toG2(d2New)})); + + long s8Off = findSectionOffset(z1Bytes, 8); + AffineG1 l0New = readG1(z1Bytes, (int) s8Off); + AffineG1 l1New = readG1(z1Bytes, (int) (s8Off + 96)); + assertTrue(l1New.isInfinity(), "L infinity entry must be preserved"); + assertTrue(BLS12381Pairing.pairingCheck( + new G1Point[]{toG1(l0New), toG1(l0).negate()}, + new G2Point[]{toG2(d2New), G2_GEN})); + + long s9Off = findSectionOffset(z1Bytes, 9); + AffineG1 h0New = readG1(z1Bytes, (int) s9Off); + AffineG1 h3New = readG1(z1Bytes, (int) (s9Off + 3 * 96)); + assertTrue(h3New.isInfinity(), "H infinity entry must be preserved"); + assertTrue(BLS12381Pairing.pairingCheck( + new G1Point[]{toG1(h0New), toG1(hPoints[0]).negate()}, + new G2Point[]{toG2(d2New), G2_GEN})); + + // Chain a second contribution with a 64-emoji name (tests multibyte UTF-8 TLV truncation <= 255B). + String emojiName = "\uD83D\uDE80".repeat(64); + Path z2 = dir.resolve("key2.zkey"); + byte[] hash2 = ZkeyContributor.contribute(z1, z2, emojiName); + assertEquals(64, hash2.length); + assertFalse(Arrays.equals(hash1, hash2)); + + // Verify the third contribution can parse key2's multi-byte TLV params without error. + Path z3 = dir.resolve("key3.zkey"); + byte[] hash3 = ZkeyContributor.contribute(z2, z3, "carol"); + assertEquals(64, hash3.length); + assertNoTempFiles(dir); + } + + // ---- S1 & S2: Framing, sections, and exact header primes ---- + + @Test + void rejectsTruncatedAndBadFramingFiles(@TempDir Path dir) throws Exception { + byte[] valid = buildValidGenesisBytes(); + + assertRejects(dir, "too-short.zkey", new byte[]{1, 2, 3}, "Truncated"); + + byte[] badMagic = valid.clone(); + badMagic[0] ^= 0x01; + assertRejects(dir, "bad-magic.zkey", badMagic, "magic"); + + byte[] badVersion = valid.clone(); + putU32(badVersion, 4, 3); + assertRejects(dir, "bad-version.zkey", badVersion, "version"); + + byte[] trailing = Arrays.copyOf(valid, valid.length + 4); + assertRejects(dir, "trailing.zkey", trailing, "Trailing"); + + // Duplicate section: turn section 3's type into 2 (after section 2) + byte[] dupSec = valid.clone(); + int sec3HeaderOff = findSectionHeaderOffset(dupSec, 3); + putU32(dupSec, sec3HeaderOff, 2); + assertRejects(dir, "dup-sec.zkey", dupSec, "Duplicate"); + + // Out-of-bounds section size + byte[] oobSec = valid.clone(); + int sec9HeaderOff = findSectionHeaderOffset(oobSec, 9); + putU64(oobSec, sec9HeaderOff + 4, 1L << 40); + assertRejects(dir, "oob-sec.zkey", oobSec, "Out-of-bounds"); + + // Unaligned / wrong-size L section (add 4 bytes to section 8 size and file) + byte[] badLSize = mutateSectionSize(valid, 8, 4); + assertRejects(dir, "bad-l-size.zkey", badLSize, "Section 8 (L)"); + + // Unaligned / wrong-size H section (add 4 bytes to section 9 size and file) + byte[] badHSize = mutateSectionSize(valid, 9, 4); + assertRejects(dir, "bad-h-size.zkey", badHSize, "Section 9 (H)"); + } + + @Test + void rejectsWrongHeaderPrimes(@TempDir Path dir) throws Exception { + byte[] valid = buildValidGenesisBytes(); + int s2Off = (int) findSectionOffset(valid, 2); + + byte[] badQ = valid.clone(); + badQ[s2Off + 4] ^= 0x01; // flip LSB of prime q + assertRejects(dir, "bad-q.zkey", badQ, "base field prime q"); + + byte[] badR = valid.clone(); + badR[s2Off + 56] ^= 0x01; // flip LSB of prime r + assertRejects(dir, "bad-r.zkey", badR, "scalar field prime r"); + } + + // ---- S3 & S4: Canonical < p, delta1/delta2 validity, pairing, chain ---- + + @Test + void rejectsInvalidDelta1AndDelta2(@TempDir Path dir) throws Exception { + // Identity delta1 + assertRejects(dir, "id-d1.zkey", + buildSyntheticZkey(AffineG1.INFINITY, G2, defaultL(), defaultH(), null), + "Identity G1"); + + // Identity delta2 (also exercises G2 infinity sentinel) + assertRejects(dir, "id-d2.zkey", + buildSyntheticZkey(G1, AffineG2.INFINITY, defaultL(), defaultH(), null), + "Identity G2"); + + // Off-curve delta1 + assertRejects(dir, "offcurve-d1.zkey", + buildSyntheticZkey(OFF_CURVE_G1, G2, defaultL(), defaultH(), null), + "Off-curve G1"); + + // Off-curve delta2 + assertRejects(dir, "offcurve-d2.zkey", + buildSyntheticZkey(G1, OFF_CURVE_G2, defaultL(), defaultH(), null), + "Off-curve G2"); + + // Small-subgroup delta1 + assertRejects(dir, "subgrp-d1.zkey", + buildSyntheticZkey(SMALL_SUBGROUP_G1, G2, defaultL(), defaultH(), null), + "Non-subgroup G1"); + + // Small-subgroup delta2 + assertRejects(dir, "subgrp-d2.zkey", + buildSyntheticZkey(G1, SMALL_SUBGROUP_G2, defaultL(), defaultH(), null), + "Non-subgroup G2"); + + // Non-canonical (>= p) coordinate in delta1 + byte[] nonCanonD1 = buildValidGenesisBytes(); + int s2Off = (int) findSectionOffset(nonCanonD1, 2); + putUnsignedLE(nonCanonD1, s2Off + 676, P, 48); // exact modulus p (>= p) + assertRejects(dir, "noncanon-d1.zkey", nonCanonD1, "Non-canonical G1"); + + // Non-canonical (>= p) coordinate in delta2 + byte[] nonCanonD2 = buildValidGenesisBytes(); + putUnsignedLE(nonCanonD2, s2Off + 772, P, 48); + assertRejects(dir, "noncanon-d2.zkey", nonCanonD2, "Non-canonical G2"); + + // Pairing mismatch: delta1 = G1, delta2 = 2*G2 (both valid subgroup, non-identity, wrong pairing) + AffineG2 twoG2 = JacobianG2BLS381.GENERATOR.doublePoint().toAffine(); + assertRejects(dir, "pairing-mismatch.zkey", + buildSyntheticZkey(G1, twoG2, defaultL(), defaultH(), null), + "pairing check"); + + // Chain mismatch at 0 priors: delta1 = 2*G1, delta2 = 2*G2 (pairing holds, but delta1 != G1) + AffineG1 twoG1 = JacobianG1BLS381.GENERATOR.doublePoint().toAffine(); + assertRejects(dir, "genesis-chain-mismatch.zkey", + buildSyntheticZkey(twoG1, twoG2, defaultL(), defaultH(), null), + "G1 generator"); + } + + @Test + void rejectsBrokenPriorChainAndMalformedPriorRecords(@TempDir Path dir) throws Exception { + // Generate a legitimate key1 first + Path z0 = dir.resolve("base0.zkey"); + Path z1 = dir.resolve("base1.zkey"); + Files.write(z0, buildValidGenesisBytes()); + ZkeyContributor.contribute(z0, z1, "alice"); + byte[] z1Bytes = Files.readAllBytes(z1); + + // Tamper prior[0].deltaAfter to G1 (valid subgroup, non-identity, but != header.delta1) + byte[] brokenChain = z1Bytes.clone(); + int s10Off = (int) findSectionOffset(brokenChain, 10); + System.arraycopy(g1Lem(G1), 0, brokenChain, s10Off + 68, 96); + assertRejects(dir, "broken-chain.zkey", brokenChain, "last contribution deltaAfter"); + + // Tamper prior[0].g1_s to identity + byte[] idPrior = z1Bytes.clone(); + Arrays.fill(idPrior, s10Off + 68 + 96, s10Off + 68 + 192, (byte) 0); + assertRejects(dir, "id-prior.zkey", idPrior, "Identity G1"); + + // Tamper prior[0].g2_spx to non-canonical (>= p) + byte[] nonCanonPrior = z1Bytes.clone(); + putUnsignedLE(nonCanonPrior, s10Off + 68 + 288, P, 48); + assertRejects(dir, "noncanon-prior.zkey", nonCanonPrior, "Non-canonical G2"); + + // Malformed TLV params in prior contribution: unsorted tag order (tag 2 then tag 1) + ByteArrayOutputStream badTlvSec10 = new ByteArrayOutputStream(); + badTlvSec10.write(new byte[64]); // csHash + writeU32(badTlvSec10, 1); // nContrib = 1 + badTlvSec10.write(g1Lem(G1)); // deltaAfter = G1 (matches header.delta1) + badTlvSec10.write(g1Lem(G1)); // g1_s + badTlvSec10.write(g1Lem(G1)); // g1_sx + badTlvSec10.write(g2Lem(G2)); // g2_spx + badTlvSec10.write(new byte[64]); // transcript + writeU32(badTlvSec10, 1); // type = beacon + byte[] badParams = new byte[]{2, 10, 1, 1, 'a'}; // tag 2 followed by tag 1 (unsorted) + writeU32(badTlvSec10, badParams.length); + badTlvSec10.write(badParams); + assertRejects(dir, "unsorted-tlv.zkey", + buildSyntheticZkey(G1, G2, defaultL(), defaultH(), badTlvSec10.toByteArray()), + "strictly sorted"); + + // Valid beacon prior (type = 1, sorted tags 1, 2, 3) accepted cleanly + ByteArrayOutputStream validBeaconSec10 = new ByteArrayOutputStream(); + validBeaconSec10.write(new byte[64]); + writeU32(validBeaconSec10, 1); + validBeaconSec10.write(g1Lem(G1)); + validBeaconSec10.write(g1Lem(G1)); + validBeaconSec10.write(g1Lem(G1)); + validBeaconSec10.write(g2Lem(G2)); + validBeaconSec10.write(new byte[64]); + writeU32(validBeaconSec10, 1); + byte[] beaconParams = new byte[]{1, 1, 'b', 2, 10, 3, 2, 0x12, 0x34}; + writeU32(validBeaconSec10, beaconParams.length); + validBeaconSec10.write(beaconParams); + Path beaconIn = dir.resolve("valid-beacon.zkey"); + Path beaconOut = dir.resolve("valid-beacon.out.zkey"); + Files.write(beaconIn, buildSyntheticZkey(G1, G2, defaultL(), defaultH(), validBeaconSec10.toByteArray())); + assertEquals(64, ZkeyContributor.contribute(beaconIn, beaconOut, "post-beacon").length); + } + + // ---- S5: L and H validation + atomic cleanup ---- + + @Test + void rejectsInvalidPointsInLAndH_withoutCreatingOutputOrTempFiles(@TempDir Path dir) throws Exception { + // Off-curve in L + assertRejects(dir, "offcurve-l.zkey", + buildSyntheticZkey(G1, G2, new AffineG1[]{OFF_CURVE_G1, G1}, defaultH(), null), + "L (section 8)"); + + // Small-subgroup in L + assertRejects(dir, "subgrp-l.zkey", + buildSyntheticZkey(G1, G2, new AffineG1[]{SMALL_SUBGROUP_G1, G1}, defaultH(), null), + "L (section 8)"); + + // Non-canonical (>= p) in L + byte[] nonCanonL = buildValidGenesisBytes(); + int s8Off = (int) findSectionOffset(nonCanonL, 8); + putUnsignedLE(nonCanonL, s8Off, P, 48); + assertRejects(dir, "noncanon-l.zkey", nonCanonL, "L (section 8)"); + + // Off-curve in H + AffineG1[] badHOff = defaultH(); + badHOff[2] = OFF_CURVE_G1; + assertRejects(dir, "offcurve-h.zkey", + buildSyntheticZkey(G1, G2, defaultL(), badHOff, null), + "H (section 9)"); + + // Small-subgroup in H + AffineG1[] badHSub = defaultH(); + badHSub[1] = SMALL_SUBGROUP_G1; + assertRejects(dir, "subgrp-h.zkey", + buildSyntheticZkey(G1, G2, defaultL(), badHSub, null), + "H (section 9)"); + + // Non-canonical (>= p) in H + byte[] nonCanonH = buildValidGenesisBytes(); + int s9Off = (int) findSectionOffset(nonCanonH, 9); + putUnsignedLE(nonCanonH, s9Off + 96, P, 48); + assertRejects(dir, "noncanon-h.zkey", nonCanonH, "H (section 9)"); + } + + // ---- S7: Overwrite & in-place protection ---- + + @Test + void overwriteProtectionAndAtomicFailureRollback(@TempDir Path dir) throws Exception { + byte[] genesisBytes = buildValidGenesisBytes(); + Path in = dir.resolve("in.zkey"); + Files.write(in, genesisBytes); + + // In-place overwrite always rejected (even with overwrite=true) + assertThrows(IOException.class, () -> ZkeyContributor.contribute(in, in, "alice", false)); + assertThrows(IOException.class, () -> ZkeyContributor.contribute(in, in, "alice", true)); + assertArrayEquals(genesisBytes, Files.readAllBytes(in), "input file must remain intact"); + + // Symlink pointing to input also rejected + Path symlink = dir.resolve("alias.zkey"); + Files.createSymbolicLink(symlink, in); + assertThrows(IOException.class, () -> ZkeyContributor.contribute(in, symlink, "alice", true)); + assertArrayEquals(genesisBytes, Files.readAllBytes(in), "symlinked input must remain intact"); + + // Existing output rejected unless overwrite=true + Path existing = dir.resolve("existing.zkey"); + byte[] sentinel = "do-not-clobber".getBytes(); + Files.write(existing, sentinel); + assertThrows(IOException.class, () -> ZkeyContributor.contribute(in, existing, "alice")); + assertArrayEquals(sentinel, Files.readAllBytes(existing), "existing output must not be clobbered"); + + // Failed contribution with overwrite=true must NOT clobber existing output + Path badIn = dir.resolve("bad-l.zkey"); + Files.write(badIn, buildSyntheticZkey(G1, G2, new AffineG1[]{SMALL_SUBGROUP_G1, G1}, defaultH(), null)); + assertThrows(IOException.class, () -> ZkeyContributor.contribute(badIn, existing, "alice", true)); + assertArrayEquals(sentinel, Files.readAllBytes(existing), "failed overwrite must leave existing output intact"); + assertNoTempFiles(dir); + + // Explicit overwrite=true succeeds on valid input + byte[] hash = ZkeyContributor.contribute(in, existing, "alice", true); + assertEquals(64, hash.length); + assertFalse(Arrays.equals(sentinel, Files.readAllBytes(existing))); + assertNoTempFiles(dir); + } + + @Test + void encodeName_matchesSnarkjsUtf16TruncationAndReplacementChar() { + // 63 ASCII 'a' + 4-byte emoji (2 UTF-16 code units) => 63 'a' + lone high surrogate => 66B ending 61 EF BF BD + byte[] splitEmoji = ZkeyContributor.encodeName("a".repeat(63) + "\uD83D\uDE00"); + assertEquals(66, splitEmoji.length); + assertEquals((byte) 'a', splitEmoji[62]); + assertEquals((byte) 0xEF, splitEmoji[63]); + assertEquals((byte) 0xBF, splitEmoji[64]); + assertEquals((byte) 0xBD, splitEmoji[65]); + + // 64 rockets (128 UTF-16 code units) => truncated at 64 code units = 32 rockets = 128 UTF-8 bytes + byte[] rockets = ZkeyContributor.encodeName("\uD83D\uDE80".repeat(64)); + assertEquals(128, rockets.length); + assertArrayEquals("\uD83D\uDE80".repeat(32).getBytes(StandardCharsets.UTF_8), rockets); + + // Lone low surrogate replaced by U+FFFD + byte[] loneLow = ZkeyContributor.encodeName("x\uDC00y"); + assertArrayEquals(new byte[]{'x', (byte) 0xEF, (byte) 0xBF, (byte) 0xBD, 'y'}, loneLow); + } + + @Test + void rejectsSection10CountOverflowAndUnboundedCount(@TempDir Path dir) throws Exception { + // nContrib = 0xFFFFFFFF (would wrap uint32 on increment) + ByteArrayOutputStream overflowSec10 = new ByteArrayOutputStream(); + overflowSec10.write(new byte[64]); + writeU32(overflowSec10, -1); // 0xFFFFFFFF unsigned + assertRejects(dir, "u32-overflow.zkey", + buildSyntheticZkey(G1, G2, defaultL(), defaultH(), overflowSec10.toByteArray()), + "overflow uint32"); + + // Large nContrib exceeding section byte budget rejected before iterating + ByteArrayOutputStream hugeCountSec10 = new ByteArrayOutputStream(); + hugeCountSec10.write(new byte[64]); + writeU32(hugeCountSec10, 1_000_000); + assertRejects(dir, "huge-count.zkey", + buildSyntheticZkey(G1, G2, defaultL(), defaultH(), hugeCountSec10.toByteArray()), + "Invalid prior contribution count"); + } + + @Test + void publishFailsClosedOnCompetingWriterAndUnsupportedFilesystem_andPreservesPosixMode(@TempDir Path dir) + throws Exception { + Path in = dir.resolve("in.zkey"); + Files.write(in, buildValidGenesisBytes()); + + // Competing writer wins the race during createHardLink -> fails closed, destination untouched, no temp left + Path outRace = dir.resolve("race.zkey"); + byte[] winnerBytes = "competing-writer".getBytes(StandardCharsets.UTF_8); + ZkeyContributor.FilePublisher competingWriter = new ZkeyContributor.FilePublisher() { + @Override + public void createHardLink(Path target, Path existing) throws IOException { + Files.write(target, winnerBytes); + throw new FileAlreadyExistsException(target.toString()); + } + + @Override + public void atomicReplace(Path source, Path target) throws IOException { + throw new AssertionError("atomicReplace must not be called when overwrite=false"); + } + }; + IOException raceEx = assertThrows(IOException.class, + () -> ZkeyContributor.contribute(in, outRace, "alice", false, competingWriter)); + assertTrue(raceEx.getMessage().contains("already exists"), raceEx.getMessage()); + assertArrayEquals(winnerBytes, Files.readAllBytes(outRace)); + assertNoTempFiles(dir); + + // Unsupported hard-link filesystem on overwrite=false -> fails closed (no check-then-move fallback) + Path outNoLink = dir.resolve("nolink.zkey"); + ZkeyContributor.FilePublisher noHardLinks = new ZkeyContributor.FilePublisher() { + @Override + public void createHardLink(Path target, Path existing) { + throw new UnsupportedOperationException("hard links unsupported"); + } + + @Override + public void atomicReplace(Path source, Path target) { + throw new AssertionError("must not fall back to move when overwrite=false"); + } + }; + IOException noLinkEx = assertThrows(IOException.class, + () -> ZkeyContributor.contribute(in, outNoLink, "alice", false, noHardLinks)); + assertTrue(noLinkEx.getMessage().contains("hard links"), noLinkEx.getMessage()); + assertFalse(Files.exists(outNoLink)); + assertNoTempFiles(dir); + + // Unsupported atomic move on overwrite=true -> fails closed, existing output untouched + Path outNoAtomic = dir.resolve("noatomic.zkey"); + byte[] existingBytes = "keep-me".getBytes(StandardCharsets.UTF_8); + Files.write(outNoAtomic, existingBytes); + ZkeyContributor.FilePublisher noAtomicMove = new ZkeyContributor.FilePublisher() { + @Override + public void createHardLink(Path target, Path existing) { + throw new AssertionError("createHardLink must not be called when overwrite=true"); + } + + @Override + public void atomicReplace(Path source, Path target) throws IOException { + throw new AtomicMoveNotSupportedException(source.toString(), target.toString(), "unsupported"); + } + }; + IOException noAtomicEx = assertThrows(IOException.class, + () -> ZkeyContributor.contribute(in, outNoAtomic, "alice", true, noAtomicMove)); + assertTrue(noAtomicEx.getMessage().contains("atomic move"), noAtomicEx.getMessage()); + assertArrayEquals(existingBytes, Files.readAllBytes(outNoAtomic)); + assertNoTempFiles(dir); + + // POSIX permissions match input (public ceremony file is not forced to 0600) + try { + Set mode644 = PosixFilePermissions.fromString("rw-r--r--"); + Files.setPosixFilePermissions(in, mode644); + Path outPerms = dir.resolve("perms.zkey"); + ZkeyContributor.contribute(in, outPerms, "alice"); + assertEquals(mode644, Files.getPosixFilePermissions(outPerms)); + assertNoTempFiles(dir); + } catch (UnsupportedOperationException ignored) { + // Non-POSIX filesystem + } + } + + // ---- Helpers ---- + + private static void assertRejects(Path dir, String name, byte[] inputBytes, String expectedMessagePart) + throws IOException { + Path in = dir.resolve(name); + Path out = dir.resolve(name + ".out"); + Files.write(in, inputBytes); + IOException ex = assertThrows(IOException.class, () -> ZkeyContributor.contribute(in, out, "tester"), + "Expected rejection for " + name); + assertTrue(ex.getMessage().contains(expectedMessagePart), + "Expected message containing '" + expectedMessagePart + "', got: " + ex.getMessage()); + assertFalse(Files.exists(out), "Output file must not exist after failed contribution: " + name); + assertNoTempFiles(dir); + } + + private static void assertNoTempFiles(Path dir) throws IOException { + try (Stream files = Files.list(dir)) { + List temps = files.filter(p -> p.getFileName().toString().startsWith(".zeroj-zkey-")).toList(); + assertTrue(temps.isEmpty(), "Leftover temp files found: " + temps); + } + } + + private static byte[] buildValidGenesisBytes() throws IOException { + return buildSyntheticZkey(G1, G2, defaultL(), defaultH(), null); + } + + private static AffineG1[] defaultL() { + return new AffineG1[]{ + JacobianG1BLS381.GENERATOR.scalarMul(BigInteger.valueOf(3)).toAffine(), + JacobianG1BLS381.GENERATOR.scalarMul(BigInteger.valueOf(5)).toAffine() + }; + } + + private static AffineG1[] defaultH() { + return new AffineG1[]{ + JacobianG1BLS381.GENERATOR.scalarMul(BigInteger.valueOf(7)).toAffine(), + JacobianG1BLS381.GENERATOR.scalarMul(BigInteger.valueOf(11)).toAffine(), + JacobianG1BLS381.GENERATOR.scalarMul(BigInteger.valueOf(13)).toAffine(), + JacobianG1BLS381.GENERATOR.scalarMul(BigInteger.valueOf(17)).toAffine() + }; + } + + private static byte[] buildSyntheticZkey( + AffineG1 delta1, AffineG2 delta2, AffineG1[] lPoints, AffineG1[] hPoints, byte[] customSec10) + throws IOException { + int nPublic = 1; + int nVars = nPublic + 1 + lPoints.length; + int domainSize = hPoints.length; + + ByteArrayOutputStream out = new ByteArrayOutputStream(); + // File header: magic "zkey", version 1, 10 sections + writeU32(out, 0x79656b7a); + writeU32(out, 1); + writeU32(out, 10); + + // Section 1: protocol = 1 (groth16) + writeSection(out, 1, u32Bytes(1)); + + // Section 2: header (964 bytes) + ByteArrayOutputStream hdr = new ByteArrayOutputStream(); + writeU32(hdr, 48); + writeUnsignedLE(hdr, P, 48); + writeU32(hdr, 32); + writeUnsignedLE(hdr, R, 32); + writeU32(hdr, nVars); + writeU32(hdr, nPublic); + writeU32(hdr, domainSize); + hdr.write(g1Lem(G1)); // alpha1 + hdr.write(g1Lem(G1)); // beta1 + hdr.write(g2Lem(G2)); // beta2 + hdr.write(g2Lem(G2)); // gamma2 + hdr.write(g1Lem(delta1)); // delta1 + hdr.write(g2Lem(delta2)); // delta2 + assertEquals(964, hdr.size()); + writeSection(out, 2, hdr.toByteArray()); + + // Section 3: IC (nPublic + 1 G1 points) + ByteArrayOutputStream s3 = new ByteArrayOutputStream(); + for (int i = 0; i <= nPublic; i++) s3.write(g1Lem(G1)); + writeSection(out, 3, s3.toByteArray()); + + // Section 4: coeffs (0 entries) + writeSection(out, 4, u32Bytes(0)); + + // Section 5 (A), 6 (B1), 7 (B2) + ByteArrayOutputStream s5 = new ByteArrayOutputStream(); + ByteArrayOutputStream s6 = new ByteArrayOutputStream(); + ByteArrayOutputStream s7 = new ByteArrayOutputStream(); + for (int i = 0; i < nVars; i++) { + s5.write(g1Lem(G1)); + s6.write(g1Lem(G1)); + s7.write(g2Lem(G2)); + } + writeSection(out, 5, s5.toByteArray()); + writeSection(out, 6, s6.toByteArray()); + writeSection(out, 7, s7.toByteArray()); + + // Section 8 (L) + ByteArrayOutputStream s8 = new ByteArrayOutputStream(); + for (AffineG1 p : lPoints) s8.write(g1Lem(p)); + writeSection(out, 8, s8.toByteArray()); + + // Section 9 (H) + ByteArrayOutputStream s9 = new ByteArrayOutputStream(); + for (AffineG1 p : hPoints) s9.write(g1Lem(p)); + writeSection(out, 9, s9.toByteArray()); + + // Section 10 (contributions) + if (customSec10 != null) { + writeSection(out, 10, customSec10); + } else { + ByteArrayOutputStream s10 = new ByteArrayOutputStream(); + byte[] csHash = new byte[64]; + for (int i = 0; i < 64; i++) csHash[i] = (byte) (i + 1); + s10.write(csHash); + writeU32(s10, 0); + writeSection(out, 10, s10.toByteArray()); + } + + return out.toByteArray(); + } + + private static byte[] mutateSectionSize(byte[] valid, int targetSection, int extraBytes) { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + out.write(valid, 0, 12); + int pos = 12; + ByteBuffer buf = ByteBuffer.wrap(valid).order(ByteOrder.LITTLE_ENDIAN); + while (pos < valid.length) { + int type = buf.getInt(pos); + long size = buf.getLong(pos + 4); + long newSize = type == targetSection ? size + extraBytes : size; + writeU32(out, type); + writeU64(out, newSize); + out.write(valid, pos + 12, (int) size); + if (type == targetSection) { + out.write(new byte[extraBytes], 0, extraBytes); + } + pos += 12 + (int) size; + } + return out.toByteArray(); + } + + private static int findSectionHeaderOffset(byte[] zkey, int targetType) { + ByteBuffer buf = ByteBuffer.wrap(zkey).order(ByteOrder.LITTLE_ENDIAN); + int pos = 12; + while (pos < zkey.length) { + int type = buf.getInt(pos); + long size = buf.getLong(pos + 4); + if (type == targetType) return pos; + pos += 12 + (int) size; + } + throw new IllegalArgumentException("Section not found: " + targetType); + } + + private static long findSectionOffset(byte[] zkey, int targetType) { + return findSectionHeaderOffset(zkey, targetType) + 12L; + } + + private static AffineG2 buildSmallSubgroupG2() { + // Find smallest integer x >= 0 where y^2 = x^3 + 4(1+u) has a root in Fp2 not in the r-subgroup. + Fp2 bTwist = Fp2.of(Fp.of(4), Fp.of(4)); + for (int xi = 0; xi < 100; xi++) { + Fp2 x = Fp2.of(Fp.of(xi), Fp.ZERO); + Fp2 rhs = x.square().mul(x).add(bTwist); + var yOpt = rhs.sqrt(); + if (yOpt.isPresent()) { + Fp2 y = yOpt.get(); + AffineG2 candidate = new AffineG2( + MontFp2_381.of(x.c0().value(), x.c1().value()), + MontFp2_381.of(y.c0().value(), y.c1().value())); + if (candidate.isOnCurve() + && !JacobianG2BLS381.fromAffine(candidate.x(), candidate.y()).scalarMul(R).isInfinity()) { + return candidate; + } + } + } + throw new AssertionError("Failed to find non-subgroup G2 point"); + } + + private static AffineG1 readG1(byte[] b, int off) { + MontFp381 x = readMontFp(b, off); + MontFp381 y = readMontFp(b, off + 48); + return (x.isZero() && y.isZero()) ? AffineG1.INFINITY : new AffineG1(x, y); + } + + private static AffineG2 readG2(byte[] b, int off) { + MontFp381 x0 = readMontFp(b, off); + MontFp381 x1 = readMontFp(b, off + 48); + MontFp381 y0 = readMontFp(b, off + 96); + MontFp381 y1 = readMontFp(b, off + 144); + if (x0.isZero() && x1.isZero() && y0.isZero() && y1.isZero()) return AffineG2.INFINITY; + return new AffineG2(MontFp2_381.of(x0, x1), MontFp2_381.of(y0, y1)); + } + + private static MontFp381 readMontFp(byte[] b, int off) { + ByteBuffer bb = ByteBuffer.wrap(b, off, 48).order(ByteOrder.LITTLE_ENDIAN); + return MontFp381.fromMontLimbs( + bb.getLong(), bb.getLong(), bb.getLong(), bb.getLong(), bb.getLong(), bb.getLong()); + } + + private static byte[] g1Lem(AffineG1 p) { + byte[] out = new byte[96]; + if (p.isInfinity()) return out; + putLimbs(p.x().toLimbs(), out, 0); + putLimbs(p.y().toLimbs(), out, 48); + return out; + } + + private static byte[] g2Lem(AffineG2 p) { + byte[] out = new byte[192]; + if (p.isInfinity()) return out; + putLimbs(p.x().re().toLimbs(), out, 0); + putLimbs(p.x().im().toLimbs(), out, 48); + putLimbs(p.y().re().toLimbs(), out, 96); + putLimbs(p.y().im().toLimbs(), out, 144); + return out; + } + + private static void putLimbs(long[] limbs, byte[] out, int off) { + ByteBuffer bb = ByteBuffer.wrap(out, off, 48).order(ByteOrder.LITTLE_ENDIAN); + for (long l : limbs) bb.putLong(l); + } + + private static void putUnsignedLE(byte[] out, int off, BigInteger v, int len) { + byte[] be = v.toByteArray(); + Arrays.fill(out, off, off + len, (byte) 0); + int start = Math.max(0, be.length - len); + int count = be.length - start; + for (int i = 0; i < count; i++) { + out[off + i] = be[be.length - 1 - i]; + } + } + + private static void writeUnsignedLE(ByteArrayOutputStream out, BigInteger v, int len) { + byte[] buf = new byte[len]; + putUnsignedLE(buf, 0, v, len); + out.write(buf, 0, len); + } + + private static void writeSection(ByteArrayOutputStream out, int type, byte[] data) throws IOException { + writeU32(out, type); + writeU64(out, data.length); + out.write(data); + } + + private static void writeU32(ByteArrayOutputStream out, int v) { + out.write(v); + out.write(v >>> 8); + out.write(v >>> 16); + out.write(v >>> 24); + } + + private static void writeU64(ByteArrayOutputStream out, long v) { + for (int i = 0; i < 8; i++) out.write((int) (v >>> (8 * i))); + } + + private static byte[] u32Bytes(int v) { + return new byte[]{(byte) v, (byte) (v >>> 8), (byte) (v >>> 16), (byte) (v >>> 24)}; + } + + private static void putU32(byte[] b, int off, int v) { + b[off] = (byte) v; + b[off + 1] = (byte) (v >>> 8); + b[off + 2] = (byte) (v >>> 16); + b[off + 3] = (byte) (v >>> 24); + } + + private static void putU64(byte[] b, int off, long v) { + for (int i = 0; i < 8; i++) b[off + i] = (byte) (v >>> (8 * i)); + } + + private static G1Point toG1(AffineG1 p) { + return p.isInfinity() ? G1Point.INFINITY : new G1Point(Fp.of(p.xBigInt()), Fp.of(p.yBigInt())); + } + + private static G2Point toG2(AffineG2 p) { + if (p.isInfinity()) return G2Point.INFINITY; + return new G2Point( + Fp2.of(Fp.of(p.x().reBigInt()), Fp.of(p.x().imBigInt())), + Fp2.of(Fp.of(p.y().reBigInt()), Fp.of(p.y().imBigInt()))); + } +}