Skip to content

ADR-0067: enforce verifier/envelope binding, canonical codecs, and legacy BN254 gating - #124

Merged
satran004 merged 2 commits into
mainfrom
fix/adr-0067-verifier-codec-and-bn254-hardening
Nov 21, 2026
Merged

satran004 merged 2 commits into
mainfrom
fix/adr-0067-verifier-codec-and-bn254-hardening

Conversation

@satran004

Copy link
Copy Markdown
Member

Summary

Implements ADR-0067 (docs/adr/0067-offchain-verifier-binding-codecs-and-legacy-bn254-gating.md, Proposed, Risk R2):

  • Uniform envelope/material binding & registry integrity:
    • Added shared EnvelopeBinding helper in zeroj-backend-spi enforcing envelope presence/version (1..currentVersion), proofSystem, curve, circuitId, material.vkHash() == SHA-256(vkBytes), and ByHash vkRef matching SHA-256(vkBytes) (returning VK_MISMATCH / MALFORMED_ENVELOPE without rejecting BBS raw public keys or empty publicInputs).
    • Enforced binding centrally in VerifierOrchestrator and defensively in Groth16BLS12381Verifier, Groth16BLS12381PureJavaVerifier, PlonkBLS12381Verifier, and BbsZkVerifier.
    • Both BLS12-381 Groth16 verifiers now decode JSON explicitly as UTF-8, validate optional proofFormat ("snarkjs-json"), validate parsed JSON protocol/curve/IC.size(), and classify CodecException as MALFORMED_ENVELOPE (preserving pure-Java / blst ReasonCode parity). BbsZkVerifier classifies malformed CBOR/key BbsException errors as MALFORMED_ENVELOPE.
    • InMemoryVerificationKeyRegistry.register rejects spoofed vkHash != SHA-256(vkBytes); VerifierRegistry uses thread-safe CopyOnWriteArrayList and returns an immutable snapshot from all().
  • Verifiable SnarkjsJsonCodec.toEnvelope & PlonK VK validation:
    • Fixed SnarkjsJsonCodec.serializeProofToBytes / serializeVkToBytes (and added public toVerificationKeyBytes(SnarkjsVerificationKey)) to emit canonical snarkjs JSON (pi_a, pi_b, pi_c, vk_alpha_1, ..., IC, decimal strings) that round-trips through parseProof/parseVerificationKey and verifies directly on both BLS12-381 Groth16 backends.
    • Updated SnarkjsPlonkCodec.toEnvelopeFromJson to parse and cross-check vkJson (protocol == "plonk", matching curve, nPublic == inputs.size()).
  • Strict canonical CborEnvelopeCodec + optional keys 8–10:
    • Implemented deterministic encoding/decoding for optional keys 8 (domainTag), 9 (metadata, sorted in RFC 8949 canonical UTF-8 byte-length-then-lexicographical order), and 10 (proofFormat) while keeping 7-key envelopes byte-identical when optional fields are absent/empty.
    • Hardened CborEnvelopeCodec.decode with setRejectDuplicateKeys(true), setMaxPreallocationSize(MAX_CBOR_BYTES), allowed-key filtering (1..10), version bounds, minimal non-negative BigInteger validation, omission of empty optional keys, and canonical round-trip byte equality.
  • Legacy BN254 gating & documentation:
    • Added LegacyCurvePolicy.requireLegacyBn254Enabled() plus bounded section framing, exact BN254 FR prime check, and canonical scalar range check to ZkeyImporter.importWtns.
    • Overrode isAvailable() on Groth16BN254Verifier and PlonkBN254Verifier to reflect LegacyCurvePolicy.legacyBn254Enabled(), added explicit "unsound against adversarial input" warnings in LegacyCurvePolicy and legacy verifier Javadocs, and added unit tests pinning ServiceLoader isolation.
    • Synchronized www/src/content/docs/guides/verifying/off-chain.md with the new verifier binding, CBOR canonical encoding, and legacy BN254 guarantees.

Verification

  • ./gradlew :zeroj-api:test :zeroj-backend-spi:test :zeroj-codec:test :zeroj-verifier-groth16:test :zeroj-verifier-plonk:test :zeroj-bbs:test :zeroj-crypto:test --tests 'org.zeroj.crypto.groth16.*' :zeroj-integration-tests:test --tests 'org.zeroj.it.spi.VerifierServiceLoaderPackagingTest' --stacktrace — PASSED across all 8 modules.

@satran004

Copy link
Copy Markdown
Member Author

[reviewer1] Changes requested on 87babf1a607c6e6807b5dd268b49e3cca905a6b1.

  1. CBOR map order and Unicode fidelity. At CborEnvelopeCodec.java:112, the default cbor-java 0.9 encoder sorts the metadata again. Its MapEncoder comparator compares signed Java bytes, undoing the explicit unsigned sort at line 239. For equal-length keys aa and é, deterministic CBOR requires aa first. Preserve the explicitly sorted order when emitting the map. Also make the UTF-8 encoder report unpaired surrogates before writing text, since Java's default replacement loses the original key or value. Pin expected wire bytes from an independent source and cover both insertion orders, valid supplementary characters and rejected malformed UTF-16. RFC 8949 §4.2.1
  2. Bound CBOR parsing before building the object tree. At line 136, decoder.decode() recursively materializes every item before the schema checks run. The byte/preallocation settings do not limit nesting depth, total nodes or top-level item count. Enforce the envelope's shallow schema and field-specific lengths/counts before recursion or collection allocation. Add bounded regression cases for one level beyond the schema, an excessive declared collection length and trailing items, with ordinary canonical envelopes as positive controls. RFC 8949 §10
  3. BBS statement inputs. BbsZkVerifier.verify verifies disclosures contained inside the presentation while ignoring the envelope's field-element vector entirely. Require this vector to be empty for the BBS profile, document where authenticated disclosures are carried, and cover direct and orchestrated calls. Keep the existing empty-vector success cases for both suites.
  4. WTNS version ceiling. ZkeyImporter.java:304 accepts every positive version using the same layout. Pin the supported versions in the ADR and reject future versions. snarkjs 0.7.6 passes a maximum version of 2 to its reader. Keep a supported-version control and assert rejection just beyond the maximum. Pinned snarkjs reader

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: 87babf1a607c6e6807b5dd268b49e3cca905a6b1

Issues found:

  • zeroj-codec/src/main/java/org/zeroj/codec/CborEnvelopeCodec.java:112 — The encoder’s signed-byte sorting puts metadata key é before aa, producing noncanonical CBOR and causing decoding to reject correctly ordered envelopes from other implementations. Could we preserve the explicit unsigned ordering and test exact bytes for these keys?

Not tested: Code and tests were read only; I did not run the build or verifier and codec tests.

@satran004

Copy link
Copy Markdown
Member Author

Addressed all Round 1 review items in commit 2cbbd37d:

  1. RFC 8949 §4.2.1 unsigned UTF-8 map ordering & strict UTF-16/UTF-8 handling (CborEnvelopeCodec):
    • Replaced cbor-java's default CborEncoder (whose MapEncoder re-sorts keys using signed Java bytes) with direct shortest-form definite-length RFC 8949 §4.2.1 encoding, preserving unsigned bytewise UTF-8 key order ("aa" 62 61 61 before "é" 62 C3 A9 before 4-byte supplementary "😀" 64 F0 9F 98 80).
    • Added strict CodingErrorAction.REPORT UTF-8 encoding and decoding so unpaired UTF-16 surrogates and invalid UTF-8 fail closed with CodecException.
    • Added an independent wire-byte test vector covering both metadata insertion orders, supplementary Unicode characters, wire-order swap rejection, and malformed UTF-16 rejection (CborEnvelopeCodecTest.metadataUsesRfc8949UnsignedUtf8OrderAndRejectsMalformedUtf16).
  2. Bounded non-recursive CBOR decoding before collection allocation (CborEnvelopeCodec, RFC 8949 §10):
    • Replaced recursive CborDecoder.decode() tree materialization with a sequential non-recursive reader that validates major types, shortest-form arguments, definite lengths, strictly ascending keys, and remaining-byte capacity (count * 2 <= remaining for publicInputs, count * 3 <= remaining for metadata) before allocating collections, plus rejects trailing bytes/items.
    • Added regression tests for 10,000-level deep nesting, one-level-beyond-schema array inside publicInputs, excessive declared collection length (1,000,000 in a tiny buffer), and trailing CBOR items (CborEnvelopeCodecTest.decodeRejectsExcessiveNestingAndDeclaredCollectionLengthBeforeAllocation).
  3. Empty publicInputs enforcement for BBS (BbsZkVerifier):
    • Required envelope.publicInputs().size() == 0 in BbsZkVerifier.verify(...) (returning INVALID_PUBLIC_INPUTS otherwise), documented in BbsZkVerifier, ADR-0067, and off-chain.md that authenticated BBS disclosures are carried inside the CBOR presentation (envelope.proofBytes()), and added direct + orchestrated non-empty-vector tests in BbsServiceTest.
  4. Pinned .wtns version ceiling (ZkeyImporter.importWtns):
    • Capped .wtns version to 1..2 (matching snarkjs 0.7.6 src/wtns_utils.js:68-71), documented the pinned ceiling in ADR-0067, and added tests verifying versions 1 and 2 succeed while 0 and 3 fail with IOException (ZkeyImporterTest).

Verification (2cbbd37d):

  • ./gradlew :zeroj-codec:test :zeroj-bbs:test :zeroj-crypto:test --tests 'org.zeroj.crypto.groth16.ZkeyImporterTest' --stacktrace — PASSED (all positive, negative, RFC 8949 wire-vector, and DoS-bound tests green).

@satran004

Copy link
Copy Markdown
Member Author

[reviewer1] Approved 2cbbd37dec2cf87bc40924bbf5368e2d6e4f2a47. I verified all four requested changes. The fixed-schema CBOR reader checks types and bounds before copying payloads or allocating collections. The writer emits unsigned UTF-8 key order and rejects malformed Unicode. The independent expected-byte assertion covers mixed ASCII and non-ASCII keys. BBS requires an empty envelope input vector through both entry points, and the WTNS reader enforces versions 1–2.

My isolated Gradle run covered the codec, verifier SPI, Groth16 and PlonK verifier suites, BBS service tests, and witness importer tests. All 173 tests passed with zero skips.

@satran004

Copy link
Copy Markdown
Member Author

[reviewer3] Review of head 2cbbd37d (round 2; I also reviewed the 87babf1a diff) — APPROVED

Scope: engineering, cross-backend consistency, codec and wire compatibility, API surface, docs.

Cross-backend binding

  • The shared EnvelopeBinding covers version, proof system, curve, circuitId, material.vkHash == sha256(vkBytes) and the ByHash ref, and does not require non-empty publicInputs. VerifierOrchestrator.verify(envelope, material) applies it, and so does every ZkVerifier in src/main: Groth16 pure-Java and blst, PlonK BLS12-381, and BBS. PlonK's private copy was replaced by the shared one, so all four backends now behave the same.
  • Groth16 now also checks the JSON protocol / curve and IC.size == nPublic + 1, and treats proofFormat snarkjs-json as the codec's own constant.
  • The legacy BN254 verifiers return isAvailable() == LegacyCurvePolicy.legacyBn254Enabled(). VerifierRegistry uses CopyOnWriteArrayList and returns snapshot copies.
  • importWtns is BN254-only and gated. All BLS12-381 callers (docs, tutorials, tests) use ZkeyImporterBLS381.importWtns, which is untouched, so the gate breaks nothing.

CBOR wire compatibility (independent check with cbor-java 0.9)

  • For a keys-1..7 envelope (Groth16, ByHash, inputs 0, 24, 255, 2^254−1, 300-byte proof), the main-branch cbor-java encoder and the new hand-written encoder emit identical bytes (439 B). The new strict decoder accepts the old encoding, so envelopes already in storage keep decoding.
  • With optional keys 8–10 and non-ASCII metadata, cbor-java's canonical re-encode differs, because cbor-java orders "é" (62 c3 a9) before "aa" (62 61 61): it compares bytes as signed values. The new encoder puts aa < é, which is the correct RFC 8949 §4.2.1 unsigned bytewise order. Moving off cbor-java for this codec was the right call.
  • The reader is non-recursive and bounded. It rejects non-minimal arguments, indefinite lengths, unsorted or duplicate keys, out-of-range values, trailing bytes and malformed UTF-8, and it checks declared counts against the remaining bytes before allocating. It then also checks that decoding and re-encoding give the same bytes.

Tests (my runs)

  • 2cbbd37d: :zeroj-codec 57, :zeroj-bbs 94, :zeroj-backend-spi 20, :zeroj-verifier-groth16 31 (pure-Java + blst parity), :zeroj-verifier-plonk 39, ZkeyImporterTest 4. All pass, 0 skipped.
  • 87babf1a: additionally :zeroj-api 127, :zeroj-crypto groth16 157, and :zeroj-integration-tests it.spi.* + it.snarkjs.* (19, with live snarkjs 0.7.6) all pass. A downstream :zeroj-tools:test run passed. The full :zeroj-integration-tests:test run was still going when I posted, with no failures so far.
  • ADR-0067 relative links resolve. off-chain.md matches the new behaviour, including the empty BBS publicInputs and CanonicalHash covering keys 1..7 only.

Non-blocking (P3)

  1. zeroj-codec/build.gradle:9 still declares api 'co.nstant.in:cbor:0.9', but no zeroj-codec main code uses cbor-java any more; only CborEnvelopeCodecTest does. As api it still lands in the published zeroj-codec POM as a transitive dependency. zeroj-bbs and zeroj-mpf-poseidon declare it themselves, so this can become testImplementation safely.
  2. The malformed-input mapping still differs by backend. The Groth16 verifiers map IllegalArgumentException (for example an off-curve point) to PROOF_INVALID, while CodecException maps to MALFORMED_ENVELOPE. BBS maps both BbsException and IllegalArgumentException to MALFORMED_ENVELOPE. Either is defensible, but ADR-0067 or the off-chain.md reason-code table should say which one integrators should expect.
  3. Related to the signed-byte ordering above: BbsPresentationCodec and PoseidonMpfCodec still use cbor-java's canonical encoder. Both use integer map keys today, so they are not affected. A one-line note would stop a future text-keyed map from picking up the same non-RFC ordering.

@satran004

Copy link
Copy Markdown
Member Author

[reviewer3] Follow-up to my approval: the full :zeroj-integration-tests:test run that was still going when I posted has now finished, at 87babf1a (round 1, before the round-2 changes). It is green: 127 tests, 0 failures, 0 skipped. :zeroj-tools:test and :zeroj-circuit-annotation-api:test also pass. My approval of 2cbbd37d stands.

@satran004
satran004 merged commit 2cfcc41 into main Nov 21, 2026
7 of 8 checks passed
@satran004
satran004 deleted the fix/adr-0067-verifier-codec-and-bn254-hardening branch November 21, 2026 09:55
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