Skip to content

Harden crypto, symbolic DSL, on-chain/JMT, CI, notices, and docs (ADR-0069) - #126

Merged
satran004 merged 4 commits into
mainfrom
fix/p3-hardening-cleanup-and-docs
Nov 21, 2026
Merged

satran004 merged 4 commits into
mainfrom
fix/p3-hardening-cleanup-and-docs

Conversation

@satran004

Copy link
Copy Markdown
Member

Summary

Comprehensive cryptographic hardening, symbolic DSL / annotation processor fixes, on-chain/JMT validation improvements, CI/NOTICE hygiene, documentation reconciliation, and a proposed PlonK v2 Cardano ADR (ADR-0069).

Key Changes

  • Proposed ADR-0069 (docs/adr/0069-plonk-v2-cardano-transcript-and-verifier.md): Documents the planned PlonK v2 Cardano profile (fully chained, domain-separated Fiat-Shamir transcript including u, single decompression per point, parameter cleanup, and preserving the xi = omega exclusion check while keeping legacy snarkjs compatibility).
  • BLS12-381 & Native Acceleration (zeroj-bls12381, zeroj-blst):
    • JacobianArith381.fromAffine and addAffine: check (0, 0) affine infinity sentinel before setting Z = 1, restoring byte-for-byte parity with JacobianG1BLS381.
    • G1Point.fromProjective: reduce pz mod Fp.P before infinity/unit checks.
    • Bls12381Codecs.scalarToLittleEndian32: delegate to scalarToBigEndian32 so intermediate buffers are wiped and BigInteger subclasses are safely copied.
    • BlstG1Msm / BlstG2Msm: zeroize le, sbuf, native sc, scal, and Pippenger scratch buffers in finally blocks inside the Arena try-with-resources scope.
  • Groth16 & PlonK Setup / Prover / Verifier Hardening (zeroj-crypto, zeroj-verifier-plonk, zeroj-codec):
    • PowersOfTauBLS381 capped at power <= 28; SetupCacheIO.validateBls12381Srs validates power bounds and minimum G1 length; SetupCacheIO.readScalar enforces minimal canonical two's-complement encoding.
    • Groth16SetupBLS381 & Groth16Pipeline: constraint count overflow guards, non-zero / non-root-of-unity scalar validation, and TrustedSetupPolicy check before Files.createDirectories.
    • Groth16ProverBLS381: shared witness[0] == 1 and proving-key point validity checks across all prove entry points (preserving the ADR-0046 public API surface).
    • Groth16SetupCache & Groth16PkStore.load: reject infinity IC entries (with ADR-0045 note); SrsCache.loadBls12381Srs enforces TrustedSetupPolicy when tau is stored and checks tau·G1 == tauG1[1].
    • SparsePointFile.Index: validates segment size, stride (96/192), 0 <= nnz <= count <= Integer.MAX_VALUE, and exact file length; Groth16PkMmap.shouldEngage widens length sum to long; FlatScalars.wrap validates backing length.
    • PlonkBLS12381Verifier: checks nPublic <= (1 << power) and zh == 0 before inverting; PlonKSetupBLS381: enforces sigma bijection across all 3 * numGates positions; KZGCommitmentBLS381.syntheticDivision: verifies zero remainder; PlonKProverBLS381: resamples/fails closed on zero denominators or infinity commitments.
    • FiatShamirTranscript.squeezeNonZeroChallenge: fails closed if squeezed value is zero; GnarkFiatShamirTranscript: explicit StandardCharsets.UTF_8; Halo2Codec.detectCurve: fails closed when curve is missing or unsupported.
  • Symbolic DSL, Annotation Processor & Gadgets (zeroj-circuit-dsl, zeroj-circuit-annotation-*, zeroj-circuit-lib):
    • @CircuitParam @Target restricted to ElementType.PARAMETER; CircuitAnnotationProcessor rejects abstract @ZKCircuit classes, @Prove with throws, static input fields, and unannotated @Prove params; removes dead @CircuitParam branch in proveCall; uses uniqueLocalName in circuitParamSuffix, single-pass template substitution in circuitName, qualified source class names, boxed Integer null guards before <= 0, parameterized-only overlap checks, and public/secret signal-list verification in validateCircuit.
    • Signal.hasSameBuilder; ZkBytes, ZkBits, and ZkArray verify single-builder ownership and reject null elements; ZkBytes.assertEqual and ZkBits.assertEqual use element-wise linear equality; added ZkContext.constantBool and ZkContext.constantUInt.
    • InCircuitPedersen, InCircuitPedersenVector, and ZkPedersen reject value and blinding sharing the same wire ID; Merkle/SignalMerkle validate array lengths and non-null arrays; CircuitAPIImpl.hintN validates args/shape; Gate.HintKind.MUL_MOD_REDUCE Javadoc corrected to 4 params; PlonKConstraintSystem.extendWitness rejects missing/out-of-range wires; added per-circuit Fe25519.HintConfig (configureHints).
  • BBS, On-Chain JuLC & Poseidon JMT (zeroj-bbs, zeroj-onchain-julc, zeroj-jmt-poseidon, zeroj-tools):
    • BbsZkVerifier: explicit accepted-ciphersuite policy (never silently downgrading a caller-configured BbsService provider) and rejects non-empty envelope.publicInputs().
    • BbsCodec.copyMessages: rejects null message entries; BbsService.verifyPresentation: checks null args, ciphersuite match, and proof framing.
    • Explicit non-value-bearing / no-ScriptContext security warnings in Javadoc on standalone Groth16BLS12381Verifier, Groth16BLS12381TxOutRefBindingVerifier, and PlonkBLS12381*Verifier.
    • Groth16AuthenticatedStateTransitionValidator: requires continuing output referenceScript to be empty; Groth16AuthenticatedStateTransitionScriptFactory: drops unbacked DELETE from TWO_ROOT_OPERATIONS.
    • Groth16VerificationKeyCodec.decode: validates compressed G1/G2 non-infinity prime-order subgroup points; ProverToCardano.writeFp: validates [0, p).
    • PoseidonJmtTree.verifyProofWire: independently verified via PoseidonJmtReference.verifyWire (rejecting compressed/skipped levels on wire).
    • CeremonyCli: closes URLClassLoader via try-with-resources.
  • CI, Notices, Build & Docs:
    • .github/workflows/heavy.yml: added hash/** and it/sha2/** PR path filters.
    • NOTICE & zeroj-tools/build.gradle: added BouncyCastle, picocli, and rfc9380 test-vector notices; bundled LICENSE and NOTICE in nativeDistZip.
    • Removed commented-out bundleJulcSources block in zeroj-onchain-julc/build.gradle.
    • Reconciled README.md, www/src/content/docs/start/status.md, docs/adr/0031-groth16-mpc-trusted-setup-ceremony.md, and SealedBidPureJavaE2ETest Javadoc.

Verification

All targeted new unit/negative tests and full module suites pass:

  • ./gradlew verifyDefaultModuleSurface verifyNoBuiltinProfileDefine :zeroj-bls12381:test :zeroj-blst:test :zeroj-bbs:test :zeroj-codec:test :zeroj-circuit-dsl:test :zeroj-circuit-annotation-api:test :zeroj-circuit-annotation-processor:test :zeroj-circuit-lib:test :zeroj-jmt-poseidon:test :zeroj-crypto:test :zeroj-verifier-plonk:test :zeroj-verifier-groth16:test :zeroj-onchain-julc:test :zeroj-tools:test :zeroj-integration-tests:compileTestJava

@satran004
satran004 requested a review from a team as a code owner November 21, 2026 01:12

Copy link
Copy Markdown

Initial automated review · Aster

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

Reviewed commit: b591fc81072d0e42e16771f2f9c646c039bcabdb

Issues found:

  • zeroj-crypto/src/main/java/org/zeroj/crypto/setup/SetupCacheIO.java:323 — The new minimum rejects valid shortened SRS caches, such as 16 G1 powers with ceremony power 4 that still support domain-8 PlonK setup. Could we preserve prefix caching or normalize the capacity metadata consistently?

Not tested: Code and tests were read only; I did not run the build, cache round trips, or proof tests.

@satran004

Copy link
Copy Markdown
Member Author

[reviewer1] Changes requested on b591fc81072d0e42e16771f2f9c646c039bcabdb.

  1. Bound the JMT proof parser before decoding. PoseidonJmtReference.verifyWire (lines 133–147) decodes a general recursive CBOR tree before checking the top-level count or node types. The one-MiB limit bounds wire bytes only. Parse the v1 schema with bounded depth, at most 65 node byte strings and lengths checked against remaining input before allocation. Apply equivalent structural limits to embedded nodes before calling the CCL decoder. Cover out-of-schema nesting and counts alongside genuine inclusion and non-inclusion proofs. RFC 8949 security considerations
  2. Validate Groth16 VK points on the script-construction path. Groth16VerificationKeyCodec.decode now checks each point, but encode checks only lengths. The state-transition factory accepts a public VkCompressed, calls encode, hashes it, and applies its bytes directly to the script. A matching manifest digest establishes identity and cannot establish point validity. Apply the same canonical, subgroup and non-infinity checks to the factory's snapshot before building the script. Exercise the public factory with a matching manifest, an invalid IC and a valid-key control.
  3. Enforce subgroup membership on stored Groth16 auxiliary points. At Groth16PkStore.java:299–310, the new G1/G2 helpers check the curve equation and infinity only. ADR-0045 explicitly treats the stored bundle as untrusted and requires prime-order subgroup membership for VK points. Reuse the checks already implemented by SetupCacheIO.validateG1/validateG2 and cover the public store loader with subgroup-rejection tests for both groups and a valid round trip.
  4. Preserve partial SRS cache compatibility. SetupCacheIO.java:323 derives a minimum G1 count from the ceremony power. The importer deliberately supports a smaller independently validated prefix and retains the original ceremony power. I generated a power-4 BLS12-381 snarkjs file, imported and cached 14 points with ADR-0068: DSL soundness, PlonK scaling, MPF canonicality & gadget hardening #125, and confirmed that this head rejected that cache with a required minimum of 17. Validate the retained count against the source format and enforce the consumer's required prefix at setup. Add a partial-import save/load/setup regression.
  5. Validate the sparse-point index at load. SparsePointFile.Index checks the file length, but rank() later trusts block offsets from the file. Before publishing the reader, check each stored rank against the bitmap's cumulative population count, require the final count to equal nnz, and reject bits beyond the logical count. A same-length inconsistent index should fail during load. Cover an honest multi-block index as a positive control.
  6. Correct the v2 transcript ADR before implementation. I1's VK digest omits the G2 opening key X2 consumed by the pairing equation. Bind its canonical encoding or specify an independently pinned, profile-wide setup identity that fixes it. I3 also suggests comparing zeta with zeta * omega as an alternative to checking zeta != omega. The existing inverse check uses zeta - omega. State the predicate directly, document its relationship to the domain exclusion and include independent VK-binding and challenge-boundary vectors in M1.

Across two isolated Gradle runs, 132 selected tests passed with zero skips on this head. They covered BLS arithmetic, codecs, setup, BBS, circuit generation, PlonK verification, JMT and the on-chain Groth16 changes. The cache compatibility check above was separate.

@satran004

Copy link
Copy Markdown
Member Author

[reviewer3] Review of head b591fc81: CHANGES REQUESTED (one regression, small fix)

Scope: engineering, cross-backend consistency, compatibility, CI/build, NOTICE and docs.

What I verified

  • Tests. I ran the following in a clean worktree at b591fc81, with snarkjs 0.7.6 on PATH:

    ./gradlew -PrequireSnarkjs verifyDefaultModuleSurface verifyNoBuiltinProfileDefine \
      :zeroj-{bls12381,blst,bbs,codec,circuit-dsl,circuit-annotation-api,circuit-annotation-processor,circuit-lib,jmt-poseidon,mpf-poseidon,crypto,verifier-plonk,verifier-groth16,onchain-julc,tools,integration-tests}:test
    

    BUILD SUCCESSFUL, with 0 failures in every module:

    Module Tests Skipped
    zeroj-bls12381 2139 0
    zeroj-blst 40 0
    zeroj-bbs 94 0
    zeroj-codec 54 0
    zeroj-circuit-dsl 135 1
    zeroj-circuit-annotation-api 23 0
    zeroj-circuit-annotation-processor 32 0
    zeroj-circuit-lib 1314 23
    zeroj-jmt-poseidon 15 0
    zeroj-mpf-poseidon 48 0
    zeroj-crypto 1136 2
    zeroj-verifier-plonk 38 0
    zeroj-verifier-groth16 29 0
    zeroj-onchain-julc 132 2
    zeroj-tools 6 0
    zeroj-integration-tests 127 0

    The integration run includes live snarkjs interop and all the *Annotated* examples, so the processor's generated code compiles and runs for every @ZKCircuit in the repo.

  • Differential and probe checks

    • JMT wire verifier vs. the CCL delegate. 1,600 honest inclusion and non-inclusion proofs, over trees of 1 to about 400 keys, are accepted by both. Wrong-statement variants are rejected by both. Of 48,000 single-bit mutations, CCL alone accepted 3,244 and the new verifyWire accepted none. So the combined AND check removes some malleability in CCL's wire format and rejects no honest proof.
    • Nested-CBOR probe. Results are under item 1.
  • Groth16 / blst / setup

    • BlstG1Msm and BlstG2Msm wipe the scalar buffers and native scratch inside the Arena scope on both the success and exception paths. sbuf and le are wiped in finally.
    • The shared witness[0] == 1 check and the PK point checks are reached on every proveBlinded path, and the ADR-0046 public surface is unchanged.
    • The new tau^(2N) == 1 check covers both domain and coset roots.
    • readScalar's minimal-encoding check matches what writeScalar writes, so existing caches still load.
    • SparsePointFile.Index exact-size and stride checks match the writers.
  • PlonK

    • Resampling is bounded at 8 attempts and only rejects events of probability about n/r. Invalid witnesses still throw and are not retried.
    • The sigma bijection check (range check plus duplicate check over 3n) is sufficient.
    • The KZG remainder check is f0 + z·q0, which is correct.
    • Off-chain nPublic <= 2^power checks power before the shift.
  • Curve arithmetic. The JacobianArith381 (0,0) reordering also fixes inf + (0,0), which used to produce a garbage point. G1Point.fromProjective now reduces pz the same way G2Point does.

  • DSL / annotations

    • The ZkBits/ZkBytes/ZkArray single-builder checks are complete for the constructors and the combining operations.
    • ZkContext.constantUInt range-checks its value.
    • uniqueLocalName is deterministic, and the single-pass template parser matches validateNameTemplate.
    • CeremonyCli uses all classes loaded by the URLClassLoader inside the try-with-resources block, so nothing is used after the loader closes.
  • BBS / codecs

    • A service-pinned BbsZkVerifier cannot switch to another suite or provider; it returns UNSUPPORTED_PROOF_SYSTEM.
    • Halo2Codec.detectCurve fails closed, and nothing outside the tests relied on the old Pallas default.
    • GnarkFiatShamirTranscript now uses UTF-8 explicitly. The labels are ASCII, so the bytes do not change.
  • CI, NOTICE and links

    • The new heavy.yml path filters (it/sha2/**, circuit/lib/hash/**) point at existing directories.
    • zeroj-bls12381/src/test/resources/rfc9380/ has its own NOTICE.
    • The README link targets exist, including the #gadget-status anchor and the new module rows.
    • 0.1.0-pre13 matches the latest tag.
    • ADR-0069's snarkjs claim about u is accurate: plonk_verify.js:267-270 resets the transcript and hashes only Wxi and Wxiw.

Blocking

  1. PoseidonJmtTree.verifyProofWire now throws StackOverflowError on a small hostile wire proof. Before this PR it returned false.
    • Where: PoseidonJmtReference.verifyWire decodes the untrusted wire with plain cbor-java at PoseidonJmtReference.java:133, with no limit on nesting depth.

    • Why it escapes: the only guard is MAX_WIRE_BYTES (1 MiB). catch (Exception) at :228 does not catch Error. PoseidonJmtTree.verifyProofWire now calls verifyWire before the CCL delegate (PoseidonJmtTree.java:113-117) and catches only RuntimeException.

    • Probe (CBOR 0x81 repeated d times, then 0x40):

      Depth verifyWire PoseidonJmtTree.verifyProofWire
      d = 300,000 (300 KB, under the cap) java.lang.StackOverflowError java.lang.StackOverflowError
      d = 1,000 false false
    • Pre-PR behaviour: the CCL delegate alone returns false for the same input. ClassicJmtProofCodec checks the input with BoundedCbor.validateSingleItem(…, 1 MiB) before decoding.

    • Impact: a StackOverflowError from a boolean verifier on untrusted bytes is a denial-of-service regression for any service that checks client-supplied proofs.

    • Fix: apply CCL's BoundedCbor.validateSingleItem (or a depth and item-count bound of your own) before the cbor-java decode, or run the delegate first. Add a regression test with deep nesting.

Non-blocking (P2/P3)

  1. On-chain validator logic changed, and nothing calls it out.
    • Groth16AuthenticatedStateTransitionValidator.java:90 adds || !continuingOutput.referenceScript().isEmpty(). That changes the compiled UPLC, so the unapplied-template SHA-256, the applied script hash, the size and the execution budget all change.
    • The factory fails closed on a stale expectedUnappliedValidatorSha256, which is good. Even so, please mention the change in the PR description and in an ADR compatibility note.
    • docs/adr/0050-…md:361 still lists 46c77c44… for this validator, and zeroj-onchain-julc/README.md does not mention the new rule.
    • All the other on-chain validator diffs are Javadoc-only.
  2. The ZkBytes/ZkBits.assertEqual R1CS shape change also needs a compatibility note.
    • ZkBytes.java:80-85 and ZkBits.java:77-82 now emit one equality per element instead of an isEqual-AND-assertTrue chain.
    • Soundness is the same: both forms compare field elements one by one, over range-bound values. There are far fewer constraints, though, so the R1CS digest, VK and fingerprint change for any circuit that calls these methods. Downstream examples are ZkCip1852.leafKeyHash(...).assertEqual(pkh) and the SHA adapters. Those circuits need new keys.
  3. Off-chain and on-chain PlonK now differ on Z_H(ζ) == 0.
    • The off-chain verifier (zeroj-verifier-plonk/.../PlonkBLS12381Verifier.java:198) now rejects it.
    • PlonkBLS12381Lib.java:76-77 (single-input) and :184 (multi-input) do not. They reject only ζ ∈ {1, ω} and ζ = ω^i at public-input positions, through the supplied inverses.
    • The probability is negligible, but it is a silent difference between verifiers. Either add the check on-chain, which needs a script-hash bump best batched with the v2 profile, or document the difference in ADR-0069 I3.
  4. Bundled-licence text in the native distribution.
    • nativeDistZip now ships the root LICENSE (MIT, ZeroJ) and NOTICE. The native binary also embeds picocli (Apache-2.0) and Bouncy Castle (MIT-style). Apache-2.0 §4(a) requires a copy of the licence, and the BC licence requires its copyright and permission notice to go with copies.
    • The new NOTICE entries only link to them. Per the repo's attribution rule, include licenses/Apache-2.0.txt and the BC licence text in the zip (and in the fat jar if it doesn't already carry them).
  5. The SRS cache now rejects SRS objects the importer produces.
    • SetupCacheIO.java:320-326 requires power <= 28 and tauG1.length >= 2^power + 1.
    • PtauImporterBLS381.importPtau(in, maxPoints) keeps the header power (up to MAX_POWER = 32) while truncating G1 to maxPoints. So saveBls12381Srs of a power-12 .ptau imported with maxPoints = 1025 used to succeed and now throws.
    • No main-code caller does this, but it is public API. Either derive the minimum from the points actually loaded, or document the restriction.
  6. "Fail before mkdir" holds only for the policy check.
    • Groth16Pipeline caps at 2^30 (:69, :149), but Groth16SetupBLS381.MAX_CONSTRAINTS is 2^29 (:91).
    • For numConstraints in (2^29, 2^30], and for the new tau zero / root-of-unity checks, Groth16Pipeline.setup creates the directory and writes r1cs.bin (:200) before setupToStore rejects the input.
    • Fix: align the caps, or clean up on failure.
  7. Test gaps
    • Pedersen: the pedersen-shared-decomp and pedersen-shared-zk cases in PedersenTest.java:275-298 use 250-bit blindings. validateBlindingWidth requires exactly BLINDING_BITS = 252 and rejects them before the new same-wire check runs, so only the first case tests the new code. Use 252-bit decompositions and check the message. InCircuitPedersenVector has no test.
    • No direct tests for:
      • the SrsCache tau-mismatch and power-28 rejection
      • readScalar minimal-encoding rejection
      • Groth16PkStore.load infinity, off-curve and non-canonical rejection
      • the SparsePointFile.Index checks
      • FlatScalars.wrap bounds
      • the Groth16 zero and root-of-unity tau checks
      • the PlonK fail-closed and resampling paths
      • Fe25519.configureHints
  8. Smaller items
    • ADR-0031 table. The prose is fixed, but the table at lines 66-70 still shows contribute in.zkey out.zkey (positional; the CLI takes --in/--out). It also still has a beacon … row marked M5, which this PR now says stays in snarkjs zkey beacon.
    • Misplaced Javadoc. In Groth16SetupBLS381.java (~305-310), requireValidSetupScalar was inserted between zeroPublicQuery and its Javadoc.
    • ADR-0069 wording.
      • "unchained per-round Fiat-Shamir" overstates it. snarkjs 0.7.6 binds VK commitments and public inputs into β (plonk_prove.js:319-340) and chains γ, α, ξ and v through the previous challenge. Only u is unchained.
      • "18 redundant decodes" should cite how it was counted.
    • PlonKProverBLS381.proveUnblinded. On small circuits it can now throw, because all-zero blinders can make t3 zero, so commitT3 is infinity. There are no callers today.
    • Exceptions. CircuitAPIImpl.hintN throws ArithmeticException (from intValueExact) rather than IllegalArgumentException for huge params, and radixBits has no upper bound. Groth16ProverBLS381.computeProofPoints dereferences readers before the null check.
    • Java style. New test code uses inline fully qualified names: org.junit.jupiter.api.Assertions.assertTrue/assertFalse (ZkSymbolicTypesTest.java:547,553, SetupCacheTest.java:119) and java.lang.reflect.InvocationTargetException (CircuitAnnotationProcessorTest.java:1412,1427). Please use imports.

Item 1 is the only thing blocking approval.

@satran004

Copy link
Copy Markdown
Member Author

Addressed all review feedback in commit a62a18d4:

Security & Correctness Fixes

  1. Iterative, bounded JMT wire CBOR decoding (PoseidonJmtReference.verifyWire): Replaced recursive CborDecoder parsing of untrusted proofWire bytes with an iterative, zero-recursion, definite-length v1 CBOR validator (decodeBoundedWireNodes + isValidFlatV1NodeCbor) that enforces the 1 MiB wire bound, <= 65 top-level byte strings, declared length <= remaining before allocation, zero trailing bytes, and flat v1 internal/leaf node layout before delegating to JmtEncoding.decode. Eliminates StackOverflowError on deeply nested CBOR inputs (e.g., 300 KB of 0x81).
  2. VK encoding & script-factory ingress validation (Groth16VerificationKeyCodec, Groth16AuthenticatedStateTransitionScriptFactory): Added Groth16VerificationKeyCodec.validate(VkCompressed) (canonical length, curve membership, prime-order subgroup membership, and non-infinity for alpha, beta, gamma, delta, and all ic[i]), invoked in encode(...) and immediately after snapshot(verificationKey) in Groth16AuthenticatedStateTransitionScriptFactory.apply(...).
  3. Subgroup checks on proving-key store aux.bin (Groth16PkStore): Added prime-order subgroup validation (scalarMul(G1Point.R).isInfinity()) to requireNonInfinityG1 and requireNonInfinityG2.
  4. Partial-prefix SRS cache compatibility (SetupCacheIO): Restored power in [1, 32] and relaxed the minimum G1 count back to >= 2 (with upper bound <= (2L << power) + 1L for power <= 29), preserving partial-prefix SRS caches (e.g., 14-point or 16-point power-4 imports) while still enforcing per-point subgroup and pairing-chain consistency.
  5. Sparse point-file bitmap & rank validation (SparsePointFile.Index): Added validateBitmapAndRanks(words) at load time to verify every 32-bit block rank matches cumulative bitmap popcount, trailing bitmap bits beyond count are zero, and total popcount equals header nnz.
  6. Setup/prover/DSL parameter guards (Groth16SetupBLS381, Groth16Pipeline, Groth16ProverBLS381, CircuitAPIImpl):
    • Fixed misplaced Javadoc on Groth16SetupBLS381.zeroPublicQuery and added Groth16SetupBLS381.validateSetupParameters(int, BigInteger).
    • Aligned Groth16Pipeline.Compiled and Dims.domain() cap to Groth16SetupBLS381.MAX_CONSTRAINTS (1 << 29) and validated nConstraints + tau before Files.createDirectories(dir).
    • Added explicit readers == null check in Groth16ProverBLS381.computeProofPoints before dereferencing readers.b2().
    • Caught ArithmeticException from intValueExact() in CircuitAPIImpl.hintN (throwing IllegalArgumentException) and bounded radixBits <= MAX_SAFE_BITS.

ADRs, Licence Notices, & Compatibility Notes

  • ADR-0069 (docs/adr/0069-plonk-v2-cardano-transcript-and-verifier.md): Bound compressed G2 X2 (tau * G2, 96 B) into the v2 VK commitment digest (I1), clarified snarkjs 0.7.6's transcript chaining (only u is unchained; plonk_verify.js:267-270), cited the 19 bls12_381_G1_uncompress call sites in PlonkBLS12381Lib, stated the exact zeta != omega (zeta - omega != 0) predicate and v1 off-chain vs. on-chain Z_H(zeta) != 0 difference (I3), and added VK/X2 + degenerate-challenge vectors to M1.
  • ADR-0050 & zeroj-onchain-julc/README.md: Documented the continuingOutput.referenceScript().isEmpty() guard on Groth16AuthenticatedStateTransitionValidator and updated the compiled UPLC size (2,845 bytes) and unapplied Plutus V3 script hash (5192732cf2c70ce2f03859f1e9f728d986f6a0e1c18e1a1ab86f8eb2).
  • ADR-0031 (docs/adr/0031-groth16-mpc-trusted-setup-ceremony.md): Updated the CLI table for contribute --in ... --out ... and clarified that beacon remains in snarkjs zkey beacon.
  • Distribution licence notices (NOTICE, zeroj-tools/build.gradle): Added the verbatim Bouncy Castle MIT-style licence text to NOTICE and bundled licenses/Apache-2.0.txt into both nativeDistZip (licenses/) and fatJar (META-INF/LICENSE, META-INF/NOTICE, META-INF/licenses/Apache-2.0.txt).
  • Compatibility notes:
    • Groth16AuthenticatedStateTransitionValidator: Adding continuingOutput.referenceScript().isEmpty() changes the compiled UPLC bytes (2,817 -> 2,845) and unapplied Plutus V3 script hash; release manifests must pin the new template digest.
    • ZkBytes.assertEqual / ZkBits.assertEqual: Switching from isEqual(...).assertTrue() to direct linear equality (assertEqual) removes auxiliary IsZero constraints and changes the R1CS constraint layout; existing circuits using those helpers require re-keying on upgrade.

Regression Tests & Style Cleanup

  • PoseidonJmtSecurityRegressionTest: Added 300 KB 0x81 deep-nesting probe, > 65 node array count, nested CBOR inside node byte string, trailing bytes, plus honest inclusion/non-inclusion wire proof controls.
  • Groth16VerificationKeyCodecTest: Tested both encode and raw-buffer decode rejecting infinity, garbage, and G1/G2 off-subgroup points.
  • Groth16AuthenticatedStateTransitionValidatorTest: Added ScriptFactory.apply test rejecting an infinity IC point even when the manifest VK SHA-256 matches the raw bytes, alongside a valid control.
  • PedersenTest: Fixed blinding widths to InCircuitPedersen.BLINDING_BITS (252), asserted the same-wire exception message, and added an InCircuitPedersenVector same-wire rejection test.
  • Fe25519HintTest: Added unit test verifying per-circuit Fe25519.configureHints routes mul() through mulHint() without mutating the global default.
  • SetupCacheTest: Added partial-prefix SRS round-trip (14-point and 16-point power-4) + PlonKSetupBLS381.setup, SrsCache tau-mismatch rejection (save & load), SetupCacheIO.readScalar non-minimal encoding rejection, Groth16SetupBLS381/Groth16Pipeline degenerate tau (0, 1) pre-mkdir rejection, and FlatScalars.wrap bounds tests.
  • Groth16PkStoreTest: Added aux.bin G1/G2 off-subgroup, infinity IC, off-curve, and non-canonical Fp rejection tests, plus multi-block (1,200 points / 3 blocks) SparsePointFile.Index positive control and tampered rank / popcount / trailing-bit rejection tests.
  • Replaced inline FQNs with explicit imports in ZkSymbolicTypesTest, SetupCacheTest, and CircuitAnnotationProcessorTest.

Verification

  • Passed ./gradlew :zeroj-jmt-poseidon:test :zeroj-onchain-julc:test :zeroj-crypto:test :zeroj-circuit-dsl:test :zeroj-circuit-lib:test :zeroj-circuit-annotation-api:test :zeroj-circuit-annotation-processor:test :zeroj-tools:test :zeroj-tools:fatJar (all tests green; verified META-INF/LICENSE, META-INF/NOTICE, and META-INF/licenses/Apache-2.0.txt in zeroj-ceremony-*-all.jar).

Ready for final re-review.

@satran004

Copy link
Copy Markdown
Member Author

[reviewer1] Changes requested on a62a18d4bc6cfc18a7fa7863e48afa4d79bbaac2. I verified the stored Groth16 subgroup checks, script-factory validation on a private key snapshot, sparse bitmap/rank consistency, and the corrected v2 transcript requirements for X2 and domain exclusion. The new JMT parser bounds the outer array and each embedded node for a stable input. All 88 selected tests passed with zero skips, including the CCL wire vectors.

  1. Preserve the smallest supported tau-free SRS prefix. I repeated the cross-PR cache check with a power-4 snarkjs file. The 14-point cache now loads. On ADR-0068: DSL soundness, PlonK scaling, MPF canonicality & gadget hardening #125 at 07ab1635, the public importer also accepts maxPoints=1 and saves that generator-only prefix. This head rejects the resulting file at SetupCacheIO.validateBls12381Srs. Preserve the one-point round trip for ordinary tau-free cache files. Keep the two-point requirement where a retained tau must be checked against G1[1], and retain the consumer's separate setup-size checks. Add a save/load regression for that boundary. Cache validation
  2. Use the same proof bytes for both JMT decoders. The reference verifier validates the embedded node on the caller's array and then copies it for CCL. The tree verifier passes that caller-owned array to CCL again after reference verification. A concurrent buffer update can therefore send different bytes to the general decoder after the bounded checks. Check the outer byte limit first, take one private snapshot at the public boundary, and use that snapshot throughout both verification passes. Give the public reference-only entry point the same ownership guarantee. Node decoding · Tree verification
  3. Serialize the exact VK bytes that passed validation. The factory now does this correctly. Direct callers of Groth16VerificationKeyCodec.encode still supply a VkCompressed containing mutable arrays and a caller-owned IC list. The method validates them, reads the list again, and writes the original point arrays. Serialize to a private buffer and validate those bytes before returning, or deep-copy the bounded components once and use that copy for validation and encoding. A successful encode should always yield bytes accepted by the decoder, including when callers reuse their buffers. Encoder

@satran004

Copy link
Copy Markdown
Member Author

[reviewer3] Re-review of head a62a18d4 (round 2, diff from b591fc81): APPROVED. My round-1 blocker is fixed. Below are three non-blocking items, all of which reviewer1 also raised and I confirmed.

Scope: engineering, cross-backend, CI/build wiring, compatibility, Java style and docs.

What I verified

  • Tests. In a clean worktree at a62a18d4, I ran ./gradlew -PrequireSnarkjs over the same 16 modules as in round 1, including zeroj-integration-tests against live snarkjs 0.7.6.
    BUILD SUCCESSFUL, with no failures. Eleven test tasks ran again. The other five (bls12381, blst, bbs, codec, verifier-groth16) were up to date, because nothing they depend on changed since round 1, when they passed:

    Module Tests Skipped
    zeroj-bls12381 2139 0
    zeroj-blst 40 0
    zeroj-bbs 94 0
    zeroj-codec 54 0
    zeroj-circuit-dsl 135 1
    zeroj-circuit-annotation-api 23 0
    zeroj-circuit-annotation-processor 32 0
    zeroj-circuit-lib 1315 26
    zeroj-jmt-poseidon 16 0
    zeroj-mpf-poseidon 48 0
    zeroj-crypto 1141 2
    zeroj-verifier-plonk 38 0
    zeroj-verifier-groth16 29 0
    zeroj-onchain-julc 133 2
    zeroj-tools 6 0
    zeroj-integration-tests 127 0
  • Round-1 blocker (JMT StackOverflowError), fixed. I re-ran my round-1 probe against this head. PoseidonJmtReference.verifyWire and PoseidonJmtTree.verifyProofWire now both return false for 300,000, 1,000 and 64 levels of nested 0x81, where the 300 KB input used to throw StackOverflowError. The new parser has no recursion, rejects indefinite lengths and the reserved additional-info values, bounds every declared length against the bytes remaining, and checks each embedded node's flat v1 layout before CCL decodes it.

  • Behaviour on real proofs (comparison against CCL). On a randomly built tree (4 rounds of up to 200 updates, 400 keys queried after each round), all 1,600 honest inclusion and non-inclusion proofs were accepted by both this verifier and CCL's own verifier. I also applied 48,000 single-bit flips to those proofs:

    • Combined check: no flipped proof was accepted by both verifiers, which is what PoseidonJmtTree requires.
    • This verifier vs CCL: this verifier never accepted a proof that CCL rejected. CCL alone accepted 3,244 of them, all on the non-inclusion path, and the extra check catches those.
  • On-chain script hash. I compiled the validators and computed the Plutus V3 script hash with CCL's PlutusV3Script, wrapping the program in CBOR twice, the same way ADR-0050 measures it. As a check on the method, Groth16BLS12381Verifier gives 1,117 bytes and 59f37dc6…5db6, matching its ADR row. Groth16AuthenticatedStateTransitionValidator gives 2,845 bytes and 5192732cf2c70ce2f03859f1e9f728d986f6a0e1c18e1a1ab86f8eb2, matching the new ADR-0050 row. The compatibility notes in your response comment cover the hash change and the ZkBytes/ZkBits re-key.

  • Licences. I built :zeroj-tools:fatJar and :zeroj-tools:nativeDistZip.

    • fat jar: META-INF/LICENSE is ZeroJ's MIT text. EXCLUDE did not let a dependency's file win, because no dependency jar ships a META-INF/LICENSE. META-INF/NOTICE and META-INF/licenses/Apache-2.0.txt are also present.
    • dist zip: contains LICENSE, NOTICE and licenses/Apache-2.0.txt.
    • Bouncy Castle text: the text added to NOTICE, including the 2000-2023 copyright line, matches org/bouncycastle/LICENSE inside bcprov-jdk18on-1.83.jar.
  • Other round-1 items, fixed.

    • Pipeline cap: now Groth16SetupBLS381.MAX_CONSTRAINTS, and validateSetupParameters runs before createDirectories.
    • zh == 0 mismatch: documented as v1 behaviour, with the fix scheduled for v2 in ADR-0069 I3.
    • ADR-0069 wording: now says only u is unchained.
    • ADR-0031 table: updated.
    • Misplaced Javadoc: now on zeroPublicQuery.
    • hintN: throws IllegalArgumentException and has the MAX_SAFE_BITS bound.
    • Pedersen tests: use BLINDING_BITS and check the same-wire message, so they now reach the new check. There is also a vector case.
    • Inline FQNs: removed. I found none in the new test code either.

Non-blocking (agree with reviewer1)

  1. The SRS cache still rejects a cache file that main accepts (reviewer1 item 1). This is the rest of my round-1 item 6. The 14- and 16-point prefixes now round-trip. However, SetupCacheIO.validateBls12381Srs now rejects tauG1.length < 2, while main rejects only tauG1.length == 0. A generator-only prefix (importer maxPoints = 1) that saves and loads on main therefore fails on this head. I agree with reviewer1's item 1: require two G1 points only when a stored tau has to be checked against G1[1], and add a save/load test at one point. A one-point SRS can't serve any real setup, so I'm keeping this non-blocking, as in round 1.

  2. Use the same proof bytes for both JMT checks (reviewer1 item 2). Confirmed: PoseidonJmtTree.verifyProofWire passes the caller's array to both verifyWire and the CCL decoder. To exploit this, a caller would have to change its own buffer while verification is running, so the risk is low. Still, one private copy taken at the public entry point closes it.

  3. Groth16VerificationKeyCodec.encode should write the exact bytes it validated (reviewer1 item 3). Confirmed: encode reads key.alpha(), key.ic() and so on again after validate. The factory path is already safe because it copies first.

P3

  1. ADR-0050's table sits under "Compiled validators whose script hash changes under 0.1.0-pre22". The state-transition row now holds the post-Harden crypto, symbolic DSL, on-chain/JMT, CI, notices, and docs (ADR-0069) #126 value rather than the pre22 one. Consider a short note under the table saying the row was updated for this change, so the historical pre22 figure isn't lost silently.

reviewer1 still has changes requested on items 1-3. If the next head changes only those, I'll re-check just that diff.

@satran004

Copy link
Copy Markdown
Member Author

Addressed all remaining items in commit 6d8de174:

  1. 1-point tau-free SRS cache compatibility (SetupCacheIO, SetupCacheTest): Lowered the minimum G1 count in SetupCacheIO.validateBls12381Srs to >= 1 so generator-only tau-free prefixes (maxPoints=1) continue to save/load cleanly, while SrsCache.verifyTauMatchesG1 continues to require tauG1.length >= 2 whenever a tau scalar is retained. Added a 1-point save/load regression test (positive tau-free round-trip + negative rejection when tau is retained) in SetupCacheTest.
  2. Single private byte snapshot across JMT wire verification (PoseidonJmtReference, PoseidonJmtTree):
    • PoseidonJmtTree.verifyProofWire now checks the MAX_WIRE_BYTES bound up front, takes one private snapshot of expectedRoot, key, expectedValue, and proofWire, and passes those exact snapshots to both PoseidonJmtReference.verifyWireSnapshot and delegate.verifyProofWire.
    • PoseidonJmtReference.verifyWire applies the same bounded ingress snapshot so direct callers also validate and decode identical private bytes.
  3. Single-snapshot validation + encoding in Groth16VerificationKeyCodec.encode: Replaced separate validate(key) + second read of caller arrays with snapshotAndValidate(key), which deep-copies bounded alpha, beta, gamma, delta, and ic elements once, validates those private copies, and serializes those exact bytes. Also fixed the raw-wire test helper magic in Groth16VerificationKeyCodecTest and Groth16AuthenticatedStateTransitionValidatorTest to "ZJG16VK1" and asserted decode reaches point validation (not magic rejection).
  4. ADR-0050 historical baseline note (docs/adr/0050-julc-pre17-org-julclang-and-typed-bls.md): Added a note below the table preserving the original 0.1.0-pre22 baseline (2,817 bytes / 46c77c445f4d16b156797d05aee6964f9c93d7446dd4f12d26824d4d) alongside the updated 2,845-byte row for the referenceScript().isEmpty() guard.

Verification

  • Passed ./gradlew :zeroj-jmt-poseidon:test :zeroj-onchain-julc:test :zeroj-crypto:test --tests 'org.zeroj.crypto.setup.SetupCacheTest'.

Ready for final approval.

@satran004

Copy link
Copy Markdown
Member Author

[reviewer1] Approved 6d8de174b9f6400e39899f2f9922a20d77f2e310. All three findings from my last review are resolved.

  • I loaded the same one-point and 14-point tau-free SRS caches produced by ADR-0068: DSL soundness, PlonK scaling, MPF canonicality & gadget hardening #125 that I used in the earlier compatibility checks. Both loaded with their original point counts. Retaining a tau still requires a second G1 point to verify it.
  • Both public JMT wire-verification entry points bound the proof length before copying it. The tree verifier passes the same private snapshot through the reference parser and the CCL verifier.
  • The direct Groth16 VK encoder validates private copies of the points and serializes those copies. The malformed-point fixtures now use the correct wire magic so they reach point validation.

All 21 selected setup-cache, JMT wire, Groth16 codec and state-transition tests passed on this head with zero skips.

@satran004

Copy link
Copy Markdown
Member Author

[reviewer3] Re-review of head 6d8de174 (round 3, diff from a62a18d4): APPROVED

What I verified

  • Tests. I ran the same 16-module -PrequireSnarkjs suite in a clean worktree at 6d8de174. BUILD SUCCESSFUL, with no failures.
    • Re-ran (affected by this diff), with skips in brackets: zeroj-jmt-poseidon 16, zeroj-crypto 1141 (2), zeroj-verifier-plonk 38, zeroj-onchain-julc 133 (2), zeroj-tools 6, and zeroj-integration-tests 127 against live snarkjs 0.7.6.
    • Up to date: the other ten modules have unchanged inputs and passed at a62a18d4.
  • Item 1 (one-point SRS), fixed. SetupCacheIO.validateBls12381Srs again accepts a single G1 point, as main does. SrsCache.verifyTauMatchesG1 still requires G1[1] whenever a tau is stored, on both save and load. The new test covers a tau-free one-point save and load, and rejection of a one-point SRS that carries a tau.
  • Item 2 (JMT proof bytes), fixed.
    • PoseidonJmtTree.verifyProofWire checks the wire length first, then copies the root, key, value and wire once. The reference check and CCL's verifyProofWire both use those copies.
    • The public PoseidonJmtReference.verifyWire makes its own copies before calling the package-private verifyWireSnapshot.
    • I re-ran my probes on this head:
      • 300 KB of nested CBOR still returns false;
      • all 1,600 honest proofs are still accepted by both checks;
      • none of the 48,000 bit-flipped proofs is accepted by both.
  • Item 3 (VK encode), fixed. encode and validate now share snapshotAndValidate. It checks lengths, copies each point once, validates the copies, and builds a private VkCompressed that encode then writes. The size of the IC list is also read only once, from a List.copyOf copy.
  • Test helper fix. Good catch on the raw-wire helpers. The old "ZJG1VK01" magic header meant the decode-rejection cases were failing on the magic check, never reaching the point checks. With "ZJG16VK1" and the new assertFalse(message.contains("magic")) check, those tests now exercise point validation.
  • Item 4 (ADR-0050). The note under the table keeps the original pre22 value (2,817 bytes, 46c77c44…) alongside the updated row.

No remaining findings from me.

@satran004

Copy link
Copy Markdown
Member Author

[reviewer1] Approved a5687db2403bd04c3ebe9c87c82f576be5762d99 after re-reviewing the merge with main. I checked all four manual conflict resolutions. BBS verification enforces envelope-to-key binding, empty public inputs and the configured ciphersuite policy together. PlonK setup checks the permutation is a bijection and uses the validated SRS snapshot for commitments and key construction. Both annotation processor regression tests are present in the merged tree.

All 65 selected tests passed on this commit with zero skips, covering BBS, annotation processing, SRS consistency and cache compatibility, and live snarkjs PlonK interoperability. I have no outstanding findings on this head.

@satran004
satran004 merged commit 362744e into main Nov 21, 2026
8 of 9 checks passed
@satran004
satran004 deleted the fix/p3-hardening-cleanup-and-docs branch November 21, 2026 12:09
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants