Skip to content

Harden ZkeyContributor validation, ctScalarMul, and CI snarkjs interop (ADR-0031) - #120

Merged
satran004 merged 2 commits into
mainfrom
fix/adr-0031-zkey-contributor-hardening
Nov 21, 2026
Merged

satran004 merged 2 commits into
mainfrom
fix/adr-0031-zkey-contributor-hardening

Conversation

@satran004

Copy link
Copy Markdown
Member

Summary

Hardens ZeroJ's Groth16 phase-2 MPC ceremony contributor (ZkeyContributor / CeremonyCli) under an R3 amendment to ADR-0031, and wires fail-closed snarkjs@0.7.6 CI coverage for all four ceremony and streaming .zkey interop suites.

Risk classification: R3 (ZkeyContributor secret-scalar operations on untrusted .zkey inputs) + R1/Process (CI snarkjs interop wiring).

1. Governing ADR-0031 R3 Hardening Amendment (Proposed)

  • Adds threat model, trust assumptions (ADR-0062 I3 honest secret-path contract: offline/isolated host remains mandatory; no JVM constant-time claim), pinned snarkjs@0.7.6 / ffjavascript@0.3.1 references, exact invariants (S1–S7), measured throughput trade-off (3.57× vs unvalidated variable-time scalarMul), breaking/compatibility notes, milestones, and revision history in docs/adr/0031-groth16-mpc-trusted-setup-ceremony.md.
  • Updates docs/ceremony/USER-GUIDE.md with --overwrite, offline/isolated host guidance, and the measured timing estimate.

2. ZkeyContributor & CeremonyCli Hardening (S1–S7)

  • Pre-secret structural & cryptographic validation (before drawing k/s):
    • Exact file framing (magic, version {1, 2}, 10 unique sections 1..10, no OOB/negative/duplicate/unknown sections, zero trailing bytes, protocol 1, header length 964).
    • Exact BLS12-381 primes (n8q == 48, q == FP, n8r == 32, r == FR) and dimension-matched section sizes for sections 3–9.
    • Canonical < p Montgomery limb decoding via MontFp381.fromMontLimbs (no silent .mod(p) reduction) and explicit G2 infinity sentinel in g2FromLem.
    • All 6 header VK points and all prior contribution points validated as canonical, non-infinity, on-curve, and in the prime-order subgroup.
    • Pairing consistency check e(delta1, G2) == e(G1, delta2) and chain continuity check (delta1 == G1 at 0 priors, delta1 == lastPrior.deltaAfter for >= 1 priors), plus strict sorted TLV validation on section-10 params.
  • Secret-scalar routing & pinned L/H infinity semantics:
    • All multiplications by s, k, and k⁻¹ routed through ADR-0062 JacobianG1BLS381.ctScalarMul / JacobianG2BLS381.ctScalarMul (checking L/H points on-curve + prime-order subgroup once inside ctScalarMul and surfacing worker errors cleanly as IOException).
    • Preserves all-zero 96-byte LEM infinity entries in L/H (k⁻¹ · O = O, zero secret leakage), matching snarkjs@0.7.6 (zkey_new.js:460-466, mpc_applykey.js:44).
  • Atomic file safety & UTF-8 --name guard:
    • Writes to a sibling temp file, forces to storage, unmaps/closes, and publishes atomically (createLink / ATOMIC_MOVE), cleaning up temp files on any error.
    • Unconditionally rejects --in == --out (including symlinks via Files.isSameFile).
    • Rejects existing --out unless explicit overwrite = true / --overwrite is supplied.
    • Truncates --name on code-point boundaries (<= 64 code points and <= 255 UTF-8 bytes) to prevent surrogate splits and 1-byte TLV length overflow.

3. Fail-Closed snarkjs@0.7.6 CI Interop

  • Adds shared non-published SnarkjsCliLocator in zeroj-crypto testFixtures (excluded from published metadata per ADR-0046) resolving snarkjs@0.7.6 from -Dzeroj.snarkjs, SNARKJS_BIN, PATH, and common npm directories.
  • Forwards -Dzeroj.snarkjs and -PrequireSnarkjs in zeroj-crypto, zeroj-tools, and zeroj-integration-tests.
  • Updates R1csSnarkjsCeremonyRoundTripTest, ZkeyPkStoreImporterTest, ZkeyContributorInteropTest, and CeremonyCliTest to use SnarkjsCliLocator and fail closed under -PrequireSnarkjs.
  • Wires all four suites into .github/workflows/assurance.yml (snarkjs-interop job) and uploads all three module test reports.

Breaking / Compatibility Notes

  • ZkeyContributor.contribute(Path, Path, String) now throws IOException if out already exists (previously deleted out unconditionally). Use contribute(in, out, name, true) or zeroj-ceremony contribute --overwrite to replace an existing output; in-place --in == --out is always rejected.
  • Malformed or unvalidated .zkey inputs (wrong primes, non-canonical coordinates, invalid points, mismatched delta1/delta2, broken prior chains) now fail closed.
  • Output .zkey wire format remains 100% bit-compatible with snarkjs@0.7.6.

Verification

  • ./gradlew -PrequireSnarkjs :zeroj-tools:check :zeroj-crypto:check :zeroj-integration-tests:test --tests 'org.zeroj.it.snarkjs.SnarkjsGroth16InteropTest' --stacktrace — PASSED (live snarkjs@0.7.6 verified mixed-tool ceremony transcripts + streaming .zkey import + ADR-0046 GenerateModuleMetadata check + all new offline adversarial tests in ZkeyContributorTest and CeremonyCliTest).
  • Measured parallel G1 rescaling throughput on 16-core Java 25 (n = 4,096): 19,006 muls/s (scalarMul) vs 5,326 muls/s (ctScalarMul, 3.57×), recorded in ADR-0031.

@satran004
satran004 requested a review from a team as a code owner November 20, 2026 15:56
@satran004

Copy link
Copy Markdown
Member Author

[reviewer1] Changes requested on d655ceb4397e7ab974c6dc5ce5355c7f2caf6003. I ran all four ceremony/streaming interop suites and the contributor unit suite on this revision with Java 25 and required snarkjs 0.7.6. All 15 tests passed with zero skips. The header delta pairing equation, canonical Montgomery decoding, and subgroup checks on the actual L/H points used for secret multiplication agree with the stated design.

  1. Preserve the publication guarantees on every filesystem path. In ZkeyContributor.publishTempFile (lines 419–444), a failed hard link leads to an existence check followed by ATOMIC_MOVE. Java permits that move to replace a concurrently created target. Both move paths also fall back to non-atomic moves. Fail closed when the filesystem cannot provide the requested semantics. Separate successful link creation from temp-file cleanup so a cleanup error cannot be reported as a competing destination. Force the mapped output segment before closing its arena to meet S7's content-flush guarantee. Please cover competing writers and unsupported operations. Java 25 Files.move
  2. Bound Section 10 heap use before allocation. At lines 255–265 the unsigned count is checked against file length, narrowed to an int, and passed directly to new ArrayList<>(nContrib). A large or sparse input can allocate a large reference array before the first record is validated. The method also retains every raw record and decoded point until publication. Stream the transcript hash and keep only the last delta plus the validated range to copy, or enforce and document an operational count/byte cap before allocation and narrowing. Check that the incremented count fits the wire format. Add a boundary test.
  3. Correct two compatibility claims. snarkjs 0.7.6 truncates names to 64 UTF-16 code units. ZeroJ truncates to 64 Unicode code points and 255 bytes. With 64 supplementary characters the tools retain 32 and 63 respectively, so a later snarkjs contribution rewrites prior name metadata. Align the common boundary and document any intentional surrogate-boundary difference, or explicitly document ZeroJ's different policy. Test the serialized name across a snarkjs round trip. Also narrow the ADR's “rejected before secret generation” wording to header/prior checks. Sections L/H are checked per point during rescaling after sampling. Pinned snarkjs name writer

One test improvement: the mixed-tool interop test exports the final verification key but only checks whether the generated proof points lie on their curves. Verify the proof against that key and its public input to substantiate the test's end-to-end verification claim.

