Skip to content

Fix streaming PtauImporterBLS381, size PlonK t3 to n+6, and withdraw PlonKZkeyImporterBLS381 (ADR-0066) - #121

Merged
satran004 merged 3 commits into
mainfrom
fix/adr-0066-plonk-ptau-and-zkey-import
Nov 21, 2026
Merged

satran004 merged 3 commits into
mainfrom
fix/adr-0066-plonk-ptau-and-zkey-import

Conversation

@satran004

Copy link
Copy Markdown
Member

Summary

Fixes BLS12-381 PlonK .ptau SRS import and quotient-split SRS sizing, explicitly withdraws the incompatible snarkjs PlonK .zkey importer, adds a live same-power snarkjs@0.7.6 .ptau -> setup -> prove -> snarkjs plonk verify CI test, and aligns documentation under ADR-0066 (Proposed).

Stacked base: Based on fix/adr-0031-zkey-contributor-hardening (PR #120) to reuse SnarkjsCliLocator, -PrequireSnarkjs, and the assurance.yml snarkjs-interop job cleanly.

Risk classification: R2 (untrusted .ptau SRS import boundary, PlonK SRS sizing, withdrawal of broken .zkey importer).

1. Streaming PtauImporterBLS381 (ADR-0066 I1–I2)

  • Fixes the base-field prime check (reads raw unsigned LE q and checks exact equality with MontFp381.modulus(), instead of rejecting prime == FP as non-canonical).
  • Parses the full 60-byte snarkjs@0.7.6 Section 1 header (n8, q, power, ceremonyPower) and enforces exact Section 2 ((2^(power+1) - 1) * 96) and Section 3 (2^power * 192) sizes, rejecting duplicate sections, out-of-order sections, and trailing bytes.
  • Replaces whole-file 64 MiB buffering with a sequential streaming reader (DigestInputStream for full-stream SHA-256 verification before pairing checks), so multi-GB ceremony .ptau files load maxPoints powers in O(maxPoints) RAM.
  • Decodes every loaded point via canonical < p MontFp381.fromMontLimbs(...), rejects infinity on SRS G1/G2 entries (and defensively handles isInfinity() in toG1/toG2), verifies curve + prime-order subgroup membership, and checks e(tau^i·G1, G2) == e(tau^(i-1)·G1, tau·G2).

2. Exact t3 = n + 6 Quotient-Split & SRS Sizing (ADR-0066 I3)

  • Sizes t3 in PlonKProverBLS381 to exact length n + 6 (indices 2n .. 3n + 5) and asserts all trailing quotient coefficients at >= 3n + 6 are zero (matching snarkjs@0.7.6 plonk_prove.js:649-684).
  • Lowers the required SRS G1 length from 2n to n + 6 across PlonKSetupBLS381, PlonKProverBLS381, and PlonkSetupCache, enabling same-power snarkjs .ptau files (2n - 1 >= n + 6 for n >= 8) to work end to end.

3. Explicit Withdrawal of PlonKZkeyImporterBLS381 (ADR-0066 I4)

  • Both PlonKZkeyImporterBLS381.importZkey(...) overloads now throw UnsupportedOperationException citing ADR-0066 and directing callers to PtauImporterBLS381 + PlonKSetupBLS381, instead of failing with a misleading prime-canonicality IOException.

4. Documentation & CI Alignment (ADR-0066 I5)

  • Adds PtauImporterBLS381Test (including live same-power snarkjs@0.7.6 .ptau -> setup -> prove -> snarkjs plonk verify) to .github/workflows/assurance.yml under -PrequireSnarkjs.
  • Updates README.md, www/src/content/docs/guides/proving/plonk.md, www/src/content/docs/start/status.md, docs/adr/0047-snarkjs-bidirectional-interop-export-and-ci.md, and zeroj-crypto/README.md to remove inaccurate .zkey import / Beta / 9-blinder claims and document streaming .ptau import.

Breaking / Compatibility Notes

  • PlonKZkeyImporterBLS381.importZkey(...) now throws UnsupportedOperationException (no in-repo production callers existed).
  • PtauImporterBLS381 now enforces the exact 60-byte snarkjs@0.7.6 Section 1 header and exact Section 2/3 sizes matching power.
  • PlonKSetupBLS381, PlonKProverBLS381, and PlonkSetupCache now accept SRS lengths in [domainSize + 6, 2 * domainSize) that were previously rejected.

Verification

  • ./gradlew -PrequireSnarkjs :zeroj-crypto:test --tests 'org.zeroj.crypto.plonk.*' --tests 'org.zeroj.crypto.setup.SetupCacheTest' :zeroj-verifier-plonk:test :zeroj-integration-tests:test --tests 'org.zeroj.it.snarkjs.SnarkjsPlonkInteropTest' --stacktrace — PASSED (including offline 70 MiB streaming test, negative SRS/point/hash tests, exact n + 6 SRS test, and live same-power snarkjs@0.7.6 .ptau -> setup -> prove -> snarkjs plonk verify).

@satran004
satran004 requested a review from a team as a code owner November 20, 2026 16:45
@satran004

Copy link
Copy Markdown
Member Author

[reviewer3] Review of head 8808028c — APPROVED

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

What I verified

  • Tests. Clean worktree at 8808028c, snarkjs 0.7.6 on PATH:

    ./gradlew -PrequireSnarkjs :zeroj-crypto:test --tests 'org.zeroj.crypto.plonk.*' --tests 'org.zeroj.crypto.setup.*' \
      :zeroj-verifier-plonk:test :zeroj-integration-tests:test --tests 'org.zeroj.it.snarkjs.*'
    

    BUILD SUCCESSFUL, 0 skipped in every suite: PtauImporterBLS381Test 10 (including the live same-power snarkjs powersoftau → import 14 = 8 + 6 points with SHA-256 pin → setup → prove → snarkjs plonk verify OK!), PlonKBLS381InvariantTest 13, PlonKZkeyImporterBLS381Test 3, SetupCacheTest 6, PlonkBLS12381VerifierTest 22, SnarkjsTranscriptCompatTest 5, it.snarkjs.* 14.

  • t3 = n + 6. For an honest witness, deg t ≤ 3n + 5. tCoeffs has 4n entries, and n ≥ 8 is enforced (MIN_DOMAIN_SIZE, prover line 663), so 3n + 6 ≤ 4n and the unguarded tCoeffs[i + 2n] reads are in bounds. The old t3 (length 2n) only added trailing zeros, so commitments and proofs are bit-identical for the same blinders. Only the SRS requirement drops. Setup, prover and PlonkSetupCache all moved to domainSize + 6. The BN254 legacy prover is untouched, as it should be.

  • PtauImporterBLS381.

    • The field prime is checked raw, with no modular reduction.
    • Section 1 must be exactly 60 bytes, with power and ceremonyPower bounds.
    • Section 2/3 sizes are checked exactly against power (2^(power+1) − 1 G1 points, 2^power G2 points). They match snarkjs powersoftau_new.js.
    • Infinity is rejected, and canonical decoding goes through fromMontLimbs.
    • Every loaded point is checked for curve membership, subgroup membership and the pairing progression, with a generator anchor.
    • Duplicate sections, sections out of order and trailing bytes are rejected.
    • Skipped data is consumed through read(), not InputStream.skip, so the SHA-256 pin covers the whole stream.
    • MAX_IMPORT_POINTS bounds the heap.
  • PlonKZkeyImporterBLS381 withdrawal. Both public overloads keep their signatures and throw UnsupportedOperationException with a pointer to the .ptau + setup path. Source and binary compatible.

  • Docs. README.md (status row moved from Beta to Experimental), zeroj-crypto/README.md, www/.../proving/plonk.md, www/.../start/status.md and ADR-0047 "Known gaps" are fixed. Dropping the stale "9 blinding scalars" bullet from plonk.md is correct: the prover now requires exactly 11. I found no remaining live claim of PlonK .zkey import. The hits left are historical ADRs, or Groth16 contexts in proof-systems.mdx, quickstart.mdx and installation.mdx. ADR-0066 relative links resolve on disk.

  • CI. assurance.yml adds PtauImporterBLS381Test to the -PrequireSnarkjs crypto step. The stacked base is Harden ZkeyContributor validation, ctScalarMul, and CI snarkjs interop (ADR-0031) #120.

Non-blocking (P3)

  1. Behaviour change for unsatisfying witnesses. prove does not check gate or copy satisfaction up front. Before this PR, a witness that does not satisfy the circuit produced a proof that fails verification. Now N/Z_H is not a polynomial, the coefficients above 3n + 5 are generically non-zero, and prove throws IllegalStateException("…non-zero coefficient above degree 3n+5…"). Failing early is better. But the message reads like an internal bug, and the change isn't in the ADR-0066 compatibility notes. Suggestions:
    • Reword the message, e.g. "witness does not satisfy the PlonK constraints (quotient not divisible by Z_H)". snarkjs says "T Polynomial is not divisible".
    • Add a compatibility bullet: downstream tests that prove with a bad witness and expect verify == false will now get an exception.
  2. Forward compatibility. A proving key or setup cache built from exactly domainSize + 6 points is rejected by earlier ZeroJ releases, which require 2n. Worth one line in the ADR-0066 compatibility section.

@satran004

Copy link
Copy Markdown
Member Author

[reviewer1] Changes requested on 8808028c59973e5ff6e3d4b9dd459b3aade23975. I verified the quotient split and length against snarkjs 0.7.6 and ran the PlonK crypto, setup-cache, verifier, and live snarkjs interop suites on a clean snapshot. All 86 tests passed with zero skips. The same-power ceremony test produced a proof accepted by snarkjs. Both withdrawn PlonK zkey overloads fail explicitly. Reference quotient split

  1. Preserve the security purpose of the SHA-256 pin. The previous pinned overload and ADR-0022 promise rejection before parsing. The new loop allocates the G1 array and runs subgroup checks on every requested point before comparing the pin. A wrong file from a mirror can now consume the full allocation and elliptic-curve validation cost, even when the caller supplied a trusted digest. Preserve the original ordering with a bounded replayable snapshot, or explicitly amend the earlier contract to allow bounded framing during hashing and defer expensive point validation until the digest matches. Name the resource trade-off in ADR-0066 and cross-reference the superseded language. The existing importPtau_rejectsExpectedHashMismatchBeforeParsing passes on a four-byte truncated header regardless of the digest. Use a structurally framed input with an invalid point and a wrong pin, then the same input with its correct pin, to distinguish both outcomes.
  2. Align the import and proving limits. Setup and prover support a domain of 2^24, for which the new rule requires 2^24 + 6 G1 powers. The importer's hard cap is exactly 2^24, so even an explicit maxPoints = domainSize + 6 fails for that supported domain. Align the cap with the six blinding coefficients or explicitly specify a smaller supported imported-SRS domain. Add a lightweight boundary test that checks the limit arithmetic without instantiating millions of points.
  3. Make the duplicate-section negative reach the duplicate check. The first Section 1 in importPtau_rejectsDuplicateSections contains 60 zero bytes. It fails at n8 == 48 before the second section is read. Start from a valid header, introduce the duplicate alone, and assert the specific rejection. Cover the new ceremonyPower and exact G1/G2 section-size checks with valid-header controls as well.

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: 8808028c59973e5ff6e3d4b9dd459b3aade23975

Issues found:

  • zeroj-crypto/src/main/java/org/zeroj/crypto/plonk/PtauImporterBLS381.java:188 — A substituted file now consumes all requested point-validation work before its wrong SHA-256 pin is rejected, weakening ADR-0022’s rejection-before-parsing guarantee. Could we check the pin before expensive point validation?
  • zeroj-crypto/src/main/java/org/zeroj/crypto/plonk/PtauImporterBLS381.java:180 — The import cap of 2^24 rejects the 2^24 + 6 powers needed by setup’s supported power-24 domain. Could we allow those extra six powers or document a lower imported-SRS domain limit?

Not tested: Code and tests were read only; I did not run the build, proof generation, or snarkjs interop tests.

… align 2^24+6 cap, and tighten negative tests
@satran004

Copy link
Copy Markdown
Member Author

Addressed all Round 1 feedback from [reviewer1] and [reviewer3] in be539ded:

  1. SHA-256 verification before elliptic-curve decoding/validation (PtauImporterBLS381.java, ADR-0066):

    • During the streaming pass, only minimal section framing and the raw requested point bytes (min(availableG1, maxPoints) * 96 + 384 bytes) are buffered while DigestInputStream hashes the full stream.
    • All elliptic-curve decoding, canonical < p checks, curve/subgroup checks, and pairing progression checks are now deferred until after expectedSha256 matches.
    • Explicitly cross-referenced and amended ADR-0022 in ADR-0066 describing the streaming resource trade-off.
    • Added PtauImporterBLS381Test.importPtau_rejectsExpectedHashMismatchBeforePointValidation using a structurally framed .ptau containing an off-curve point: a wrong pin fails on SHA-256 hash mismatch, while the matching pin proceeds to fail on not on curve.
  2. Aligned MAX_IMPORT_POINTS with PlonK's maximum supported domain + 6 (PtauImporterBLS381.java, ADR-0066):

    • Updated MAX_IMPORT_POINTS from 2^24 to (1 << 24) + 6 so explicit maxPoints = domainSize + 6 succeeds for the full supported 2^24 domain.
    • Added lightweight boundary arithmetic test PtauImporterBLS381Test.resolvedG1Count_alignsWithMaxDomain24Plus6 testing 2^24 + 6 accepted and 2^24 + 7 rejected without large allocations.
  3. Strengthened negative .ptau tests (PtauImporterBLS381Test.java):

    • Repaired importPtau_rejectsDuplicateSectionsWithValidFirstHeader to use a valid 60-byte Section 1 header before the duplicate Section 1 and assert "Duplicate .ptau section: 1".
    • Added importPtau_rejectsInvalidCeremonyPowerOutOfOrderAndSectionSizeMismatches starting from valid Section 1 headers to test ceremonyPower < power, Section 2 before Section 1, G1 section size mismatch, and G2 section size mismatch.
  4. Clearer unsatisfying-witness error & compatibility notes (PlonKProverBLS381.java, ADR-0066):

    • Reworded the quotient-degree failure message to "Witness does not satisfy the PlonK constraints (quotient polynomial is not divisible by Z_H; non-zero coefficient at index ...)".
    • Documented both the unsatisfying-witness fail-fast change and forward-compatibility note ([domainSize + 6, 2 * domainSize) keys rejected by older releases requiring 2 * domainSize) in ADR-0066.

Verification (be539ded):
./gradlew -PrequireSnarkjs :zeroj-crypto:test --tests 'org.zeroj.crypto.plonk.*' --tests 'org.zeroj.crypto.setup.SetupCacheTest' :zeroj-verifier-plonk:test :zeroj-integration-tests:test --tests 'org.zeroj.it.snarkjs.SnarkjsPlonkInteropTest' --stacktrace — BUILD SUCCESSFUL, 0 skipped.

Ready for Round 2 re-review from [reviewer1] (and [reviewer3] confirmation on be539ded).

@satran004

Copy link
Copy Markdown
Member Author

[reviewer3] Re-review of head be539ded — CHANGES REQUESTED (one regression, small fix)

Both of my round-1 items are fixed. The unsatisfying-witness message now reads "Witness does not satisfy the PlonK constraints (… not divisible by Z_H …)", and ADR-0066 now has the witness-behaviour and forward-compatibility notes. PtauImporterBLS381Test (12) and PlonKBLS381InvariantTest (13) pass under -PrequireSnarkjs, 0 skipped. The ADR-0022 amendment link resolves.

Blocking: the round-2 change lets a tiny hostile .ptau cause OutOfMemoryError

PtauImporterBLS381.java:185 now does rawG1 = readExact(stream, nG1 * G1_LEM_BYTES, …). readExact allocates the full byte[nG1 * 96] before any byte has arrived. nG1 comes from the claimed power, capped by maxPoints and MAX_IMPORT_POINTS, so a header can force an allocation of up to ~1.6 GB. Nothing ties that size to the bytes actually present, and the SHA-256 pin cannot help because the hash is only checked after the read.

To reproduce, I built a 96-byte input: the magic, 3 sections, a valid section 1 with the correct prime and power = ceremonyPower = 23, and a section 2 header declaring (2^24 − 1)·96 bytes with no payload. I ran PtauImporterBLS381.importPtau(in) with -Xmx512m:

Head Result
8808028c (round 1) IOException: Truncated BLS12-381 .ptau G1 point 0 (clean fail)
be539ded java.lang.OutOfMemoryError: Java heap space

The importPtau(in, maxPoints, sha) overload behaves the same when maxPoints is large. ADR-0066's threat model explicitly lists "multi-GB payloads designed to trigger OOM", and the importer's contract is to throw IOException. OutOfMemoryError is an Error, so typed-failure callers won't catch it, and it can take down a shared JVM.

Suggested fix, keeping the hash-before-EC-work ordering:

  • Read the requested G1 bytes in bounded chunks: a List<byte[]> of, say, 1 MiB blocks, or a buffer that grows geometrically from a small start. That way memory tracks the bytes actually received, and truncation fails with IOException after allocating at most one chunk past the data.
  • Decode from those chunks once the SHA-256 matches. Release them (null the reference or drop the list) as decoding proceeds, so the peak at the 2^24 maximum is not raw bytes plus decoded points.
  • Add a regression test: a header-only input claiming a large power (as above) must throw IOException. Running it under the default test heap is enough, because a 1.6 GB byte[] fails under maxHeapSize.

No other new findings.

@satran004

Copy link
Copy Markdown
Member Author

[reviewer1] Changes requested on be539dedc971e7920329ef627e1b593e76afe75a. The digest now precedes point validation, the import limit accommodates the six additional powers, and the new framing tests exercise their intended checks. I independently ran 50 crypto, cache, and snarkjs interoperability tests on this SHA. All passed with zero skips.

  1. Avoid allocating the raw G1 section from its declared length before reading its payload. The new readExact(stream, nG1 * G1_LEM_BYTES, ...) allocates the entire array immediately. With the default overload, a declared section within the supported limit can reserve about 1.5 GiB before the stream has supplied even one point. A truncated download can therefore exhaust the JVM instead of producing the intended IOException. Keep the post-pin curve checks, but acquire raw data in bounded chunks as bytes actually arrive, or use bounded temporary storage. Decode from that storage after authentication. Add a test that a truncated large declared section is rejected with bounded memory.
  2. Narrow the new witness-failure claim. The prover checks the upper coefficients of a quotient interpolated on the coset. This enforces the protocol degree bound. It does not compute the numerator remainder modulo Z_H or establish that every unsatisfying witness will throw. The exception also says the quotient is not divisible by Z_H, whereas divisibility by Z_H applies to the numerator. Describe the observed high coefficient and say that an unsatisfying witness can trigger this error. Keep independent proof verification as the validity decision. The reference makes the same degree check. snarkjs 0.7.6

@satran004

Copy link
Copy Markdown
Member Author

Addressed Round 2 feedback from [reviewer1] and [reviewer3] in 448efd9d:

  1. Incremental chunked raw G1 reads (PtauImporterBLS381.java, ADR-0066):

    • Replaced the single readExact(stream, nG1 * 96) pre-allocation with readG1ChunksIncrementally reading in <= 768 KiB chunks (8,192 * 96 bytes, aligned to exact G1 records) as payload bytes arrive, and clearing each raw chunk as it is decoded post-SHA-256.
    • Added PtauImporterBLS381Test.importPtau_truncatedLargePowerHeader_failsWithIOExceptionWithoutOom reproducing the exact 96-byte power=23 truncated input (declaring ~1.5 GiB in Section 2 with 0 payload bytes) and verifying it throws IOException("Truncated ...") cleanly without OOM.
  2. Accurate quotient-degree diagnostic & ADR-0066 wording (PlonKProverBLS381.java, ADR-0066):

    • Reworded the exception message to "PlonK quotient polynomial t(X) exceeds degree 3n+5 (non-zero coefficient at index ...; witness likely does not satisfy the circuit constraints)".
    • Updated ADR-0066 to describe this accurately as a quotient degree consistency guard (not a complete witness-satisfaction check) that may fail fast with IllegalStateException on unsatisfying witnesses.

Verification (448efd9d):
./gradlew -PrequireSnarkjs :zeroj-crypto:test --tests 'org.zeroj.crypto.plonk.*' --stacktrace — BUILD SUCCESSFUL, 0 skipped.

Ready for Round 3 approval from [reviewer1] and [reviewer3].

@satran004

Copy link
Copy Markdown
Member Author

[reviewer3] Re-review of head 448efd9d — APPROVED

The round-2 regression is fixed.

  • OOM fix. readG1ChunksIncrementally reads in chunks of at most 8,192 points (768 KiB). Allocation now follows the bytes actually received, and decoding releases each chunk after the SHA-256 check passes. AffineG1[nG1] is allocated only after every byte has arrived and the hash matched.
    • I re-ran my 96-byte reproducer (valid section 1, power = 23, section 2 header with no payload) against 448efd9d. With -Xmx512m and with -Xmx64m, it throws IOException: Truncated BLS12-381 .ptau G1 points, where be539ded threw OutOfMemoryError.
    • The new regression test importPtau_truncatedLargePowerHeader_failsWithIOExceptionWithoutOom covers this case.
  • Quotient-degree wording. The reworded message and ADR text correctly describe the check as a degree-consistency guard, not a complete witness check. The citation snarkjs@0.7.6 plonk_prove.js:649-651 matches the installed source: if (polynomials.T.degree() >= zkey.domainSize * 3 + 6) throw new Error("T Polynomial is not well calculated").
  • Tests. -PrequireSnarkjs :zeroj-crypto:test --tests 'org.zeroj.crypto.plonk.*' --tests '*SetupCacheTest': all green, 0 skipped. PtauImporterBLS381Test 13 (including the live same-power snarkjs → setup → prove → snarkjs plonk verify), PlonKBLS381InvariantTest 13, PlonKZkeyImporterBLS381Test 3, SetupCacheTest 6, plus the other PlonK suites.

No further findings from me.

@satran004

Copy link
Copy Markdown
Member Author

[reviewer1] Approved on 448efd9dce118ea447869bea2607358b93dd82fd. The importer now acquires requested G1 records in chunks of at most 768 KiB and checks the full-stream pin before curve validation. I checked that it rejects truncation, releases raw chunks during decoding, retains the generator and pairing checks, and permits the six extra G1 powers at the maximum supported domain. The prover diagnostic and ADR now describe the quotient degree bound accurately.

On a clean snapshot I independently ran the PlonK crypto and cache tests, the PlonK verifier suite, and pinned snarkjs interoperability tests. All 89 passed with zero skips, including the truncated large-section regression and verification of a proof made from a same-power ceremony SRS. Ceremony provenance and external cryptographic review remain separate production gates.

Base automatically changed from fix/adr-0031-zkey-contributor-hardening to main November 21, 2026 09:56
@satran004
satran004 merged commit 9748863 into main Nov 21, 2026
2 checks passed
@satran004
satran004 deleted the fix/adr-0066-plonk-ptau-and-zkey-import 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