diff --git a/.github/workflows/assurance.yml b/.github/workflows/assurance.yml
index 457b6228..1b3ff5dc 100644
--- a/.github/workflows/assurance.yml
+++ b/.github/workflows/assurance.yml
@@ -111,6 +111,7 @@ jobs:
:zeroj-integration-tests:test --tests 'org.zeroj.it.snarkjs.*' \
:zeroj-crypto:test --tests 'org.zeroj.crypto.groth16.R1csSnarkjsCeremonyRoundTripTest' \
--tests 'org.zeroj.crypto.groth16.ZkeyPkStoreImporterTest' \
+ --tests 'org.zeroj.crypto.plonk.PtauImporterBLS381Test' \
:zeroj-tools:test --tests 'org.zeroj.ceremony.ZkeyContributorInteropTest' \
--tests 'org.zeroj.ceremony.CeremonyCliTest' \
--stacktrace
diff --git a/README.md b/README.md
index fd9462d6..6fe2d8cf 100644
--- a/README.md
+++ b/README.md
@@ -38,7 +38,7 @@ remaining production gates are tracked in
| Circuit definition (DSL, symbolic annotations, gadgets) | `zeroj-circuit-dsl`, `zeroj-circuit-annotation-*`, `zeroj-circuit-lib` ([per-gadget table](zeroj-circuit-lib/README.md)) | **Beta** |
| Groth16 BLS12-381 — pure Java prove + verify | `zeroj-crypto`, `zeroj-verifier-groth16` | **Beta** (production trusted setup requires an external snarkjs MPC ceremony; in-repo setup is dev-only and flag-gated) |
| Groth16 BLS12-381 — on-chain (Julc / Plutus V3) | `zeroj-onchain-julc` | **Beta — testnet only**, not value-bearing; bind `ScriptContext` in real validators (see `Groth16BLS12381TxOutRefBindingVerifier`) |
-| PlonK BLS12-381 — pure Java prove + verify, `.ptau`/`.zkey` import | `zeroj-crypto`, `zeroj-verifier-plonk` | **Beta** |
+| PlonK BLS12-381 — pure Java prove + verify, `.ptau` SRS import | `zeroj-crypto`, `zeroj-verifier-plonk` | **Experimental** — universal `.ptau` SRS import (`PtauImporterBLS381`) + pure-Java prove/verify; snarkjs PlonK `.zkey` import is unsupported ([ADR-0066](docs/adr/0066-plonk-bls12381-ptau-and-zkey-import.md)) |
| PlonK BLS12-381 — on-chain (Julc / Plutus V3) | `zeroj-onchain-julc` | **Experimental** — full KZG check implemented; labeled testnet trials only |
| BBS (CFRG draft-10) — verification | `zeroj-bbs` | **Beta** (spec is an IRTF draft, not yet an RFC) |
| BBS — issuance / proof generation | `zeroj-bbs` | **Beta with caveat** — offline/isolated only: no provider (pure Java or blst) has an evidenced side-channel contract ([ADR-0062](docs/adr/0062-bls12381-independent-review-and-remediation.md)) |
@@ -61,7 +61,7 @@ remaining production gates are tracked in
- **Pure Java prover** (recommended) — Groth16 + PlonK for BLS12-381. Zero native dependencies. GraalVM compatible. Allocation-lean flat arithmetic, an `mmap`-able proving key, and a streaming trusted setup keep large circuits (millions of constraints) within commodity memory, no JNI (ADR-0029/0033/0034/0035).
- **blst-accelerated prover backend** — optional, opt-in FFM-bound native MSM (`blst_p1s/p2s_mult_pippenger`); a faster Groth16 proving backend, bit-identical proofs. The MSM's `libblst` is built from source (no third-party wrapper) ([ADR-0029](docs/adr/0029-blst-accelerated-groth16-prover.md)).
- **snarkjs CLI** — external CLI for circom-based circuits
-- **snarkjs key import** — import `.zkey` files, prove with the pure Java prover
+- **snarkjs key & SRS import** — import Groth16 `.zkey` files and streaming BLS12-381 `.ptau` SRS files, prove with the pure Java prover
### Verify ZK Proofs (Pure Java, Zero Native Deps)
- **Groth16 BLS12-381** — pure Java verification; optional blst-backed native verifier is also available
diff --git a/docs/adr/0047-snarkjs-bidirectional-interop-export-and-ci.md b/docs/adr/0047-snarkjs-bidirectional-interop-export-and-ci.md
index 34d37926..41a7efff 100644
--- a/docs/adr/0047-snarkjs-bidirectional-interop-export-and-ci.md
+++ b/docs/adr/0047-snarkjs-bidirectional-interop-export-and-ci.md
@@ -21,7 +21,7 @@ produced by this ADR's code (see invariant V8).
## Context
ZeroJ already consumed snarkjs artifacts (`SnarkjsJsonCodec`, `SnarkjsPlonkCodec`,
-`ZkeyImporterBLS381`, `PlonKZkeyImporterBLS381`, `R1csExporter`) and its verifiers were checked
+`ZkeyImporterBLS381`, `PlonKZkeyImporterBLS381` *(later withdrawn by [ADR-0066](0066-plonk-bls12381-ptau-and-zkey-import.md))*, `R1csExporter`) and its verifiers were checked
against snarkjs-generated vectors in the default build. The other direction did not exist: nothing
in the repository could write a ZeroJ Groth16 or PlonK proof or verification key in the format
`snarkjs groth16 verify` / `snarkjs plonk verify` reads, so the claim "ZeroJ proofs are
@@ -248,10 +248,12 @@ Independent evidence, per AGENTS.md "Testing":
## Known gaps
-- **ZeroJ proof under a snarkjs PlonK zkey is not covered.** `PlonKZkeyImporterBLS381` reads the
- header, selectors, sigmas and SRS but not the A/B/C wire-map sections, so ZeroJ cannot assign
- wires for a snarkjs-arithmetised circuit. Closing this needs an importer extension (its own
- R2 change), tracked separately.
+- **ZeroJ proof under a snarkjs PlonK zkey is not supported.** `PlonKZkeyImporterBLS381.importZkey`
+ fails explicitly with `UnsupportedOperationException` ([ADR-0066](0066-plonk-bls12381-ptau-and-zkey-import.md)):
+ supporting snarkjs 0.7.6 PlonK `.zkey` files requires a full layout rework (sections 3–6 wire
+ maps, sections 7–11 `Qm/Ql/Qr/Qo/Qc` extended evaluations, and section 13 Fr Lagrange
+ polynomials). Universal ceremony SRS import works via `PtauImporterBLS381.importPtau(...)` +
+ `PlonKSetupBLS381.setup(...)`.
- The live suites use one small circuit (`c = a·b`, `nPublic = 1`); the checked-in vectors add
`nPublic = 2` (Groth16) and identity selector commitments (PlonK). Larger circuits and
`nPublic = 0` are not exercised live.
diff --git a/docs/adr/0066-plonk-bls12381-ptau-and-zkey-import.md b/docs/adr/0066-plonk-bls12381-ptau-and-zkey-import.md
new file mode 100644
index 00000000..a4536fdc
--- /dev/null
+++ b/docs/adr/0066-plonk-bls12381-ptau-and-zkey-import.md
@@ -0,0 +1,179 @@
+# ADR-0066: BLS12-381 PlonK `.ptau` Streaming Import, `n + 6` SRS Sizing, and `.zkey` Importer Withdrawal
+
+## Status
+
+Proposed (2026-11-21)
+
+## Risk classification
+
+- **R2:** Untrusted `.ptau` SRS codec/import boundary (`PtauImporterBLS381`), PlonK quotient-split
+ and SRS sizing (`PlonKProverBLS381`, `PlonKSetupBLS381`, `PlonkSetupCache`), and explicit
+ withdrawal of the broken `PlonKZkeyImporterBLS381` entry point.
+
+## Context
+
+Three coupled defects broke BLS12-381 PlonK ceremony-SRS interoperability against `snarkjs@0.7.6`:
+
+1. **`PtauImporterBLS381` rejected every valid BLS12-381 `.ptau` file and could not stream large
+ ceremony files.** Header prime parsing called `readFieldLE(..., FP, ...)` which rejected any
+ value `>= FP`, unconditionally rejecting `prime == FP`. It also ignored `ceremonyPower`, mapped
+ infinity sentinels `(0, 0)` / `(0, 0, 0, 0)` in `readG1Mont`/`readG2Mont` (which `toG1`/`toG2`
+ then converted into off-curve non-infinity `(0, 0)` points), and buffered the entire `.ptau`
+ stream in memory under a 64 MiB cap (too small for real BLS12-381 `.ptau` files above power ~15).
+2. **`PlonKProverBLS381`, `PlonKSetupBLS381`, and `PlonkSetupCache` required `2n` SRS G1 powers
+ instead of `n + 6`.** Because `t3` was allocated to `tCoeffs.length - 2n = 2n` (with `n - 6`
+ trailing zero coefficients), a same-power `snarkjs` `.ptau` — which contains `2n - 1` G1 powers
+ — was rejected even though `deg(t) <= 3n + 5` and `t3` only ever has `n + 6` coefficients.
+3. **`PlonKZkeyImporterBLS381` was fundamentally incompatible with `snarkjs@0.7.6` PlonK `.zkey`
+ files.** Beyond the same prime-parsing bug, it read sections 7–11 in the wrong order
+ (`Ql, Qr, Qm, Qo, Qc` vs `snarkjs` `Qm, Ql, Qr, Qo, Qc`, each stored as `n` coefficients + `4n`
+ extended evaluations), misparsed section 13 (`Fr` Lagrange polynomials) as 96-byte G1 points,
+ required `2n` points in section 14 (snarkjs writes `n + 6`), and skipped sections 3–6 (additions
+ and A/B/C wire maps). Several documentation pages still advertised `.zkey` import as working.
+
+## Threat model & trust assumptions
+
+- **Untrusted `.ptau` stream:** Callers may import `.ptau` files downloaded from public or untrusted
+ mirrors. Malicious inputs may contain wrong curve primes, non-canonical coordinates (`>= p`),
+ identity points, off-curve or small-subgroup points, inconsistent powers of `tau`, malformed or
+ duplicate sections, trailing bytes, or multi-GB payloads designed to trigger OOM.
+- **Content pinning & streaming trade-off (amends [ADR-0022](0022-pure-java-plonk-hardening.md)):**
+ ADR-0022's original bounded-buffer `.ptau` importer buffered up to 64 MiB in memory and verified
+ `expectedSha256` before reading headers. Because real BLS12-381 `.ptau` files exceed 64 MiB above
+ power ~15, this ADR amends that boundary to a single streaming pass: only minimal section framing
+ and incrementally acquired raw point chunks (`<= 768 KiB` per chunk, tracking received bytes up
+ to `min(availableG1, maxPoints) * 96 + 384` bytes, capped at `(2^24 + 6) * 96` bytes) are
+ allocated while `DigestInputStream` hashes the entire stream. Truncated large-power headers fail
+ with `IOException` without pre-allocating the declared size, and **zero elliptic-curve decoding,
+ subgroup checks, or pairing checks run before `expectedSha256` matches**, so a substituted file
+ from a mirror fails on SHA-256 without spending elliptic-curve validation CPU.
+- **Ceremony trust:** SRS soundness still depends on at least one honest phase-1 ceremony
+ participant; `PtauImporterBLS381` verifies algebraic structure and optional SHA-256 pinning, not
+ ceremony provenance.
+
+## Pinned normative references
+
+- `snarkjs@0.7.6`:
+ - `src/powersoftau_utils.js` (`writePTauHeader`, `readPTauHeader`: 60-byte Section 1 = `n8`,
+ raw unsigned LE `q`, `power`, `ceremonyPower`)
+ - `src/powersoftau_new.js` (Section 2 = `(2^(power+1) - 1) * 96` B, Section 3 = `2^power * 192` B)
+ - `src/plonk_setup.js` (Sections 7–11 selector layout, Section 13 Lagrange Fr, Section 14 `n + 6` G1)
+ - `src/plonk_prove.js` (lines 649–684: `deg(T) < 3n + 6` degree assertion and `T3` length `n + 6`)
+- `ffjavascript@0.3.1`: `src/wasm_curve.js` (LEM affine zero encoding `0^96` / `0^192`).
+- [ADR-0047](0047-snarkjs-bidirectional-interop-export-and-ci.md) (pinned `snarkjs@0.7.6` CI oracle
+ and `-PrequireSnarkjs`).
+
+## Decision & exact security invariants
+
+### I1 — Streaming `.ptau` parser with exact `snarkjs@0.7.6` framing
+
+`PtauImporterBLS381.importPtau(InputStream, int maxPoints, byte[] expectedSha256)` streams the input
+sequentially without buffering the entire file:
+
+- Validates global header (`"ptau"`, `version == 1`, `1 <= numSections <= 64`) and rejects duplicate
+ section IDs, negative sizes, premature EOF, and trailing bytes after the final section.
+- Section 1 (must precede Sections 2 and 3): exact size `60` bytes; `n8 == 48`; raw unsigned LE
+ `prime == MontFp381.modulus()`; `1 <= power <= 32`; `power <= ceremonyPower <= 32`.
+- Section 2 (`tauG1`): exact size `((1L << (power + 1)) - 1) * 96`; reads `min(availableG1, maxPoints)`
+ raw point records (bounded by `MAX_IMPORT_POINTS = 2^24 + 6`, aligned with PlonK's maximum
+ supported `2^24` domain plus 6 blinding powers) and streams past remaining bytes.
+- Section 3 (`tauG2`): exact size `(1L << power) * 192`; reads the first 2 raw G2 point records
+ and streams past remaining bytes.
+- Remaining sections (4–7, 12–15, etc.) are streamed past while still feeding `SHA-256` when
+ `expectedSha256 != null`. Full-stream SHA-256 equality is verified **before** decoding points or
+ running curve, subgroup, and pairing checks.
+
+### I2 — Strict SRS point validation & infinity rejection
+
+- Every loaded coordinate is decoded via `MontFp381.fromMontLimbs(...)` (canonical `< p`, no silent
+ modular reduction).
+- Infinity (`(0, 0)` in G1, `(0, 0, 0, 0)` in G2) is explicitly rejected for all loaded SRS points.
+ Defensively, `toG1`/`toG2` also map `isInfinity()` to `G1Point.INFINITY`/`G2Point.INFINITY` rather
+ than constructing off-curve `(0, 0)`.
+- Every loaded point is checked for curve membership (`isOnCurve()`) and prime-order subgroup
+ membership (`isValid()`).
+- Anchors `tauG1[0] == G1`, `tauG2[0] == G2`, and pairing progression
+ `e(tauG1[i], G2) == e(tauG1[i-1], tauG2[1])` are verified for every loaded G1 power.
+
+### I3 — Exact `t3 = n + 6` quotient-split & SRS sizing
+
+- With 11 blinding scalars (`deg(aBlind), deg(bBlind), deg(cBlind) <= n + 1`, `deg(zBlind) <= n + 2`),
+ the quotient polynomial `t(X)` has degree `<= 3n + 5` (`3n + 6` coefficients).
+- `PlonKProverBLS381` sizes `t3` to exact length `n + 6` (indices `2n .. 3n + 5`) and throws
+ `IllegalStateException` if any coefficient at index `>= 3n + 6` is non-zero (matching
+ `snarkjs@0.7.6` `plonk_prove.js:649-651`).
+- `PlonKSetupBLS381.validateSrs`, `PlonKProverBLS381.validateProverInputs`, and
+ `PlonkSetupCache` require `srsG1.length >= domainSize + 6` (minimum `domainSize = 8`, where
+ same-power `.ptau` provides `2n - 1 = 15 >= 14 = n + 6` powers).
+
+### I4 — Explicit withdrawal of `PlonKZkeyImporterBLS381`
+
+- Both `PlonKZkeyImporterBLS381.importZkey(InputStream)` and `importZkey(InputStream, byte[])`
+ fail explicitly with `UnsupportedOperationException` citing this ADR and directing callers to
+ `PtauImporterBLS381` + `PlonKSetupBLS381`. Full snarkjs PlonK `.zkey` import requires a separate
+ format/wire-map rework.
+
+### I5 — Documentation accuracy
+
+- Align `README.md`, `www/src/content/docs/guides/proving/plonk.md`,
+ [ADR-0047](0047-snarkjs-bidirectional-interop-export-and-ci.md), and `zeroj-crypto/README.md`
+ to remove false `.zkey` import claims, document `PtauImporterBLS381` + `PlonKSetupBLS381`, and
+ reconcile PlonK's status as Experimental (with 11 blinding scalars already implemented).
+
+## Alternatives considered
+
+1. **Full snarkjs PlonK `.zkey` rework now:** Requires implementing snarkjs addition gates, wire-map
+ deserialization (sections 3–6), `writeP4` selector/sigma layout (sections 7–12), and Fr Lagrange
+ loading (section 13). Deferred because PlonK remains Experimental and universal `.ptau` import +
+ `PlonKSetupBLS381` already unlocks public-ceremony BLS12-381 PlonK proving.
+2. **Keep `2n` SRS requirement and require a `.ptau` one power larger:** Rejected because `t3` has
+ exact degree `<= n + 5` (`n + 6` coefficients); lowering to `n + 6` eliminates wasted MSM work
+ on `n - 6` trailing zeros and makes same-power `.ptau` files work natively.
+
+## Compatibility & breaking notes
+
+- `PlonKZkeyImporterBLS381.importZkey(...)` now throws `UnsupportedOperationException` instead of
+ failing with a misleading `IOException` ("prime is not canonical"). No in-repo production code
+ called it.
+- `PtauImporterBLS381` now requires exact `snarkjs@0.7.6` Section 1 length (60 bytes including
+ `ceremonyPower`) and exact Section 2/3 sizes matching `power`; synthetic test fixtures must
+ conform to the `snarkjs` layout.
+- `PlonKSetupBLS381`, `PlonKProverBLS381`, and `PlonkSetupCache` now accept SRS lengths in
+ `[domainSize + 6, 2 * domainSize)` that were previously rejected. Forward compatibility note:
+ proving keys or setup caches built from fewer than `2 * domainSize` G1 powers will be rejected by
+ earlier ZeroJ releases that required `2 * domainSize`.
+- **Quotient degree check in `PlonKProverBLS381.prove`:** Because `t(X)` is now checked for
+ `deg(t) <= 3n + 5` (matching `snarkjs@0.7.6` `plonk_prove.js:649-651`), proving with an
+ unsatisfying witness may now fail fast with `IllegalStateException` when the interpolated
+ quotient polynomial has non-zero coefficients above `3n + 5`, rather than always emitting an
+ unverifiable proof. This degree check is a consistency guard, not a complete witness-satisfaction
+ check; downstream negative tests expecting `verify == false` should tamper with an honest proof
+ or public input.
+
+## Milestones
+
+| Milestone | Scope | Status |
+|---|---|---|
+| M1 | Streaming `PtauImporterBLS381` + infinity/canonical/subgroup/SHA-256 enforcement | Implemented |
+| M2 | `t3 = n + 6` sizing & degree check across `PlonKProverBLS381`, `PlonKSetupBLS381`, `PlonkSetupCache` | Implemented |
+| M3 | Explicit `UnsupportedOperationException` withdrawal of `PlonKZkeyImporterBLS381` | Implemented |
+| M4 | Offline positive/negative/70 MiB streaming tests + live same-power `snarkjs@0.7.6` `.ptau -> setup -> prove -> snarkjs plonk verify` CI test | Implemented |
+| M5 | Documentation alignment across `README.md`, `plonk.md`, ADR-0047, and `zeroj-crypto/README.md` | Implemented |
+| M6 | External cryptographic review before any promotion of PlonK out of Experimental | Open (mandatory gate) |
+
+## Verification & test-vector strategy
+
+- Offline positive tests: synthetic BLS12-381 `.ptau` full + bounded `maxPoints` import, SHA-256
+ pin pass/mismatch, and a 70 MiB virtual streaming test exceeding the former 64 MiB cap.
+- Offline negative tests: null/truncated/wrong-hash/duplicate-section/wrong-prime/trailing-bytes,
+ infinity in G1/G2, off-curve, small-subgroup `(0, 2)`, non-canonical `>= p`, pairing-inconsistent
+ SRS power, and `domainSize + 5` short SRS rejection alongside `domainSize + 6` acceptance.
+- Live differential CI test (`PtauImporterBLS381Test` in `.github/workflows/assurance.yml` under
+ `-PrequireSnarkjs`): generates a live same-power `snarkjs@0.7.6` `power=3` BLS12-381 `.ptau`,
+ imports exact `14` (`8 + 6`) points with SHA-256 pinning, runs `PlonKSetupBLS381` +
+ `PlonKProverBLS381`, exports snarkjs JSON, and verifies with live `snarkjs plonk verify`.
+
+## Revision history
+
+- **2026-11-21:** Initial `Proposed` ADR for PR-4 (`PtauImporterBLS381` streaming fix, `t3 = n + 6`
+ SRS sizing, `PlonKZkeyImporterBLS381` withdrawal, and doc alignment).
diff --git a/www/src/content/docs/guides/proving/plonk.md b/www/src/content/docs/guides/proving/plonk.md
index 7868b657..e429deaa 100644
--- a/www/src/content/docs/guides/proving/plonk.md
+++ b/www/src/content/docs/guides/proving/plonk.md
@@ -7,10 +7,10 @@ sidebar:
:::caution[Experimental, with no correctness claims]
ZeroJ's PlonK support is **experimental everywhere**: pure-Java proving, off-chain verification,
-`.zkey` import, and the on-chain validators. ZeroJ makes no claim that it is correct, sound, or
-ready for use. **Groth16 on BLS12-381 is the supported path for the current release**; use
-[Prove with Groth16](/guides/proving/groth16/) for anything you build on. Use PlonK only to
-evaluate or experiment, and never where value is at stake.
+`.ptau` SRS import, and the on-chain validators (snarkjs PlonK `.zkey` import is unsupported).
+ZeroJ makes no claim that it is correct, sound, or ready for use. **Groth16 on BLS12-381 is the
+supported path for the current release**; use [Prove with Groth16](/guides/proving/groth16/) for
+anything you build on. Use PlonK only to evaluate or experiment, and never where value is at stake.
:::
PlonK uses a *universal* setup: one powers-of-tau reference string (SRS) serves every circuit up
@@ -23,10 +23,9 @@ BLS12-381. This page describes what exists and how to try it, briefly and withou
|-------|-----|--------|
| Compile a circuit | `circuit.compilePlonK(CurveId.BLS12_381)` → `PlonKConstraintSystem` | `zeroj-circuit-dsl` |
| Development SRS | `PowersOfTauBLS381.generate(power)` (needs the insecure-setup flag) | `zeroj-crypto` |
-| Import a `.ptau` SRS | `PtauImporterBLS381.importPtau(input, maxPoints, expectedSha256)` | `zeroj-crypto` |
+| Import a `.ptau` SRS | `PtauImporterBLS381.importPtau(input, maxPoints, expectedSha256)` (streaming; `domainSize + 6` points suffice) | `zeroj-crypto` |
| Setup | `PlonKSetupBLS381.setup(...)` → `PlonKProvingKeyBLS381` | `zeroj-crypto` |
| Prove | `PlonKProverBLS381.prove(...)`; `proveCardano(...)` and `proveCardanoMpi(...)` for the on-chain profiles | `zeroj-crypto` |
-| Import a snarkjs PlonK `.zkey` | `PlonKZkeyImporterBLS381.importZkey(input, expectedSha256)` | `zeroj-crypto` |
| Export snarkjs JSON | `SnarkjsPlonkJson.proofJson`, `verificationKeyJson`, `publicJson` | `zeroj-crypto` |
| Verify off-chain | `PlonkBLS12381Verifier` | `zeroj-verifier-plonk` |
| Verify on-chain | `PlonkBLS12381Verifier`, `PlonkBLS12381MultiInputVerifier`, `PlonkBLS12381MultiInputParamVerifier` (JuLC validators) | `zeroj-onchain-julc` |
@@ -43,12 +42,10 @@ BN254 PlonK exists only as a legacy path and is disabled unless you start the JV
## Known gaps
-- **Blinding.** The PlonK prover uses 9 blinding scalars, while the PlonK paper and snarkjs use 11
- (the quotient-split blinding factors are missing). This is tracked as an open issue affecting
- the zero-knowledge margin.
-- **snarkjs PlonK keys.** `PlonKZkeyImporterBLS381` reads the header, selectors, permutations and
- SRS, but not the wire-map sections, so ZeroJ can't prove a snarkjs-arithmetized circuit under an
- imported PlonK `.zkey`.
+- **snarkjs PlonK `.zkey` import is unsupported.** `PlonKZkeyImporterBLS381.importZkey(...)` fails
+ explicitly with `UnsupportedOperationException` (snarkjs PlonK `.zkey` layout and wire-map
+ sections are not implemented). Use `PtauImporterBLS381.importPtau(...)` with a BLS12-381 `.ptau`
+ ceremony SRS and `PlonKSetupBLS381.setup(...)` for ZeroJ-authored circuits instead.
- **No large-circuit work.** The memory and speed work that makes Groth16 practical at millions of
constraints hasn't been applied to PlonK.
- **Not audited,** and on-chain use is limited to bounded profiles (below).
diff --git a/www/src/content/docs/start/status.md b/www/src/content/docs/start/status.md
index 164199ac..42709cc7 100644
--- a/www/src/content/docs/start/status.md
+++ b/www/src/content/docs/start/status.md
@@ -53,7 +53,7 @@ current release and the default in every recommendation.
| Area | Modules | Status |
|------|---------|--------|
-| PlonK BLS12-381: pure-Java prove and verify, `.ptau`/`.zkey` import | `zeroj-crypto`, `zeroj-verifier-plonk` | **Experimental** |
+| PlonK BLS12-381: pure-Java prove and verify, streaming `.ptau` SRS import (snarkjs PlonK `.zkey` import unsupported) | `zeroj-crypto`, `zeroj-verifier-plonk` | **Experimental** |
| PlonK BLS12-381: on-chain (JuLC / Plutus V3) | `zeroj-onchain-julc` | **Experimental**. Labeled testnet trials only. |
:::caution[PlonK is experimental everywhere]
diff --git a/zeroj-crypto/README.md b/zeroj-crypto/README.md
index 0ddc23ea..59e81417 100644
--- a/zeroj-crypto/README.md
+++ b/zeroj-crypto/README.md
@@ -17,7 +17,7 @@ shared Fiat-Shamir transcript utilities used by PlonK.
| Legacy BN254 Groth16 | `Groth16Setup`, `Groth16Prover`, `ZkeyImporter` (requires `-Dzeroj.allowLegacyBn254=true`) |
| Legacy BN254 PlonK | `PlonKSetup`, `PlonKProver`, `PlonKZkeyImporter`, `PtauImporter` (requires `-Dzeroj.allowLegacyBn254=true`) |
| R1CS import | `R1CSImporter` |
-| snarkjs interop (ADR-0047) | `R1csExporter` (iden3 `.r1cs` for a snarkjs ceremony), `ZkeyImporterBLS381`, `PlonKZkeyImporterBLS381`; `SnarkjsGroth16Json` / `SnarkjsPlonkJson` write `proof.json`, `verification_key.json`, `public.json` byte-for-byte as snarkjs 0.7.6 does, so ZeroJ proofs and ZeroJ-native keys verify under `snarkjs groth16/plonk verify` |
+| snarkjs interop (ADR-0047 / ADR-0066) | `R1csExporter` (iden3 `.r1cs` for a snarkjs ceremony), `ZkeyImporterBLS381` (Groth16 `.zkey`), `PtauImporterBLS381` (streaming BLS12-381 `.ptau` SRS); `SnarkjsGroth16Json` / `SnarkjsPlonkJson` write `proof.json`, `verification_key.json`, `public.json` byte-for-byte as snarkjs 0.7.6 does, so ZeroJ proofs and ZeroJ-native keys verify under `snarkjs groth16/plonk verify` (snarkjs PlonK `.zkey` import is unsupported) |
| Polynomial tools | `FieldFFT`, `FieldFFTBLS381`, `KZGCommitment`, `Pippenger` |
| Setup helpers | `PowersOfTau`, `PowersOfTauBLS381`, `Groth16SetupCache`, `PlonkSetupCache` |
| Transcript | `FiatShamirTranscript`, `Keccak256` |
diff --git a/zeroj-crypto/src/main/java/org/zeroj/crypto/plonk/PlonKProverBLS381.java b/zeroj-crypto/src/main/java/org/zeroj/crypto/plonk/PlonKProverBLS381.java
index a51768bf..5f2d11a6 100644
--- a/zeroj-crypto/src/main/java/org/zeroj/crypto/plonk/PlonKProverBLS381.java
+++ b/zeroj-crypto/src/main/java/org/zeroj/crypto/plonk/PlonKProverBLS381.java
@@ -309,16 +309,27 @@ private static PlonKProofBLS381 proveInternal(PlonKProvingKeyBLS381 pk, MontFr38
var tCoeffs = cosetIFFT(tCoset, shift, n4, logN4);
// Split t into three parts; T1/T2 reserve degree n for quotient-split blinders.
- var t1 = new MontFr381[n + 1]; var t2 = new MontFr381[n + 1];
- // T3 gets all remaining coefficients (degree 2n onwards) — may exceed n due to blinding
- int t3Len = Math.max(n, tCoeffs.length - 2 * n);
+ // deg(aBlind), deg(bBlind), deg(cBlind) <= n + 1 and deg(zBlind) <= n + 2, so the
+ // numerator has degree <= 4n + 5 and t(X) has degree <= 3n + 5 (3n + 6 coefficients).
+ // Therefore T3 has exact length n + 6 (indices 2n .. 3n + 5), matching snarkjs 0.7.6
+ // plonk_prove.js and allowing a same-power .ptau (2n - 1 >= n + 6 for n >= 8).
+ var t1 = new MontFr381[n + 1];
+ var t2 = new MontFr381[n + 1];
+ int t3Len = n + 6;
var t3 = new MontFr381[t3Len];
for (int i = 0; i < n; i++) {
- t1[i] = i < tCoeffs.length ? tCoeffs[i] : MontFr381.ZERO;
- t2[i] = i + n < tCoeffs.length ? tCoeffs[i + n] : MontFr381.ZERO;
+ t1[i] = tCoeffs[i];
+ t2[i] = tCoeffs[i + n];
}
for (int i = 0; i < t3Len; i++) {
- t3[i] = i + 2 * n < tCoeffs.length ? tCoeffs[i + 2 * n] : MontFr381.ZERO;
+ t3[i] = tCoeffs[i + 2 * n];
+ }
+ for (int i = 3 * n + 6; i < tCoeffs.length; i++) {
+ if (!tCoeffs[i].isZero()) {
+ throw new IllegalStateException(
+ "PlonK quotient polynomial t(X) exceeds degree 3n+5 (non-zero coefficient at index "
+ + i + "; witness likely does not satisfy the circuit constraints)");
+ }
}
// PLONK 8.4 / snarkjs v0.7.6: randomize the split without changing T(X).
@@ -623,8 +634,9 @@ private static void validateProverInputs(
if (pk.omega() == null) {
throw new IllegalArgumentException("omega must not be null");
}
- if (pk.srsG1() == null || pk.srsG1().length < 2 * n) {
- throw new IllegalArgumentException("SRS G1 length must be at least " + (2 * n));
+ int requiredSrsG1 = n + 6;
+ if (pk.srsG1() == null || pk.srsG1().length < requiredSrsG1) {
+ throw new IllegalArgumentException("SRS G1 length must be at least " + requiredSrsG1);
}
requireWireArray("wireA", wireA, n);
diff --git a/zeroj-crypto/src/main/java/org/zeroj/crypto/plonk/PlonKSetupBLS381.java b/zeroj-crypto/src/main/java/org/zeroj/crypto/plonk/PlonKSetupBLS381.java
index 11b804cd..b439bdc6 100644
--- a/zeroj-crypto/src/main/java/org/zeroj/crypto/plonk/PlonKSetupBLS381.java
+++ b/zeroj-crypto/src/main/java/org/zeroj/crypto/plonk/PlonKSetupBLS381.java
@@ -225,7 +225,7 @@ private static void validateSrs(PtauImporterBLS381.SRS srs, int domainSize) {
Objects.requireNonNull(srs, "srs");
AffineG1[] tauG1 = srs.tauG1();
AffineG2[] tauG2 = srs.tauG2();
- int requiredG1 = 2 * domainSize;
+ int requiredG1 = domainSize + 6;
if (tauG1 == null || tauG1.length < requiredG1) {
throw new IllegalArgumentException("BLS12-381 SRS G1 length must be at least " + requiredG1);
}
diff --git a/zeroj-crypto/src/main/java/org/zeroj/crypto/plonk/PlonKZkeyImporterBLS381.java b/zeroj-crypto/src/main/java/org/zeroj/crypto/plonk/PlonKZkeyImporterBLS381.java
index b7c19117..3d6ddcc2 100644
--- a/zeroj-crypto/src/main/java/org/zeroj/crypto/plonk/PlonKZkeyImporterBLS381.java
+++ b/zeroj-crypto/src/main/java/org/zeroj/crypto/plonk/PlonKZkeyImporterBLS381.java
@@ -1,426 +1,44 @@
package org.zeroj.crypto.plonk;
-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.MontFp381;
-import org.zeroj.bls12381.field.MontFp2_381;
-import org.zeroj.bls12381.field.MontFr381;
-import org.zeroj.bls12381.pairing.BLS12381Pairing;
-import org.zeroj.crypto.poly.FieldFFTBLS381;
-
-import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
-import java.math.BigInteger;
-import java.nio.ByteBuffer;
-import java.nio.ByteOrder;
-import java.security.MessageDigest;
-import java.security.NoSuchAlgorithmException;
-import java.util.*;
/**
- * Imports PlonK proving keys from snarkjs PlonK .zkey binary format (BLS12-381 curve).
+ * Placeholder entry point for snarkjs BLS12-381 PlonK {@code .zkey} import (ADR-0066).
+ *
+ *
Unsupported: snarkjs 0.7.6 PlonK {@code .zkey} import is currently unsupported and
+ * intentionally fails fast with {@link UnsupportedOperationException}. snarkjs PlonK {@code .zkey}
+ * files store circuit-specific wire-addition/permutation maps (sections 3–6), selector polynomials
+ * ordered {@code Qm, Ql, Qr, Qo, Qc} with extended evaluations (sections 7–11), and Fr Lagrange
+ * polynomials (section 13) that require a dedicated format rework before ZeroJ can safely prove
+ * snarkjs-arithmetized PlonK circuits.
*
- * PlonK .zkey (protocol ID = 2) has 14 sections:
- *
- * - 1: Protocol (= 2 for PlonK)
- * - 2: Header (dimensions, k1/k2, selector/permutation commitments, X_2)
- * - 3: Additions (circuit optimization — wire additions before constraints)
- * - 4-6: A/B/C wire maps (constraint → wire mapping)
- * - 7-11: Ql/Qr/Qm/Qo/Qc selector polynomials (Lagrange evaluations on domain)
- * - 12: Sigma permutation polynomials S1/S2/S3 (Lagrange evaluations)
- * - 13: Lagrange-basis SRS points
- * - 14: Powers-of-tau SRS points (monomial basis)
- *
+ * For BLS12-381 PlonK with a public ceremony SRS, import the universal {@code .ptau} file via
+ * {@link PtauImporterBLS381#importPtau(InputStream, int, byte[])} and run
+ * {@link PlonKSetupBLS381#setup}. For Groth16 {@code .zkey} import, use
+ * {@link org.zeroj.crypto.groth16.ZkeyImporterBLS381} or
+ * {@link org.zeroj.crypto.groth16.ZkeyPkStoreImporter}.
*/
public final class PlonKZkeyImporterBLS381 {
- private PlonKZkeyImporterBLS381() {}
-
- private static final byte[] ZKEY_MAGIC = {0x7a, 0x6b, 0x65, 0x79};
- private static final int MAX_ZKEY_BYTES = 64 * 1024 * 1024;
- private static final int MAX_SECTIONS = 64;
- private static final int MIN_DOMAIN_SIZE = 8;
- private static final int MAX_DOMAIN_POWER = 24;
+ private static final String UNSUPPORTED_MESSAGE =
+ "snarkjs BLS12-381 PlonK .zkey import is not supported (ADR-0066: requires full snarkjs 0.7.6 "
+ + "PlonK section-layout and wire-map rework). Import a BLS12-381 .ptau SRS via "
+ + "PtauImporterBLS381.importPtau(...) and run PlonKSetupBLS381.setup(...) instead.";
- // Montgomery R for Fp (base field) — for converting points from .zkey
- private static final BigInteger FP = MontFp381.modulus();
- private static final BigInteger FR = MontFr381.modulus();
- private static final BigInteger FP_R = BigInteger.ONE.shiftLeft(384).mod(FP);
- private static final BigInteger FP_R_INV = FP_R.modInverse(FP);
-
- // Montgomery R for Fr (scalar field) — for converting polynomial evaluations
- private static final BigInteger FR_R = BigInteger.ONE.shiftLeft(256).mod(FR);
- private static final BigInteger FR_R_INV = FR_R.modInverse(FR);
+ private PlonKZkeyImporterBLS381() {}
/**
- * Import a PlonK proving key from a snarkjs PlonK .zkey file (BLS12-381).
+ * Unsupported; always throws {@link UnsupportedOperationException} (see class Javadoc and ADR-0066).
*/
public static PlonKProvingKeyBLS381 importZkey(InputStream input) throws IOException {
- return importZkey(input, null);
+ throw new UnsupportedOperationException(UNSUPPORTED_MESSAGE);
}
/**
- * Import a PlonK proving key from a snarkjs PlonK .zkey file (BLS12-381)
- * and require an exact SHA-256 content-hash match before parsing.
- *
- * @param expectedSha256 expected SHA-256 hash, or {@code null} for dev/test
- * callers that intentionally skip artifact pinning
+ * Unsupported; always throws {@link UnsupportedOperationException} (see class Javadoc and ADR-0066).
*/
public static PlonKProvingKeyBLS381 importZkey(InputStream input, byte[] expectedSha256) throws IOException {
- byte[] data = readBounded(input, ".zkey input");
- requireExpectedSha256(data, expectedSha256, ".zkey");
- ByteBuffer buf = ByteBuffer.wrap(data).order(ByteOrder.LITTLE_ENDIAN);
- if (buf.remaining() < 12) {
- throw new IOException("Truncated .zkey header");
- }
-
- // Global header
- byte[] magic = new byte[4];
- buf.get(magic);
- if (!Arrays.equals(magic, ZKEY_MAGIC))
- throw new IOException("Invalid .zkey magic");
- int version = buf.getInt();
- int numSections = buf.getInt();
- if (version <= 0) {
- throw new IOException("Invalid .zkey version: " + version);
- }
- if (numSections <= 0 || numSections > MAX_SECTIONS) {
- throw new IOException("Invalid .zkey section count: " + numSections);
- }
-
- // Read section directory
- Map sections = new LinkedHashMap<>();
- for (int i = 0; i < numSections; i++) {
- requireRemaining(buf, 12, ".zkey section header");
- int stype = buf.getInt();
- long ssize = buf.getLong();
- if (sections.containsKey(stype)) {
- throw new IOException("Duplicate .zkey section: " + stype);
- }
- if (ssize < 0 || ssize > buf.remaining() || ssize > Integer.MAX_VALUE) {
- throw new IOException("Invalid .zkey section size for section " + stype);
- }
- sections.put(stype, new long[]{buf.position(), ssize});
- buf.position(buf.position() + (int) ssize);
- }
- for (int sectionId : new int[]{1, 2, 7, 8, 9, 10, 11, 12, 13, 14}) {
- requireSection(sections, sectionId);
- }
-
- // Section 1: Protocol (must be 2 for PlonK)
- buf.position((int) sections.get(1)[0]);
- requireSectionSize(sections, 1, 4);
- int protocol = buf.getInt();
- if (protocol != 2)
- throw new IOException("Not a PlonK .zkey (protocol=" + protocol + ")");
-
- // Section 2: Header
- buf.position((int) sections.get(2)[0]);
- requireSectionSize(sections, 2, 4 + 48 + 4 + 32 + 5 * 4L + 2 * 32L + 8 * 96L + 192L);
- int n8q = buf.getInt();
- if (n8q != 48) throw new IOException("Only BLS12-381 (n8q=48) supported");
- BigInteger q = readFieldLE(buf, n8q, FP, "BLS12-381 .zkey base-field prime");
- if (!FP.equals(q)) {
- throw new IOException("Wrong BLS12-381 .zkey base-field prime");
- }
-
- int n8r = buf.getInt();
- if (n8r != 32) throw new IOException("Only BLS12-381 (n8r=32) supported");
- BigInteger r = readFieldLE(buf, n8r, FR, "BLS12-381 .zkey scalar-field prime");
- if (!FR.equals(r)) {
- throw new IOException("Wrong BLS12-381 .zkey scalar-field prime");
- }
-
- int nVars = buf.getInt();
- int nPublic = buf.getInt();
- int domainSize = buf.getInt();
- int nAdditions = buf.getInt();
- int nConstraints = buf.getInt();
- validateHeaderDimensions(nVars, nPublic, domainSize, nAdditions, nConstraints);
-
- BigInteger k1 = readFieldLE(buf, n8r, r, "BLS12-381 k1").multiply(FR_R_INV).mod(r);
- BigInteger k2 = readFieldLE(buf, n8r, r, "BLS12-381 k2").multiply(FR_R_INV).mod(r);
-
- // Read committed selector/permutation points (8 G1 + 1 G2) from header
- AffineG1 qmCommit = readG1Mont(buf, n8q, q, true, "Qm");
- AffineG1 qlCommit = readG1Mont(buf, n8q, q, true, "Ql");
- AffineG1 qrCommit = readG1Mont(buf, n8q, q, true, "Qr");
- AffineG1 qoCommit = readG1Mont(buf, n8q, q, true, "Qo");
- AffineG1 qcCommit = readG1Mont(buf, n8q, q, true, "Qc");
- AffineG1 s1Commit = readG1Mont(buf, n8q, q, false, "S1");
- AffineG1 s2Commit = readG1Mont(buf, n8q, q, false, "S2");
- AffineG1 s3Commit = readG1Mont(buf, n8q, q, false, "S3");
- AffineG2 x2 = readG2Mont(buf, n8q, q, false, "X_2");
-
- // Section 7-11: Selector polynomial evaluations on the domain
- // Each section has domainSize * n8r bytes of Fr evaluations in Montgomery form
- // BUT: snarkjs stores these as buffers of size (domainSize * 5 * n8r) across sections
- // Actually looking at section sizes: section 7 has 1280 bytes = 40 Fr elements
- // With domainSize=8, that's 5*8 = 40, meaning each section has domainSize Fr evals
- // Wait, 1280 / 32 = 40 elements, but domainSize = 8... This is because snarkjs
- // stores the polynomial in evaluation form over a LARGER domain for the quotient computation
-
- MontFr381[] ql = readFrArrayMont(buf, sections, 7, n8r, r, domainSize);
- MontFr381[] qr = readFrArrayMont(buf, sections, 8, n8r, r, domainSize);
- MontFr381[] qm = readFrArrayMont(buf, sections, 9, n8r, r, domainSize);
- MontFr381[] qo = readFrArrayMont(buf, sections, 10, n8r, r, domainSize);
- MontFr381[] qc = readFrArrayMont(buf, sections, 11, n8r, r, domainSize);
-
- // Section 12: Sigma permutation evaluations (3 * domainSize Fr elements)
- buf.position((int) sections.get(12)[0]);
- if (sections.get(12)[1] % n8r != 0) {
- throw new IOException("Invalid BLS12-381 .zkey sigma section size");
- }
- int sigmaTotal = (int) (sections.get(12)[1] / n8r);
- if (sigmaTotal % 3 != 0) {
- throw new IOException("BLS12-381 .zkey sigma section is not divisible into 3 polynomials");
- }
- int sigmaPerPoly = sigmaTotal / 3;
- if (sigmaPerPoly < domainSize) {
- throw new IOException("BLS12-381 .zkey sigma section is too short");
- }
- // Read only domainSize elements per polynomial
- MontFr381[] s1Eval = new MontFr381[domainSize];
- MontFr381[] s2Eval = new MontFr381[domainSize];
- MontFr381[] s3Eval = new MontFr381[domainSize];
- buf.position((int) sections.get(12)[0]);
- for (int i = 0; i < domainSize; i++) s1Eval[i] = readFrMont(buf, n8r, r);
- // Skip to s2 start (skip remaining s1 entries beyond domainSize)
- buf.position((int) sections.get(12)[0] + sigmaPerPoly * n8r);
- for (int i = 0; i < domainSize; i++) s2Eval[i] = readFrMont(buf, n8r, r);
- buf.position((int) sections.get(12)[0] + 2 * sigmaPerPoly * n8r);
- for (int i = 0; i < domainSize; i++) s3Eval[i] = readFrMont(buf, n8r, r);
-
- // Section 13: Lagrange-basis SRS points
- buf.position((int) sections.get(13)[0]);
- if (sections.get(13)[1] % (2L * n8q) != 0) {
- throw new IOException("Invalid BLS12-381 .zkey Lagrange SRS section size");
- }
- int nLagrangeSRS = (int) (sections.get(13)[1] / (2 * n8q));
- if (nLagrangeSRS < domainSize) {
- throw new IOException("BLS12-381 .zkey Lagrange SRS is too short");
- }
- AffineG1[] srsG1Lagrange = readG1Array(buf, nLagrangeSRS, n8q, q, "lagrangeSrsG1");
-
- // Section 14: Powers-of-tau SRS points (monomial basis)
- buf.position((int) sections.get(14)[0]);
- if (sections.get(14)[1] % (2L * n8q) != 0) {
- throw new IOException("Invalid BLS12-381 .zkey monomial SRS section size");
- }
- int nPtauSRS = (int) (sections.get(14)[1] / (2 * n8q));
- if (nPtauSRS < 2 * domainSize) {
- throw new IOException("BLS12-381 .zkey monomial SRS is too short");
- }
- AffineG1[] srsG1 = readG1Array(buf, nPtauSRS, n8q, q, "monomialSrsG1");
- validateMonomialSrsConsistency(srsG1, x2, 2 * domainSize);
-
- // Compute omega (primitive domainSize-th root of unity)
- int logN = Integer.numberOfTrailingZeros(domainSize);
- MontFr381 omega = FieldFFTBLS381.rootOfUnity(logN);
-
- return new PlonKProvingKeyBLS381(
- domainSize, nPublic, nConstraints, k1, k2, omega,
- ql, qr, qm, qo, qc, s1Eval, s2Eval, s3Eval,
- srsG1, srsG1Lagrange, x2,
- qmCommit, qlCommit, qrCommit, qoCommit, qcCommit,
- s1Commit, s2Commit, s3Commit);
- }
-
- // --- Reading helpers ---
-
- private static MontFr381[] readFrArrayMont(ByteBuffer buf, Map sections,
- int sectionId, int n8r, BigInteger rField, int count) throws IOException {
- if (sections.get(sectionId)[1] % n8r != 0 || sections.get(sectionId)[1] < (long) count * n8r) {
- throw new IOException("Invalid BLS12-381 .zkey Fr section size: " + sectionId);
- }
- buf.position((int) sections.get(sectionId)[0]);
- MontFr381[] result = new MontFr381[count];
- for (int i = 0; i < count; i++) {
- result[i] = readFrMont(buf, n8r, rField);
- }
- return result;
- }
-
- private static MontFr381 readFrMont(ByteBuffer buf, int n8r, BigInteger rField) throws IOException {
- BigInteger val = readFieldLE(buf, n8r, rField, "BLS12-381 Fr element");
- // Convert from Montgomery form
- BigInteger normal = val.multiply(FR_R_INV).mod(rField);
- return MontFr381.fromBigInteger(normal);
- }
-
- private static AffineG1 readG1Mont(ByteBuffer buf, int n8q, BigInteger q,
- boolean allowInfinity, String label) throws IOException {
- BigInteger x = readFieldLE(buf, n8q, q, label + " x").multiply(FP_R_INV).mod(q);
- BigInteger y = readFieldLE(buf, n8q, q, label + " y").multiply(FP_R_INV).mod(q);
- if (x.signum() == 0 && y.signum() == 0) {
- if (allowInfinity) return AffineG1.INFINITY;
- throw new IOException(label + " must not be infinity");
- }
- AffineG1 point = new AffineG1(MontFp381.fromBigInteger(x), MontFp381.fromBigInteger(y));
- if (!point.isOnCurve()) {
- throw new IOException(label + " is not on BLS12-381 G1");
- }
- G1Point subgroupPoint = new G1Point(Fp.of(point.xBigInt()), Fp.of(point.yBigInt()));
- if (!subgroupPoint.isValid()) {
- throw new IOException(label + " is not in BLS12-381 G1 subgroup");
- }
- return point;
- }
-
- private static AffineG2 readG2Mont(ByteBuffer buf, int n8q, BigInteger q,
- boolean allowInfinity, String label) throws IOException {
- BigInteger x0 = readFieldLE(buf, n8q, q, label + " x0").multiply(FP_R_INV).mod(q);
- BigInteger x1 = readFieldLE(buf, n8q, q, label + " x1").multiply(FP_R_INV).mod(q);
- BigInteger y0 = readFieldLE(buf, n8q, q, label + " y0").multiply(FP_R_INV).mod(q);
- BigInteger y1 = readFieldLE(buf, n8q, q, label + " y1").multiply(FP_R_INV).mod(q);
- if (x0.signum() == 0 && x1.signum() == 0 && y0.signum() == 0 && y1.signum() == 0) {
- if (allowInfinity) return AffineG2.INFINITY;
- throw new IOException(label + " must not be infinity");
- }
- AffineG2 point = new AffineG2(MontFp2_381.of(x0, x1), MontFp2_381.of(y0, y1));
- if (!point.isOnCurve()) {
- throw new IOException(label + " is not on BLS12-381 G2");
- }
- G2Point subgroupPoint = new G2Point(
- Fp2.of(Fp.of(point.x().reBigInt()), Fp.of(point.x().imBigInt())),
- Fp2.of(Fp.of(point.y().reBigInt()), Fp.of(point.y().imBigInt())));
- if (!subgroupPoint.isValid()) {
- throw new IOException(label + " is not in BLS12-381 G2 subgroup");
- }
- return point;
- }
-
- private static AffineG1[] readG1Array(ByteBuffer buf, int count, int n8q, BigInteger q,
- String label) throws IOException {
- AffineG1[] points = new AffineG1[count];
- for (int i = 0; i < count; i++) points[i] = readG1Mont(buf, n8q, q, false, label + "[" + i + "]");
- return points;
- }
-
- private static void validateMonomialSrsConsistency(AffineG1[] srsG1, AffineG2 x2, int count) throws IOException {
- if (!srsG1[0].equals(JacobianG1BLS381.GENERATOR.toAffine())) {
- throw new IOException("BLS12-381 .zkey monomial SRS G1 generator anchor mismatch");
- }
- G2Point g2 = toG2(JacobianG2BLS381.GENERATOR.toAffine());
- G2Point tauG2Point = toG2(x2);
- for (int i = 1; i < count; i++) {
- boolean consistent = BLS12381Pairing.pairingCheck(
- new G1Point[]{toG1(srsG1[i]), toG1(srsG1[i - 1]).negate()},
- new G2Point[]{g2, tauG2Point});
- if (!consistent) {
- throw new IOException("BLS12-381 .zkey monomial SRS powers are inconsistent at G1 index " + i);
- }
- }
- }
-
- private static G1Point toG1(AffineG1 point) {
- return new G1Point(Fp.of(point.xBigInt()), Fp.of(point.yBigInt()));
- }
-
- private static G2Point toG2(AffineG2 point) {
- return new G2Point(
- Fp2.of(Fp.of(point.x().reBigInt()), Fp.of(point.x().imBigInt())),
- Fp2.of(Fp.of(point.y().reBigInt()), Fp.of(point.y().imBigInt())));
- }
-
- private static BigInteger readFieldLE(ByteBuffer buf, int n8, BigInteger modulus, String label) throws IOException {
- requireRemaining(buf, n8, label);
- byte[] bytes = new byte[n8];
- buf.get(bytes);
- for (int i = 0; i < n8 / 2; i++) {
- byte tmp = bytes[i]; bytes[i] = bytes[n8 - 1 - i]; bytes[n8 - 1 - i] = tmp;
- }
- BigInteger value = new BigInteger(1, bytes);
- if (value.compareTo(modulus) >= 0) {
- throw new IOException(label + " is not canonical");
- }
- return value;
- }
-
- private static void validateHeaderDimensions(
- int nVars,
- int nPublic,
- int domainSize,
- int nAdditions,
- int nConstraints) throws IOException {
- if (nVars <= 0) {
- throw new IOException("Invalid BLS12-381 .zkey variable count");
- }
- if (domainSize < MIN_DOMAIN_SIZE || (domainSize & (domainSize - 1)) != 0) {
- throw new IOException("BLS12-381 .zkey domainSize must be a power of two >= " + MIN_DOMAIN_SIZE);
- }
- int logN = Integer.numberOfTrailingZeros(domainSize);
- if (logN > MAX_DOMAIN_POWER) {
- throw new IOException("BLS12-381 .zkey domainSize exceeds 2^" + MAX_DOMAIN_POWER);
- }
- if (nPublic < 0 || nPublic > domainSize) {
- throw new IOException("Invalid BLS12-381 .zkey public input count");
- }
- if (nAdditions < 0 || nConstraints < 0 || nConstraints > domainSize) {
- throw new IOException("Invalid BLS12-381 .zkey constraint dimensions");
- }
- }
-
- private static void requireSection(Map sections, int sectionId) throws IOException {
- if (!sections.containsKey(sectionId)) {
- throw new IOException("Missing .zkey section: " + sectionId);
- }
- }
-
- private static void requireSectionSize(Map sections, int sectionId, long minSize) throws IOException {
- if (sections.get(sectionId)[1] < minSize) {
- throw new IOException("Truncated .zkey section: " + sectionId);
- }
- }
-
- private static void requireRemaining(ByteBuffer buf, int bytes, String label) throws IOException {
- if (bytes < 0 || buf.remaining() < bytes) {
- throw new IOException("Truncated " + label);
- }
- }
-
- private static byte[] readBounded(InputStream input, String label) throws IOException {
- if (input == null) {
- throw new IOException(label + " is null");
- }
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- byte[] buffer = new byte[8192];
- int total = 0;
- int read;
- while ((read = input.read(buffer)) != -1) {
- total += read;
- if (total > MAX_ZKEY_BYTES) {
- throw new IOException(label + " exceeds " + MAX_ZKEY_BYTES + " bytes");
- }
- out.write(buffer, 0, read);
- }
- return out.toByteArray();
- }
-
- private static void requireExpectedSha256(byte[] data, byte[] expectedSha256, String label) throws IOException {
- if (expectedSha256 == null) {
- return;
- }
- if (expectedSha256.length != 32) {
- throw new IOException(label + " expected SHA-256 hash must be 32 bytes");
- }
- if (!MessageDigest.isEqual(sha256(data), expectedSha256)) {
- throw new IOException(label + " SHA-256 hash mismatch");
- }
- }
-
- private static byte[] sha256(byte[] data) throws IOException {
- try {
- return MessageDigest.getInstance("SHA-256").digest(data);
- } catch (NoSuchAlgorithmException e) {
- throw new IOException("SHA-256 is not available", e);
- }
+ throw new UnsupportedOperationException(UNSUPPORTED_MESSAGE);
}
}
diff --git a/zeroj-crypto/src/main/java/org/zeroj/crypto/plonk/PtauImporterBLS381.java b/zeroj-crypto/src/main/java/org/zeroj/crypto/plonk/PtauImporterBLS381.java
index 50340386..34b63381 100644
--- a/zeroj-crypto/src/main/java/org/zeroj/crypto/plonk/PtauImporterBLS381.java
+++ b/zeroj-crypto/src/main/java/org/zeroj/crypto/plonk/PtauImporterBLS381.java
@@ -8,41 +8,62 @@
import org.zeroj.bls12381.ec.JacobianG2BLS381.AffineG2;
import org.zeroj.bls12381.field.Fp;
import org.zeroj.bls12381.field.Fp2;
-import org.zeroj.bls12381.field.MontFp381;
import org.zeroj.bls12381.field.MontFp2_381;
+import org.zeroj.bls12381.field.MontFp381;
import org.zeroj.bls12381.pairing.BLS12381Pairing;
-import java.io.ByteArrayOutputStream;
+import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
+import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
-import java.util.*;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
/**
- * Imports SRS (Structured Reference String) from Powers of Tau .ptau files for BLS12-381.
+ * Streaming importer for BLS12-381 Powers of Tau ({@code .ptau}) SRS files produced by
+ * {@code snarkjs} 0.7.6 (ADR-0066).
*
- * Key differences from BN254 ({@link PtauImporter}):
+ *
Format summary ({@code snarkjs@0.7.6} {@code powersoftau_utils.js} / {@code powersoftau_new.js}):
*
- * - n8 = 48 (BLS12-381 Fp is 48 bytes)
- * - Montgomery R = 2^384 mod p
- * - G1 points: 96 bytes, G2 points: 192 bytes
+ * - Global header (12 bytes): magic {@code "ptau"}, {@code version = 1}, {@code numSections}
+ * - Section 1 (60 bytes): {@code n8 = 48}, raw unsigned LE base prime {@code q = FP},
+ * {@code power}, {@code ceremonyPower}
+ * - Section 2 ({@code (2^(power+1) - 1) * 96} bytes): {@code tau^i * G1} in affine LEM format
+ * - Section 3 ({@code 2^power * 192} bytes): {@code tau^i * G2} in affine LEM format
*
+ *
+ * The stream is read sequentially without buffering the full file in RAM, so multi-GB ceremony
+ * files can load {@code maxPoints} powers in {@code O(maxPoints)} memory while still computing
+ * and verifying the full-stream SHA-256 when {@code expectedSha256} is provided. Only bounded
+ * framing and raw point bytes are read during the streaming pass; all elliptic-curve decoding,
+ * subgroup checks, and pairing checks are deferred until after {@code expectedSha256} matches.
*/
public final class PtauImporterBLS381 {
private PtauImporterBLS381() {}
private static final byte[] PTAU_MAGIC = {0x70, 0x74, 0x61, 0x75}; // "ptau"
- private static final int MAX_PTAU_BYTES = 64 * 1024 * 1024;
private static final int MAX_SECTIONS = 64;
private static final int MAX_POWER = 32;
+ /**
+ * Maximum G1 SRS points loaded in one call: aligned with PlonK's maximum supported domain
+ * ({@code 2^24}) plus the 6 blinding powers required by {@code T3} ({@code 2^24 + 6}).
+ */
+ static final int MAX_IMPORT_POINTS = (1 << 24) + 6;
+ /** Chunk size for incremental G1 raw reads (8,192 points = 768 KiB, exact multiple of 96B). */
+ private static final int G1_CHUNK_POINTS = 8192;
+ private static final int SECTION1_LEN = 4 + 48 + 4 + 4; // n8 + prime(48) + power + ceremonyPower
+ private static final int G1_LEM_BYTES = 96;
+ private static final int G2_LEM_BYTES = 192;
private static final BigInteger FP = MontFp381.modulus();
- // Montgomery R^{-1} for Fp: (2^384 mod p)^{-1} mod p
- private static final BigInteger FP_R_INV = BigInteger.ONE.shiftLeft(384).mod(FP).modInverse(FP);
/** Parsed SRS for BLS12-381. */
public record SRS(
@@ -59,159 +80,245 @@ public SRS(AffineG1[] tauG1, AffineG2[] tauG2, int power) {
}
/**
- * Import SRS from a BLS12-381 .ptau file.
+ * Import SRS from a BLS12-381 {@code .ptau} stream, loading up to {@code maxPoints} G1 powers.
*
- * @param maxPoints maximum number of G1 points to load
+ * @param maxPoints maximum number of G1 powers to load (for PlonK, {@code domainSize + 6} suffices)
*/
public static SRS importPtau(InputStream input, int maxPoints) throws IOException {
return importPtau(input, maxPoints, null);
}
/**
- * Import SRS from a BLS12-381 .ptau file and require an exact SHA-256
- * content-hash match before parsing.
+ * Import SRS from a BLS12-381 {@code .ptau} stream and require an exact full-stream SHA-256
+ * match before decoding or validating elliptic-curve points (ADR-0066).
*
- * @param maxPoints maximum number of G1 points to load
- * @param expectedSha256 expected SHA-256 hash, or {@code null} for dev/test
- * callers that intentionally skip artifact pinning
+ * @param maxPoints maximum number of G1 powers to load (capped at {@value #MAX_IMPORT_POINTS})
+ * @param expectedSha256 expected 32-byte SHA-256 digest of the entire {@code .ptau} stream, or
+ * {@code null} for dev/test callers that intentionally skip pinning
*/
public static SRS importPtau(InputStream input, int maxPoints, byte[] expectedSha256) throws IOException {
+ if (input == null) {
+ throw new IOException(".ptau input is null");
+ }
if (maxPoints <= 0) {
throw new IOException("maxPoints must be positive");
}
- byte[] data = readBounded(input, ".ptau input");
- requireExpectedSha256(data, expectedSha256, ".ptau");
- ByteBuffer buf = ByteBuffer.wrap(data).order(ByteOrder.LITTLE_ENDIAN);
- if (buf.remaining() < 12) {
- throw new IOException("Truncated .ptau header");
+ if (expectedSha256 != null && expectedSha256.length != 32) {
+ throw new IOException(".ptau expected SHA-256 hash must be 32 bytes");
+ }
+
+ MessageDigest sha256 = null;
+ InputStream stream = new BufferedInputStream(input, 65536);
+ if (expectedSha256 != null) {
+ sha256 = newSha256();
+ stream = new DigestInputStream(stream, sha256);
}
- byte[] magic = new byte[4];
- buf.get(magic);
- if (!Arrays.equals(magic, PTAU_MAGIC))
+ byte[] headerBuf = readExact(stream, 12, ".ptau header");
+ if (!Arrays.equals(headerBuf, 0, 4, PTAU_MAGIC, 0, 4)) {
throw new IOException("Invalid .ptau magic");
- int version = buf.getInt();
- int numSections = buf.getInt();
- if (version <= 0) {
- throw new IOException("Invalid .ptau version: " + version);
+ }
+ ByteBuffer hdr = ByteBuffer.wrap(headerBuf).order(ByteOrder.LITTLE_ENDIAN);
+ hdr.position(4);
+ int version = hdr.getInt();
+ int numSections = hdr.getInt();
+ if (version != 1) {
+ throw new IOException("Unsupported .ptau version: " + version);
}
if (numSections <= 0 || numSections > MAX_SECTIONS) {
throw new IOException("Invalid .ptau section count: " + numSections);
}
- Map sections = new LinkedHashMap<>();
- for (int i = 0; i < numSections; i++) {
- requireRemaining(buf, 12, ".ptau section header");
- int stype = buf.getInt();
- long ssize = buf.getLong();
- if (sections.containsKey(stype)) {
+ Set seenSections = new HashSet<>();
+ boolean hasHeader = false;
+ int power = -1;
+ int nG1 = -1;
+ List rawG1Chunks = null;
+ byte[] rawG2 = null;
+ byte[] skipScratch = new byte[8192];
+
+ for (int s = 0; s < numSections; s++) {
+ byte[] secHdrBytes = readExact(stream, 12, ".ptau section header");
+ ByteBuffer secHdr = ByteBuffer.wrap(secHdrBytes).order(ByteOrder.LITTLE_ENDIAN);
+ int stype = secHdr.getInt();
+ long ssize = secHdr.getLong();
+ if (!seenSections.add(stype)) {
throw new IOException("Duplicate .ptau section: " + stype);
}
- if (ssize < 0 || ssize > buf.remaining() || ssize > Integer.MAX_VALUE) {
- throw new IOException("Invalid .ptau section size for section " + stype);
+ if (ssize < 0) {
+ throw new IOException("Invalid .ptau section size for section " + stype + ": " + ssize);
+ }
+
+ if (stype == 1) {
+ if (ssize != SECTION1_LEN) {
+ throw new IOException("Invalid BLS12-381 .ptau header section size: expected "
+ + SECTION1_LEN + " bytes, got " + ssize);
+ }
+ byte[] sec1 = readExact(stream, SECTION1_LEN, "BLS12-381 .ptau header section");
+ ByteBuffer s1 = ByteBuffer.wrap(sec1).order(ByteOrder.LITTLE_ENDIAN);
+ int n8 = s1.getInt();
+ if (n8 != 48) {
+ throw new IOException("Not a BLS12-381 .ptau (n8=" + n8 + ", expected 48)");
+ }
+ BigInteger prime = readUnsignedLE(sec1, 4, 48);
+ if (!FP.equals(prime)) {
+ throw new IOException("Wrong BLS12-381 .ptau base-field prime");
+ }
+ s1.position(52);
+ power = s1.getInt();
+ int ceremonyPower = s1.getInt();
+ if (power < 1 || power > MAX_POWER) {
+ throw new IOException("Invalid BLS12-381 .ptau power: " + power);
+ }
+ if (ceremonyPower < power || ceremonyPower > MAX_POWER) {
+ throw new IOException("Invalid BLS12-381 .ptau ceremonyPower: " + ceremonyPower
+ + " (power=" + power + ")");
+ }
+ hasHeader = true;
+ } else if (stype == 2) {
+ if (!hasHeader) {
+ throw new IOException("BLS12-381 .ptau section 2 appeared before header section 1");
+ }
+ long availableG1 = (1L << (power + 1)) - 1L;
+ long expectedSize = availableG1 * G1_LEM_BYTES;
+ if (ssize != expectedSize) {
+ throw new IOException("Invalid BLS12-381 .ptau G1 section size: expected "
+ + expectedSize + " bytes for power " + power + ", got " + ssize);
+ }
+ nG1 = resolvedG1Count(availableG1, maxPoints);
+ rawG1Chunks = readG1ChunksIncrementally(stream, nG1);
+ long remainingBytes = (availableG1 - nG1) * G1_LEM_BYTES;
+ skipExact(stream, remainingBytes, skipScratch, ".ptau section 2 trailing G1 points");
+ } else if (stype == 3) {
+ if (!hasHeader) {
+ throw new IOException("BLS12-381 .ptau section 3 appeared before header section 1");
+ }
+ long availableG2 = 1L << power;
+ long expectedSize = availableG2 * G2_LEM_BYTES;
+ if (ssize != expectedSize) {
+ throw new IOException("Invalid BLS12-381 .ptau G2 section size: expected "
+ + expectedSize + " bytes for power " + power + ", got " + ssize);
+ }
+ if (availableG2 < 2) {
+ throw new IOException("BLS12-381 .ptau must contain at least two G2 powers");
+ }
+ rawG2 = readExact(stream, 2 * G2_LEM_BYTES, "BLS12-381 .ptau G2 points");
+ long remainingBytes = (availableG2 - 2L) * G2_LEM_BYTES;
+ skipExact(stream, remainingBytes, skipScratch, ".ptau section 3 trailing G2 points");
+ } else {
+ skipExact(stream, ssize, skipScratch, ".ptau section " + stype);
}
- sections.put(stype, new long[]{buf.position(), ssize});
- buf.position(buf.position() + (int) ssize);
- }
- requireSection(sections, 1);
- requireSection(sections, 2);
- requireSection(sections, 3);
-
- // Section 1: Header
- buf.position((int) sections.get(1)[0]);
- requireSectionSize(sections, 1, 4 + 48 + 4);
- int n8 = buf.getInt();
- if (n8 != 48)
- throw new IOException("Not a BLS12-381 .ptau (n8=" + n8 + ", expected 48)");
- BigInteger prime = readFieldLE(buf, n8, FP, "BLS12-381 .ptau prime");
- if (!FP.equals(prime)) {
- throw new IOException("Wrong BLS12-381 .ptau base-field prime");
- }
- int power = buf.getInt();
- if (power < 1 || power > MAX_POWER) {
- throw new IOException("Invalid BLS12-381 .ptau power: " + power);
- }
-
- // Section 2: tau^i * G1 (affine, LE, Montgomery)
- if (sections.get(2)[1] % (2L * n8) != 0) {
- throw new IOException("Invalid BLS12-381 .ptau G1 section size");
- }
- buf.position((int) sections.get(2)[0]);
- int availableG1 = (int) (sections.get(2)[1] / (2 * n8));
- int nG1 = Math.min(availableG1, maxPoints);
- if (nG1 == 0) {
- throw new IOException("BLS12-381 .ptau contains no G1 powers");
}
- AffineG1[] tauG1 = new AffineG1[nG1];
- for (int i = 0; i < nG1; i++) {
- tauG1[i] = readG1Mont(buf, n8);
+
+ if (!hasHeader) {
+ throw new IOException("Missing .ptau section: 1");
+ }
+ if (rawG1Chunks == null) {
+ throw new IOException("Missing .ptau section: 2");
+ }
+ if (rawG2 == null) {
+ throw new IOException("Missing .ptau section: 3");
+ }
+ if (stream.read() != -1) {
+ throw new IOException("Trailing bytes after .ptau sections");
}
- // Section 3: tau^i * G2 (only need first 2)
- if (sections.get(3)[1] % (4L * n8) != 0) {
- throw new IOException("Invalid BLS12-381 .ptau G2 section size");
+ // Verify SHA-256 BEFORE any expensive elliptic-curve decoding, subgroup checks, or pairings.
+ if (expectedSha256 != null && !MessageDigest.isEqual(sha256.digest(), expectedSha256)) {
+ throw new IOException(".ptau SHA-256 hash mismatch");
}
- buf.position((int) sections.get(3)[0]);
- int nG2 = Math.min((int) (sections.get(3)[1] / (4 * n8)), 2);
- if (nG2 < 2) {
- throw new IOException("BLS12-381 .ptau must contain at least two G2 powers");
+
+ AffineG1[] tauG1 = new AffineG1[nG1];
+ int pointIndex = 0;
+ for (int c = 0; c < rawG1Chunks.size(); c++) {
+ byte[] chunk = rawG1Chunks.get(c);
+ rawG1Chunks.set(c, null); // release raw chunk as soon as decoded
+ int chunkPoints = chunk.length / G1_LEM_BYTES;
+ for (int j = 0; j < chunkPoints; j++) {
+ tauG1[pointIndex] = decodeSrsG1(chunk, j * G1_LEM_BYTES, pointIndex);
+ pointIndex++;
+ }
}
- AffineG2[] tauG2 = new AffineG2[nG2];
- for (int i = 0; i < nG2; i++) {
- tauG2[i] = readG2Mont(buf, n8);
+ AffineG2[] tauG2 = new AffineG2[2];
+ for (int i = 0; i < 2; i++) {
+ tauG2[i] = decodeSrsG2(rawG2, i * G2_LEM_BYTES, i);
}
- validateSrsConsistency(tauG1, tauG2, nG1);
+ validateSrsConsistency(tauG1, tauG2, tauG1.length);
return new SRS(tauG1, tauG2, power);
}
+ /**
+ * Import all G1 powers (up to {@value #MAX_IMPORT_POINTS}) from a BLS12-381 {@code .ptau} stream.
+ * For large ceremony files, prefer {@link #importPtau(InputStream, int, byte[])} with an explicit
+ * {@code maxPoints} (e.g. {@code domainSize + 6}).
+ */
public static SRS importPtau(InputStream input) throws IOException {
return importPtau(input, Integer.MAX_VALUE);
}
/**
- * Import SRS from a BLS12-381 .ptau file and require an exact SHA-256
- * content-hash match before parsing.
+ * Import SRS from a BLS12-381 {@code .ptau} stream and require an exact full-stream SHA-256
+ * match before decoding or validating elliptic-curve points.
*/
public static SRS importPtau(InputStream input, byte[] expectedSha256) throws IOException {
return importPtau(input, Integer.MAX_VALUE, expectedSha256);
}
- private static AffineG1 readG1Mont(ByteBuffer buf, int n8) throws IOException {
- BigInteger x = readFieldLE(buf, n8, FP, "BLS12-381 G1 x").multiply(FP_R_INV).mod(FP);
- BigInteger y = readFieldLE(buf, n8, FP, "BLS12-381 G1 y").multiply(FP_R_INV).mod(FP);
- if (x.signum() == 0 && y.signum() == 0) return AffineG1.INFINITY;
- AffineG1 point = new AffineG1(MontFp381.fromBigInteger(x), MontFp381.fromBigInteger(y));
+ static int resolvedG1Count(long availableG1, int maxPoints) throws IOException {
+ long nG1Long = Math.min(availableG1, (long) maxPoints);
+ if (nG1Long > MAX_IMPORT_POINTS) {
+ throw new IOException("Requested G1 power count " + nG1Long + " exceeds maximum "
+ + MAX_IMPORT_POINTS + " (pass an explicit maxPoints bound <= " + MAX_IMPORT_POINTS + ")");
+ }
+ return (int) nG1Long;
+ }
+
+ private static AffineG1 decodeSrsG1(byte[] ptBuf, int off, int index) throws IOException {
+ MontFp381 x = decodeMontFp(ptBuf, off, "BLS12-381 .ptau G1[" + index + "].x");
+ MontFp381 y = decodeMontFp(ptBuf, off + 48, "BLS12-381 .ptau G1[" + index + "].y");
+ if (x.isZero() && y.isZero()) {
+ throw new IOException("BLS12-381 .ptau G1[" + index + "] must not be the point at infinity");
+ }
+ AffineG1 point = new AffineG1(x, y);
if (!point.isOnCurve()) {
- throw new IOException("BLS12-381 .ptau G1 point is not on curve");
+ throw new IOException("BLS12-381 .ptau G1[" + index + "] is not on curve");
}
- G1Point subgroupPoint = new G1Point(Fp.of(point.xBigInt()), Fp.of(point.yBigInt()));
- if (!subgroupPoint.isValid()) {
- throw new IOException("BLS12-381 .ptau G1 point is not in subgroup");
+ if (!toG1(point).isValid()) {
+ throw new IOException("BLS12-381 .ptau G1[" + index + "] is not in subgroup");
}
return point;
}
- private static AffineG2 readG2Mont(ByteBuffer buf, int n8) throws IOException {
- BigInteger x0 = readFieldLE(buf, n8, FP, "BLS12-381 G2 x0").multiply(FP_R_INV).mod(FP);
- BigInteger x1 = readFieldLE(buf, n8, FP, "BLS12-381 G2 x1").multiply(FP_R_INV).mod(FP);
- BigInteger y0 = readFieldLE(buf, n8, FP, "BLS12-381 G2 y0").multiply(FP_R_INV).mod(FP);
- BigInteger y1 = readFieldLE(buf, n8, FP, "BLS12-381 G2 y1").multiply(FP_R_INV).mod(FP);
- if (x0.signum() == 0 && x1.signum() == 0 && y0.signum() == 0 && y1.signum() == 0)
- return AffineG2.INFINITY;
+ private static AffineG2 decodeSrsG2(byte[] ptBuf, int off, int index) throws IOException {
+ MontFp381 x0 = decodeMontFp(ptBuf, off, "BLS12-381 .ptau G2[" + index + "].x.c0");
+ MontFp381 x1 = decodeMontFp(ptBuf, off + 48, "BLS12-381 .ptau G2[" + index + "].x.c1");
+ MontFp381 y0 = decodeMontFp(ptBuf, off + 96, "BLS12-381 .ptau G2[" + index + "].y.c0");
+ MontFp381 y1 = decodeMontFp(ptBuf, off + 144, "BLS12-381 .ptau G2[" + index + "].y.c1");
+ if (x0.isZero() && x1.isZero() && y0.isZero() && y1.isZero()) {
+ throw new IOException("BLS12-381 .ptau G2[" + index + "] must not be the point at infinity");
+ }
AffineG2 point = new AffineG2(MontFp2_381.of(x0, x1), MontFp2_381.of(y0, y1));
if (!point.isOnCurve()) {
- throw new IOException("BLS12-381 .ptau G2 point is not on curve");
+ throw new IOException("BLS12-381 .ptau G2[" + index + "] is not on curve");
}
- G2Point subgroupPoint = new G2Point(
- Fp2.of(Fp.of(point.x().reBigInt()), Fp.of(point.x().imBigInt())),
- Fp2.of(Fp.of(point.y().reBigInt()), Fp.of(point.y().imBigInt())));
- if (!subgroupPoint.isValid()) {
- throw new IOException("BLS12-381 .ptau G2 point is not in subgroup");
+ if (!toG2(point).isValid()) {
+ throw new IOException("BLS12-381 .ptau G2[" + index + "] is not in subgroup");
}
return point;
}
+ private static MontFp381 decodeMontFp(byte[] buf, int off, String label) throws IOException {
+ ByteBuffer bb = ByteBuffer.wrap(buf, off, 48).order(ByteOrder.LITTLE_ENDIAN);
+ try {
+ return MontFp381.fromMontLimbs(
+ bb.getLong(), bb.getLong(), bb.getLong(),
+ bb.getLong(), bb.getLong(), bb.getLong());
+ } catch (IllegalArgumentException e) {
+ throw new IOException(label + " is not canonical (< p)", e);
+ }
+ }
+
private static void validateSrsConsistency(AffineG1[] tauG1, AffineG2[] tauG2, int count) throws IOException {
if (!tauG1[0].equals(JacobianG1BLS381.GENERATOR.toAffine())) {
throw new IOException("BLS12-381 .ptau G1 generator anchor mismatch");
@@ -232,80 +339,71 @@ private static void validateSrsConsistency(AffineG1[] tauG1, AffineG2[] tauG2, i
}
private static G1Point toG1(AffineG1 point) {
+ if (point.isInfinity()) return G1Point.INFINITY;
return new G1Point(Fp.of(point.xBigInt()), Fp.of(point.yBigInt()));
}
private static G2Point toG2(AffineG2 point) {
+ if (point.isInfinity()) return G2Point.INFINITY;
return new G2Point(
Fp2.of(Fp.of(point.x().reBigInt()), Fp.of(point.x().imBigInt())),
Fp2.of(Fp.of(point.y().reBigInt()), Fp.of(point.y().imBigInt())));
}
- private static BigInteger readFieldLE(ByteBuffer buf, int n8, BigInteger modulus, String label) throws IOException {
- requireRemaining(buf, n8, label);
- byte[] bytes = new byte[n8];
- buf.get(bytes);
- for (int i = 0; i < n8 / 2; i++) {
- byte tmp = bytes[i]; bytes[i] = bytes[n8 - 1 - i]; bytes[n8 - 1 - i] = tmp;
- }
- BigInteger value = new BigInteger(1, bytes);
- if (value.compareTo(modulus) >= 0) {
- throw new IOException(label + " is not canonical");
+ private static BigInteger readUnsignedLE(byte[] buf, int off, int len) {
+ byte[] be = new byte[len];
+ for (int i = 0; i < len; i++) {
+ be[len - 1 - i] = buf[off + i];
}
- return value;
+ return new BigInteger(1, be);
}
- private static void requireSection(Map sections, int sectionId) throws IOException {
- if (!sections.containsKey(sectionId)) {
- throw new IOException("Missing .ptau section: " + sectionId);
- }
+ private static List readG1ChunksIncrementally(InputStream stream, int nG1) throws IOException {
+ // Allocate in <= 768 KiB chunks as bytes actually arrive so a truncated header claiming a
+ // huge power (e.g. power=23 with 0 payload bytes) throws IOException without OOM.
+ List chunks = new ArrayList<>();
+ int remainingPoints = nG1;
+ while (remainingPoints > 0) {
+ int batchPoints = Math.min(remainingPoints, G1_CHUNK_POINTS);
+ byte[] chunk = readExact(stream, batchPoints * G1_LEM_BYTES, "BLS12-381 .ptau G1 points");
+ chunks.add(chunk);
+ remainingPoints -= batchPoints;
+ }
+ return chunks;
}
- private static void requireSectionSize(Map sections, int sectionId, long minSize) throws IOException {
- if (sections.get(sectionId)[1] < minSize) {
- throw new IOException("Truncated .ptau section: " + sectionId);
- }
+ private static byte[] readExact(InputStream stream, int len, String label) throws IOException {
+ byte[] out = new byte[len];
+ readExactInto(stream, out, label);
+ return out;
}
- private static void requireRemaining(ByteBuffer buf, int bytes, String label) throws IOException {
- if (bytes < 0 || buf.remaining() < bytes) {
- throw new IOException("Truncated " + label);
- }
- }
-
- private static byte[] readBounded(InputStream input, String label) throws IOException {
- if (input == null) {
- throw new IOException(label + " is null");
- }
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- byte[] buffer = new byte[8192];
- int total = 0;
- int read;
- while ((read = input.read(buffer)) != -1) {
- total += read;
- if (total > MAX_PTAU_BYTES) {
- throw new IOException(label + " exceeds " + MAX_PTAU_BYTES + " bytes");
+ private static void readExactInto(InputStream stream, byte[] buf, String label) throws IOException {
+ int offset = 0;
+ while (offset < buf.length) {
+ int n = stream.read(buf, offset, buf.length - offset);
+ if (n < 0) {
+ throw new IOException("Truncated " + label);
}
- out.write(buffer, 0, read);
+ offset += n;
}
- return out.toByteArray();
}
- private static void requireExpectedSha256(byte[] data, byte[] expectedSha256, String label) throws IOException {
- if (expectedSha256 == null) {
- return;
- }
- if (expectedSha256.length != 32) {
- throw new IOException(label + " expected SHA-256 hash must be 32 bytes");
- }
- if (!MessageDigest.isEqual(sha256(data), expectedSha256)) {
- throw new IOException(label + " SHA-256 hash mismatch");
+ private static void skipExact(InputStream stream, long bytes, byte[] scratch, String label) throws IOException {
+ long remaining = bytes;
+ while (remaining > 0) {
+ int toRead = (int) Math.min(remaining, scratch.length);
+ int n = stream.read(scratch, 0, toRead);
+ if (n < 0) {
+ throw new IOException("Truncated " + label);
+ }
+ remaining -= n;
}
}
- private static byte[] sha256(byte[] data) throws IOException {
+ private static MessageDigest newSha256() throws IOException {
try {
- return MessageDigest.getInstance("SHA-256").digest(data);
+ return MessageDigest.getInstance("SHA-256");
} catch (NoSuchAlgorithmException e) {
throw new IOException("SHA-256 is not available", e);
}
diff --git a/zeroj-crypto/src/main/java/org/zeroj/crypto/setup/PlonkSetupCache.java b/zeroj-crypto/src/main/java/org/zeroj/crypto/setup/PlonkSetupCache.java
index 085d1550..a005f5c4 100644
--- a/zeroj-crypto/src/main/java/org/zeroj/crypto/setup/PlonkSetupCache.java
+++ b/zeroj-crypto/src/main/java/org/zeroj/crypto/setup/PlonkSetupCache.java
@@ -181,7 +181,7 @@ private static void validatePlonkProvingKeyShape(
requireFrArrayLength("s1", s1, domainSize);
requireFrArrayLength("s2", s2, domainSize);
requireFrArrayLength("s3", s3, domainSize);
- if (srsG1.length < 2 * domainSize || srsG1Lagrange.length < domainSize) {
+ if (srsG1.length < domainSize + 6 || srsG1Lagrange.length < domainSize) {
throw new IOException("PlonK proving key SRS is too small for domain size " + domainSize);
}
}
diff --git a/zeroj-crypto/src/test/java/org/zeroj/crypto/plonk/PlonKBLS381InvariantTest.java b/zeroj-crypto/src/test/java/org/zeroj/crypto/plonk/PlonKBLS381InvariantTest.java
index 0dcc81c9..0cc6d1aa 100644
--- a/zeroj-crypto/src/test/java/org/zeroj/crypto/plonk/PlonKBLS381InvariantTest.java
+++ b/zeroj-crypto/src/test/java/org/zeroj/crypto/plonk/PlonKBLS381InvariantTest.java
@@ -50,8 +50,9 @@ void setup_rejectsSigmaTargetOutsidePermutationRange() {
@Test
void setup_rejectsSrsTooShortForBlindedPlonkPolynomials() {
+ // domainSize = 8 requires domainSize + 6 = 14 G1 powers; 13 must fail
var shortSrs = new PtauImporterBLS381.SRS(
- Arrays.copyOf(fixture.srs().tauG1(), 15),
+ Arrays.copyOf(fixture.srs().tauG1(), 13),
fixture.srs().tauG2(),
fixture.srs().power(),
fixture.srs().tauScalar());
@@ -60,6 +61,21 @@ void setup_rejectsSrsTooShortForBlindedPlonkPolynomials() {
fixture.sigmaA(), fixture.sigmaB(), fixture.sigmaC(), shortSrs));
}
+ @Test
+ void setupAndProve_acceptsExactDomainPlus6Srs() {
+ // Exact domainSize + 6 = 14 G1 powers (matching a same-power snarkjs .ptau with 2n - 1 = 15 >= 14)
+ var exactSrs = new PtauImporterBLS381.SRS(
+ Arrays.copyOf(fixture.srs().tauG1(), 14),
+ fixture.srs().tauG2(),
+ fixture.srs().power(),
+ fixture.srs().tauScalar());
+ var pk = setupWith(fixture.gateSelectors(),
+ fixture.sigmaA(), fixture.sigmaB(), fixture.sigmaC(), exactSrs);
+ var proof = PlonKProverBLS381.prove(
+ pk, fixture.wireA(), fixture.wireB(), fixture.wireC(), fixture.pubInputs());
+ assertTrue(proof.commitT3().isOnCurve());
+ }
+
@Test
void setup_rejectsInconsistentSrsPowersOfTau() {
var badTauG1 = fixture.srs().tauG1().clone();
diff --git a/zeroj-crypto/src/test/java/org/zeroj/crypto/plonk/PlonKZkeyImporterBLS381Test.java b/zeroj-crypto/src/test/java/org/zeroj/crypto/plonk/PlonKZkeyImporterBLS381Test.java
index 5c1358fb..b045967d 100644
--- a/zeroj-crypto/src/test/java/org/zeroj/crypto/plonk/PlonKZkeyImporterBLS381Test.java
+++ b/zeroj-crypto/src/test/java/org/zeroj/crypto/plonk/PlonKZkeyImporterBLS381Test.java
@@ -3,89 +3,34 @@
import org.junit.jupiter.api.Test;
import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.nio.ByteBuffer;
-import java.nio.ByteOrder;
import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
class PlonKZkeyImporterBLS381Test {
@Test
- void importZkey_rejectsNullInput() {
- assertThrows(IOException.class, () -> PlonKZkeyImporterBLS381.importZkey(null));
+ void importZkey_singleArg_failsExplicitlyWithUnsupportedOperationException() {
+ UnsupportedOperationException ex = assertThrows(
+ UnsupportedOperationException.class,
+ () -> PlonKZkeyImporterBLS381.importZkey(new ByteArrayInputStream(new byte[]{'z', 'k', 'e', 'y'})));
+ assertTrue(ex.getMessage().contains("ADR-0066"), ex.getMessage());
+ assertTrue(ex.getMessage().contains("PtauImporterBLS381"), ex.getMessage());
}
@Test
- void importZkey_rejectsTruncatedHeader() {
- assertThrows(IOException.class, () -> PlonKZkeyImporterBLS381.importZkey(
- new ByteArrayInputStream(new byte[]{'z', 'k', 'e', 'y'})));
+ void importZkey_pinnedArg_failsExplicitlyWithUnsupportedOperationException() {
+ UnsupportedOperationException ex = assertThrows(
+ UnsupportedOperationException.class,
+ () -> PlonKZkeyImporterBLS381.importZkey(
+ new ByteArrayInputStream(new byte[]{'z', 'k', 'e', 'y'}), new byte[32]));
+ assertTrue(ex.getMessage().contains("ADR-0066"), ex.getMessage());
+ assertTrue(ex.getMessage().contains("PtauImporterBLS381"), ex.getMessage());
}
@Test
- void importZkey_rejectsExpectedHashLengthMismatch() {
- assertThrows(IOException.class, () -> PlonKZkeyImporterBLS381.importZkey(
- new ByteArrayInputStream(new byte[]{'z', 'k', 'e', 'y'}), new byte[31]));
- }
-
- @Test
- void importZkey_rejectsExpectedHashMismatchBeforeParsing() {
- assertThrows(IOException.class, () -> PlonKZkeyImporterBLS381.importZkey(
- new ByteArrayInputStream(new byte[]{'z', 'k', 'e', 'y'}), new byte[32]));
- }
-
- @Test
- void importZkey_rejectsDuplicateSections() throws IOException {
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- out.write(new byte[]{'z', 'k', 'e', 'y'});
- out.write(leInt(1));
- out.write(leInt(2));
- writeSection(out, 1, new byte[0]);
- writeSection(out, 1, new byte[0]);
-
- assertThrows(IOException.class, () -> PlonKZkeyImporterBLS381.importZkey(
- new ByteArrayInputStream(out.toByteArray())));
- }
-
- @Test
- void importZkey_rejectsMissingRequiredSections() throws IOException {
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- out.write(new byte[]{'z', 'k', 'e', 'y'});
- out.write(leInt(1));
- out.write(leInt(1));
- writeSection(out, 1, leInt(2));
-
- assertThrows(IOException.class, () -> PlonKZkeyImporterBLS381.importZkey(
- new ByteArrayInputStream(out.toByteArray())));
- }
-
- @Test
- void importZkey_rejectsWrongProtocol() throws IOException {
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- out.write(new byte[]{'z', 'k', 'e', 'y'});
- out.write(leInt(1));
- out.write(leInt(10));
- writeSection(out, 1, leInt(1));
- for (int sectionId : new int[]{2, 7, 8, 9, 10, 11, 12, 13, 14}) {
- writeSection(out, sectionId, new byte[0]);
- }
-
- assertThrows(IOException.class, () -> PlonKZkeyImporterBLS381.importZkey(
- new ByteArrayInputStream(out.toByteArray())));
- }
-
- private static void writeSection(ByteArrayOutputStream out, int sectionType, byte[] data) throws IOException {
- out.write(leInt(sectionType));
- out.write(leLong(data.length));
- out.write(data);
- }
-
- private static byte[] leInt(int value) {
- return ByteBuffer.allocate(Integer.BYTES).order(ByteOrder.LITTLE_ENDIAN).putInt(value).array();
- }
-
- private static byte[] leLong(long value) {
- return ByteBuffer.allocate(Long.BYTES).order(ByteOrder.LITTLE_ENDIAN).putLong(value).array();
+ void importZkey_nullInput_failsExplicitlyWithUnsupportedOperationException() {
+ assertThrows(UnsupportedOperationException.class, () -> PlonKZkeyImporterBLS381.importZkey(null));
+ assertThrows(UnsupportedOperationException.class, () -> PlonKZkeyImporterBLS381.importZkey(null, null));
}
}
diff --git a/zeroj-crypto/src/test/java/org/zeroj/crypto/plonk/PtauImporterBLS381Test.java b/zeroj-crypto/src/test/java/org/zeroj/crypto/plonk/PtauImporterBLS381Test.java
index f29f5ff5..161eed61 100644
--- a/zeroj-crypto/src/test/java/org/zeroj/crypto/plonk/PtauImporterBLS381Test.java
+++ b/zeroj-crypto/src/test/java/org/zeroj/crypto/plonk/PtauImporterBLS381Test.java
@@ -1,17 +1,192 @@
package org.zeroj.crypto.plonk;
import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+import org.zeroj.api.CurveId;
+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.MontFp381;
+import org.zeroj.bls12381.field.MontFr381;
+import org.zeroj.circuit.CircuitBuilder;
+import org.zeroj.circuit.plonk.PlonKConstraintSystem;
+import org.zeroj.crypto.snarkjs.SnarkjsPlonkJson;
+import org.zeroj.crypto.testsupport.SnarkjsCliLocator;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
+import java.io.InputStream;
+import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.security.MessageDigest;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.TimeUnit;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
+import static org.junit.jupiter.api.Assumptions.assumeTrue;
class PtauImporterBLS381Test {
+ private static final BigInteger FP = MontFp381.modulus();
+ private static final AffineG1 G1 = JacobianG1BLS381.GENERATOR.toAffine();
+ private static final AffineG2 G2 = JacobianG2BLS381.GENERATOR.toAffine();
+ private static final AffineG1 SMALL_SUBGROUP_G1 = new AffineG1(MontFp381.ZERO, MontFp381.TWO);
+ private static final AffineG1 OFF_CURVE_G1 = new AffineG1(G1.x(), G1.y().add(MontFp381.ONE));
+
+ // ---- Positive offline tests ----
+
+ @Test
+ void importPtau_parsesValidSyntheticPtauWithPinAndBoundedMaxPoints() throws Exception {
+ BigInteger tau = BigInteger.valueOf(7);
+ byte[] ptau = buildSyntheticPtau(2, tau); // power=2 => 7 G1 points, 4 G2 points
+ byte[] sha256 = MessageDigest.getInstance("SHA-256").digest(ptau);
+
+ // Full import with SHA-256 pin
+ PtauImporterBLS381.SRS full = PtauImporterBLS381.importPtau(new ByteArrayInputStream(ptau), sha256);
+ assertEquals(2, full.power());
+ assertEquals(7, full.tauG1().length);
+ assertEquals(2, full.tauG2().length);
+ assertEquals(G1, full.tauG1()[0]);
+ assertEquals(JacobianG1BLS381.GENERATOR.scalarMul(tau).toAffine(), full.tauG1()[1]);
+ assertEquals(G2, full.tauG2()[0]);
+ assertEquals(JacobianG2BLS381.GENERATOR.scalarMul(tau).toAffine(), full.tauG2()[1]);
+
+ // Bounded maxPoints import with SHA-256 pin (still hashes full stream)
+ PtauImporterBLS381.SRS bounded = PtauImporterBLS381.importPtau(new ByteArrayInputStream(ptau), 4, sha256);
+ assertEquals(4, bounded.tauG1().length);
+ assertEquals(2, bounded.tauG2().length);
+
+ // 1-bit flipped SHA-256 rejected
+ byte[] wrongHash = sha256.clone();
+ wrongHash[0] ^= 0x01;
+ IOException ex = assertThrows(IOException.class,
+ () -> PtauImporterBLS381.importPtau(new ByteArrayInputStream(ptau), 4, wrongHash));
+ assertTrue(ex.getMessage().contains("SHA-256 hash mismatch"), ex.getMessage());
+ }
+
+ @Test
+ void importPtau_streamsBeyond64MiBWithoutBufferingFullFile() throws Exception {
+ // Virtual stream with valid power=2 sections 1-3 + a 70 MiB dummy section 4 (> old 64 MiB cap)
+ BigInteger tau = BigInteger.valueOf(5);
+ byte[] prefix = buildSyntheticPtauSections1To3(2, tau, 4); // declares 4 sections
+ long extraSectionBytes = 70L * 1024 * 1024;
+ ByteArrayOutputStream sec4Hdr = new ByteArrayOutputStream();
+ sec4Hdr.write(leInt(4));
+ sec4Hdr.write(leLong(extraSectionBytes));
+ byte[] sec4HdrBytes = sec4Hdr.toByteArray();
+
+ // Compute exact SHA-256 in streaming fashion too
+ MessageDigest md = MessageDigest.getInstance("SHA-256");
+ md.update(prefix);
+ md.update(sec4HdrBytes);
+ byte[] zeros = new byte[65536];
+ long rem = extraSectionBytes;
+ while (rem > 0) {
+ int n = (int) Math.min(rem, zeros.length);
+ md.update(zeros, 0, n);
+ rem -= n;
+ }
+ byte[] expectedSha = md.digest();
+
+ InputStream largeStream = new LargeZeroSectionStream(prefix, sec4HdrBytes, extraSectionBytes);
+ PtauImporterBLS381.SRS srs = PtauImporterBLS381.importPtau(largeStream, 4, expectedSha);
+ assertEquals(2, srs.power());
+ assertEquals(4, srs.tauG1().length);
+ assertEquals(2, srs.tauG2().length);
+ }
+
+ // ---- Live snarkjs 0.7.6 same-power .ptau -> setup -> prove -> snarkjs plonk verify ----
+
+ @Test
+ void importPtau_liveSnarkjsSamePowerPtau_setupProveAndVerifyWithSnarkjs(@TempDir Path dir) throws Exception {
+ String snarkjs = requireSnarkjs();
+
+ // Same-power .ptau: power = 3 => domainSize = 8, available G1 = 2^4 - 1 = 15 >= n + 6 = 14
+ run(dir, snarkjs, "powersoftau", "new", "bls12-381", "3", "pot0.ptau");
+ run(dir, snarkjs, "powersoftau", "contribute", "pot0.ptau", "pot1.ptau", "--name=p4", "-e=ptau-interop-e1");
+ run(dir, snarkjs, "powersoftau", "prepare", "phase2", "pot1.ptau", "pot.ptau");
+
+ Path ptauFile = dir.resolve("pot.ptau");
+ byte[] ptauSha = MessageDigest.getInstance("SHA-256").digest(Files.readAllBytes(ptauFile));
+
+ // Import exact n + 6 = 14 points from the live snarkjs .ptau with SHA-256 pin
+ PtauImporterBLS381.SRS srs;
+ try (InputStream in = Files.newInputStream(ptauFile)) {
+ srs = PtauImporterBLS381.importPtau(in, 14, ptauSha);
+ }
+ assertEquals(3, srs.power());
+ assertEquals(14, srs.tauG1().length);
+ assertEquals(2, srs.tauG2().length);
+
+ // Tampered SHA-256 rejected on live .ptau
+ byte[] badSha = ptauSha.clone();
+ badSha[31] ^= 0x01;
+ try (InputStream in = Files.newInputStream(ptauFile)) {
+ assertThrows(IOException.class, () -> PtauImporterBLS381.importPtau(in, 14, badSha));
+ }
+
+ // Build multiplier circuit, run PlonK setup + prove with the imported same-power SRS,
+ // and verify with live `snarkjs plonk verify`.
+ var circuit = CircuitBuilder.create("ptau-mul")
+ .publicVar("c")
+ .secretVar("a")
+ .secretVar("b")
+ .define(api -> api.assertEqual(api.mul(api.var("a"), api.var("b")), api.var("c")));
+ BigInteger[] witness = circuit.calculateWitness(Map.of(
+ "c", List.of(BigInteger.valueOf(33)),
+ "a", List.of(BigInteger.valueOf(3)),
+ "b", List.of(BigInteger.valueOf(11))), CurveId.BLS12_381);
+ PlonKConstraintSystem plonk = circuit.compilePlonK(CurveId.BLS12_381);
+ int numGates = plonk.numGates();
+ BigInteger[][] selectors = new BigInteger[numGates][];
+ for (int i = 0; i < numGates; i++) {
+ var row = plonk.gateRows().get(i);
+ selectors[i] = new BigInteger[]{row.qL(), row.qR(), row.qO(), row.qM(), row.qC()};
+ }
+ PlonKProvingKeyBLS381 pk = PlonKSetupBLS381.setup(
+ numGates, plonk.numPublicInputs(), selectors,
+ plonk.sigmaA(), plonk.sigmaB(), plonk.sigmaC(), plonk.numWires(), srs);
+ assertEquals(8, pk.domainSize());
+
+ BigInteger[] ext = plonk.extendWitness(witness);
+ int n = pk.domainSize();
+ MontFr381[] wireA = new MontFr381[n];
+ MontFr381[] wireB = new MontFr381[n];
+ MontFr381[] wireC = new MontFr381[n];
+ for (int i = 0; i < n; i++) {
+ if (i < numGates) {
+ var row = plonk.gateRows().get(i);
+ wireA[i] = MontFr381.fromBigInteger(ext[row.wireA()]);
+ wireB[i] = MontFr381.fromBigInteger(ext[row.wireB()]);
+ wireC[i] = MontFr381.fromBigInteger(ext[row.wireC()]);
+ } else {
+ wireA[i] = wireB[i] = wireC[i] = MontFr381.ZERO;
+ }
+ }
+ BigInteger[] publicInputs = Arrays.copyOfRange(witness, 1, 1 + plonk.numPublicInputs());
+ PlonKProofBLS381 proof = PlonKProverBLS381.prove(pk, wireA, wireB, wireC, publicInputs);
+
+ Files.writeString(dir.resolve("verification_key.json"), SnarkjsPlonkJson.verificationKeyJson(pk));
+ Files.writeString(dir.resolve("proof.json"), SnarkjsPlonkJson.proofJson(proof));
+ Files.writeString(dir.resolve("public.json"), SnarkjsPlonkJson.publicJson(publicInputs));
+
+ String verifyOut = run(dir, snarkjs, "plonk", "verify",
+ "verification_key.json", "public.json", "proof.json");
+ assertTrue(verifyOut.contains("OK!"), "snarkjs plonk verify did not report OK!: " + verifyOut);
+ }
+
+ // ---- Negative tests ----
+
@Test
void importPtau_rejectsNullInput() {
assertThrows(IOException.class, () -> PtauImporterBLS381.importPtau(null, 1));
@@ -30,22 +205,114 @@ void importPtau_rejectsExpectedHashLengthMismatch() {
}
@Test
- void importPtau_rejectsExpectedHashMismatchBeforeParsing() {
- assertThrows(IOException.class, () -> PtauImporterBLS381.importPtau(
- new ByteArrayInputStream(new byte[]{'p', 't', 'a', 'u'}), 1, new byte[32]));
+ void importPtau_rejectsExpectedHashMismatchBeforePointValidation() throws Exception {
+ // Structurally framed .ptau containing an off-curve point in tauG1[1]:
+ // - with a WRONG pin, must fail on SHA-256 BEFORE point decoding/subgroup validation;
+ // - with the CORRECT pin, must pass SHA-256 and then fail on curve validation.
+ byte[] badPointPtau = buildSyntheticPtau(2, BigInteger.valueOf(7));
+ int sec2PayloadOff = 12 + 12 + 60 + 12;
+ System.arraycopy(g1Lem(OFF_CURVE_G1), 0, badPointPtau, sec2PayloadOff + 96, 96);
+
+ byte[] correctPin = MessageDigest.getInstance("SHA-256").digest(badPointPtau);
+ byte[] wrongPin = correctPin.clone();
+ wrongPin[0] ^= 0x01;
+
+ IOException wrongPinEx = assertThrows(IOException.class,
+ () -> PtauImporterBLS381.importPtau(new ByteArrayInputStream(badPointPtau), 7, wrongPin));
+ assertTrue(wrongPinEx.getMessage().contains("SHA-256 hash mismatch"), wrongPinEx.getMessage());
+
+ IOException rightPinEx = assertThrows(IOException.class,
+ () -> PtauImporterBLS381.importPtau(new ByteArrayInputStream(badPointPtau), 7, correctPin));
+ assertTrue(rightPinEx.getMessage().contains("not on curve"), rightPinEx.getMessage());
+ }
+
+ @Test
+ void resolvedG1Count_alignsWithMaxDomain24Plus6() throws Exception {
+ long power24AvailableG1 = (1L << 25) - 1L;
+ int maxDomainPlus6 = (1 << 24) + 6;
+ assertEquals(maxDomainPlus6, PtauImporterBLS381.resolvedG1Count(power24AvailableG1, maxDomainPlus6));
+ IOException ex = assertThrows(IOException.class,
+ () -> PtauImporterBLS381.resolvedG1Count(power24AvailableG1, maxDomainPlus6 + 1));
+ assertTrue(ex.getMessage().contains("exceeds maximum"), ex.getMessage());
}
@Test
- void importPtau_rejectsDuplicateSections() throws IOException {
+ void importPtau_truncatedLargePowerHeader_failsWithIOExceptionWithoutOom() throws IOException {
+ // 96-byte input claiming power=23 and (2^24 - 1)*96 bytes (~1.5 GiB) in Section 2 with 0 payload bytes.
+ // Incremental chunked reads must reject immediately on EOF without pre-allocating ~1.5 GiB.
ByteArrayOutputStream out = new ByteArrayOutputStream();
out.write(new byte[]{'p', 't', 'a', 'u'});
out.write(leInt(1));
+ out.write(leInt(3));
+ writeSection(out, 1, buildValidSection1(23, 23));
out.write(leInt(2));
- writeSection(out, 1, new byte[0]);
- writeSection(out, 1, new byte[0]);
+ out.write(leLong(((1L << 24) - 1L) * 96L)); // declared ~1.5 GiB, 0 bytes follow
- assertThrows(IOException.class, () -> PtauImporterBLS381.importPtau(
- new ByteArrayInputStream(out.toByteArray()), 1));
+ IOException ex = assertThrows(IOException.class,
+ () -> PtauImporterBLS381.importPtau(new ByteArrayInputStream(out.toByteArray())));
+ assertTrue(ex.getMessage().contains("Truncated"), ex.getMessage());
+ }
+
+ @Test
+ void importPtau_rejectsDuplicateSectionsWithValidFirstHeader() throws IOException {
+ byte[] validSec1 = buildValidSection1(2, 2);
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ out.write(new byte[]{'p', 't', 'a', 'u'});
+ out.write(leInt(1));
+ out.write(leInt(2));
+ writeSection(out, 1, validSec1);
+ writeSection(out, 1, validSec1);
+
+ IOException ex = assertThrows(IOException.class,
+ () -> PtauImporterBLS381.importPtau(new ByteArrayInputStream(out.toByteArray()), 1));
+ assertTrue(ex.getMessage().contains("Duplicate .ptau section: 1"), ex.getMessage());
+ }
+
+ @Test
+ void importPtau_rejectsInvalidCeremonyPowerOutOfOrderAndSectionSizeMismatches() throws IOException {
+ // ceremonyPower < power (with valid prime & n8)
+ ByteArrayOutputStream badCeremony = new ByteArrayOutputStream();
+ badCeremony.write(new byte[]{'p', 't', 'a', 'u'});
+ badCeremony.write(leInt(1));
+ badCeremony.write(leInt(1));
+ writeSection(badCeremony, 1, buildValidSection1(4, 3));
+ IOException exCp = assertThrows(IOException.class,
+ () -> PtauImporterBLS381.importPtau(new ByteArrayInputStream(badCeremony.toByteArray()), 1));
+ assertTrue(exCp.getMessage().contains("ceremonyPower"), exCp.getMessage());
+
+ // Section 2 appearing before Section 1
+ ByteArrayOutputStream outOfOrder = new ByteArrayOutputStream();
+ outOfOrder.write(new byte[]{'p', 't', 'a', 'u'});
+ outOfOrder.write(leInt(1));
+ outOfOrder.write(leInt(2));
+ writeSection(outOfOrder, 2, new byte[96]);
+ writeSection(outOfOrder, 1, buildValidSection1(2, 2));
+ IOException exOrder = assertThrows(IOException.class,
+ () -> PtauImporterBLS381.importPtau(new ByteArrayInputStream(outOfOrder.toByteArray()), 1));
+ assertTrue(exOrder.getMessage().contains("before header section 1"), exOrder.getMessage());
+
+ // Section 2 size mismatch (valid power=2 header expects 7*96 bytes, provide 6*96)
+ ByteArrayOutputStream badSec2 = new ByteArrayOutputStream();
+ badSec2.write(new byte[]{'p', 't', 'a', 'u'});
+ badSec2.write(leInt(1));
+ badSec2.write(leInt(2));
+ writeSection(badSec2, 1, buildValidSection1(2, 2));
+ writeSection(badSec2, 2, new byte[6 * 96]);
+ IOException exSec2 = assertThrows(IOException.class,
+ () -> PtauImporterBLS381.importPtau(new ByteArrayInputStream(badSec2.toByteArray()), 4));
+ assertTrue(exSec2.getMessage().contains("G1 section size"), exSec2.getMessage());
+
+ // Section 3 size mismatch (valid power=2 header + valid section 2, section 3 has 3*192 instead of 4*192)
+ ByteArrayOutputStream badSec3 = new ByteArrayOutputStream();
+ badSec3.write(new byte[]{'p', 't', 'a', 'u'});
+ badSec3.write(leInt(1));
+ badSec3.write(leInt(3));
+ writeSection(badSec3, 1, buildValidSection1(2, 2));
+ writeSection(badSec3, 2, new byte[7 * 96]);
+ writeSection(badSec3, 3, new byte[3 * 192]);
+ IOException exSec3 = assertThrows(IOException.class,
+ () -> PtauImporterBLS381.importPtau(new ByteArrayInputStream(badSec3.toByteArray()), 4));
+ assertTrue(exSec3.getMessage().contains("G2 section size"), exSec3.getMessage());
}
@Test
@@ -54,6 +321,7 @@ void importPtau_rejectsWrongBaseFieldPrime() throws IOException {
header.write(leInt(48));
header.write(new byte[48]);
header.write(leInt(4));
+ header.write(leInt(4));
ByteArrayOutputStream out = new ByteArrayOutputStream();
out.write(new byte[]{'p', 't', 'a', 'u'});
@@ -67,6 +335,212 @@ void importPtau_rejectsWrongBaseFieldPrime() throws IOException {
new ByteArrayInputStream(out.toByteArray()), 1));
}
+ @Test
+ void importPtau_rejectsInfinityOffCurveSmallSubgroupNonCanonicalAndInconsistentSrs() throws IOException {
+ byte[] valid = buildSyntheticPtau(2, BigInteger.valueOf(7));
+ int sec2PayloadOff = 12 + 12 + 60 + 12; // global(12) + sec1(12+60) + sec2hdr(12)
+ int sec3PayloadOff = sec2PayloadOff + 7 * 96 + 12;
+
+ // Infinity in tauG1[1]
+ byte[] infG1 = valid.clone();
+ Arrays.fill(infG1, sec2PayloadOff + 96, sec2PayloadOff + 192, (byte) 0);
+ IOException exInf1 = assertThrows(IOException.class,
+ () -> PtauImporterBLS381.importPtau(new ByteArrayInputStream(infG1), 7));
+ assertTrue(exInf1.getMessage().contains("infinity"), exInf1.getMessage());
+
+ // Infinity in tauG2[1]
+ byte[] infG2 = valid.clone();
+ Arrays.fill(infG2, sec3PayloadOff + 192, sec3PayloadOff + 384, (byte) 0);
+ IOException exInf2 = assertThrows(IOException.class,
+ () -> PtauImporterBLS381.importPtau(new ByteArrayInputStream(infG2), 7));
+ assertTrue(exInf2.getMessage().contains("infinity"), exInf2.getMessage());
+
+ // Off-curve G1 in tauG1[1]
+ byte[] offCurve = valid.clone();
+ System.arraycopy(g1Lem(OFF_CURVE_G1), 0, offCurve, sec2PayloadOff + 96, 96);
+ IOException exOff = assertThrows(IOException.class,
+ () -> PtauImporterBLS381.importPtau(new ByteArrayInputStream(offCurve), 7));
+ assertTrue(exOff.getMessage().contains("not on curve"), exOff.getMessage());
+
+ // Small-subgroup G1 in tauG1[1]
+ byte[] smallSub = valid.clone();
+ System.arraycopy(g1Lem(SMALL_SUBGROUP_G1), 0, smallSub, sec2PayloadOff + 96, 96);
+ IOException exSub = assertThrows(IOException.class,
+ () -> PtauImporterBLS381.importPtau(new ByteArrayInputStream(smallSub), 7));
+ assertTrue(exSub.getMessage().contains("not in subgroup"), exSub.getMessage());
+
+ // Non-canonical (>= p) coordinate in tauG1[1]
+ byte[] nonCanon = valid.clone();
+ System.arraycopy(unsignedLE(FP, 48), 0, nonCanon, sec2PayloadOff + 96, 48);
+ IOException exCanon = assertThrows(IOException.class,
+ () -> PtauImporterBLS381.importPtau(new ByteArrayInputStream(nonCanon), 7));
+ assertTrue(exCanon.getMessage().contains("not canonical"), exCanon.getMessage());
+
+ // Pairing-inconsistent SRS power (replace tauG1[2] with G1)
+ byte[] inconsistent = valid.clone();
+ System.arraycopy(g1Lem(G1), 0, inconsistent, sec2PayloadOff + 2 * 96, 96);
+ IOException exPair = assertThrows(IOException.class,
+ () -> PtauImporterBLS381.importPtau(new ByteArrayInputStream(inconsistent), 7));
+ assertTrue(exPair.getMessage().contains("inconsistent"), exPair.getMessage());
+
+ // Trailing bytes rejected
+ byte[] trailing = Arrays.copyOf(valid, valid.length + 1);
+ IOException exTrail = assertThrows(IOException.class,
+ () -> PtauImporterBLS381.importPtau(new ByteArrayInputStream(trailing), 7));
+ assertTrue(exTrail.getMessage().contains("Trailing"), exTrail.getMessage());
+ }
+
+ // ---- Helpers ----
+
+ private static byte[] buildValidSection1(int power, int ceremonyPower) throws IOException {
+ ByteArrayOutputStream sec1 = new ByteArrayOutputStream();
+ sec1.write(leInt(48));
+ sec1.write(unsignedLE(FP, 48));
+ sec1.write(leInt(power));
+ sec1.write(leInt(ceremonyPower));
+ return sec1.toByteArray();
+ }
+
+ private static byte[] buildSyntheticPtau(int power, BigInteger tau) throws IOException {
+ return buildSyntheticPtauSections1To3(power, tau, 3);
+ }
+
+ private static byte[] buildSyntheticPtauSections1To3(int power, BigInteger tau, int declaredSections)
+ throws IOException {
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ out.write(new byte[]{'p', 't', 'a', 'u'});
+ out.write(leInt(1));
+ out.write(leInt(declaredSections));
+
+ // Section 1: 60 bytes (n8, prime, power, ceremonyPower)
+ ByteArrayOutputStream sec1 = new ByteArrayOutputStream();
+ sec1.write(leInt(48));
+ sec1.write(unsignedLE(FP, 48));
+ sec1.write(leInt(power));
+ sec1.write(leInt(power));
+ writeSection(out, 1, sec1.toByteArray());
+
+ // Section 2: 2^(power+1) - 1 G1 powers
+ int nG1 = (1 << (power + 1)) - 1;
+ ByteArrayOutputStream sec2 = new ByteArrayOutputStream();
+ BigInteger cur = BigInteger.ONE;
+ BigInteger r = MontFr381.modulus();
+ for (int i = 0; i < nG1; i++) {
+ sec2.write(g1Lem(JacobianG1BLS381.GENERATOR.scalarMul(cur).toAffine()));
+ cur = cur.multiply(tau).mod(r);
+ }
+ writeSection(out, 2, sec2.toByteArray());
+
+ // Section 3: 2^power G2 powers
+ int nG2 = 1 << power;
+ ByteArrayOutputStream sec3 = new ByteArrayOutputStream();
+ cur = BigInteger.ONE;
+ for (int i = 0; i < nG2; i++) {
+ sec3.write(g2Lem(JacobianG2BLS381.GENERATOR.scalarMul(cur).toAffine()));
+ cur = cur.multiply(tau).mod(r);
+ }
+ writeSection(out, 3, sec3.toByteArray());
+
+ return out.toByteArray();
+ }
+
+ private static final class LargeZeroSectionStream extends InputStream {
+ private final byte[] p1;
+ private final byte[] p2;
+ private int pos1 = 0;
+ private int pos2 = 0;
+ private long zerosRemaining;
+
+ LargeZeroSectionStream(byte[] p1, byte[] p2, long zerosRemaining) {
+ this.p1 = p1;
+ this.p2 = p2;
+ this.zerosRemaining = zerosRemaining;
+ }
+
+ @Override
+ public int read() {
+ byte[] one = new byte[1];
+ int n = read(one, 0, 1);
+ return n < 0 ? -1 : (one[0] & 0xFF);
+ }
+
+ @Override
+ public int read(byte[] b, int off, int len) {
+ if (pos1 < p1.length) {
+ int n = Math.min(len, p1.length - pos1);
+ System.arraycopy(p1, pos1, b, off, n);
+ pos1 += n;
+ return n;
+ }
+ if (pos2 < p2.length) {
+ int n = Math.min(len, p2.length - pos2);
+ System.arraycopy(p2, pos2, b, off, n);
+ pos2 += n;
+ return n;
+ }
+ if (zerosRemaining > 0) {
+ int n = (int) Math.min(len, zerosRemaining);
+ Arrays.fill(b, off, off + n, (byte) 0);
+ zerosRemaining -= n;
+ return n;
+ }
+ return -1;
+ }
+ }
+
+ 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 res.binary();
+ }
+
+ private static String run(Path dir, String... cmd) throws IOException, InterruptedException {
+ Process p = new ProcessBuilder(cmd).directory(dir.toFile()).redirectErrorStream(true).start();
+ String out = new String(p.getInputStream().readAllBytes());
+ assertTrue(p.waitFor(180, TimeUnit.SECONDS), "snarkjs timed out: " + String.join(" ", cmd));
+ assertEquals(0, p.exitValue(), "snarkjs failed: " + String.join(" ", cmd) + "\n" + out);
+ return out;
+ }
+
+ 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 byte[] unsignedLE(BigInteger v, int len) {
+ byte[] out = new byte[len];
+ byte[] be = v.toByteArray();
+ int start = Math.max(0, be.length - len);
+ int count = be.length - start;
+ for (int i = 0; i < count; i++) {
+ out[i] = be[be.length - 1 - i];
+ }
+ return out;
+ }
+
private static void writeSection(ByteArrayOutputStream out, int sectionType, byte[] data) throws IOException {
out.write(leInt(sectionType));
out.write(leLong(data.length));