@satran004

Copy link
Copy Markdown
Member Author

[reviewer3] Review of head d655ceb4 — CHANGES REQUESTED

Scope: engineering, cross-backend, CI/build wiring, docs/links.

What I verified

  • Ran ./gradlew -PrequireSnarkjs :zeroj-tools:test :zeroj-crypto:test --tests '*R1csSnarkjsCeremonyRoundTripTest' --tests '*ZkeyPkStoreImporterTest' in a clean worktree at d655ceb4 with snarkjs 0.7.6 on PATH. BUILD SUCCESSFUL. The JUnit XML shows 0 skipped: CeremonyCliTest 5/5, ZkeyContributorInteropTest 1/1, ZkeyContributorTest 7/7, R1csSnarkjsCeremonyRoundTripTest 1/1, ZkeyPkStoreImporterTest 1/1. So the fail-closed wiring runs the suites instead of quietly skipping them.

  • Checked the snarkjs 0.7.6 citations against the installed package source:

    • zkey_utils.js readContribution: sorted TLV tags 1/2/3, "Parameters do not match".
    • zkey_new.js:460-466: the zero-point branch.
    • mpc_applykey.js:44: batchApplyKey.
    • zkey_verify_frominit.js:48,141: curDelta = G1.g and the delta1 check.

    All match the ADR text.

  • Framing (S1/S2): sizes are bounds-checked before every read; duplicate and unknown sections, trailing bytes and section sizes derived from the header are all rejected; section 4 is 4 + 44·nCoeffs.

  • Canonical decoding goes through MontFp381.fromMontLimbs, which throws on limbs >= p rather than reducing. The G2 infinity sentinel is present.

  • Every multiplication by k, k⁻¹ and s goes through ctScalarMul. For L/H, the invalid-point IllegalArgumentException raised inside parallelRange is mapped to a single IOException, and no temp file or output is left behind (covered by assertNoTempFiles).

  • CLI and library both reject in-place use, including via isSameFile for symlinks and hard links.

  • zeroj-tools → testFixtures(zeroj-crypto) is test-scoped only, and the fixtures variants stay skipped from the published component (ADR-0046).

  • The assurance.yml -PrequireSnarkjs step now covers zeroj-crypto and zeroj-tools, and the report upload paths cover all three modules.

  • Java style: no new inline FQNs; the interop test FQNs are now imports.

Blocking

  1. The ceremony docs now contradict the PR's own measurement. The PR raises the 19M-constraint contribution estimate to ~4.0 h (docs/ceremony/USER-GUIDE.md:44, ADR-0031 amendment). That is slower than the ~2.5–3 h quoted for snarkjs. Three places still state the old numbers or claim ZeroJ is faster:

    • docs/ceremony/USER-GUIDE.md:171-172, in the same file this PR edits: "ZeroJ is ~3× faster on large circuits (measured: ~0.9 h vs ~2.5–3 h …)".
    • www/src/content/docs/guides/proving/trusted-setup-ceremony.mdx:148-150: "roughly 0.9 hours versus 2.5 to 3 hours for snarkjs".
    • docs/adr/0031-groth16-mpc-trusted-setup-ceremony.md:170 (M5 row, "≈ 0.9 h"). This row is historical, so a "superseded by the 2026-11-20 amendment measurement" note is enough.

    Please also bring the www page up to date with this PR's CLI and API changes:

    • The options table at trusted-setup-ceremony.mdx:140-144 has no --overwrite row and no note that --out must not already exist.
    • Line 169 presents ZkeyContributor.contribute(in, out, name) without saying it now throws if out exists. The 4-argument overload should be mentioned.
    • The offline/isolated-host requirement that USER-GUIDE.md now states is missing.

Non-blocking (P3)

  1. --name truncation does not match snarkjs 0.7.6 for non-BMP characters, so the "100% bit-compatible" claim is not quite accurate. snarkjs (zkey_utils.js:514) does new TextEncoder().encode(c.name.substring(0,64)). That cuts at 64 UTF-16 code units, and a split surrogate pair is encoded as U+FFFD (EF BF BD). encodeName instead cuts at 64 code points with a 255-byte cap. Checked with node:

    • "a".repeat(63) + "😀": snarkjs writes 66 bytes ending …61 EF BF BD; ZeroJ writes 67 bytes containing the whole emoji.
    • "🚀".repeat(64): snarkjs writes 128 bytes (32 emoji); ZeroJ writes 252 bytes (63 emoji). ZkeyContributorTest:121-124 uses this input, but only checks that the contribution succeeds.

    The name is not part of any hash, so snarkjs zkey verify is unaffected. Two ways to fix it:

    • Match snarkjs: truncate at min(64, length()) code units, and replace an unpaired surrogate (including one created by the cut) with U+FFFD before UTF-8 encoding. Java's getBytes writes ? there; TextEncoder writes U+FFFD. The 255-byte cap then cannot trigger, since the maximum is 192 bytes. Add a known-answer test with the byte strings above.
    • Keep the current behaviour: reword S7, the Javadoc and the "Wire compatibility" line to describe the deviation.
  2. SnarkjsCliLocator ignores a bad explicit override. If -Dzeroj.snarkjs or SNARKJS_BIN points to a wrong-version or broken binary, the locator moves on to PATH and the common install directories, and can pass using a different binary. Under -PrequireSnarkjs an explicit override should be authoritative and fail closed. Otherwise a pinned SNARKJS_BIN in CI could stop being the binary under test without anyone noticing.

  3. Two snarkjs locators remain, and their discovery orders differ. zeroj-integration-tests still uses SnarkjsProver.findSnarkjs() plus SnarkjsInteropSupport.version(). SnarkjsProver.findSnarkjs() checks the property, then the env var, then Path.of("snarkjs") resolved against the working directory, then the common directories. The ADR text calls SnarkjsCliLocator "shared". Also, the SnarkjsInteropSupport class Javadoc ("SNARKJS_BIN, then common npm locations, then PATH") is now out of date because the system property is checked first. Either migrate the integration tests to SnarkjsCliLocator (it is already a test fixture) or fix the Javadoc and narrow the ADR wording.

  4. Publish-path edge cases in publishTempFile:

    • If createLink fails with an IOException other than FileAlreadyExistsException, the code falls back to an exists-check followed by move(ATOMIC_MOVE). That is check-then-act, and on POSIX rename(2) replaces the target, so the "non-clobbering" guarantee in S7 does not hold on that path. At least note it in S7.
    • Files.createTempFile creates the file with mode 0600 on POSIX, so the published .zkey is now owner-only. Before this PR it was created with the umask default, typically 0644. The .zkey is public material that participants hand on, so either set the permissions explicitly (for example, match the input's permissions) or mention the change in the compatibility notes.

Copy link
Copy Markdown

Initial automated review · Aster

Hi @satran004, thanks for the PR! 🙏 This is an automatic first check by an AI reviewer. It does not replace maintainer review and may be wrong.

Reviewed commit: d655ceb4397e7ab974c6dc5ce5355c7f2caf6003

Issues found:

  • zeroj-tools/src/main/java/org/zeroj/tools/zkey/ZkeyContributor.java:433 — On Linux VFAT, which lacks hard links, concurrent contributions can pass the existence check and overwrite each other through ATOMIC_MOVE despite overwrite=false. Could we fail closed when atomic publication without replacement is unavailable?

Not tested: Code and tests were read only; I did not run ceremonies, interop tests, or filesystem race tests.

…tion 10 streaming, UTF-16 name parity, and ceremony docs
@satran004

Copy link
Copy Markdown
Member Author

Addressed all review items from [reviewer1] and [reviewer3] in 80f543d3:

  1. Strict fail-closed atomic publication, mapped flush, and POSIX permissions (ZkeyContributor.java, ADR-0031 S7):

    • Calls o.force() on the mapped output MemorySegment before closing its Arena and outCh.force(true) before closing FileChannel.
    • Removed the check-then-move and non-atomic move fallbacks in publishTempFile: !overwrite requires Files.createLink (fails closed on FileAlreadyExistsException or unsupported filesystems), and overwrite requires Files.move(..., ATOMIC_MOVE, REPLACE_EXISTING) (fails closed on AtomicMoveNotSupportedException).
    • Separated temp-file unlink from hard-link publication so cleanup errors cannot be misreported as a competing destination.
    • Copies POSIX permissions from --in to the staged temp file on POSIX filesystems so public ceremony .zkey files are not silently downgraded to 0600.
    • Added ZkeyContributorTest.publishFailsClosedOnCompetingWriterAndUnsupportedFilesystem_andPreservesPosixMode.
  2. Bounded O(1)-heap Section 10 streaming & u32 overflow check (ZkeyContributor.java, ADR-0031 S4):

    • Removed the per-record ArrayList and byte[] buffering: Section 10 transcript hashing now streams directly during validation, keeping only lastDeltaAfter, and copies the validated prior-record byte range directly via MemorySegment.copy.
    • Rejects nContrib >= 0xFFFFFFFF before incrementing so the uint32 wire count cannot wrap.
    • Added ZkeyContributorTest.rejectsSection10CountOverflowAndUnboundedCount.
  3. Bit-exact snarkjs@0.7.6 UTF-16 --name truncation & narrowed validation timing wording (ZkeyContributor.java, ADR-0031):

    • encodeName now truncates at 64 UTF-16 code units and replaces unpaired surrogates (including splits at index 64) with U+FFFD (EF BF BD), matching new TextEncoder("utf-8").encode(c.name.substring(0, 64)) bit-for-bit (max 192 bytes).
    • Added exact KATs in ZkeyContributorTest.encodeName_matchesSnarkjsUtf16TruncationAndReplacementChar ("a".repeat(63) + "😀" -> 66B ending 61 EF BF BD; "🚀".repeat(64) -> 128B) and exercised "a".repeat(63) + "😀" in ZkeyContributorInteropTest through live snarkjs zkey verify + snarkjs zkey contribute.
    • Narrowed ADR-0031 wording to state that header/prior checks run before secret sampling while L/H points are validated per point during rescaling right before each ctScalarMul.
  4. Mixed-tool interop proof pairing verification (ZkeyContributorInteropTest.java):

    • Added full BLS12381Pairing.pairingCheck verification of the mixed-tool ceremony proof against the exported vk.json and witness[1].
  5. Ceremony docs synchronized (docs/adr/0031-groth16-mpc-trusted-setup-ceremony.md, docs/ceremony/USER-GUIDE.md, www/src/content/docs/guides/proving/trusted-setup-ceremony.mdx):

    • Updated USER-GUIDE.md FAQ, trusted-setup-ceremony.mdx (timing, --overwrite option, non-existing --out, 4-arg ZkeyContributor.contribute, offline/isolated-host contract), and annotated the historical ADR-0031 M5 row as superseded by the 2026-11-20 measurement.
  6. Authoritative overrides & unified SnarkjsCliLocator across all 3 modules (SnarkjsCliLocator.java, SnarkjsCliLocatorTest.java, zeroj-integration-tests):

    • Explicit -Dzeroj.snarkjs and SNARKJS_BIN are now authoritative (fail closed if missing or wrong version rather than falling through to PATH), covered by SnarkjsCliLocatorTest.
    • Migrated zeroj-integration-tests (SnarkjsInteropSupport and SnarkjsProver) onto the shared SnarkjsCliLocator fixture and updated SnarkjsInteropSupport Javadoc.

Verification (80f543d3):
./gradlew -PrequireSnarkjs :zeroj-tools:test :zeroj-crypto:test --tests 'org.zeroj.crypto.groth16.R1csSnarkjsCeremonyRoundTripTest' --tests 'org.zeroj.crypto.groth16.ZkeyPkStoreImporterTest' --tests 'org.zeroj.crypto.testsupport.SnarkjsCliLocatorTest' :zeroj-crypto:generateMetadataFileForMavenJavaPublication :zeroj-integration-tests:test --tests 'org.zeroj.it.snarkjs.SnarkjsGroth16InteropTest' --stacktrace — BUILD SUCCESSFUL, 0 skipped.

Ready for Round 2 re-review from [reviewer1] and [reviewer3].

@satran004

Copy link
Copy Markdown
Member Author

[reviewer1] Approved on 80f543d39508223755781027a880b5e5d1f5dd7a. I rechecked the full PR against the base and the revisions since my first review. Publication now uses atomic create-if-absent or explicitly requested atomic replacement and flushes the mapped bytes first. Section 10 hashes one record at a time and guards the wire count before incrementing it. The name encoder matches the pinned snarkjs UTF-16 boundary and replacement behavior. The ADR describes when each group check runs and retains the offline-host and external-review requirements.

I ran the contributor, ceremony, streaming import, oracle locator, and bidirectional Groth16/PlonK interop tests from a clean snapshot of this SHA with -PrequireSnarkjs. All 35 passed with zero skips. The mixed-tool test now checks the actual Groth16 pairing equation against the snarkjs-exported VK and the public input.

@satran004

Copy link
Copy Markdown
Member Author

[reviewer3] Re-review of head 80f543d3 — APPROVED

All five points from my review of d655ceb4 are resolved:

  1. Docs vs measurement: fixed. USER-GUIDE.md FAQ, the www ceremony page (adds the --overwrite row, the "out must not exist" rule, the offline/isolated-host note, and the 4-argument library call) and the ADR-0031 M5 row (marked as superseded) now all match the ~4.0 h estimate and say ZeroJ is slower than snarkjs at that size.
  2. encodeName: now cuts at 64 UTF-16 code units and replaces unpaired surrogates with U+FFFD. I checked the known-answer bytes in ZkeyContributorTest against node TextEncoder: 63×'a'+😀 gives 66 B ending EF BF BD, and 🚀×64 gives 128 B. Both match.
  3. Explicit -Dzeroj.snarkjs / SNARKJS_BIN: these are now authoritative and fail closed instead of falling back to PATH, with a unit test for each case.
  4. Single shared locator: SnarkjsInteropSupport and SnarkjsProver now use SnarkjsCliLocator, and the Javadoc order is correct.
  5. Publish path: there is no check-then-move fallback any more. Without --overwrite, publishing uses a hard link and fails closed if out exists or links are unsupported. With --overwrite, it uses an atomic move and fails closed if that is unsupported. POSIX permissions are copied from --in. The publish logic can be swapped in tests, and it is tested for a competing writer and for an unsupported filesystem.

Also checked: Section 10 is now streamed (the prior-record byte range is copied mapping-to-mapping, and the transcript hash input is unchanged). The nContrib + 1 uint32 overflow guard is present. MemorySegment.force() runs before the channel force(true).

Verification (clean worktree at 80f543d3, snarkjs 0.7.6, -PrequireSnarkjs): BUILD SUCCESSFUL, 0 skipped.

Module Suite Tests
zeroj-tools ZkeyContributorTest 10
zeroj-tools CeremonyCliTest 5
zeroj-tools ZkeyContributorInteropTest 1
zeroj-crypto R1csSnarkjsCeremonyRoundTripTest 1
zeroj-crypto ZkeyPkStoreImporterTest 1
zeroj-crypto SnarkjsCliLocatorTest 3
zeroj-integration-tests it.snarkjs.* 14

verifyDefaultModuleSurface also passes with the new testFixtures(zeroj-crypto) test edges.

Non-blocking follow-ups (optional):

  • After a successful no-overwrite publish, Files.deleteIfExists(tmp) can still throw. contribute then fails even though out is already in place, the contribution hash is never returned, and a retry is refused because out exists. Consider catching that error and printing a warning instead.
  • The default (no --overwrite) path now needs hard-link support, so it fails closed on FAT/exFAT. Air-gapped contributors often move files on that kind of USB media. A line in USER-GUIDE.md would help: write --out to a local disk, then copy it.

@satran004
satran004 merged commit af4caa3 into main Nov 21, 2026
8 of 9 checks passed
@satran004
satran004 deleted the fix/adr-0031-zkey-contributor-hardening branch November 21, 2026 09:56
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants