diff --git a/docs/adr/0067-offchain-verifier-binding-codecs-and-legacy-bn254-gating.md b/docs/adr/0067-offchain-verifier-binding-codecs-and-legacy-bn254-gating.md new file mode 100644 index 00000000..8be160eb --- /dev/null +++ b/docs/adr/0067-offchain-verifier-binding-codecs-and-legacy-bn254-gating.md @@ -0,0 +1,100 @@ +# ADR-0067: Off-Chain Verifier Envelope Binding, Canonical Codecs, and Legacy BN254 Gating + +## Status + +Proposed + +## Date + +2026-11-21 + +## Risk Classification + +**R2** — Security-sensitive validation, serialization/deserialization trust boundaries, cross-backend verifier consistency, and legacy curve isolation. + +## Context + +Four off-chain trust-boundary gaps existed across ZeroJ's verification orchestration, backend verifiers, envelope codecs, and legacy BN254 surface: + +1. **Divergent envelope-to-material binding across off-chain backends:** `PlonkBLS12381Verifier` validated that `envelope.proofSystem()`, `envelope.curve()`, `envelope.circuitId()`, `material.vkHash()`, and `envelope.vkRef()` (`ByHash`) matched `VerificationMaterial` before verifying cryptography, returning `VK_MISMATCH` on any mismatch. However, `VerifierOrchestrator`, `Groth16BLS12381Verifier`, `Groth16BLS12381PureJavaVerifier`, and `BbsZkVerifier` did not enforce these checks. An attacker could supply a valid proof for `circuit-a` inside an envelope claiming `circuit-b` (or referencing a different `ByHash` VK digest) and receive `proofValid = true` from `VerifierOrchestrator` or the Groth16/BBS verifiers. In addition: + - `InMemoryVerificationKeyRegistry.register` indexed `material.vkHash()` without checking that it equaled `SHA-256(material.vkBytes())`. + - `VerifierRegistry` stored backends in an unsynchronized `ArrayList`. + - Groth16 verifiers decoded proof/VK bytes with the platform default charset instead of UTF-8, did not check parsed JSON `protocol`/`curve`, and mapped `CodecException` to `INTERNAL_ERROR` instead of `MALFORMED_ENVELOPE`. + - `BbsZkVerifier` mapped malformed CBOR/public-key `BbsException` failures to `INTERNAL_ERROR` instead of `MALFORMED_ENVELOPE`. +2. **Broken `SnarkjsJsonCodec.toEnvelope` serialization & unchecked PlonK VK JSON:** `SnarkjsJsonCodec.toEnvelope(SnarkjsProof, SnarkjsVerificationKey, ...)` serialized Java record field names (`piA`, `vkAlpha1`, numeric JSON numbers) rather than snarkjs JSON (`pi_a`, `vk_alpha_1`, canonical decimal strings), producing envelopes that failed `SnarkjsJsonCodec.parseProof` and computed `vkRef` hashes over non-snarkjs JSON. Meanwhile `SnarkjsPlonkCodec.toEnvelopeFromJson` never parsed or cross-checked `vkJson` (`protocol`, `curve`, `nPublic`). +3. **Lossy and non-canonical `CborEnvelopeCodec`:** `CborEnvelopeCodec` documented optional keys `8` (`domainTag`), `9` (`metadata`), and `10` (`proofFormat`) but dropped them on encode/decode — stripping `proofFormat` needed by format-sensitive verifiers (e.g., Cardano PlonK profiles and BBS). On decode it used default `CborDecoder.decode(cbor)` without duplicate-key rejection, preallocation bounds, unknown-key rejection, version bounds, minimal `BigInteger` checks, or canonical re-encoding verification. +4. **Incomplete legacy BN254 gating:** `ZkeyImporter.importWtns` lacked both `LegacyCurvePolicy.requireLegacyBn254Enabled()` and binary framing/prime/bounds validation. Legacy BN254 verifiers (`Groth16BN254Verifier`, `PlonkBN254Verifier`) also returned `isAvailable() == true` even when BN254 was disabled, and `LegacyCurvePolicy` did not explicitly warn that legacy BN254 verifiers are unsound against adversarial input. + +## Threat Model & Trust Assumptions + +- **Untrusted inputs:** `ZkProofEnvelope` (including `version`, `proofSystem`, `curve`, `circuitId`, `proofBytes`, `publicInputs`, `vkRef`, `proofFormat`, `domainTag`, `metadata`), CBOR envelope bytes, snarkjs proof/VK/public JSON strings, and `.wtns` streams. +- **Trusted boundary:** `VerificationMaterial` registered in a trusted `VerificationKeyRegistry` (or passed directly by the caller after binding it to the intended statement/circuit) represents the expected statement and verification key bytes. +- **Threats addressed:** + - Cross-circuit or cross-VK substitution via mismatched `circuitId`, `proofSystem`, `curve`, `ByHash` VK digest, or spoofed `material.vkHash()`. + - Silent cross-backend divergence where PlonK rejects a substituted envelope while Groth16 or BBS accepts it. + - CBOR malleability, duplicate-key smuggling, unknown-key injection, preallocation DoS, and silent stripping of `proofFormat`/`domainTag`/`metadata` on round-trip. + - Accidental exposure or unbounded parsing of legacy BN254 `.wtns` files or BN254 verifiers via `ServiceLoader` or `VerifierRegistry`. +- **Non-goals:** Cryptographic proof validity still does not confer application authorization, replay protection, or `ScriptContext` binding. + +## Normative References + +- **RFC 8949 §4.2 & §10** — Deterministic Encoding for CBOR (shortest-form integers, definite lengths, no duplicate keys, unsigned bytewise canonical map key ordering, and resource-bounded parsing before object-tree materialization). +- **snarkjs 0.7.6** — Groth16 and PlonK JSON proof / verification key / public input schemas (`pi_a`, `pi_b`, `pi_c`, `vk_alpha_1`, `vk_beta_2`, `vk_gamma_2`, `vk_delta_2`, `vk_alphabeta_12`, `IC`, decimal strings) and binary `.wtns` section format (`magic = "wtns"`, `src/wtns_utils.js:68-71` max version `2`, section 1 header + section 2 witness). +- **CFRG BBS draft-10 (`draft-irtf-cfrg-bbs-signatures-10`)** — ZeroJ's `BbsPresentationCodec` strict canonical CBOR model and dual-suite (`SHA-256` / `SHAKE-256`) `BbsZkVerifier` adapter. +- **ADR-0044** — Module surface isolation (`zeroj-backend-spi`, opt-in backends, no BN254 in default `ServiceLoader` surface). +- **ADR-0062** — BLS12-381 Groth16 pure-Java / `blst` verifier parity and canonical point encoding (`z = 1`). + +## Security Invariants + +1. **I1 — Uniform envelope/material binding:** `VerifierOrchestrator.verify(envelope, material)` AND each BLS12-381 verifier (`Groth16BLS12381Verifier`, `Groth16BLS12381PureJavaVerifier`, `PlonkBLS12381Verifier`, `BbsZkVerifier`) enforce: + - `envelope != null` (else `MALFORMED_ENVELOPE`), `material != null` (else `VK_MISMATCH`); + - `1 <= envelope.version() <= ZkProofEnvelope.currentVersion()` (else `MALFORMED_ENVELOPE`); + - `material.proofSystemId() == envelope.proofSystem()`, `material.curveId() == envelope.curve()`, and `material.circuitId().equals(envelope.circuitId())` (else `VK_MISMATCH`); + - `actualVkHash = SHA-256(material.vkBytes())`: if `material.vkHash()` is present it must equal `actualVkHash`, and if `envelope.vkRef()` is `ByHash` it must equal `actualVkHash` (else `VK_MISMATCH`). + - Binding MUST NOT assume Groth16 JSON structure for `material.vkBytes()` (BBS uses raw 96-byte G2 public keys) and MUST NOT reject empty `publicInputs` (valid for BBS and 0-public-input circuits). + - For BBS presentations, authenticated disclosures (revealed messages, header, and presentation header) are carried inside the canonical CBOR presentation in `envelope.proofBytes()`, not in the SNARK field-element vector; `BbsZkVerifier` therefore rejects non-empty `envelope.publicInputs()` with `INVALID_PUBLIC_INPUTS`. +2. **I2 — Registry integrity & thread safety:** `InMemoryVerificationKeyRegistry.register(material)` rejects any `material` whose declared `vkHash` disagrees with `SHA-256(material.vkBytes())`. `VerifierRegistry` uses thread-safe `CopyOnWriteArrayList` storage and returns an immutable snapshot from `all()`. +3. **I3 — Backend metadata validation & error classification:** Both BLS12-381 Groth16 verifiers decode JSON explicitly as UTF-8, validate optional `proofFormat` (`"snarkjs-json"` if present), validate parsed JSON `protocol == "groth16"`, `curve == "bls12-381"`, and `IC.size() == nPublic + 1`, and map `CodecException` to `MALFORMED_ENVELOPE` (preserving pure-Java / `blst` `ReasonCode` parity). `BbsZkVerifier` maps malformed CBOR/key `BbsException` errors to `MALFORMED_ENVELOPE` rather than `INTERNAL_ERROR`. +4. **I4 — Verifiable snarkjs JSON round-trip:** `SnarkjsJsonCodec.serializeProofToBytes` and `serializeVkToBytes` (exposed via `toVerificationKeyBytes`) emit canonical snarkjs JSON (`pi_a`, `pi_b`, `pi_c`, `vk_alpha_1`, ..., `IC`, canonical decimal strings) that round-trips through `parseProof` / `parseVerificationKey` and verifies against BLS12-381 Groth16 verifiers. `SnarkjsPlonkCodec.toEnvelopeFromJson` parses and cross-checks `vkJson` (`protocol == "plonk"`, `vk.curve() == proof.curve()`, `vk.nPublic() == inputs.size()`). +5. **I5 — Strict canonical CBOR envelope wire format (v1):** `CborEnvelopeCodec` carries required keys `1..7` and optional keys `8` (`domainTag`, omitted when empty), `9` (`metadata`, omitted when empty, keys sorted in RFC 8949 §4.2.1 unsigned bytewise order of encoded UTF-8 keys), and `10` (`proofFormat`, omitted when absent). Envelopes with none of keys `8..10` populated emit the exact existing 7-key v1 bytes. Encoding rejects malformed UTF-16 (unpaired surrogates) via `CodingErrorAction.REPORT` and writes canonical CBOR directly without relying on signed-byte map re-sorting. Decoding parses sequentially without recursion and enforces before collection allocation: + - `MAX_CBOR_BYTES` bound, definite-length shortest-form CBOR only, and exact remaining-byte checks on declared collection/string lengths; + - single definite-length CBOR map with strictly ascending keys in `{1..10}` (no duplicate, out-of-order, or unknown keys, and no nesting deeper than the envelope's shallow schema); + - `1 <= version <= ZkProofEnvelope.currentVersion()` and strict UTF-8 decoding; + - minimal non-negative `BigInteger.toByteArray()` encodings in `publicInputs`; + - strict omission of empty optional keys (`domainTag == ""`, `metadata == {}`, blank `proofFormat`); + - zero trailing bytes and byte-for-byte canonical round-trip equality (`Arrays.equals(cbor, encode(decoded))`). + Local non-wire fields (`proofUri`, `proofHash`, `createdAt`, `producerId`) are explicitly documented as not serialized in CBOR. +6. **I6 — Legacy BN254 fail-closed isolation:** `ZkeyImporter.importWtns` enforces `LegacyCurvePolicy.requireLegacyBn254Enabled()`, pinned `.wtns` version range `1..2` (matching `snarkjs 0.7.6` `src/wtns_utils.js:68-71`), bounded section framing, exact BN254 scalar prime `FR`, and canonical scalar range `< FR`. `Groth16BN254Verifier` and `PlonkBN254Verifier` report `isAvailable() == LegacyCurvePolicy.legacyBn254Enabled()`, carry explicit Javadoc/policy warnings that they are unsound against adversarial input, and remain absent from all `META-INF/services/org.zeroj.backend.spi.ZkVerifier` files. + +## Decision & Alternatives Considered + +- **Shared `EnvelopeBinding` helper in `zeroj-backend-spi`:** Placing the shared binding logic in `org.zeroj.backend.spi.EnvelopeBinding` avoids duplicating hash/binding checks across `VerifierOrchestrator`, Groth16, PlonK, and BBS while keeping `zeroj-backend-spi` free of `zeroj-codec` dependencies. + - *Alternative rejected:* Wiring `EnvelopeValidator` centrally. `EnvelopeValidator` currently rejects empty `publicInputs`, which would break BBS presentations and 0-public-input circuits. +- **Keep CBOR envelope version = 1 with optional keys 8–10:** Existing 7-key envelopes (where `domainTag` is empty, `metadata` is empty, and `proofFormat` is absent) remain 100% byte-compatible with v1, while envelopes carrying `domainTag`/`metadata`/`proofFormat` now round-trip losslessly using the exact key numbers already documented in `CborEnvelopeCodec`. + - *Alternative rejected:* Bumping to version 2 or stripping keys 8–10 from Javadoc. Bumping version unnecessarily breaks existing v1 7-key fixtures, while dropping `proofFormat` breaks Cardano PlonK and BBS envelope round-trips. +- **Fix `SnarkjsJsonCodec.toEnvelope` rather than deleting it:** Emitting true snarkjs JSON fixes the broken API in place while keeping binary/source compatibility for callers; `toVerificationKeyBytes(SnarkjsVerificationKey)` lets callers materialize matching `VerificationMaterial` cleanly, while raw-file callers continue to prefer `toEnvelopeFromJson`. + +## Compatibility + +- **Breaking for callers passing mismatched envelopes/materials:** Callers that previously constructed Groth16 or BBS envelopes with dummy/mismatched `ByHash(new byte[32])` or mismatched `circuitId` now receive `VK_MISMATCH` instead of `proofValid = true` (matching `PlonkBLS12381Verifier`). +- **Breaking for non-canonical CBOR inputs:** `CborEnvelopeCodec.decode` now rejects non-canonical CBOR (non-minimal ints, indefinite lengths, duplicate/unknown/out-of-order keys, padded `BigInteger` bytes) and `encode` now emits keys `8..10` when populated. +- **Breaking for ungated `ZkeyImporter.importWtns`:** Callers of `ZkeyImporter.importWtns` (BN254) must now opt in via `-Dzeroj.allowLegacyBn254=true` or `ZEROJ_ALLOW_LEGACY_BN254=true`, matching `ZkeyImporter.importZkey`. + +## Implementation Milestones + +- **M1:** Add `EnvelopeBinding` in `zeroj-backend-spi`; harden `VerifierOrchestrator`, `InMemoryVerificationKeyRegistry`, `VerifierRegistry`, `Groth16BLS12381Verifier`, `Groth16BLS12381PureJavaVerifier`, `PlonkBLS12381Verifier` (reuse `EnvelopeBinding`), and `BbsZkVerifier`. +- **M2:** Fix `SnarkjsJsonCodec.toEnvelope` / `serializeProofToBytes` / `serializeVkToBytes` + `toVerificationKeyBytes` and `SnarkjsPlonkCodec.toEnvelopeFromJson` VK validation. +- **M3:** Implement keys 8–10 and strict canonical CBOR validation in `CborEnvelopeCodec`. +- **M4:** Gate and harden `ZkeyImporter.importWtns`, override `isAvailable()` and add unsoundness warnings on `LegacyCurvePolicy` / `Groth16BN254Verifier` / `PlonkBN254Verifier`, add ServiceLoader isolation tests, and update `www/src/content/docs/guides/verifying/off-chain.md`. + +## Verification & Test Strategy + +- **Positive + negative binding tests** across `VerifierOrchestrator`, `InMemoryVerificationKeyRegistry`, `Groth16BLS12381Verifier` & `Groth16BLS12381PureJavaVerifier` (with exact blst/pure-Java `ReasonCode` parity), and `BbsZkVerifier` (including `ById`, `ByHash`, dual SHA-256/SHAKE-256 suites, malformed CBOR -> `MALFORMED_ENVELOPE`). +- **Round-trip + verification test** proving `SnarkjsJsonCodec.toEnvelope(...)` produces a proof verifiable by BLS12-381 Groth16 verifiers, plus negative `SnarkjsPlonkCodec.toEnvelopeFromJson` VK mismatch tests. +- **Adversarial CBOR tests** rejecting indefinite lengths, non-minimal ints, duplicate keys, unknown keys, out-of-order keys, padded `BigInteger`, bad versions, and empty optional keys, plus round-trip tests preserving `domainTag`, `metadata`, and `proofFormat`. +- **Legacy BN254 tests** confirming `ZkeyImporter.importWtns` rejects disabled policy, wrong prime, bad framing, and non-canonical witness scalars; confirming `Groth16BN254Verifier` / `PlonkBN254Verifier` report `isAvailable() == false` by default and never appear in `META-INF/services/org.zeroj.backend.spi.ZkVerifier`. + +## Remaining Production & Audit Gates + +- Independent external cryptographic review of all verifier backends, codecs, and on-chain/off-chain integration boundaries remains required prior to production or value-bearing promotion. +- Application-level authorization, replay protection, nullifier tracking, and `ScriptContext` binding remain the application's responsibility outside the generic verifier SPI. diff --git a/www/src/content/docs/guides/verifying/off-chain.md b/www/src/content/docs/guides/verifying/off-chain.md index 7a3a8248..134c39a1 100644 --- a/www/src/content/docs/guides/verifying/off-chain.md +++ b/www/src/content/docs/guides/verifying/off-chain.md @@ -116,10 +116,10 @@ The `ReasonCode` enum covers both sides: |---|---| | `INVALID_PROOF` | A backend: the pairing check failed, or a point was malformed | | `INVALID_PUBLIC_INPUTS` | A backend: wrong count, or a value outside `[0, r)` | -| `INTERNAL_ERROR` | A backend: an unexpected exception, e.g. unparseable proof bytes | +| `INTERNAL_ERROR` | A backend: an unexpected internal or native-loading error | | `UNKNOWN_VERIFICATION_KEY` | The orchestrator: the envelope's `vkRef` isn't registered | | `UNSUPPORTED_PROOF_SYSTEM` | The orchestrator (no backend registered) or a backend given the wrong proof system | -| `VK_MISMATCH`, `UNSUPPORTED_CURVE`, `MALFORMED_ENVELOPE` | Consistency checks in the PlonK and BBS backends, and in your own gate | +| `VK_MISMATCH`, `UNSUPPORTED_CURVE`, `MALFORMED_ENVELOPE` | Envelope-to-material binding and format checks in `VerifierOrchestrator` and all BLS12-381 backends (Groth16, PlonK, BBS), plus your own policy gate | | `UNKNOWN_CIRCUIT`, `RETIRED_CIRCUIT`, `STALE_STATE_ROOT`, `DUPLICATE_NONCE`, `UNAUTHORIZED_SUBMITTER`, `USED_NULLIFIER` | Your policy layer | ## Choose a backend @@ -142,9 +142,10 @@ The PlonK verifier is an experimental, opt-in path. Groth16 on BLS12-381 is the the current release; don't treat PlonK verification as production evidence. ::: -The legacy BN254 verifiers are not registered with `ServiceLoader` and refuse to run unless you -start the JVM with `-Dzeroj.allowLegacyBn254=true`. BN254 is not a Cardano curve; ignore it -unless you are running old off-chain experiments. +The legacy BN254 verifiers are not registered with `ServiceLoader`, report `isAvailable() == false` +by default, and refuse to run unless you start the JVM with `-Dzeroj.allowLegacyBn254=true`. They +are **unsound against adversarial input** and BN254 is not a Cardano curve; ignore them unless you +are running trusted local off-chain experiments. ## Route proofs with registries @@ -201,10 +202,18 @@ The Groth16 backends fail closed on malformed input before any pairing work: An infinity `IC` entry would leave a public input unbound, so ZeroJ's setup refuses to create one and every verifier rejects it. -What the Groth16 backends do **not** check: that `envelope.circuitId()` or `envelope.vkRef()` -matches the `VerificationMaterial` you passed. They verify the proof against whatever key you give -them. (The experimental PlonK verifier does compare them and returns `VK_MISMATCH`.) Do that -comparison yourself, as the next section shows. +- **Envelope-to-material binding.** `VerifierOrchestrator` and every BLS12-381 backend (Groth16 + pure-Java, Groth16 blst, PlonK, and BBS) verify that `envelope.version()`, `proofSystem()`, + `curve()`, `circuitId()`, `material.vkHash()`, and `ByHash` `vkRef()` match the provided + `VerificationMaterial` (`VK_MISMATCH` on mismatch; `MALFORMED_ENVELOPE` on invalid version, + unsupported `proofFormat`, or unparseable JSON/CBOR). The Groth16 backends also verify the + parsed JSON `protocol` (`"groth16"`) and `curve` (`"bls12-381"`). For BBS, authenticated + disclosures are carried inside the canonical CBOR presentation in `proofBytes()`, so + `BbsZkVerifier` requires `envelope.publicInputs()` to be empty (`INVALID_PUBLIC_INPUTS` otherwise). + +Your application gate must still decide *which* `circuitId` and pinned VK hash an endpoint expects +(for example, rejecting a valid proof for `circuit-a` on an endpoint that requires `circuit-b`), as +the next section shows. ## Build a verification service @@ -308,11 +317,14 @@ ZkProofEnvelope decoded = CborEnvelopeCodec.decode(cbor); // bounded, typed Cod byte[] id = CanonicalHash.hash(envelope); // SHA-256 over the core fields ``` -The CBOR encoding carries the core fields only: version, proof system, curve, circuit ID, proof -bytes, public inputs, and the VK reference. Optional fields such as `metadata()` (where annotated -circuits put their version) and `proofFormat()` are **not** carried, and `CanonicalHash` ignores -them too. If your policy depends on them, send them another way, or rely on the pinned VK hash, -which already distinguishes circuit versions. +The CBOR encoding is strictly canonical (RFC 8949 §4.2): keys `1..7` carry version, proof system, +curve, circuit ID, proof bytes, minimal non-negative `BigInteger` public inputs, and the VK +reference, while optional keys `8` (`domainTag`), `9` (`metadata`, sorted canonically), and `10` +(`proofFormat`) are included whenever populated and omitted when empty. `CborEnvelopeCodec.decode` +fails closed on duplicate keys, unknown keys, non-minimal integers, indefinite lengths, padded +`BigInteger` bytes, or any non-canonical re-encoding. Local builder metadata (`proofUri`, +`proofHash`, `createdAt`, `producerId`) is not carried in CBOR, and `CanonicalHash` hashes the core +fields (`1..7`) only. ## Write a custom backend diff --git a/zeroj-api/src/main/java/org/zeroj/api/LegacyCurvePolicy.java b/zeroj-api/src/main/java/org/zeroj/api/LegacyCurvePolicy.java index c4a09c14..282382ad 100644 --- a/zeroj-api/src/main/java/org/zeroj/api/LegacyCurvePolicy.java +++ b/zeroj-api/src/main/java/org/zeroj/api/LegacyCurvePolicy.java @@ -2,6 +2,11 @@ /** * Central policy for legacy curves that are not part of the Cardano production surface. + * + *

Security warning: Legacy BN254 verifiers and importers lack adversarial point, + * subgroup, infinity, and envelope-binding validation and are unsound against adversarial + * input. They are disabled by default and intended solely for trusted local off-chain + * experiments.

*/ public final class LegacyCurvePolicy { @@ -17,9 +22,9 @@ public static boolean legacyBn254Enabled() { public static String legacyBn254DisabledMessage() { return "BN254 is disabled by default because ZeroJ targets Cardano " - + "production flows and Cardano only supports BLS12-381 on-chain. " - + "For legacy off-chain experiments, start the JVM with -D" - + ALLOW_LEGACY_BN254_PROPERTY + "=true."; + + "production flows (BLS12-381 only) and legacy BN254 verifiers/importers are " + + "unsound against adversarial input. For trusted local off-chain experiments only, " + + "start the JVM with -D" + ALLOW_LEGACY_BN254_PROPERTY + "=true."; } public static void requireLegacyBn254Enabled() { diff --git a/zeroj-backend-spi/src/main/java/org/zeroj/backend/spi/EnvelopeBinding.java b/zeroj-backend-spi/src/main/java/org/zeroj/backend/spi/EnvelopeBinding.java new file mode 100644 index 00000000..31ffefea --- /dev/null +++ b/zeroj-backend-spi/src/main/java/org/zeroj/backend/spi/EnvelopeBinding.java @@ -0,0 +1,85 @@ +package org.zeroj.backend.spi; + +import org.zeroj.api.VerificationKeyRef; +import org.zeroj.api.VerificationMaterial; +import org.zeroj.api.VerificationResult; +import org.zeroj.api.ZkProofEnvelope; + +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Arrays; +import java.util.Optional; + +/** + * Shared envelope-to-verification-material binding checks enforced centrally by + * {@link org.zeroj.verifier.core.VerifierOrchestrator} and defensively by concrete + * {@link ZkVerifier} backends (ADR-0067). + * + *

Validates envelope version, proof system, curve, circuit identifier, and SHA-256 + * verification-key digest consistency without assuming any proof-system-specific key encoding + * or rejecting empty {@code publicInputs} (which are valid for BBS and zero-input circuits).

+ */ +public final class EnvelopeBinding { + + private EnvelopeBinding() {} + + /** + * Validate that {@code envelope} and {@code material} are structurally consistent and + * bound to the same statement and verification key bytes. + * + * @return {@link Optional#empty()} if all binding invariants hold, otherwise the + * {@link VerificationResult} describing the failure + */ + public static Optional validateBinding( + ZkProofEnvelope envelope, + VerificationMaterial material) { + if (envelope == null) { + return Optional.of(VerificationResult.error( + VerificationResult.ReasonCode.MALFORMED_ENVELOPE, + "Proof envelope must not be null")); + } + if (envelope.version() < 1 || envelope.version() > ZkProofEnvelope.currentVersion()) { + return Optional.of(VerificationResult.error( + VerificationResult.ReasonCode.MALFORMED_ENVELOPE, + "Unsupported proof envelope version: " + envelope.version())); + } + if (material == null) { + return Optional.of(VerificationResult.error( + VerificationResult.ReasonCode.VK_MISMATCH, + "Verification material must not be null")); + } + if (material.proofSystemId() != envelope.proofSystem() + || material.curveId() != envelope.curve() + || !material.circuitId().equals(envelope.circuitId())) { + return Optional.of(VerificationResult.error( + VerificationResult.ReasonCode.VK_MISMATCH, + "Verification material does not match proof envelope")); + } + + byte[] actualVkHash = sha256(material.vkBytes()); + if (material.vkHash().isPresent() + && !Arrays.equals(material.vkHash().orElseThrow(), actualVkHash)) { + return Optional.of(VerificationResult.error( + VerificationResult.ReasonCode.VK_MISMATCH, + "Verification material hash does not match VK bytes")); + } + if (envelope.vkRef() instanceof VerificationKeyRef.ByHash byHash + && !Arrays.equals(byHash.hash(), actualVkHash)) { + return Optional.of(VerificationResult.error( + VerificationResult.ReasonCode.VK_MISMATCH, + "Proof envelope VK hash does not match verification material")); + } + return Optional.empty(); + } + + /** + * Compute the SHA-256 digest of {@code data}. + */ + public static byte[] sha256(byte[] data) { + try { + return MessageDigest.getInstance("SHA-256").digest(data); + } catch (NoSuchAlgorithmException e) { + throw new IllegalStateException("SHA-256 not available", e); + } + } +} diff --git a/zeroj-backend-spi/src/main/java/org/zeroj/backend/spi/InMemoryVerificationKeyRegistry.java b/zeroj-backend-spi/src/main/java/org/zeroj/backend/spi/InMemoryVerificationKeyRegistry.java index 8ff59a84..3117fcd0 100644 --- a/zeroj-backend-spi/src/main/java/org/zeroj/backend/spi/InMemoryVerificationKeyRegistry.java +++ b/zeroj-backend-spi/src/main/java/org/zeroj/backend/spi/InMemoryVerificationKeyRegistry.java @@ -3,10 +3,9 @@ import org.zeroj.api.VerificationKeyRef; import org.zeroj.api.VerificationMaterial; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; import java.util.Arrays; import java.util.Map; +import java.util.Objects; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; @@ -22,6 +21,7 @@ public class InMemoryVerificationKeyRegistry implements VerificationKeyRegistry @Override public Optional lookup(VerificationKeyRef ref) { + Objects.requireNonNull(ref, "VerificationKeyRef must not be null"); return switch (ref) { case VerificationKeyRef.ById id -> Optional.ofNullable(byId.get(id.id())); case VerificationKeyRef.ByHash h -> Optional.ofNullable(byHash.get(new HashKey(h.hash()))); @@ -30,23 +30,19 @@ public Optional lookup(VerificationKeyRef ref) { @Override public void register(VerificationMaterial material) { - // Register by hash (computed from VK bytes if not provided) - byte[] hash = material.vkHash() - .orElseGet(() -> sha256(material.vkBytes())); - byHash.put(new HashKey(hash), material); + Objects.requireNonNull(material, "VerificationMaterial must not be null"); + byte[] actualHash = EnvelopeBinding.sha256(material.vkBytes()); + if (material.vkHash().isPresent() + && !Arrays.equals(material.vkHash().orElseThrow(), actualHash)) { + throw new IllegalArgumentException( + "VerificationMaterial vkHash does not match SHA-256 of vkBytes"); + } + byHash.put(new HashKey(actualHash), material); // Also register by circuit id for convenience byId.put(material.circuitId().value(), material); } - private static byte[] sha256(byte[] data) { - try { - return MessageDigest.getInstance("SHA-256").digest(data); - } catch (NoSuchAlgorithmException e) { - throw new RuntimeException("SHA-256 not available", e); - } - } - private record HashKey(byte[] hash) { @Override public boolean equals(Object o) { diff --git a/zeroj-backend-spi/src/main/java/org/zeroj/verifier/core/VerifierOrchestrator.java b/zeroj-backend-spi/src/main/java/org/zeroj/verifier/core/VerifierOrchestrator.java index 79f32963..6d2317ee 100644 --- a/zeroj-backend-spi/src/main/java/org/zeroj/verifier/core/VerifierOrchestrator.java +++ b/zeroj-backend-spi/src/main/java/org/zeroj/verifier/core/VerifierOrchestrator.java @@ -3,6 +3,7 @@ import org.zeroj.api.VerificationMaterial; import org.zeroj.api.VerificationResult; import org.zeroj.api.ZkProofEnvelope; +import org.zeroj.backend.spi.EnvelopeBinding; import org.zeroj.backend.spi.VerificationKeyRegistry; import org.zeroj.backend.spi.ZkVerifier; @@ -12,7 +13,8 @@ * Routes proof verification requests to the correct backend based on proof system and curve. * *

This is the main entry point for verifying proofs. It resolves the verification key - * from the registry, finds the appropriate backend, and delegates verification.

+ * from the registry, checks envelope-to-material binding (ADR-0067), finds the appropriate + * backend, and delegates verification.

*/ public class VerifierOrchestrator { @@ -29,12 +31,25 @@ public VerifierOrchestrator(VerifierRegistry registry, VerificationKeyRegistry v * *

Steps:

*
    + *
  1. Validate envelope presence and version
  2. *
  3. Resolve the verification key from the VK registry
  4. + *
  5. Validate envelope-to-material binding (proof system, curve, circuit id, VK hash)
  6. *
  7. Find a backend that supports the proof's system + curve
  8. *
  9. Delegate cryptographic verification to the backend
  10. *
*/ public VerificationResult verify(ZkProofEnvelope envelope) { + if (envelope == null) { + return VerificationResult.error( + VerificationResult.ReasonCode.MALFORMED_ENVELOPE, + "Proof envelope must not be null"); + } + if (envelope.version() < 1 || envelope.version() > ZkProofEnvelope.currentVersion()) { + return VerificationResult.error( + VerificationResult.ReasonCode.MALFORMED_ENVELOPE, + "Unsupported proof envelope version: " + envelope.version()); + } + // Resolve VK var material = vkRegistry.lookup(envelope.vkRef()); if (material.isEmpty()) { @@ -50,6 +65,11 @@ public VerificationResult verify(ZkProofEnvelope envelope) { * Verify a proof envelope with an explicitly provided verification material. */ public VerificationResult verify(ZkProofEnvelope envelope, VerificationMaterial material) { + var bindingError = EnvelopeBinding.validateBinding(envelope, material); + if (bindingError.isPresent()) { + return bindingError.get(); + } + // Find backend var verifier = registry.find(envelope.proofSystem(), envelope.curve()); if (verifier.isEmpty()) { diff --git a/zeroj-backend-spi/src/main/java/org/zeroj/verifier/core/VerifierRegistry.java b/zeroj-backend-spi/src/main/java/org/zeroj/verifier/core/VerifierRegistry.java index f0958e80..54a91f7d 100644 --- a/zeroj-backend-spi/src/main/java/org/zeroj/verifier/core/VerifierRegistry.java +++ b/zeroj-backend-spi/src/main/java/org/zeroj/verifier/core/VerifierRegistry.java @@ -4,16 +4,20 @@ import org.zeroj.api.ProofSystemId; import org.zeroj.backend.spi.ZkVerifier; -import java.util.*; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.ServiceLoader; +import java.util.concurrent.CopyOnWriteArrayList; /** - * Registry of available verification backends. + * Thread-safe registry of available verification backends. * *

Backends can be registered manually or discovered via {@link java.util.ServiceLoader}.

*/ public class VerifierRegistry { - private final List verifiers = new ArrayList<>(); + private final List verifiers = new CopyOnWriteArrayList<>(); /** * Create a registry that auto-discovers backends via ServiceLoader. @@ -53,9 +57,9 @@ public Optional find(ProofSystemId proofSystem, CurveId curve) { } /** - * List all registered backends. + * List all registered backends as an immutable snapshot. */ public List all() { - return Collections.unmodifiableList(verifiers); + return List.copyOf(verifiers); } } diff --git a/zeroj-backend-spi/src/test/java/org/zeroj/verifier/core/VerifierCoreTest.java b/zeroj-backend-spi/src/test/java/org/zeroj/verifier/core/VerifierCoreTest.java index 6a497b49..b7125674 100644 --- a/zeroj-backend-spi/src/test/java/org/zeroj/verifier/core/VerifierCoreTest.java +++ b/zeroj-backend-spi/src/test/java/org/zeroj/verifier/core/VerifierCoreTest.java @@ -149,8 +149,117 @@ void orchestrator_invalidProofPropagated() { assertFalse(result.proofValid()); } + @Test + void orchestrator_rejectsMismatchedCircuitIdBeforeCallingBackend() { + var registry = VerifierRegistry.empty(); + registry.register(failingIfCalledVerifier(ProofSystemId.GROTH16, CurveId.BLS12_381)); + var vkRegistry = new InMemoryVerificationKeyRegistry(); + var material = VerificationMaterial.of("vk-a".getBytes(), ProofSystemId.GROTH16, + CurveId.BLS12_381, new CircuitId("circuit-a")); + vkRegistry.register(material); + + var orchestrator = new VerifierOrchestrator(registry, vkRegistry); + var envelope = ZkProofEnvelope.builder() + .proofSystem(ProofSystemId.GROTH16) + .curve(CurveId.BLS12_381) + .circuitId(new CircuitId("circuit-b")) + .proofBytes(new byte[]{1, 2, 3}) + .publicInputs(new PublicInputs(List.of(BigInteger.ONE))) + .vkRef(new VerificationKeyRef.ById("circuit-a")) + .build(); + + var result = orchestrator.verify(envelope); + assertFalse(result.proofValid()); + assertEquals(VerificationResult.ReasonCode.VK_MISMATCH, result.reasonCode().orElse(null)); + } + + @Test + void orchestrator_rejectsMismatchedByHashAndSpoofedMaterialHash() { + var registry = VerifierRegistry.empty(); + registry.register(failingIfCalledVerifier(ProofSystemId.GROTH16, CurveId.BLS12_381)); + var vkRegistry = new InMemoryVerificationKeyRegistry(); + var orchestrator = new VerifierOrchestrator(registry, vkRegistry); + + var material = VerificationMaterial.of("vk-a".getBytes(), ProofSystemId.GROTH16, + CurveId.BLS12_381, new CircuitId("test")); + var wrongHashEnvelope = ZkProofEnvelope.builder() + .proofSystem(ProofSystemId.GROTH16) + .curve(CurveId.BLS12_381) + .circuitId(new CircuitId("test")) + .proofBytes(new byte[]{1}) + .publicInputs(new PublicInputs(List.of(BigInteger.ONE))) + .vkRef(new VerificationKeyRef.ByHash(new byte[32])) + .build(); + + var wrongHashResult = orchestrator.verify(wrongHashEnvelope, material); + assertEquals(VerificationResult.ReasonCode.VK_MISMATCH, wrongHashResult.reasonCode().orElse(null)); + + var spoofedMaterial = new VerificationMaterial( + "vk-a".getBytes(), ProofSystemId.GROTH16, CurveId.BLS12_381, + new CircuitId("test"), java.util.Optional.of(new byte[32])); + var spoofedResult = orchestrator.verify( + makeEnvelope(ProofSystemId.GROTH16, CurveId.BLS12_381), spoofedMaterial); + assertEquals(VerificationResult.ReasonCode.VK_MISMATCH, spoofedResult.reasonCode().orElse(null)); + } + + @Test + void orchestrator_rejectsUnsupportedVersionAndAllowsEmptyPublicInputs() { + var registry = VerifierRegistry.empty(); + registry.register(fakeVerifier(ProofSystemId.BBS, CurveId.BLS12_381, true)); + var vkRegistry = new InMemoryVerificationKeyRegistry(); + var orchestrator = new VerifierOrchestrator(registry, vkRegistry); + var material = VerificationMaterial.of(new byte[96], ProofSystemId.BBS, + CurveId.BLS12_381, new CircuitId("bbs-circuit")); + + var badVersion = ZkProofEnvelope.builder() + .version(99) + .proofSystem(ProofSystemId.BBS) + .curve(CurveId.BLS12_381) + .circuitId(new CircuitId("bbs-circuit")) + .proofBytes(new byte[]{1}) + .publicInputs(new PublicInputs(List.of())) + .vkRef(new VerificationKeyRef.ById("issuer-key")) + .build(); + assertEquals(VerificationResult.ReasonCode.MALFORMED_ENVELOPE, + orchestrator.verify(badVersion, material).reasonCode().orElse(null)); + + var emptyPublicInputs = ZkProofEnvelope.builder() + .proofSystem(ProofSystemId.BBS) + .curve(CurveId.BLS12_381) + .circuitId(new CircuitId("bbs-circuit")) + .proofBytes(new byte[]{1}) + .publicInputs(new PublicInputs(List.of())) + .vkRef(new VerificationKeyRef.ById("issuer-key")) + .build(); + assertTrue(orchestrator.verify(emptyPublicInputs, material).proofValid()); + } + + @Test + void vkRegistry_rejectsSpoofedVkHashOnRegister() { + var vkRegistry = new InMemoryVerificationKeyRegistry(); + var spoofed = new VerificationMaterial( + "real-vk".getBytes(), ProofSystemId.GROTH16, CurveId.BLS12_381, + new CircuitId("test"), java.util.Optional.of(new byte[32])); + + assertThrows(IllegalArgumentException.class, () -> vkRegistry.register(spoofed)); + } + // --- Helpers --- + private static ZkVerifier failingIfCalledVerifier(ProofSystemId ps, CurveId curve) { + return new ZkVerifier() { + @Override + public VerificationResult verify(ZkProofEnvelope e, VerificationMaterial m) { + throw new AssertionError("backend must not be called when binding fails"); + } + + @Override + public BackendDescriptor descriptor() { + return new BackendDescriptor(ps, curve, "guard-" + ps + "-" + curve); + } + }; + } + private static ZkVerifier fakeVerifier(ProofSystemId ps, CurveId curve, boolean valid) { return new ZkVerifier() { @Override diff --git a/zeroj-bbs/src/main/java/org/zeroj/bbs/verifier/BbsZkVerifier.java b/zeroj-bbs/src/main/java/org/zeroj/bbs/verifier/BbsZkVerifier.java index 26c43bcf..ba11a009 100644 --- a/zeroj-bbs/src/main/java/org/zeroj/bbs/verifier/BbsZkVerifier.java +++ b/zeroj-bbs/src/main/java/org/zeroj/bbs/verifier/BbsZkVerifier.java @@ -6,14 +6,23 @@ import org.zeroj.api.VerificationResult; import org.zeroj.api.ZkProofEnvelope; import org.zeroj.backend.spi.BackendDescriptor; +import org.zeroj.backend.spi.EnvelopeBinding; import org.zeroj.backend.spi.ZkVerifier; import org.zeroj.bbs.BbsCiphersuite; +import org.zeroj.bbs.BbsException; import org.zeroj.bbs.BbsPresentationCodec; import org.zeroj.bbs.BbsPublicKey; import org.zeroj.bbs.BbsService; +import java.util.Objects; + /** * ZeroJ verifier adapter for CFRG BBS draft-10 presentations. + * + *

Authenticated BBS disclosures (revealed messages, header, and presentation header) are carried + * inside the canonical CBOR presentation in {@code envelope.proofBytes()}, not in the SNARK-oriented + * {@code envelope.publicInputs()} field-element vector. Consequently, {@code envelope.publicInputs()} + * must be empty.

*/ public final class BbsZkVerifier implements ZkVerifier { private static final BackendDescriptor DESCRIPTOR = @@ -26,29 +35,43 @@ public BbsZkVerifier() { } public BbsZkVerifier(BbsService service) { - this.service = java.util.Objects.requireNonNull(service, "BBS service required"); + this.service = Objects.requireNonNull(service, "BBS service required"); } @Override public VerificationResult verify(ZkProofEnvelope envelope, VerificationMaterial material) { - try { - if (envelope.proofSystem() != ProofSystemId.BBS || material.proofSystemId() != ProofSystemId.BBS) { - return VerificationResult.error( - VerificationResult.ReasonCode.UNSUPPORTED_PROOF_SYSTEM, - "BBS verifier only supports proof system bbs"); - } - if (envelope.curve() != CurveId.BLS12_381 || material.curveId() != CurveId.BLS12_381) { - return VerificationResult.error( - VerificationResult.ReasonCode.UNSUPPORTED_CURVE, - "BBS verifier only supports BLS12-381"); - } - if (envelope.proofFormat().isPresent() - && !BbsCiphersuite.DEFAULT_PROOF_FORMAT.equals(envelope.proofFormat().get())) { - return VerificationResult.error( - VerificationResult.ReasonCode.MALFORMED_ENVELOPE, - "Unsupported BBS proof format: " + envelope.proofFormat().get()); - } + if (envelope == null) { + return VerificationResult.error( + VerificationResult.ReasonCode.MALFORMED_ENVELOPE, + "Proof envelope must not be null"); + } + if (envelope.proofSystem() != ProofSystemId.BBS) { + return VerificationResult.error( + VerificationResult.ReasonCode.UNSUPPORTED_PROOF_SYSTEM, + "BBS verifier only supports proof system bbs"); + } + if (envelope.curve() != CurveId.BLS12_381) { + return VerificationResult.error( + VerificationResult.ReasonCode.UNSUPPORTED_CURVE, + "BBS verifier only supports BLS12-381"); + } + var bindingError = EnvelopeBinding.validateBinding(envelope, material); + if (bindingError.isPresent()) { + return bindingError.get(); + } + if (envelope.proofFormat().isPresent() + && !BbsCiphersuite.DEFAULT_PROOF_FORMAT.equals(envelope.proofFormat().get())) { + return VerificationResult.error( + VerificationResult.ReasonCode.MALFORMED_ENVELOPE, + "Unsupported BBS proof format: " + envelope.proofFormat().get()); + } + if (envelope.publicInputs().size() != 0) { + return VerificationResult.error( + VerificationResult.ReasonCode.INVALID_PUBLIC_INPUTS, + "BBS proof envelopes carry disclosures in the CBOR presentation; publicInputs must be empty"); + } + try { var presentation = BbsPresentationCodec.decode(envelope.proofBytes()); BbsCiphersuite ciphersuite = presentation.proof().ciphersuite(); BbsService verifierService = service.provider().ciphersuite() == ciphersuite @@ -58,6 +81,10 @@ public VerificationResult verify(ZkProofEnvelope envelope, VerificationMaterial boolean valid = verifierService.verifyPresentation(publicKey, presentation); return valid ? VerificationResult.cryptoValid() : VerificationResult.proofInvalid("BBS proof verification failed"); + } catch (BbsException | IllegalArgumentException e) { + return VerificationResult.error( + VerificationResult.ReasonCode.MALFORMED_ENVELOPE, + "Malformed BBS presentation or public key: " + e.getMessage()); } catch (Exception e) { return VerificationResult.error( VerificationResult.ReasonCode.INTERNAL_ERROR, diff --git a/zeroj-bbs/src/test/java/org/zeroj/bbs/BbsServiceTest.java b/zeroj-bbs/src/test/java/org/zeroj/bbs/BbsServiceTest.java index 62f5c518..702465c4 100644 --- a/zeroj-bbs/src/test/java/org/zeroj/bbs/BbsServiceTest.java +++ b/zeroj-bbs/src/test/java/org/zeroj/bbs/BbsServiceTest.java @@ -240,6 +240,82 @@ void zkVerifierAcceptsShake256PresentationEnvelope() { assertTrue(result.proofValid(), result.message().orElse("")); } + @Test + void zkVerifierEnforcesMaterialBindingAndClassifiesMalformedInput() throws Exception { + BbsService service = BbsService.pureJava(); + BbsKeyPair keyPair = service.keyPair(bytes("012345678901234567890123456789ef"), bytes("issuer-key")); + List messages = List.of(bytes("given:Alice"), bytes("age:20")); + byte[] header = bytes("credential-v1"); + BbsSignature signature = service.sign(keyPair.secretKey(), keyPair.publicKey(), messages, header); + BbsPresentation presentation = service.derivePresentation( + keyPair.publicKey(), signature, messages, header, bytes("verifier-nonce"), new int[]{0}); + byte[] pkBytes = keyPair.publicKey().bytes(); + byte[] pkHash = java.security.MessageDigest.getInstance("SHA-256").digest(pkBytes); + byte[] proofBytes = BbsPresentationCodec.encode(presentation); + + VerificationMaterial material = VerificationMaterial.of( + pkBytes, ProofSystemId.BBS, CurveId.BLS12_381, new CircuitId("bbs-a")); + BbsZkVerifier verifier = new BbsZkVerifier(service); + + // Matching ByHash succeeds + ZkProofEnvelope matchingHash = ZkProofEnvelope.builder() + .proofSystem(ProofSystemId.BBS).curve(CurveId.BLS12_381) + .circuitId(new CircuitId("bbs-a")).proofBytes(proofBytes) + .publicInputs(new PublicInputs(List.of())) + .vkRef(new VerificationKeyRef.ByHash(pkHash)) + .proofFormat(BbsCiphersuite.DEFAULT_PROOF_FORMAT).build(); + assertTrue(verifier.verify(matchingHash, material).proofValid()); + + // Mismatched circuitId -> VK_MISMATCH + ZkProofEnvelope wrongCircuit = ZkProofEnvelope.builder() + .proofSystem(ProofSystemId.BBS).curve(CurveId.BLS12_381) + .circuitId(new CircuitId("bbs-other")).proofBytes(proofBytes) + .publicInputs(new PublicInputs(List.of())) + .vkRef(new VerificationKeyRef.ByHash(pkHash)) + .proofFormat(BbsCiphersuite.DEFAULT_PROOF_FORMAT).build(); + assertEquals(org.zeroj.api.VerificationResult.ReasonCode.VK_MISMATCH, + verifier.verify(wrongCircuit, material).reasonCode().orElse(null)); + + // Mismatched ByHash -> VK_MISMATCH + ZkProofEnvelope wrongHash = ZkProofEnvelope.builder() + .proofSystem(ProofSystemId.BBS).curve(CurveId.BLS12_381) + .circuitId(new CircuitId("bbs-a")).proofBytes(proofBytes) + .publicInputs(new PublicInputs(List.of())) + .vkRef(new VerificationKeyRef.ByHash(new byte[32])) + .proofFormat(BbsCiphersuite.DEFAULT_PROOF_FORMAT).build(); + assertEquals(org.zeroj.api.VerificationResult.ReasonCode.VK_MISMATCH, + verifier.verify(wrongHash, material).reasonCode().orElse(null)); + + // Malformed CBOR presentation -> MALFORMED_ENVELOPE (not INTERNAL_ERROR) + ZkProofEnvelope malformedCbor = ZkProofEnvelope.builder() + .proofSystem(ProofSystemId.BBS).curve(CurveId.BLS12_381) + .circuitId(new CircuitId("bbs-a")).proofBytes(new byte[]{0x01, 0x02, 0x03}) + .publicInputs(new PublicInputs(List.of())) + .vkRef(new VerificationKeyRef.ByHash(pkHash)) + .proofFormat(BbsCiphersuite.DEFAULT_PROOF_FORMAT).build(); + assertEquals(org.zeroj.api.VerificationResult.ReasonCode.MALFORMED_ENVELOPE, + verifier.verify(malformedCbor, material).reasonCode().orElse(null)); + + // Non-empty publicInputs vector must be rejected on both direct and orchestrated BBS calls + ZkProofEnvelope nonEmptyPublicInputs = ZkProofEnvelope.builder() + .proofSystem(ProofSystemId.BBS).curve(CurveId.BLS12_381) + .circuitId(new CircuitId("bbs-a")).proofBytes(proofBytes) + .publicInputs(new PublicInputs(List.of(java.math.BigInteger.ONE))) + .vkRef(new VerificationKeyRef.ByHash(pkHash)) + .proofFormat(BbsCiphersuite.DEFAULT_PROOF_FORMAT).build(); + assertEquals(org.zeroj.api.VerificationResult.ReasonCode.INVALID_PUBLIC_INPUTS, + verifier.verify(nonEmptyPublicInputs, material).reasonCode().orElse(null)); + + var registry = org.zeroj.verifier.core.VerifierRegistry.empty(); + registry.register(verifier); + var vkRegistry = new org.zeroj.backend.spi.InMemoryVerificationKeyRegistry(); + vkRegistry.register(material); + var orchestrator = new org.zeroj.verifier.core.VerifierOrchestrator(registry, vkRegistry); + assertTrue(orchestrator.verify(matchingHash).proofValid()); + assertEquals(org.zeroj.api.VerificationResult.ReasonCode.INVALID_PUBLIC_INPUTS, + orchestrator.verify(nonEmptyPublicInputs).reasonCode().orElse(null)); + } + @Test void signingAndProofGenerationUseSecretScalarProviderBoundary() { var bls = new CountingBlsProvider(Bls12381Providers.pureJava()); diff --git a/zeroj-codec/src/main/java/org/zeroj/codec/CborEnvelopeCodec.java b/zeroj-codec/src/main/java/org/zeroj/codec/CborEnvelopeCodec.java index 1d623336..8ba84940 100644 --- a/zeroj-codec/src/main/java/org/zeroj/codec/CborEnvelopeCodec.java +++ b/zeroj-codec/src/main/java/org/zeroj/codec/CborEnvelopeCodec.java @@ -1,36 +1,50 @@ package org.zeroj.codec; -import co.nstant.in.cbor.CborBuilder; -import co.nstant.in.cbor.CborDecoder; -import co.nstant.in.cbor.CborEncoder; -import co.nstant.in.cbor.CborException; -import co.nstant.in.cbor.model.*; -import org.zeroj.api.*; - -import java.io.ByteArrayInputStream; +import org.zeroj.api.CircuitId; +import org.zeroj.api.CurveId; +import org.zeroj.api.ProofSystemId; +import org.zeroj.api.PublicInputs; +import org.zeroj.api.VerificationKeyRef; +import org.zeroj.api.ZkProofEnvelope; + import java.io.ByteArrayOutputStream; import java.math.BigInteger; +import java.nio.ByteBuffer; +import java.nio.CharBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; import java.util.ArrayList; -import java.util.HashMap; +import java.util.Arrays; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.Objects; /** - * CBOR serialization and deserialization for {@link ZkProofEnvelope}. + * Strict deterministic CBOR serialization and deserialization for {@link ZkProofEnvelope} + * (ADR-0067, RFC 8949 §4.2 & §10). * - *

Uses a deterministic CBOR map with integer keys for compact encoding:

+ *

Uses a deterministic CBOR map with ascending integer keys:

*
- * 1: version (uint)
+ * 1: version (uint, 1..currentVersion)
  * 2: proofSystem (text)
  * 3: curve (text)
  * 4: circuitId (text)
- * 5: proofBytes (bstr)
- * 6: publicInputs (array of bstr — BigInteger.toByteArray())
- * 7: vkRef (tagged: 0x01 + hash | 0x02 + id)
- * 8: domainTag (text, optional)
- * 9: metadata (map, optional)
- * 10: proofFormat (text, optional)
+ * 5: proofBytes (bstr, non-empty)
+ * 6: publicInputs (array of minimal non-negative BigInteger.toByteArray() bstr)
+ * 7: vkRef (2-element array: [1, sha256-bstr] | [2, id-text])
+ * 8: domainTag (text, optional — omitted when empty)
+ * 9: metadata (map of text->text sorted in RFC 8949 §4.2.1 bytewise order, optional — omitted when empty)
+ * 10: proofFormat (text, optional — omitted when absent)
  * 
+ * + *

Local non-wire fields ({@code proofUri}, {@code proofHash}, {@code createdAt}, + * {@code producerId}) are not carried in the CBOR wire encoding. Encoding validates UTF-16 input + * strictly (rejecting unpaired surrogates) and emits shortest-form definite-length CBOR directly in + * RFC 8949 §4.2.1 unsigned bytewise key order. Decoding parses sequentially without recursion and + * checks schema types, lengths, and collection counts against remaining input bytes before + * allocating collections.

*/ public final class CborEnvelopeCodec { @@ -40,62 +54,220 @@ public final class CborEnvelopeCodec { private static final int MAX_PUBLIC_INPUT_BYTES = 128; private static final int SHA256_BYTES = 32; private static final int MAX_TEXT_BYTES = 256; + private static final int MAX_METADATA_ENTRIES = 64; + + private static final int MAJOR_UINT = 0; + private static final int MAJOR_BSTR = 2; + private static final int MAJOR_TEXT = 3; + private static final int MAJOR_ARRAY = 4; + private static final int MAJOR_MAP = 5; private CborEnvelopeCodec() {} /** - * Serialize a proof envelope to CBOR bytes. + * Serialize a proof envelope to canonical deterministic CBOR bytes (RFC 8949 §4.2). */ public static byte[] encode(ZkProofEnvelope envelope) { - try { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - new CborEncoder(baos).encode(new CborBuilder() - .addMap() - .put(new UnsignedInteger(1), new UnsignedInteger(envelope.version())) - .put(new UnsignedInteger(2), new UnicodeString(envelope.proofSystem().value())) - .put(new UnsignedInteger(3), new UnicodeString(envelope.curve().value())) - .put(new UnsignedInteger(4), new UnicodeString(envelope.circuitId().value())) - .put(new UnsignedInteger(5), new ByteString(envelope.proofBytes())) - .put(new UnsignedInteger(6), encodePublicInputs(envelope.publicInputs())) - .put(new UnsignedInteger(7), encodeVkRef(envelope.vkRef())) - .end() - .build()); - return baos.toByteArray(); - } catch (CborException e) { - throw new CodecException("Failed to encode envelope to CBOR", e); + Objects.requireNonNull(envelope, "envelope must not be null"); + if (envelope.version() < 1 || envelope.version() > ZkProofEnvelope.currentVersion()) { + throw new CodecException("Unsupported envelope version: " + envelope.version()); + } + byte[] proofSystemBytes = encodeNonBlankUtf8(envelope.proofSystem().value(), "proofSystem"); + byte[] curveBytes = encodeNonBlankUtf8(envelope.curve().value(), "curve"); + byte[] circuitIdBytes = encodeNonBlankUtf8(envelope.circuitId().value(), "circuitId"); + byte[] proofBytes = envelope.proofBytes(); + if (proofBytes.length == 0 || proofBytes.length > MAX_PROOF_BYTES) { + throw new CodecException("Invalid proofBytes length: " + proofBytes.length); + } + + List publicInputBytes = encodePublicInputList(envelope.publicInputs()); + boolean hasDomainTag = !envelope.domainTag().isEmpty(); + byte[] domainTagBytes = hasDomainTag ? encodeStrictUtf8(envelope.domainTag(), "domainTag") : null; + boolean hasMetadata = !envelope.metadata().isEmpty(); + List metadataEntries = hasMetadata ? encodeMetadataEntries(envelope.metadata()) : null; + boolean hasProofFormat = envelope.proofFormat().isPresent(); + byte[] proofFormatBytes = hasProofFormat + ? encodeNonBlankUtf8(envelope.proofFormat().orElseThrow(), "proofFormat") + : null; + + int mapSize = 7 + (hasDomainTag ? 1 : 0) + (hasMetadata ? 1 : 0) + (hasProofFormat ? 1 : 0); + + ByteArrayOutputStream out = new ByteArrayOutputStream(); + writeHead(out, MAJOR_MAP, mapSize); + + // 1: version + writeHead(out, MAJOR_UINT, 1); + writeHead(out, MAJOR_UINT, envelope.version()); + + // 2: proofSystem + writeHead(out, MAJOR_UINT, 2); + writeBytes(out, MAJOR_TEXT, proofSystemBytes); + + // 3: curve + writeHead(out, MAJOR_UINT, 3); + writeBytes(out, MAJOR_TEXT, curveBytes); + + // 4: circuitId + writeHead(out, MAJOR_UINT, 4); + writeBytes(out, MAJOR_TEXT, circuitIdBytes); + + // 5: proofBytes + writeHead(out, MAJOR_UINT, 5); + writeBytes(out, MAJOR_BSTR, proofBytes); + + // 6: publicInputs + writeHead(out, MAJOR_UINT, 6); + writeHead(out, MAJOR_ARRAY, publicInputBytes.size()); + for (byte[] input : publicInputBytes) { + writeBytes(out, MAJOR_BSTR, input); } + + // 7: vkRef + writeHead(out, MAJOR_UINT, 7); + writeHead(out, MAJOR_ARRAY, 2); + switch (envelope.vkRef()) { + case VerificationKeyRef.ByHash h -> { + byte[] hash = h.hash(); + if (hash.length != SHA256_BYTES) { + throw new CodecException("VK hash ref must be a SHA-256 hash"); + } + writeHead(out, MAJOR_UINT, 1); + writeBytes(out, MAJOR_BSTR, hash); + } + case VerificationKeyRef.ById id -> { + byte[] idBytes = encodeNonBlankUtf8(id.id(), "vkRef.id"); + writeHead(out, MAJOR_UINT, 2); + writeBytes(out, MAJOR_TEXT, idBytes); + } + } + + // 8: domainTag (optional) + if (hasDomainTag) { + writeHead(out, MAJOR_UINT, 8); + writeBytes(out, MAJOR_TEXT, domainTagBytes); + } + + // 9: metadata (optional, sorted by RFC 8949 §4.2.1 encoded key bytes) + if (hasMetadata) { + writeHead(out, MAJOR_UINT, 9); + writeHead(out, MAJOR_MAP, metadataEntries.size()); + for (MapEntryBytes entry : metadataEntries) { + writeBytes(out, MAJOR_TEXT, entry.keyUtf8()); + writeBytes(out, MAJOR_TEXT, entry.valueUtf8()); + } + } + + // 10: proofFormat (optional) + if (hasProofFormat) { + writeHead(out, MAJOR_UINT, 10); + writeBytes(out, MAJOR_TEXT, proofFormatBytes); + } + + byte[] encoded = out.toByteArray(); + if (encoded.length > MAX_CBOR_BYTES) { + throw new CodecException("Encoded CBOR envelope exceeds maximum size"); + } + return encoded; } /** - * Deserialize a proof envelope from CBOR bytes. + * Deserialize a strictly canonical CBOR proof envelope using bounded non-recursive parsing. */ public static ZkProofEnvelope decode(byte[] cbor) { + if (cbor == null || cbor.length == 0 || cbor.length > MAX_CBOR_BYTES) { + throw new CodecException("Invalid CBOR envelope size"); + } try { - if (cbor == null || cbor.length > MAX_CBOR_BYTES) { - throw new CodecException("CBOR envelope is too large"); - } - List items = CborDecoder.decode(cbor); - if (items.size() != 1 || !(items.getFirst() instanceof co.nstant.in.cbor.model.Map map)) { - throw new CodecException("CBOR envelope must be a map"); + Reader reader = new Reader(cbor); + int mapSize = reader.readBoundedArg(MAJOR_MAP, 7, 10, "CBOR envelope map"); + + int version = -1; + String proofSystem = null; + String curve = null; + String circuitId = null; + byte[] proofBytes = null; + PublicInputs publicInputs = null; + VerificationKeyRef vkRef = null; + String domainTag = null; + Map metadata = null; + String proofFormat = null; + + int prevKey = 0; + int requiredMask = 0; + for (int i = 0; i < mapSize; i++) { + int key = reader.readBoundedArg(MAJOR_UINT, 1, 10, "CBOR envelope map key"); + if (key <= prevKey) { + throw new CodecException("CBOR envelope map keys must be strictly ascending without duplicates"); + } + prevKey = key; + switch (key) { + case 1 -> { + version = reader.readBoundedArg( + MAJOR_UINT, 1, ZkProofEnvelope.currentVersion(), "envelope version"); + requiredMask |= 1 << 1; + } + case 2 -> { + proofSystem = requireNonBlank(reader.readStrictText(1, MAX_TEXT_BYTES, "proofSystem"), "proofSystem"); + requiredMask |= 1 << 2; + } + case 3 -> { + curve = requireNonBlank(reader.readStrictText(1, MAX_TEXT_BYTES, "curve"), "curve"); + requiredMask |= 1 << 3; + } + case 4 -> { + circuitId = requireNonBlank(reader.readStrictText(1, MAX_TEXT_BYTES, "circuitId"), "circuitId"); + requiredMask |= 1 << 4; + } + case 5 -> { + proofBytes = reader.readByteString(1, MAX_PROOF_BYTES, "proofBytes"); + requiredMask |= 1 << 5; + } + case 6 -> { + publicInputs = readPublicInputs(reader); + requiredMask |= 1 << 6; + } + case 7 -> { + vkRef = readVkRef(reader); + requiredMask |= 1 << 7; + } + case 8 -> domainTag = reader.readStrictText(1, MAX_TEXT_BYTES, "domainTag"); + case 9 -> metadata = readMetadata(reader); + case 10 -> proofFormat = requireNonBlank( + reader.readStrictText(1, MAX_TEXT_BYTES, "proofFormat"), "proofFormat"); + default -> throw new CodecException("Unknown CBOR envelope map key: " + key); + } } - int version = getUint(map, 1); - String proofSystem = getText(map, 2); - String curve = getText(map, 3); - String circuitId = getText(map, 4); - byte[] proofBytes = getBytes(map, 5, MAX_PROOF_BYTES); - PublicInputs publicInputs = decodePublicInputs(getArray(map, 6)); - VerificationKeyRef vkRef = decodeVkRef(getArray(map, 7)); + if (requiredMask != 0b11111110) { + throw new CodecException("Missing required CBOR envelope map key"); + } + if (reader.remaining() != 0) { + throw new CodecException("Trailing bytes after CBOR envelope: " + reader.remaining()); + } - return ZkProofEnvelope.builder() + ZkProofEnvelope.Builder builder = ZkProofEnvelope.builder() .version(version) .proofSystem(ProofSystemId.fromValue(proofSystem)) .curve(CurveId.fromValue(curve)) .circuitId(new CircuitId(circuitId)) .proofBytes(proofBytes) .publicInputs(publicInputs) - .vkRef(vkRef) - .build(); + .vkRef(vkRef); + if (domainTag != null) { + builder.domainTag(domainTag); + } + if (metadata != null) { + builder.metadata(metadata); + } + if (proofFormat != null) { + builder.proofFormat(proofFormat); + } + + ZkProofEnvelope envelope = builder.build(); + if (!Arrays.equals(cbor, encode(envelope))) { + throw new CodecException("CBOR proof envelope is not canonically encoded"); + } + return envelope; } catch (CodecException e) { throw e; } catch (Exception e) { @@ -105,134 +277,266 @@ public static ZkProofEnvelope decode(byte[] cbor) { // --- Encoding helpers --- - private static Array encodePublicInputs(PublicInputs inputs) { - Array array = new Array(); + private static List encodePublicInputList(PublicInputs inputs) { + if (inputs.size() > MAX_PUBLIC_INPUTS) { + throw new CodecException("Too many public inputs in CBOR envelope"); + } + List encoded = new ArrayList<>(inputs.size()); for (BigInteger value : inputs.values()) { - array.add(new ByteString(value.toByteArray())); + if (value == null || value.signum() < 0) { + throw new CodecException("Public input must be non-negative"); + } + byte[] bytes = value.toByteArray(); + if (bytes.length > MAX_PUBLIC_INPUT_BYTES) { + throw new CodecException("Public input exceeds maximum byte length"); + } + encoded.add(bytes); } - return array; + return encoded; } - private static Array encodeVkRef(VerificationKeyRef ref) { - Array array = new Array(); - switch (ref) { - case VerificationKeyRef.ByHash h -> { - array.add(new UnsignedInteger(1)); - array.add(new ByteString(h.hash())); - } - case VerificationKeyRef.ById id -> { - array.add(new UnsignedInteger(2)); - array.add(new UnicodeString(id.id())); - } + private static List encodeMetadataEntries(Map metadata) { + if (metadata.size() > MAX_METADATA_ENTRIES) { + throw new CodecException("Too many metadata entries in CBOR envelope"); + } + List entries = new ArrayList<>(metadata.size()); + for (Map.Entry entry : metadata.entrySet()) { + byte[] keyUtf8 = encodeNonBlankUtf8(entry.getKey(), "metadata key"); + byte[] valueUtf8 = encodeStrictUtf8(entry.getValue(), "metadata value"); + entries.add(new MapEntryBytes(keyUtf8, valueUtf8)); } - return array; + // RFC 8949 §4.2.1 bytewise lexicographic order of encoded CBOR text keys: + // shorter UTF-8 byte length has a smaller CBOR length head; equal lengths compare unsigned UTF-8 bytes. + entries.sort((a, b) -> compareCanonicalTextBytes(a.keyUtf8(), b.keyUtf8())); + return entries; } - // --- Decoding helpers --- + private static int compareCanonicalTextBytes(byte[] a, byte[] b) { + int lenCmp = Integer.compare(a.length, b.length); + return lenCmp != 0 ? lenCmp : Arrays.compareUnsigned(a, b); + } - private static PublicInputs decodePublicInputs(Array array) { - if (array.getDataItems().size() > MAX_PUBLIC_INPUTS) { - throw new CodecException("Too many public inputs in CBOR envelope"); + private static byte[] encodeNonBlankUtf8(String text, String label) { + if (text == null || text.isBlank()) { + throw new CodecException("Invalid blank CBOR text value for " + label); } - List values = new ArrayList<>(); - for (DataItem item : array.getDataItems()) { - if (item instanceof ByteString bs) { - byte[] bytes = bs.getBytes(); - if (bytes == null || bytes.length == 0 || bytes.length > MAX_PUBLIC_INPUT_BYTES) { - throw new CodecException("Invalid public input byte length"); - } - BigInteger value = new BigInteger(bytes); - if (value.signum() < 0) { - throw new CodecException("Public input must be non-negative"); - } - values.add(value); - } else { - throw new CodecException("Public input must be a byte string"); + return encodeStrictUtf8(text, label); + } + + private static byte[] encodeStrictUtf8(String text, String label) { + if (text == null) { + throw new CodecException("Null CBOR text value for " + label); + } + try { + ByteBuffer bb = StandardCharsets.UTF_8.newEncoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .encode(CharBuffer.wrap(text)); + byte[] bytes = new byte[bb.remaining()]; + bb.get(bytes); + if (bytes.length > MAX_TEXT_BYTES) { + throw new CodecException("CBOR text value exceeds maximum length for " + label); } + return bytes; + } catch (CharacterCodingException e) { + throw new CodecException("Malformed Unicode text for " + label, e); } - return new PublicInputs(values); } - private static VerificationKeyRef decodeVkRef(Array array) { - List items = array.getDataItems(); - if (items.size() != 2) { - throw new CodecException("VK ref must be a 2-element array"); + private static void writeHead(ByteArrayOutputStream out, int majorType, int arg) { + if (arg < 0) { + throw new CodecException("Negative CBOR argument: " + arg); } - if (!(items.get(0) instanceof UnsignedInteger tagItem)) { - throw new CodecException("VK ref tag must be an unsigned integer"); + int prefix = majorType << 5; + if (arg < 24) { + out.write(prefix | arg); + } else if (arg <= 0xFF) { + out.write(prefix | 24); + out.write(arg); + } else if (arg <= 0xFFFF) { + out.write(prefix | 25); + out.write((arg >>> 8) & 0xFF); + out.write(arg & 0xFF); + } else { + out.write(prefix | 26); + out.write((arg >>> 24) & 0xFF); + out.write((arg >>> 16) & 0xFF); + out.write((arg >>> 8) & 0xFF); + out.write(arg & 0xFF); } - int tag = tagItem.getValue().intValueExact(); - return switch (tag) { - case 1 -> { - if (!(items.get(1) instanceof ByteString hashItem)) { - throw new CodecException("VK hash ref must be a byte string"); - } - byte[] hash = hashItem.getBytes(); - if (hash == null || hash.length != SHA256_BYTES) { - throw new CodecException("VK hash ref must be a SHA-256 hash"); - } - yield new VerificationKeyRef.ByHash(hash); + } + + private static void writeBytes(ByteArrayOutputStream out, int majorType, byte[] data) { + writeHead(out, majorType, data.length); + out.writeBytes(data); + } + + // --- Bounded non-recursive decoding helpers --- + + private static PublicInputs readPublicInputs(Reader reader) { + int count = reader.readBoundedArg(MAJOR_ARRAY, 0, MAX_PUBLIC_INPUTS, "publicInputs"); + // Each public input is a non-empty bstr (at least 2 bytes: 1-byte head + >=1 payload byte). + if ((long) count * 2L > reader.remaining()) { + throw new CodecException("Declared publicInputs count exceeds remaining CBOR bytes"); + } + List values = new ArrayList<>(count); + for (int i = 0; i < count; i++) { + byte[] bytes = reader.readByteString(1, MAX_PUBLIC_INPUT_BYTES, "publicInputs[" + i + "]"); + BigInteger value = new BigInteger(bytes); + if (value.signum() < 0) { + throw new CodecException("Public input must be non-negative"); } - case 2 -> { - if (!(items.get(1) instanceof UnicodeString idItem)) { - throw new CodecException("VK id ref must be text"); - } - String id = idItem.getString(); - if (id == null || id.isBlank() || id.getBytes(java.nio.charset.StandardCharsets.UTF_8).length > MAX_TEXT_BYTES) { - throw new CodecException("Invalid VK id ref"); - } - yield new VerificationKeyRef.ById(id); + if (!Arrays.equals(bytes, value.toByteArray())) { + throw new CodecException("Public input byte encoding must be minimal"); } + values.add(value); + } + return new PublicInputs(values); + } + + private static VerificationKeyRef readVkRef(Reader reader) { + reader.readBoundedArg(MAJOR_ARRAY, 2, 2, "vkRef"); + int tag = reader.readBoundedArg(MAJOR_UINT, 1, 2, "vkRef tag"); + return switch (tag) { + case 1 -> new VerificationKeyRef.ByHash( + reader.readByteString(SHA256_BYTES, SHA256_BYTES, "vkRef hash")); + case 2 -> new VerificationKeyRef.ById( + requireNonBlank(reader.readStrictText(1, MAX_TEXT_BYTES, "vkRef id"), "vkRef id")); default -> throw new CodecException("Unknown VK ref tag: " + tag); }; } - private static int getUint(co.nstant.in.cbor.model.Map map, int key) { - DataItem item = map.get(new UnsignedInteger(key)); - if (item == null) throw new CodecException("Missing CBOR map key: " + key); - if (!(item instanceof UnsignedInteger number)) { - throw new CodecException("CBOR map key " + key + " must be an unsigned integer"); + private static Map readMetadata(Reader reader) { + int count = reader.readBoundedArg(MAJOR_MAP, 1, MAX_METADATA_ENTRIES, "metadata"); + // Each metadata entry has a non-empty key (>= 2 bytes) and a text value (>= 1 byte). + if ((long) count * 3L > reader.remaining()) { + throw new CodecException("Declared metadata count exceeds remaining CBOR bytes"); } - try { - return number.getValue().intValueExact(); - } catch (ArithmeticException e) { - throw new CodecException("CBOR map key " + key + " integer is too large", e); + Map result = new LinkedHashMap<>(count); + byte[] prevKeyBytes = null; + for (int i = 0; i < count; i++) { + byte[] keyBytes = reader.readTextBytes(1, MAX_TEXT_BYTES, "metadata key"); + if (prevKeyBytes != null && compareCanonicalTextBytes(keyBytes, prevKeyBytes) <= 0) { + throw new CodecException("CBOR metadata keys must be strictly ascending in RFC 8949 canonical order"); + } + prevKeyBytes = keyBytes; + String key = requireNonBlank(decodeStrictUtf8(keyBytes, "metadata key"), "metadata key"); + String value = reader.readStrictText(0, MAX_TEXT_BYTES, "metadata value"); + result.put(key, value); } + return result; } - private static String getText(co.nstant.in.cbor.model.Map map, int key) { - DataItem item = map.get(new UnsignedInteger(key)); - if (item == null) throw new CodecException("Missing CBOR map key: " + key); - if (!(item instanceof UnicodeString textItem)) { - throw new CodecException("CBOR map key " + key + " must be text"); - } - String value = textItem.getString(); - if (value == null || value.isBlank() - || value.getBytes(java.nio.charset.StandardCharsets.UTF_8).length > MAX_TEXT_BYTES) { - throw new CodecException("Invalid CBOR text value for key: " + key); + private static String requireNonBlank(String value, String label) { + if (value == null || value.isBlank()) { + throw new CodecException("Invalid blank CBOR text value for " + label); } return value; } - private static byte[] getBytes(co.nstant.in.cbor.model.Map map, int key, int maxLength) { - DataItem item = map.get(new UnsignedInteger(key)); - if (item == null) throw new CodecException("Missing CBOR map key: " + key); - if (!(item instanceof ByteString bytesItem)) { - throw new CodecException("CBOR map key " + key + " must be a byte string"); - } - byte[] bytes = bytesItem.getBytes(); - if (bytes == null || bytes.length == 0 || bytes.length > maxLength) { - throw new CodecException("Invalid CBOR byte string length for key: " + key); + private static String decodeStrictUtf8(byte[] bytes, String label) { + try { + return StandardCharsets.UTF_8.newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(bytes)) + .toString(); + } catch (CharacterCodingException e) { + throw new CodecException("Invalid UTF-8 text in CBOR field: " + label, e); } - return bytes; } - private static Array getArray(co.nstant.in.cbor.model.Map map, int key) { - DataItem item = map.get(new UnsignedInteger(key)); - if (item == null) throw new CodecException("Missing CBOR map key: " + key); - if (!(item instanceof Array array)) { - throw new CodecException("CBOR map key " + key + " must be an array"); + private record MapEntryBytes(byte[] keyUtf8, byte[] valueUtf8) {} + + /** + * Minimal, non-recursive, shortest-form definite-length CBOR byte reader (RFC 8949 §4.2 & §10). + */ + private static final class Reader { + private final byte[] data; + private int pos; + + Reader(byte[] data) { + this.data = data; + } + + int remaining() { + return data.length - pos; + } + + int readBoundedArg(int expectedMajor, int min, int max, String label) { + if (remaining() < 1) { + throw new CodecException("Truncated CBOR while reading " + label); + } + int initial = data[pos++] & 0xFF; + int major = initial >>> 5; + int ai = initial & 0x1F; + if (major != expectedMajor) { + throw new CodecException("Unexpected CBOR major type " + major + " for " + label); + } + if (ai == 31) { + throw new CodecException("Indefinite-length CBOR is forbidden for " + label); + } + long value; + if (ai < 24) { + value = ai; + } else if (ai == 24) { + if (remaining() < 1) { + throw new CodecException("Truncated 1-byte CBOR argument for " + label); + } + value = data[pos++] & 0xFFL; + if (value < 24) { + throw new CodecException("Non-minimal CBOR integer encoding for " + label); + } + } else if (ai == 25) { + if (remaining() < 2) { + throw new CodecException("Truncated 2-byte CBOR argument for " + label); + } + value = ((data[pos++] & 0xFFL) << 8) | (data[pos++] & 0xFFL); + if (value < 256) { + throw new CodecException("Non-minimal CBOR integer encoding for " + label); + } + } else if (ai == 26) { + if (remaining() < 4) { + throw new CodecException("Truncated 4-byte CBOR argument for " + label); + } + value = ((data[pos++] & 0xFFL) << 24) + | ((data[pos++] & 0xFFL) << 16) + | ((data[pos++] & 0xFFL) << 8) + | (data[pos++] & 0xFFL); + if (value < 65536) { + throw new CodecException("Non-minimal CBOR integer encoding for " + label); + } + } else { + throw new CodecException("Unsupported CBOR additional info " + ai + " for " + label); + } + if (value < min || value > max) { + throw new CodecException("CBOR value " + value + " out of bounds [" + min + ", " + max + "] for " + label); + } + return (int) value; + } + + byte[] readByteString(int minLen, int maxLen, String label) { + int len = readBoundedArg(MAJOR_BSTR, minLen, maxLen, label); + if (len > remaining()) { + throw new CodecException("Declared byte string length exceeds remaining CBOR bytes for " + label); + } + byte[] slice = Arrays.copyOfRange(data, pos, pos + len); + pos += len; + return slice; + } + + byte[] readTextBytes(int minLen, int maxLen, String label) { + int len = readBoundedArg(MAJOR_TEXT, minLen, maxLen, label); + if (len > remaining()) { + throw new CodecException("Declared text string length exceeds remaining CBOR bytes for " + label); + } + byte[] slice = Arrays.copyOfRange(data, pos, pos + len); + pos += len; + return slice; + } + + String readStrictText(int minLen, int maxLen, String label) { + return decodeStrictUtf8(readTextBytes(minLen, maxLen, label), label); } - return array; } } diff --git a/zeroj-codec/src/main/java/org/zeroj/codec/SnarkjsJsonCodec.java b/zeroj-codec/src/main/java/org/zeroj/codec/SnarkjsJsonCodec.java index 9790595b..c2195cb2 100644 --- a/zeroj-codec/src/main/java/org/zeroj/codec/SnarkjsJsonCodec.java +++ b/zeroj-codec/src/main/java/org/zeroj/codec/SnarkjsJsonCodec.java @@ -6,6 +6,8 @@ import com.fasterxml.jackson.core.StreamReadFeature; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; import java.io.ByteArrayOutputStream; import java.io.IOException; @@ -18,6 +20,7 @@ import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.List; +import java.util.Objects; /** * Codec for snarkjs JSON proof files (proof.json, verification_key.json, public.json). @@ -212,9 +215,13 @@ public static PublicInputs parsePublicInputs(String json) { /** * Build a {@link ZkProofEnvelope} from parsed snarkjs components. * - *

Note: the proof bytes are stored as Jackson-serialized JSON (record field names). - * Use {@link #toEnvelopeFromJson(String, String, String, CircuitId)} to preserve the - * original snarkjs JSON format in the envelope.

+ *

Serializes {@code proof} and {@code vk} into canonical snarkjs JSON ({@code pi_a}, + * {@code pi_b}, {@code pi_c}, {@code vk_alpha_1}, ..., {@code IC} with decimal string + * coordinates) so the resulting envelope can be parsed and verified directly by ZeroJ + * Groth16 verifiers. The envelope's {@link VerificationKeyRef.ByHash} hashes the canonical + * bytes returned by {@link #toVerificationKeyBytes(SnarkjsVerificationKey)}. When you hold + * raw {@code verification_key.json} bytes whose SHA-256 must match an existing registry entry, + * use {@link #toEnvelopeFromJson(String, String, String, CircuitId)} instead.

* * @param proof parsed snarkjs proof * @param vk parsed snarkjs verification key @@ -224,6 +231,10 @@ public static PublicInputs parsePublicInputs(String json) { */ public static ZkProofEnvelope toEnvelope(SnarkjsProof proof, SnarkjsVerificationKey vk, PublicInputs inputs, CircuitId circuitId) { + Objects.requireNonNull(proof, "proof is required"); + Objects.requireNonNull(vk, "vk is required"); + Objects.requireNonNull(inputs, "inputs is required"); + Objects.requireNonNull(circuitId, "circuitId is required"); ProofSystemId proofSystem = ProofSystemId.fromValue(proof.protocol()); CurveId curve = CurveId.fromValue(proof.curve()); validateProofVkInputs(proof, vk, inputs); @@ -257,6 +268,7 @@ public static ZkProofEnvelope toEnvelope(SnarkjsProof proof, SnarkjsVerification */ public static ZkProofEnvelope toEnvelopeFromJson(String proofJson, String vkJson, String publicJson, CircuitId circuitId) { + Objects.requireNonNull(circuitId, "circuitId is required"); var proof = parseProof(proofJson); var vk = parseVerificationKey(vkJson); var inputs = parsePublicInputs(publicJson); @@ -265,44 +277,164 @@ public static ZkProofEnvelope toEnvelopeFromJson(String proofJson, String vkJson ProofSystemId proofSystem = ProofSystemId.fromValue(proof.protocol()); CurveId curve = CurveId.fromValue(proof.curve()); - byte[] vkBytes = vkJson.getBytes(java.nio.charset.StandardCharsets.UTF_8); + byte[] vkBytes = vkJson.getBytes(StandardCharsets.UTF_8); byte[] vkHash = sha256(vkBytes); return ZkProofEnvelope.builder() .proofSystem(proofSystem) .curve(curve) .circuitId(circuitId) - .proofBytes(proofJson.getBytes(java.nio.charset.StandardCharsets.UTF_8)) + .proofBytes(proofJson.getBytes(StandardCharsets.UTF_8)) .publicInputs(inputs) .vkRef(new VerificationKeyRef.ByHash(vkHash)) .proofFormat("snarkjs-json") .build(); } + /** + * Serialize a parsed {@link SnarkjsVerificationKey} to canonical snarkjs JSON UTF-8 bytes + * matching the {@link VerificationKeyRef.ByHash} produced by + * {@link #toEnvelope(SnarkjsProof, SnarkjsVerificationKey, PublicInputs, CircuitId)}. + */ + public static byte[] toVerificationKeyBytes(SnarkjsVerificationKey vk) { + return serializeVkToBytes(vk); + } + // --- Serialization helpers --- /** - * Serialize a snarkjs proof to its canonical JSON bytes (UTF-8, deterministic field order). + * Serialize a snarkjs proof to canonical snarkjs JSON bytes (UTF-8, deterministic field order, + * decimal string coordinates). */ static byte[] serializeProofToBytes(SnarkjsProof proof) { + Objects.requireNonNull(proof, "proof is required"); try { - return MAPPER.writeValueAsBytes(proof); + ObjectNode root = MAPPER.createObjectNode(); + root.set("pi_a", encodeG1Point(proof.piA(), "pi_a")); + root.set("pi_b", encodeG2Point(proof.piB(), "pi_b")); + root.set("pi_c", encodeG1Point(proof.piC(), "pi_c")); + root.put("protocol", requireValidText(proof.protocol(), "protocol")); + root.put("curve", requireValidText(proof.curve(), "curve")); + return MAPPER.writeValueAsBytes(root); + } catch (CodecException e) { + throw e; } catch (Exception e) { throw new CodecException("Failed to serialize proof", e); } } /** - * Serialize a snarkjs verification key to its canonical JSON bytes. + * Serialize a snarkjs verification key to canonical snarkjs JSON bytes (UTF-8, deterministic + * field order, decimal string coordinates). */ static byte[] serializeVkToBytes(SnarkjsVerificationKey vk) { + Objects.requireNonNull(vk, "vk is required"); try { - return MAPPER.writeValueAsBytes(vk); + if (vk.nPublic() < 0 || vk.nPublic() > MAX_PUBLIC_INPUTS) { + throw new CodecException("Invalid verification_key nPublic: " + vk.nPublic()); + } + if (vk.ic() == null || vk.ic().size() != vk.nPublic() + 1) { + throw new CodecException("verification_key IC length must be nPublic + 1"); + } + ObjectNode root = MAPPER.createObjectNode(); + root.put("protocol", requireValidText(vk.protocol(), "protocol")); + root.put("curve", requireValidText(vk.curve(), "curve")); + root.put("nPublic", vk.nPublic()); + root.set("vk_alpha_1", encodeG1Point(vk.vkAlpha1(), "vk_alpha_1")); + root.set("vk_beta_2", encodeG2Point(vk.vkBeta2(), "vk_beta_2")); + root.set("vk_gamma_2", encodeG2Point(vk.vkGamma2(), "vk_gamma_2")); + root.set("vk_delta_2", encodeG2Point(vk.vkDelta2(), "vk_delta_2")); + root.set("vk_alphabeta_12", encodeGtElement(vk.vkAlphabeta12(), "vk_alphabeta_12")); + root.set("IC", encodeG1PointArray(vk.ic(), "IC")); + return MAPPER.writeValueAsBytes(root); + } catch (CodecException e) { + throw e; } catch (Exception e) { throw new CodecException("Failed to serialize verification key", e); } } + private static ArrayNode encodeG1Point(List point, String fieldName) { + if (point == null || point.size() != 3) { + throw new CodecException("G1 point must have 3 coordinates: " + fieldName); + } + ArrayNode arr = MAPPER.createArrayNode(); + for (BigInteger coord : point) { + arr.add(encodeDecimal(coord, fieldName)); + } + return arr; + } + + private static ArrayNode encodeG2Point(List> point, String fieldName) { + if (point == null || point.size() != 3) { + throw new CodecException("G2 point must have 3 Fp2 coordinates: " + fieldName); + } + ArrayNode arr = MAPPER.createArrayNode(); + for (List pair : point) { + if (pair == null || pair.size() != 2) { + throw new CodecException("G2 coordinate must be a 2-element Fp2 array: " + fieldName); + } + ArrayNode pairNode = MAPPER.createArrayNode(); + pairNode.add(encodeDecimal(pair.get(0), fieldName)); + pairNode.add(encodeDecimal(pair.get(1), fieldName)); + arr.add(pairNode); + } + return arr; + } + + private static ArrayNode encodeGtElement(List>> gt, String fieldName) { + if (gt == null || gt.size() != 2) { + throw new CodecException("GT element must have 2 outer Fp6 entries: " + fieldName); + } + ArrayNode outer = MAPPER.createArrayNode(); + for (List> mid : gt) { + if (mid == null || mid.size() != 3) { + throw new CodecException("GT Fp6 entry must have 3 Fp2 entries: " + fieldName); + } + ArrayNode midNode = MAPPER.createArrayNode(); + for (List pair : mid) { + if (pair == null || pair.size() != 2) { + throw new CodecException("GT Fp2 entry must have 2 Fp elements: " + fieldName); + } + ArrayNode pairNode = MAPPER.createArrayNode(); + pairNode.add(encodeDecimal(pair.get(0), fieldName)); + pairNode.add(encodeDecimal(pair.get(1), fieldName)); + midNode.add(pairNode); + } + outer.add(midNode); + } + return outer; + } + + private static ArrayNode encodeG1PointArray(List> points, String fieldName) { + if (points == null || points.isEmpty() || points.size() > MAX_IC_POINTS) { + throw new CodecException("Invalid G1 point array size: " + fieldName); + } + ArrayNode arr = MAPPER.createArrayNode(); + for (int i = 0; i < points.size(); i++) { + arr.add(encodeG1Point(points.get(i), fieldName + "[" + i + "]")); + } + return arr; + } + + private static String encodeDecimal(BigInteger value, String fieldName) { + if (value == null || value.signum() < 0) { + throw new CodecException("Coordinate must be a non-negative integer: " + fieldName); + } + String text = value.toString(); + if (text.length() > MAX_DECIMAL_CHARS) { + throw new CodecException("Coordinate exceeds maximum decimal length: " + fieldName); + } + return text; + } + + private static String requireValidText(String value, String fieldName) { + if (value == null || value.isBlank() || value.length() > MAX_TEXT_CHARS) { + throw new CodecException("Invalid text field: " + fieldName); + } + return value; + } + // --- Internal parsing helpers --- private static List parseG1Point(JsonNode node, String fieldName) { diff --git a/zeroj-codec/src/main/java/org/zeroj/codec/SnarkjsPlonkCodec.java b/zeroj-codec/src/main/java/org/zeroj/codec/SnarkjsPlonkCodec.java index f0f42a79..f80665d8 100644 --- a/zeroj-codec/src/main/java/org/zeroj/codec/SnarkjsPlonkCodec.java +++ b/zeroj-codec/src/main/java/org/zeroj/codec/SnarkjsPlonkCodec.java @@ -147,9 +147,23 @@ public static SnarkjsPlonkVerificationKey parseVerificationKey(String json) { */ public static ZkProofEnvelope toEnvelopeFromJson(String proofJson, String vkJson, String publicJson, CircuitId circuitId) { + if (circuitId == null) { + throw new CodecException("circuitId must not be null"); + } var proof = parseProof(proofJson); + var vk = parseVerificationKey(vkJson); var inputs = SnarkjsJsonCodec.parsePublicInputs(publicJson); + if (!"plonk".equals(proof.protocol()) || !"plonk".equals(vk.protocol())) { + throw new CodecException("PlonK proof and verification key must have protocol 'plonk'"); + } + if (!proof.curve().equals(vk.curve())) { + throw new CodecException("PlonK proof and verification key curves do not match"); + } + if (vk.nPublic() != inputs.size()) { + throw new CodecException("PlonK public input count does not match verification key nPublic"); + } + ProofSystemId proofSystem = ProofSystemId.PLONK; CurveId curve = CurveId.fromValue(proof.curve()); diff --git a/zeroj-codec/src/test/java/org/zeroj/codec/CborEnvelopeCodecTest.java b/zeroj-codec/src/test/java/org/zeroj/codec/CborEnvelopeCodecTest.java index 71e4cfcd..4891f990 100644 --- a/zeroj-codec/src/test/java/org/zeroj/codec/CborEnvelopeCodecTest.java +++ b/zeroj-codec/src/test/java/org/zeroj/codec/CborEnvelopeCodecTest.java @@ -133,4 +133,277 @@ void decodeRejectsNonSha256VkHashRef() throws Exception { assertThrows(CodecException.class, () -> CborEnvelopeCodec.decode(baos.toByteArray())); } + + @Test + void roundTripPreservesDomainTagMetadataAndProofFormat() { + var original = ZkProofEnvelope.builder() + .proofSystem(ProofSystemId.PLONK) + .curve(CurveId.BLS12_381) + .circuitId(new CircuitId("cardano-plonk-circuit")) + .proofBytes(new byte[]{7, 8, 9}) + .publicInputs(new PublicInputs(List.of(BigInteger.ZERO, BigInteger.valueOf(42)))) + .vkRef(new VerificationKeyRef.ById("vk-plonk")) + .domainTag("cardano-preprod") + .metadata(java.util.Map.of("zebra", "last", "a", "short", "bb", "mid")) + .proofFormat("cardano-plonk-v1") + .build(); + + byte[] cbor = CborEnvelopeCodec.encode(original); + var decoded = CborEnvelopeCodec.decode(cbor); + + assertEquals(original, decoded); + assertEquals("cardano-preprod", decoded.domainTag()); + assertEquals(java.util.Map.of("zebra", "last", "a", "short", "bb", "mid"), decoded.metadata()); + assertEquals("cardano-plonk-v1", decoded.proofFormat().orElse(null)); + } + + @Test + void decodeRejectsUnknownDuplicateNonCanonicalAndPaddedCbor() throws Exception { + // Build a valid minimal 7-key envelope bytes reference + var base = ZkProofEnvelope.builder() + .proofSystem(ProofSystemId.GROTH16) + .curve(CurveId.BLS12_381) + .circuitId(new CircuitId("c")) + .proofBytes(new byte[]{1}) + .publicInputs(new PublicInputs(List.of(BigInteger.ONE))) + .vkRef(new VerificationKeyRef.ById("vk")) + .build(); + byte[] valid = CborEnvelopeCodec.encode(base); + assertEquals(base, CborEnvelopeCodec.decode(valid)); + + // 1. Indefinite-length map (0xBF ... 0xFF) instead of 0xA7 ... + byte[] indefiniteMap = new byte[valid.length + 1]; + indefiniteMap[0] = (byte) 0xBF; + System.arraycopy(valid, 1, indefiniteMap, 1, valid.length - 1); + indefiniteMap[indefiniteMap.length - 1] = (byte) 0xFF; + assertThrows(CodecException.class, () -> CborEnvelopeCodec.decode(indefiniteMap)); + + // 2. Unknown map key (11) + var publicInputs = new co.nstant.in.cbor.model.Array(); + publicInputs.add(new ByteString(BigInteger.ONE.toByteArray())); + var vkRef = new co.nstant.in.cbor.model.Array(); + vkRef.add(new UnsignedInteger(2)); + vkRef.add(new UnicodeString("vk")); + ByteArrayOutputStream unknownKeyOut = new ByteArrayOutputStream(); + new CborEncoder(unknownKeyOut).encode(new CborBuilder() + .addMap() + .put(new UnsignedInteger(1), new UnsignedInteger(1)) + .put(new UnsignedInteger(2), new UnicodeString("groth16")) + .put(new UnsignedInteger(3), new UnicodeString("bls12-381")) + .put(new UnsignedInteger(4), new UnicodeString("c")) + .put(new UnsignedInteger(5), new ByteString(new byte[]{1})) + .put(new UnsignedInteger(6), publicInputs) + .put(new UnsignedInteger(7), vkRef) + .put(new UnsignedInteger(11), new UnicodeString("extra")) + .end().build()); + assertThrows(CodecException.class, () -> CborEnvelopeCodec.decode(unknownKeyOut.toByteArray())); + + // 3. Out-of-order keys (2 before 1) + ByteArrayOutputStream outOfOrderOut = new ByteArrayOutputStream(); + new CborEncoder(outOfOrderOut).encode(new CborBuilder() + .addMap() + .put(new UnsignedInteger(2), new UnicodeString("groth16")) + .put(new UnsignedInteger(1), new UnsignedInteger(1)) + .put(new UnsignedInteger(3), new UnicodeString("bls12-381")) + .put(new UnsignedInteger(4), new UnicodeString("c")) + .put(new UnsignedInteger(5), new ByteString(new byte[]{1})) + .put(new UnsignedInteger(6), publicInputs) + .put(new UnsignedInteger(7), vkRef) + .end().build()); + assertThrows(CodecException.class, () -> CborEnvelopeCodec.decode(outOfOrderOut.toByteArray())); + + // 4. Non-minimal BigInteger encoding ([0x00, 0x01] instead of [0x01]) + var paddedInputs = new co.nstant.in.cbor.model.Array(); + paddedInputs.add(new ByteString(new byte[]{0x00, 0x01})); + ByteArrayOutputStream paddedOut = new ByteArrayOutputStream(); + new CborEncoder(paddedOut).encode(new CborBuilder() + .addMap() + .put(new UnsignedInteger(1), new UnsignedInteger(1)) + .put(new UnsignedInteger(2), new UnicodeString("groth16")) + .put(new UnsignedInteger(3), new UnicodeString("bls12-381")) + .put(new UnsignedInteger(4), new UnicodeString("c")) + .put(new UnsignedInteger(5), new ByteString(new byte[]{1})) + .put(new UnsignedInteger(6), paddedInputs) + .put(new UnsignedInteger(7), vkRef) + .end().build()); + assertThrows(CodecException.class, () -> CborEnvelopeCodec.decode(paddedOut.toByteArray())); + + // 5. Unsupported version (2) + ByteArrayOutputStream badVersionOut = new ByteArrayOutputStream(); + new CborEncoder(badVersionOut).encode(new CborBuilder() + .addMap() + .put(new UnsignedInteger(1), new UnsignedInteger(2)) + .put(new UnsignedInteger(2), new UnicodeString("groth16")) + .put(new UnsignedInteger(3), new UnicodeString("bls12-381")) + .put(new UnsignedInteger(4), new UnicodeString("c")) + .put(new UnsignedInteger(5), new ByteString(new byte[]{1})) + .put(new UnsignedInteger(6), publicInputs) + .put(new UnsignedInteger(7), vkRef) + .end().build()); + assertThrows(CodecException.class, () -> CborEnvelopeCodec.decode(badVersionOut.toByteArray())); + + // 6. Explicitly encoded empty optional domainTag (key 8 = "") + ByteArrayOutputStream emptyDomainOut = new ByteArrayOutputStream(); + new CborEncoder(emptyDomainOut).encode(new CborBuilder() + .addMap() + .put(new UnsignedInteger(1), new UnsignedInteger(1)) + .put(new UnsignedInteger(2), new UnicodeString("groth16")) + .put(new UnsignedInteger(3), new UnicodeString("bls12-381")) + .put(new UnsignedInteger(4), new UnicodeString("c")) + .put(new UnsignedInteger(5), new ByteString(new byte[]{1})) + .put(new UnsignedInteger(6), publicInputs) + .put(new UnsignedInteger(7), vkRef) + .put(new UnsignedInteger(8), new UnicodeString("")) + .end().build()); + assertThrows(CodecException.class, () -> CborEnvelopeCodec.decode(emptyDomainOut.toByteArray())); + + // 7. Non-minimal uint encoding for key 1 value (0x18 0x01 instead of 0x01) + // valid starts with: 0xA7 (map 7), 0x01 (key 1), 0x01 (val 1), ... + assertEquals((byte) 0xA7, valid[0]); + assertEquals((byte) 0x01, valid[1]); + assertEquals((byte) 0x01, valid[2]); + byte[] nonMinimalInt = new byte[valid.length + 1]; + nonMinimalInt[0] = valid[0]; + nonMinimalInt[1] = valid[1]; + nonMinimalInt[2] = 0x18; + nonMinimalInt[3] = 0x01; + System.arraycopy(valid, 3, nonMinimalInt, 4, valid.length - 3); + assertThrows(CodecException.class, () -> CborEnvelopeCodec.decode(nonMinimalInt)); + + // 8. Duplicate key (key 1 repeated inside 8-entry map) + byte[] dupKey = new byte[valid.length + 2]; + dupKey[0] = (byte) 0xA8; + dupKey[1] = 0x01; + dupKey[2] = 0x01; + System.arraycopy(valid, 1, dupKey, 3, valid.length - 1); + assertThrows(CodecException.class, () -> CborEnvelopeCodec.decode(dupKey)); + + // 9. Trailing CBOR item appended to a valid canonical envelope + byte[] trailing = new byte[valid.length + 1]; + System.arraycopy(valid, 0, trailing, 0, valid.length); + trailing[valid.length] = 0x00; + assertThrows(CodecException.class, () -> CborEnvelopeCodec.decode(trailing)); + } + + @Test + void metadataUsesRfc8949UnsignedUtf8OrderAndRejectsMalformedUtf16() { + // RFC 8949 §4.2.1: "aa" = UTF-8 0x61 0x61 (len 2), "é" = UTF-8 0xC3 0xA9 (len 2), + // "😀" = UTF-8 0xF0 0x9F 0x98 0x80 (len 4). Unsigned bytewise order is "aa" < "é" < "😀". + var mapOrder1 = new java.util.LinkedHashMap(); + mapOrder1.put("é", "2"); + mapOrder1.put("😀", "3"); + mapOrder1.put("aa", "1"); + + var mapOrder2 = new java.util.LinkedHashMap(); + mapOrder2.put("aa", "1"); + mapOrder2.put("é", "2"); + mapOrder2.put("😀", "3"); + + var env1 = ZkProofEnvelope.builder() + .proofSystem(ProofSystemId.GROTH16).curve(CurveId.BLS12_381) + .circuitId(new CircuitId("c")).proofBytes(new byte[]{1}) + .publicInputs(new PublicInputs(List.of())) + .vkRef(new VerificationKeyRef.ById("v")) + .metadata(mapOrder1).build(); + var env2 = ZkProofEnvelope.builder() + .proofSystem(ProofSystemId.GROTH16).curve(CurveId.BLS12_381) + .circuitId(new CircuitId("c")).proofBytes(new byte[]{1}) + .publicInputs(new PublicInputs(List.of())) + .vkRef(new VerificationKeyRef.ById("v")) + .metadata(mapOrder2).build(); + + byte[] cbor1 = CborEnvelopeCodec.encode(env1); + byte[] cbor2 = CborEnvelopeCodec.encode(env2); + assertArrayEquals(cbor1, cbor2, "Metadata insertion order must not affect canonical CBOR"); + + // Independent RFC 8949 §4.2.1 expected wire suffix for key 9 (metadata): + // 09 A3 62 61 61 61 31 62 C3 A9 61 32 64 F0 9F 98 80 61 33 + byte[] expectedMetaSuffix = new byte[]{ + 0x09, (byte) 0xA3, + 0x62, 0x61, 0x61, 0x61, 0x31, + 0x62, (byte) 0xC3, (byte) 0xA9, 0x61, 0x32, + 0x64, (byte) 0xF0, (byte) 0x9F, (byte) 0x98, (byte) 0x80, 0x61, 0x33 + }; + byte[] actualSuffix = java.util.Arrays.copyOfRange( + cbor1, cbor1.length - expectedMetaSuffix.length, cbor1.length); + assertArrayEquals(expectedMetaSuffix, actualSuffix, + "Metadata map bytes must match RFC 8949 §4.2.1 unsigned UTF-8 bytewise ordering"); + + var decoded = CborEnvelopeCodec.decode(cbor1); + assertEquals(mapOrder2, decoded.metadata()); + + // Swapping "é" before "aa" on the wire must be rejected + byte[] wrongOrder = cbor1.clone(); + byte[] swappedSuffix = new byte[]{ + 0x09, (byte) 0xA3, + 0x62, (byte) 0xC3, (byte) 0xA9, 0x61, 0x32, + 0x62, 0x61, 0x61, 0x61, 0x31, + 0x64, (byte) 0xF0, (byte) 0x9F, (byte) 0x98, (byte) 0x80, 0x61, 0x33 + }; + System.arraycopy(swappedSuffix, 0, wrongOrder, wrongOrder.length - swappedSuffix.length, swappedSuffix.length); + assertThrows(CodecException.class, () -> CborEnvelopeCodec.decode(wrongOrder)); + + // Malformed UTF-16 (unpaired surrogates) must be rejected on encode + String unpairedHigh = "bad\uD800key"; + String unpairedLow = "bad\uDC00val"; + assertThrows(CodecException.class, () -> CborEnvelopeCodec.encode(ZkProofEnvelope.builder() + .proofSystem(ProofSystemId.GROTH16).curve(CurveId.BLS12_381) + .circuitId(new CircuitId("c")).proofBytes(new byte[]{1}) + .publicInputs(new PublicInputs(List.of())) + .vkRef(new VerificationKeyRef.ById("v")) + .domainTag(unpairedHigh).build())); + assertThrows(CodecException.class, () -> CborEnvelopeCodec.encode(ZkProofEnvelope.builder() + .proofSystem(ProofSystemId.GROTH16).curve(CurveId.BLS12_381) + .circuitId(new CircuitId("c")).proofBytes(new byte[]{1}) + .publicInputs(new PublicInputs(List.of())) + .vkRef(new VerificationKeyRef.ById("v")) + .metadata(java.util.Map.of(unpairedHigh, "ok")).build())); + assertThrows(CodecException.class, () -> CborEnvelopeCodec.encode(ZkProofEnvelope.builder() + .proofSystem(ProofSystemId.GROTH16).curve(CurveId.BLS12_381) + .circuitId(new CircuitId("c")).proofBytes(new byte[]{1}) + .publicInputs(new PublicInputs(List.of())) + .vkRef(new VerificationKeyRef.ById("v")) + .metadata(java.util.Map.of("ok", unpairedLow)).build())); + } + + @Test + void decodeRejectsExcessiveNestingAndDeclaredCollectionLengthBeforeAllocation() { + // 1. Deeply nested CBOR arrays (10,000 levels) must fail fast with CodecException, not StackOverflowError + byte[] deepNesting = new byte[10_000]; + java.util.Arrays.fill(deepNesting, (byte) 0x81); + assertThrows(CodecException.class, () -> CborEnvelopeCodec.decode(deepNesting)); + + // 2. One level beyond schema: array inside publicInputs instead of byte string + // Valid 7-key envelope with empty publicInputs: find key 6 (06 80) and replace with 06 81 80 ([[]]) + var base = ZkProofEnvelope.builder() + .proofSystem(ProofSystemId.GROTH16).curve(CurveId.BLS12_381) + .circuitId(new CircuitId("c")).proofBytes(new byte[]{1}) + .publicInputs(new PublicInputs(List.of())) + .vkRef(new VerificationKeyRef.ById("v")).build(); + byte[] valid = CborEnvelopeCodec.encode(base); + int key6Idx = -1; + for (int i = 0; i < valid.length - 1; i++) { + if (valid[i] == 0x06 && valid[i + 1] == (byte) 0x80) { + key6Idx = i; + break; + } + } + assertTrue(key6Idx > 0); + byte[] nestedPublicInput = new byte[valid.length + 1]; + System.arraycopy(valid, 0, nestedPublicInput, 0, key6Idx + 1); + nestedPublicInput[key6Idx + 1] = (byte) 0x81; // array(1) + nestedPublicInput[key6Idx + 2] = (byte) 0x80; // nested array(0) instead of bstr + System.arraycopy(valid, key6Idx + 2, nestedPublicInput, key6Idx + 3, valid.length - key6Idx - 2); + assertThrows(CodecException.class, () -> CborEnvelopeCodec.decode(nestedPublicInput)); + + // 3. Excessive declared publicInputs length (1,000,000 elements) in tiny buffer must not OOM + byte[] hugeDeclaredCount = new byte[key6Idx + 6]; + System.arraycopy(valid, 0, hugeDeclaredCount, 0, key6Idx + 1); + hugeDeclaredCount[key6Idx + 1] = (byte) 0x9A; // array with 4-byte uint length + hugeDeclaredCount[key6Idx + 2] = 0x00; + hugeDeclaredCount[key6Idx + 3] = 0x0F; + hugeDeclaredCount[key6Idx + 4] = 0x42; + hugeDeclaredCount[key6Idx + 5] = 0x40; // 1,000,000 + assertThrows(CodecException.class, () -> CborEnvelopeCodec.decode(hugeDeclaredCount)); + } } diff --git a/zeroj-codec/src/test/java/org/zeroj/codec/SnarkjsJsonCodecTest.java b/zeroj-codec/src/test/java/org/zeroj/codec/SnarkjsJsonCodecTest.java index 09c89708..920e0586 100644 --- a/zeroj-codec/src/test/java/org/zeroj/codec/SnarkjsJsonCodecTest.java +++ b/zeroj-codec/src/test/java/org/zeroj/codec/SnarkjsJsonCodecTest.java @@ -4,10 +4,12 @@ import org.zeroj.api.CurveId; import org.zeroj.api.ProofSystemId; import org.zeroj.api.PublicInputs; +import org.zeroj.api.VerificationKeyRef; import org.junit.jupiter.api.Test; import java.io.InputStream; import java.math.BigInteger; +import java.nio.charset.StandardCharsets; import static org.junit.jupiter.api.Assertions.*; @@ -150,6 +152,19 @@ void toEnvelopeFromRealVectors() { assertEquals(2, envelope.publicInputs().size()); assertTrue(envelope.proofBytes().length > 0); assertEquals("snarkjs-json", envelope.proofFormat().orElse(null)); + + // Emitted proofBytes and toVerificationKeyBytes must round-trip as canonical snarkjs JSON + var reparsedProof = SnarkjsJsonCodec.parseProof( + new String(envelope.proofBytes(), StandardCharsets.UTF_8)); + assertEquals(proof, reparsedProof); + + byte[] vkBytes = SnarkjsJsonCodec.toVerificationKeyBytes(vk); + var reparsedVk = SnarkjsJsonCodec.parseVerificationKey( + new String(vkBytes, StandardCharsets.UTF_8)); + assertEquals(vk, reparsedVk); + assertArrayEquals( + CanonicalHash.sha256(vkBytes), + ((VerificationKeyRef.ByHash) envelope.vkRef()).hash()); } @Test diff --git a/zeroj-codec/src/test/java/org/zeroj/codec/SnarkjsPlonkCodecTest.java b/zeroj-codec/src/test/java/org/zeroj/codec/SnarkjsPlonkCodecTest.java index bc28a32a..877c5d65 100644 --- a/zeroj-codec/src/test/java/org/zeroj/codec/SnarkjsPlonkCodecTest.java +++ b/zeroj-codec/src/test/java/org/zeroj/codec/SnarkjsPlonkCodecTest.java @@ -231,6 +231,27 @@ void toEnvelopeFromJson_buildsCorrectEnvelope() { assertTrue(envelope.proofBytes().length > 0); } + @Test + void toEnvelopeFromJson_validatesVkJsonAndCrossChecks() { + var proofJson = loadString("/test-vectors/plonk-bn254/proof.json"); + var vkJson = loadString("/test-vectors/plonk-bn254/verification_key.json"); + var publicJson = loadString("/test-vectors/plonk-bn254/public.json"); + + assertThrows(CodecException.class, () -> SnarkjsPlonkCodec.toEnvelopeFromJson( + proofJson, "{not json", publicJson, new CircuitId("multiplier"))); + + String wrongProtocolVk = replaceTopLevelValue(vkJson, "protocol", "\"groth16\""); + assertThrows(CodecException.class, () -> SnarkjsPlonkCodec.toEnvelopeFromJson( + proofJson, wrongProtocolVk, publicJson, new CircuitId("multiplier"))); + + String wrongCurveVk = replaceTopLevelValue(vkJson, "curve", "\"bls12-381\""); + assertThrows(CodecException.class, () -> SnarkjsPlonkCodec.toEnvelopeFromJson( + proofJson, wrongCurveVk, publicJson, new CircuitId("multiplier"))); + + assertThrows(CodecException.class, () -> SnarkjsPlonkCodec.toEnvelopeFromJson( + proofJson, vkJson, "[\"33\"]", new CircuitId("multiplier"))); + } + // --- Cross-check: proof values are in the BN254 scalar field --- @Test diff --git a/zeroj-crypto/src/main/java/org/zeroj/crypto/groth16/ZkeyImporter.java b/zeroj-crypto/src/main/java/org/zeroj/crypto/groth16/ZkeyImporter.java index a42b5748..f39ca886 100644 --- a/zeroj-crypto/src/main/java/org/zeroj/crypto/groth16/ZkeyImporter.java +++ b/zeroj-crypto/src/main/java/org/zeroj/crypto/groth16/ZkeyImporter.java @@ -6,7 +6,9 @@ import org.zeroj.crypto.ec.JacobianG2BN254.AffineG2; import org.zeroj.crypto.field.MontFp254; import org.zeroj.crypto.field.MontFp2_254; +import org.zeroj.crypto.field.MontFr254; +import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.math.BigInteger; @@ -267,40 +269,127 @@ private static BigInteger fromMontgomery(BigInteger montValue, BigInteger q) { // --- .wtns witness file parsing --- private static final byte[] WTNS_MAGIC = {0x77, 0x74, 0x6e, 0x73}; // "wtns" + private static final int MAX_WTNS_VERSION = 2; // matches snarkjs 0.7.6 src/wtns_utils.js readBinFile(fd, "wtns", 2) + private static final int MAX_WTNS_BYTES = 128 * 1024 * 1024; + private static final int MAX_WTNS_SECTIONS = 16; + private static final int MAX_WITNESS_VALUES = 1 << 22; + private static final BigInteger BN254_FR = MontFr254.modulus(); /** - * Parse a snarkjs .wtns binary witness file. + * Parse a legacy BN254 snarkjs {@code .wtns} binary witness file (versions {@code 1..2}). * - * @param input the .wtns file contents - * @return witness vector as BigInteger array + *

Requires {@link LegacyCurvePolicy#requireLegacyBn254Enabled()} (disabled by default).

+ * + * @param input the {@code .wtns} file contents + * @return canonical BN254 witness vector in {@code [0, Fr)} + * @throws IllegalStateException if legacy BN254 support is not explicitly enabled + * @throws IOException if the file format, version, prime, section bounds, or witness scalars are invalid */ public static BigInteger[] importWtns(InputStream input) throws IOException { - byte[] data = input.readAllBytes(); + LegacyCurvePolicy.requireLegacyBn254Enabled(); + byte[] data = readBounded(input, MAX_WTNS_BYTES, ".wtns input"); ByteBuffer buf = ByteBuffer.wrap(data).order(ByteOrder.LITTLE_ENDIAN); + if (buf.remaining() < 12) { + throw new IOException("Truncated .wtns header"); + } // Global header byte[] magic = new byte[4]; buf.get(magic); - if (!Arrays.equals(magic, WTNS_MAGIC)) + if (!Arrays.equals(magic, WTNS_MAGIC)) { throw new IOException("Invalid .wtns magic: expected 'wtns'"); + } int version = buf.getInt(); int numSections = buf.getInt(); + if (version < 1 || version > MAX_WTNS_VERSION) { + throw new IOException("Unsupported .wtns version: " + version + " (supported: 1.." + MAX_WTNS_VERSION + ")"); + } + if (numSections <= 0 || numSections > MAX_WTNS_SECTIONS) { + throw new IOException("Invalid .wtns section count: " + numSections); + } + + Map sections = readWtnsSections(buf, numSections); + if (!sections.containsKey(1) || !sections.containsKey(2)) { + throw new IOException("Missing required .wtns section (expected sections 1 and 2)"); + } - // Section 1: Header - int sType = buf.getInt(); - long sSize = buf.getLong(); + // Section 1: Header (n8 + 32-byte prime + nWitness = 40 bytes) + long[] sec1 = sections.get(1); + if (sec1[1] != 4 + 32 + 4) { + throw new IOException("Invalid .wtns header section size: " + sec1[1]); + } + buf.position((int) sec1[0]); int n8 = buf.getInt(); + if (n8 != 32) { + throw new IOException("Not a BN254 witness (n8=" + n8 + ", expected 32)"); + } BigInteger prime = readFieldElementLE(buf, n8); + if (!BN254_FR.equals(prime)) { + throw new IOException("Wrong BN254 witness scalar-field prime"); + } int nWitness = buf.getInt(); + if (nWitness < 0 || nWitness > MAX_WITNESS_VALUES) { + throw new IOException("Invalid .wtns witness count: " + nWitness); + } // Section 2: Witness values - sType = buf.getInt(); - sSize = buf.getLong(); + long[] sec2 = sections.get(2); + long expectedWitnessBytes = (long) nWitness * n8; + if (sec2[1] != expectedWitnessBytes) { + throw new IOException("Invalid .wtns witness section size: " + sec2[1]); + } + buf.position((int) sec2[0]); BigInteger[] witness = new BigInteger[nWitness]; for (int i = 0; i < nWitness; i++) { - witness[i] = readFieldElementLE(buf, n8); + BigInteger value = readFieldElementLE(buf, n8); + if (value.compareTo(BN254_FR) >= 0) { + throw new IOException("Non-canonical BN254 witness scalar at index " + i); + } + witness[i] = value; } return witness; } + + private static Map readWtnsSections(ByteBuffer buf, int numSections) throws IOException { + Map sections = new LinkedHashMap<>(); + int limit = buf.limit(); + for (int i = 0; i < numSections; i++) { + if (buf.remaining() < 12) { + throw new IOException("Truncated .wtns section header " + i); + } + int sType = buf.getInt(); + long sSize = buf.getLong(); + long dataStart = buf.position(); + if (sSize < 0 || sSize > limit - dataStart) { + throw new IOException("Invalid .wtns section " + sType + " size: " + sSize); + } + if (sections.putIfAbsent(sType, new long[]{dataStart, sSize}) != null) { + throw new IOException("Duplicate .wtns section type: " + sType); + } + buf.position((int) (dataStart + sSize)); + } + if (buf.remaining() != 0) { + throw new IOException("Trailing bytes after .wtns sections: " + buf.remaining()); + } + return sections; + } + + private static byte[] readBounded(InputStream input, int maxBytes, String label) throws IOException { + if (input == null) { + throw new IOException(label + " must not be 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 > maxBytes) { + throw new IOException(label + " exceeds maximum size of " + maxBytes + " bytes"); + } + out.write(buffer, 0, read); + } + return out.toByteArray(); + } } diff --git a/zeroj-crypto/src/test/java/org/zeroj/crypto/groth16/ZkeyImporterTest.java b/zeroj-crypto/src/test/java/org/zeroj/crypto/groth16/ZkeyImporterTest.java index d57f5f51..e338bc7e 100644 --- a/zeroj-crypto/src/test/java/org/zeroj/crypto/groth16/ZkeyImporterTest.java +++ b/zeroj-crypto/src/test/java/org/zeroj/crypto/groth16/ZkeyImporterTest.java @@ -86,6 +86,99 @@ void importZkey_multiplier_dimensionsCorrect() throws IOException { assertTrue(pk.pointsH().length >= 4, "H should have at least domainSize=4 points"); } + @Test + void importWtns_requiresLegacyPolicyAndValidatesPrimeAndBounds() throws Exception { + byte[] validWtns = buildWtns(org.zeroj.crypto.field.MontFr254.modulus(), + new BigInteger[]{BigInteger.ONE, BigInteger.valueOf(33)}); + + String prev = System.getProperty(org.zeroj.api.LegacyCurvePolicy.ALLOW_LEGACY_BN254_PROPERTY); + try { + System.clearProperty(org.zeroj.api.LegacyCurvePolicy.ALLOW_LEGACY_BN254_PROPERTY); + var ex = assertThrows(IllegalStateException.class, + () -> ZkeyImporter.importWtns(new java.io.ByteArrayInputStream(validWtns))); + assertTrue(ex.getMessage().contains("unsound against adversarial input")); + } finally { + if (prev != null) { + System.setProperty(org.zeroj.api.LegacyCurvePolicy.ALLOW_LEGACY_BN254_PROPERTY, prev); + } else { + System.clearProperty(org.zeroj.api.LegacyCurvePolicy.ALLOW_LEGACY_BN254_PROPERTY); + } + } + + // Valid BN254 witness succeeds when enabled + BigInteger[] parsed = ZkeyImporter.importWtns(new java.io.ByteArrayInputStream(validWtns)); + assertArrayEquals(new BigInteger[]{BigInteger.ONE, BigInteger.valueOf(33)}, parsed); + + // Wrong prime (BLS12-381 Fr) rejected + BigInteger blsFr = new BigInteger("73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001", 16); + byte[] wrongPrime = buildWtns(blsFr, new BigInteger[]{BigInteger.ONE}); + assertThrows(IOException.class, + () -> ZkeyImporter.importWtns(new java.io.ByteArrayInputStream(wrongPrime))); + + // Non-canonical scalar (>= BN254 Fr) rejected + byte[] nonCanonical = buildWtns(org.zeroj.crypto.field.MontFr254.modulus(), + new BigInteger[]{BigInteger.ONE, org.zeroj.crypto.field.MontFr254.modulus()}); + assertThrows(IOException.class, + () -> ZkeyImporter.importWtns(new java.io.ByteArrayInputStream(nonCanonical))); + + // Trailing bytes rejected + byte[] trailing = java.util.Arrays.copyOf(validWtns, validWtns.length + 1); + assertThrows(IOException.class, + () -> ZkeyImporter.importWtns(new java.io.ByteArrayInputStream(trailing))); + + // Supported WTNS version 1 succeeds; version 0 and version 3 (> snarkjs 0.7.6 max 2) rejected + byte[] wtnsV1 = buildWtns(1, org.zeroj.crypto.field.MontFr254.modulus(), + new BigInteger[]{BigInteger.ONE, BigInteger.valueOf(33)}); + assertArrayEquals(new BigInteger[]{BigInteger.ONE, BigInteger.valueOf(33)}, + ZkeyImporter.importWtns(new java.io.ByteArrayInputStream(wtnsV1))); + + byte[] wtnsV0 = buildWtns(0, org.zeroj.crypto.field.MontFr254.modulus(), + new BigInteger[]{BigInteger.ONE}); + assertThrows(IOException.class, + () -> ZkeyImporter.importWtns(new java.io.ByteArrayInputStream(wtnsV0))); + + byte[] wtnsV3 = buildWtns(3, org.zeroj.crypto.field.MontFr254.modulus(), + new BigInteger[]{BigInteger.ONE}); + assertThrows(IOException.class, + () -> ZkeyImporter.importWtns(new java.io.ByteArrayInputStream(wtnsV3))); + } + + private static byte[] buildWtns(BigInteger prime, BigInteger[] values) { + return buildWtns(2, prime, values); + } + + private static byte[] buildWtns(int version, BigInteger prime, BigInteger[] values) { + int sec1Size = 4 + 32 + 4; + int sec2Size = values.length * 32; + var buf = java.nio.ByteBuffer.allocate(12 + 12 + sec1Size + 12 + sec2Size) + .order(java.nio.ByteOrder.LITTLE_ENDIAN); + buf.put(new byte[]{'w', 't', 'n', 's'}); + buf.putInt(version); + buf.putInt(2); + // Section 1 + buf.putInt(1); + buf.putLong(sec1Size); + buf.putInt(32); + buf.put(toLE32(prime)); + buf.putInt(values.length); + // Section 2 + buf.putInt(2); + buf.putLong(sec2Size); + for (BigInteger v : values) { + buf.put(toLE32(v)); + } + return buf.array(); + } + + private static byte[] toLE32(BigInteger v) { + byte[] be = v.toByteArray(); + byte[] le = new byte[32]; + for (int i = 0; i < Math.min(32, be.length); i++) { + le[i] = be[be.length - 1 - i]; + } + return le; + } + // --- Helper --- private Groth16ProvingKey loadProvingKey() throws IOException { diff --git a/zeroj-verifier-groth16/src/main/java/org/zeroj/verifier/groth16/bls12381/Groth16BLS12381PureJavaVerifier.java b/zeroj-verifier-groth16/src/main/java/org/zeroj/verifier/groth16/bls12381/Groth16BLS12381PureJavaVerifier.java index 52c71542..7c6e96ba 100644 --- a/zeroj-verifier-groth16/src/main/java/org/zeroj/verifier/groth16/bls12381/Groth16BLS12381PureJavaVerifier.java +++ b/zeroj-verifier-groth16/src/main/java/org/zeroj/verifier/groth16/bls12381/Groth16BLS12381PureJavaVerifier.java @@ -2,13 +2,16 @@ import org.zeroj.api.*; import org.zeroj.backend.spi.BackendDescriptor; +import org.zeroj.backend.spi.EnvelopeBinding; import org.zeroj.backend.spi.ZkVerifier; +import org.zeroj.codec.CodecException; import org.zeroj.codec.SnarkjsJsonCodec; import org.zeroj.bls12381.ec.*; import org.zeroj.bls12381.field.*; import org.zeroj.bls12381.pairing.BLS12381Pairing; import java.math.BigInteger; +import java.nio.charset.StandardCharsets; import java.util.List; /** @@ -37,9 +40,54 @@ public BackendDescriptor descriptor() { @Override public VerificationResult verify(ZkProofEnvelope envelope, VerificationMaterial material) { + if (envelope == null) { + return VerificationResult.error( + VerificationResult.ReasonCode.MALFORMED_ENVELOPE, + "Proof envelope must not be null"); + } + if (envelope.proofSystem() != ProofSystemId.GROTH16) { + return VerificationResult.error( + VerificationResult.ReasonCode.UNSUPPORTED_PROOF_SYSTEM, + "Expected Groth16 proof envelope"); + } + if (envelope.curve() != CurveId.BLS12_381) { + return VerificationResult.error( + VerificationResult.ReasonCode.UNSUPPORTED_CURVE, + "Expected BLS12-381 proof envelope"); + } + var bindingError = EnvelopeBinding.validateBinding(envelope, material); + if (bindingError.isPresent()) { + return bindingError.get(); + } + if (envelope.proofFormat().isPresent() + && !"snarkjs-json".equals(envelope.proofFormat().orElseThrow())) { + return VerificationResult.error( + VerificationResult.ReasonCode.MALFORMED_ENVELOPE, + "Unsupported Groth16 proof format: " + envelope.proofFormat().orElseThrow()); + } + try { - var proof = SnarkjsJsonCodec.parseProof(new String(envelope.proofBytes())); - var vk = SnarkjsJsonCodec.parseVerificationKey(new String(material.vkBytes())); + var proof = SnarkjsJsonCodec.parseProof( + new String(envelope.proofBytes(), StandardCharsets.UTF_8)); + var vk = SnarkjsJsonCodec.parseVerificationKey( + new String(material.vkBytes(), StandardCharsets.UTF_8)); + + if (!"groth16".equals(proof.protocol()) || !"groth16".equals(vk.protocol())) { + return VerificationResult.error( + VerificationResult.ReasonCode.UNSUPPORTED_PROOF_SYSTEM, + "Expected Groth16 proof and verification key"); + } + if (!CurveId.BLS12_381.value().equals(proof.curve()) + || !CurveId.BLS12_381.value().equals(vk.curve())) { + return VerificationResult.error( + VerificationResult.ReasonCode.UNSUPPORTED_CURVE, + "Expected BLS12-381 proof and verification key"); + } + if (vk.ic().size() != vk.nPublic() + 1) { + return VerificationResult.error( + VerificationResult.ReasonCode.MALFORMED_ENVELOPE, + "Verification key IC length must equal nPublic + 1"); + } var publicInputs = envelope.publicInputs(); if (publicInputs.size() != vk.nPublic()) { @@ -79,6 +127,10 @@ public VerificationResult verify(ZkProofEnvelope envelope, VerificationMaterial return valid ? VerificationResult.cryptoValid() : VerificationResult.proofInvalid("Groth16 BLS12-381 pairing check failed"); + } catch (CodecException e) { + return VerificationResult.error( + VerificationResult.ReasonCode.MALFORMED_ENVELOPE, + "Malformed Groth16 BLS12-381 proof or verification key JSON: " + e.getMessage()); } catch (IllegalArgumentException | UnsupportedOperationException e) { return VerificationResult.proofInvalid("Malformed Groth16 BLS12-381 proof or verification key: " + e.getMessage()); } catch (Exception e) { diff --git a/zeroj-verifier-groth16/src/main/java/org/zeroj/verifier/groth16/bls12381/Groth16BLS12381Verifier.java b/zeroj-verifier-groth16/src/main/java/org/zeroj/verifier/groth16/bls12381/Groth16BLS12381Verifier.java index a2194c95..375feeec 100644 --- a/zeroj-verifier-groth16/src/main/java/org/zeroj/verifier/groth16/bls12381/Groth16BLS12381Verifier.java +++ b/zeroj-verifier-groth16/src/main/java/org/zeroj/verifier/groth16/bls12381/Groth16BLS12381Verifier.java @@ -2,14 +2,15 @@ import org.zeroj.api.*; import org.zeroj.backend.spi.BackendDescriptor; +import org.zeroj.backend.spi.EnvelopeBinding; import org.zeroj.backend.spi.ZkVerifier; +import org.zeroj.codec.CodecException; import org.zeroj.codec.SnarkjsJsonCodec; -import org.zeroj.codec.SnarkjsProof; -import org.zeroj.codec.SnarkjsVerificationKey; import org.zeroj.blst.ffm.BlstCurve; import org.zeroj.blst.ffm.BlstPlatform; import java.math.BigInteger; +import java.nio.charset.StandardCharsets; import java.util.List; /** @@ -55,9 +56,54 @@ public boolean isAvailable() { @Override public VerificationResult verify(ZkProofEnvelope envelope, VerificationMaterial material) { + if (envelope == null) { + return VerificationResult.error( + VerificationResult.ReasonCode.MALFORMED_ENVELOPE, + "Proof envelope must not be null"); + } + if (envelope.proofSystem() != ProofSystemId.GROTH16) { + return VerificationResult.error( + VerificationResult.ReasonCode.UNSUPPORTED_PROOF_SYSTEM, + "Expected Groth16 proof envelope"); + } + if (envelope.curve() != CurveId.BLS12_381) { + return VerificationResult.error( + VerificationResult.ReasonCode.UNSUPPORTED_CURVE, + "Expected BLS12-381 proof envelope"); + } + var bindingError = EnvelopeBinding.validateBinding(envelope, material); + if (bindingError.isPresent()) { + return bindingError.get(); + } + if (envelope.proofFormat().isPresent() + && !"snarkjs-json".equals(envelope.proofFormat().orElseThrow())) { + return VerificationResult.error( + VerificationResult.ReasonCode.MALFORMED_ENVELOPE, + "Unsupported Groth16 proof format: " + envelope.proofFormat().orElseThrow()); + } + try { - var proof = SnarkjsJsonCodec.parseProof(new String(envelope.proofBytes())); - var vk = SnarkjsJsonCodec.parseVerificationKey(new String(material.vkBytes())); + var proof = SnarkjsJsonCodec.parseProof( + new String(envelope.proofBytes(), StandardCharsets.UTF_8)); + var vk = SnarkjsJsonCodec.parseVerificationKey( + new String(material.vkBytes(), StandardCharsets.UTF_8)); + + if (!"groth16".equals(proof.protocol()) || !"groth16".equals(vk.protocol())) { + return VerificationResult.error( + VerificationResult.ReasonCode.UNSUPPORTED_PROOF_SYSTEM, + "Expected Groth16 proof and verification key"); + } + if (!CurveId.BLS12_381.value().equals(proof.curve()) + || !CurveId.BLS12_381.value().equals(vk.curve())) { + return VerificationResult.error( + VerificationResult.ReasonCode.UNSUPPORTED_CURVE, + "Expected BLS12-381 proof and verification key"); + } + if (vk.ic().size() != vk.nPublic() + 1) { + return VerificationResult.error( + VerificationResult.ReasonCode.MALFORMED_ENVELOPE, + "Verification key IC length must equal nPublic + 1"); + } var publicInputs = envelope.publicInputs(); if (publicInputs.size() != vk.nPublic()) { @@ -99,6 +145,10 @@ public VerificationResult verify(ZkProofEnvelope envelope, VerificationMaterial } else { return VerificationResult.proofInvalid("Pairing check failed"); } + } catch (CodecException e) { + return VerificationResult.error( + VerificationResult.ReasonCode.MALFORMED_ENVELOPE, + "Malformed Groth16 BLS12-381 proof or verification key JSON: " + e.getMessage()); } catch (IllegalArgumentException | UnsupportedOperationException e) { return VerificationResult.proofInvalid("Malformed Groth16 BLS12-381 proof or verification key: " + e.getMessage()); } catch (Exception e) { diff --git a/zeroj-verifier-groth16/src/main/java/org/zeroj/verifier/groth16/bn254/Groth16BN254Verifier.java b/zeroj-verifier-groth16/src/main/java/org/zeroj/verifier/groth16/bn254/Groth16BN254Verifier.java index 04b1f8a3..9c85991f 100644 --- a/zeroj-verifier-groth16/src/main/java/org/zeroj/verifier/groth16/bn254/Groth16BN254Verifier.java +++ b/zeroj-verifier-groth16/src/main/java/org/zeroj/verifier/groth16/bn254/Groth16BN254Verifier.java @@ -10,7 +10,13 @@ import java.math.BigInteger; /** - * Groth16 verifier for BN254 curve using pure Java pairing arithmetic. + * Legacy Groth16 verifier for BN254 curve using pure Java pairing arithmetic. + * + *

SECURITY WARNING — LEGACY EXPERIMENTAL ONLY — UNSOUND AGAINST ADVERSARIAL INPUT: + * This verifier omits canonical coordinate, curve/subgroup, infinity, and envelope-binding + * checks enforced by the BLS12-381 verifiers. It is NOT registered via {@code ServiceLoader}, + * reports {@link #isAvailable()} as {@code false} unless {@link LegacyCurvePolicy#legacyBn254Enabled()} + * is explicitly enabled, and must only be used for trusted local off-chain experiments.

* *

Verification algorithm:

*
    @@ -29,6 +35,11 @@ public BackendDescriptor descriptor() { return DESCRIPTOR; } + @Override + public boolean isAvailable() { + return LegacyCurvePolicy.legacyBn254Enabled(); + } + @Override public VerificationResult verify(ZkProofEnvelope envelope, VerificationMaterial material) { if (!LegacyCurvePolicy.legacyBn254Enabled()) { diff --git a/zeroj-verifier-groth16/src/test/java/org/zeroj/verifier/groth16/bls12381/Groth16AdversarialEnvelopeParityTest.java b/zeroj-verifier-groth16/src/test/java/org/zeroj/verifier/groth16/bls12381/Groth16AdversarialEnvelopeParityTest.java index 60108d49..b74f7a20 100644 --- a/zeroj-verifier-groth16/src/test/java/org/zeroj/verifier/groth16/bls12381/Groth16AdversarialEnvelopeParityTest.java +++ b/zeroj-verifier-groth16/src/test/java/org/zeroj/verifier/groth16/bls12381/Groth16AdversarialEnvelopeParityTest.java @@ -6,6 +6,7 @@ import org.zeroj.api.ProofSystemId; import org.zeroj.api.VerificationKeyRef; import org.zeroj.api.VerificationMaterial; +import org.zeroj.api.VerificationResult; import org.zeroj.api.ZkProofEnvelope; import org.zeroj.bls12381.ec.G2Point; import org.zeroj.bls12381.field.Fp; @@ -17,6 +18,7 @@ import java.security.MessageDigest; import java.util.ArrayList; import java.util.List; +import java.util.Optional; import static org.junit.jupiter.api.Assertions.*; @@ -86,6 +88,90 @@ class Groth16AdversarialEnvelopeParityTest { } } + @Test void bindingMetadataFormatAndParsedJsonParityBetweenJavaAndBlst() throws Exception { + String proof = load("proof.json"), vk = load("verification_key.json"), pub = load("public.json"); + byte[] vkBytes = vk.getBytes(StandardCharsets.UTF_8); + byte[] vkHash = MessageDigest.getInstance("SHA-256").digest(vkBytes); + var validInputs = SnarkjsJsonCodec.parsePublicInputs(pub); + var validMaterial = VerificationMaterial.of(vkBytes, ProofSystemId.GROTH16, CurveId.BLS12_381, CIRCUIT); + + // Mismatched circuitId -> VK_MISMATCH + var wrongCircuit = ZkProofEnvelope.builder().proofSystem(ProofSystemId.GROTH16).curve(CurveId.BLS12_381) + .circuitId(new CircuitId("other-circuit")).proofFormat("snarkjs-json") + .proofBytes(proof.getBytes(StandardCharsets.UTF_8)).publicInputs(validInputs) + .vkRef(new VerificationKeyRef.ByHash(vkHash)).build(); + assertParityError(wrongCircuit, validMaterial, VerificationResult.ReasonCode.VK_MISMATCH, "wrong circuitId"); + + // Mismatched ByHash -> VK_MISMATCH + var wrongHash = ZkProofEnvelope.builder().proofSystem(ProofSystemId.GROTH16).curve(CurveId.BLS12_381) + .circuitId(CIRCUIT).proofFormat("snarkjs-json") + .proofBytes(proof.getBytes(StandardCharsets.UTF_8)).publicInputs(validInputs) + .vkRef(new VerificationKeyRef.ByHash(new byte[32])).build(); + assertParityError(wrongHash, validMaterial, VerificationResult.ReasonCode.VK_MISMATCH, "wrong vkRef hash"); + + // Spoofed material.vkHash() -> VK_MISMATCH + var validEnvelope = SnarkjsJsonCodec.toEnvelopeFromJson(proof, vk, pub, CIRCUIT); + var spoofedMaterial = new VerificationMaterial(vkBytes, ProofSystemId.GROTH16, CurveId.BLS12_381, + CIRCUIT, java.util.Optional.of(new byte[32])); + assertParityError(validEnvelope, spoofedMaterial, VerificationResult.ReasonCode.VK_MISMATCH, "spoofed material hash"); + + // Unsupported proofFormat -> MALFORMED_ENVELOPE + var badFormat = ZkProofEnvelope.builder().proofSystem(ProofSystemId.GROTH16).curve(CurveId.BLS12_381) + .circuitId(CIRCUIT).proofFormat("gnark-plonk-json") + .proofBytes(proof.getBytes(StandardCharsets.UTF_8)).publicInputs(validInputs) + .vkRef(new VerificationKeyRef.ByHash(vkHash)).build(); + assertParityError(badFormat, validMaterial, VerificationResult.ReasonCode.MALFORMED_ENVELOPE, "bad proofFormat"); + + // Unsupported envelope version -> MALFORMED_ENVELOPE + var badVersion = ZkProofEnvelope.builder().version(99).proofSystem(ProofSystemId.GROTH16).curve(CurveId.BLS12_381) + .circuitId(CIRCUIT).proofFormat("snarkjs-json") + .proofBytes(proof.getBytes(StandardCharsets.UTF_8)).publicInputs(validInputs) + .vkRef(new VerificationKeyRef.ByHash(vkHash)).build(); + assertParityError(badVersion, validMaterial, VerificationResult.ReasonCode.MALFORMED_ENVELOPE, "bad version"); + + // Unparseable JSON -> MALFORMED_ENVELOPE (never INTERNAL_ERROR) + var brokenJson = ZkProofEnvelope.builder().proofSystem(ProofSystemId.GROTH16).curve(CurveId.BLS12_381) + .circuitId(CIRCUIT).proofFormat("snarkjs-json") + .proofBytes("{not json".getBytes(StandardCharsets.UTF_8)).publicInputs(validInputs) + .vkRef(new VerificationKeyRef.ByHash(vkHash)).build(); + assertParityError(brokenJson, validMaterial, VerificationResult.ReasonCode.MALFORMED_ENVELOPE, "broken JSON"); + + // Parsed JSON wrong protocol / wrong curve + String wrongProtocolProof = proof.replace("\"groth16\"", "\"plonk\""); + var wrongProtocolEnv = ZkProofEnvelope.builder().proofSystem(ProofSystemId.GROTH16).curve(CurveId.BLS12_381) + .circuitId(CIRCUIT).proofFormat("snarkjs-json") + .proofBytes(wrongProtocolProof.getBytes(StandardCharsets.UTF_8)).publicInputs(validInputs) + .vkRef(new VerificationKeyRef.ByHash(vkHash)).build(); + assertParityError(wrongProtocolEnv, validMaterial, VerificationResult.ReasonCode.UNSUPPORTED_PROOF_SYSTEM, "wrong JSON protocol"); + + String wrongCurveProof = proof.replace("\"bls12381\"", "\"bn128\"").replace("\"bls12-381\"", "\"bn128\""); + var wrongCurveEnv = ZkProofEnvelope.builder().proofSystem(ProofSystemId.GROTH16).curve(CurveId.BLS12_381) + .circuitId(CIRCUIT).proofFormat("snarkjs-json") + .proofBytes(wrongCurveProof.getBytes(StandardCharsets.UTF_8)).publicInputs(validInputs) + .vkRef(new VerificationKeyRef.ByHash(vkHash)).build(); + assertParityError(wrongCurveEnv, validMaterial, VerificationResult.ReasonCode.UNSUPPORTED_CURVE, "wrong JSON curve"); + + // SnarkjsJsonCodec.toEnvelope(parsed...) + toVerificationKeyBytes(vk) verifies on both backends + var parsedProof = SnarkjsJsonCodec.parseProof(proof); + var parsedVk = SnarkjsJsonCodec.parseVerificationKey(vk); + var serializedEnvelope = SnarkjsJsonCodec.toEnvelope(parsedProof, parsedVk, validInputs, CIRCUIT); + var serializedMaterial = VerificationMaterial.of( + SnarkjsJsonCodec.toVerificationKeyBytes(parsedVk), + ProofSystemId.GROTH16, CurveId.BLS12_381, CIRCUIT); + assertTrue(pure.verify(serializedEnvelope, serializedMaterial).proofValid(), "Java toEnvelope round-trip"); + assertTrue(nativeVerifier.verify(serializedEnvelope, serializedMaterial).proofValid(), "blst toEnvelope round-trip"); + } + + private void assertParityError(ZkProofEnvelope env, VerificationMaterial mat, + VerificationResult.ReasonCode expected, String label) { + var pj = pure.verify(env, mat); + var bl = nativeVerifier.verify(env, mat); + assertFalse(pj.proofValid(), "Java " + label); + assertFalse(bl.proofValid(), "blst " + label); + assertEquals(expected, pj.reasonCode().orElse(null), "Java reason " + label); + assertEquals(expected, bl.reasonCode().orElse(null), "blst reason " + label); + } + private static String rescaleG1(List point, BigInteger lambda) { assertEquals(BigInteger.ONE, point.get(2)); return "[\"" + point.get(0).multiply(lambda).mod(Fp.P) + "\",\"" diff --git a/zeroj-verifier-groth16/src/test/java/org/zeroj/verifier/groth16/bls12381/Groth16BLS12381PureJavaVerifierTest.java b/zeroj-verifier-groth16/src/test/java/org/zeroj/verifier/groth16/bls12381/Groth16BLS12381PureJavaVerifierTest.java index 684f80c2..68b8ae53 100644 --- a/zeroj-verifier-groth16/src/test/java/org/zeroj/verifier/groth16/bls12381/Groth16BLS12381PureJavaVerifierTest.java +++ b/zeroj-verifier-groth16/src/test/java/org/zeroj/verifier/groth16/bls12381/Groth16BLS12381PureJavaVerifierTest.java @@ -50,21 +50,17 @@ void descriptorIsBLS12381Groth16Java() { void rejectWrongPublicInputs() { String proofJson = loadString("/test-vectors/groth16-bls12381/proof.json"); String vkJson = loadString("/test-vectors/groth16-bls12381/verification_key.json"); - // Wrong public inputs (different values) - var wrongInputs = new PublicInputs(java.util.List.of(java.math.BigInteger.valueOf(999))); - var envelope = ZkProofEnvelope.builder() - .proofSystem(ProofSystemId.GROTH16) - .curve(CurveId.BLS12_381) - .circuitId(new CircuitId("multiplier-bls")) - .proofBytes(proofJson.getBytes(StandardCharsets.UTF_8)) - .publicInputs(wrongInputs) - .vkRef(new VerificationKeyRef.ByHash(new byte[32])) - .proofFormat("snarkjs-json") - .build(); + String publicJson = loadString("/test-vectors/groth16-bls12381/public.json"); + var inputs = SnarkjsJsonCodec.parsePublicInputs(publicJson); + String wrongPublicJson = replaceFirstDecimal(publicJson, inputs.get(0), BigInteger.valueOf(999)); + // Wrong public inputs (different value, matching count & valid VK hash) so pairing check is reached + var envelope = SnarkjsJsonCodec.toEnvelopeFromJson( + proofJson, vkJson, wrongPublicJson, new CircuitId("multiplier-bls")); var material = loadMaterial("/test-vectors/groth16-bls12381/verification_key.json", "multiplier-bls"); var result = verifier.verify(envelope, material); assertFalse(result.proofValid(), "Wrong public inputs should fail"); + assertEquals(VerificationResult.ReasonCode.INVALID_PROOF, result.reasonCode().orElseThrow()); } @Test diff --git a/zeroj-verifier-groth16/src/test/java/org/zeroj/verifier/groth16/bn254/Groth16BN254VerifierTest.java b/zeroj-verifier-groth16/src/test/java/org/zeroj/verifier/groth16/bn254/Groth16BN254VerifierTest.java index 0a7500c6..a166ddc5 100644 --- a/zeroj-verifier-groth16/src/test/java/org/zeroj/verifier/groth16/bn254/Groth16BN254VerifierTest.java +++ b/zeroj-verifier-groth16/src/test/java/org/zeroj/verifier/groth16/bn254/Groth16BN254VerifierTest.java @@ -120,6 +120,21 @@ void rejectWrongVerificationKey() { assertFalse(result.accepted(), "Wrong VK should be rejected"); } + @Test + void isAvailableTracksPolicyAndNeverAppearsInServiceLoader() { + System.clearProperty(LegacyCurvePolicy.ALLOW_LEGACY_BN254_PROPERTY); + assertFalse(verifier.isAvailable(), "Legacy BN254 verifier must be unavailable by default"); + assertTrue(LegacyCurvePolicy.legacyBn254DisabledMessage().contains("unsound against adversarial input")); + + enableLegacyBn254(); + assertTrue(verifier.isAvailable(), "Legacy BN254 verifier becomes available only when explicitly enabled"); + var discovered = java.util.ServiceLoader.load(org.zeroj.backend.spi.ZkVerifier.class).stream() + .map(p -> p.type().getName()) + .toList(); + assertFalse(discovered.contains(Groth16BN254Verifier.class.getName()), + "Legacy Groth16BN254Verifier must never be registered in META-INF/services"); + } + @Test void descriptorIsBN254Groth16() { var desc = verifier.descriptor(); diff --git a/zeroj-verifier-plonk/src/main/java/org/zeroj/verifier/plonk/PlonkBLS12381Verifier.java b/zeroj-verifier-plonk/src/main/java/org/zeroj/verifier/plonk/PlonkBLS12381Verifier.java index 3e2cef7b..c784ea9c 100644 --- a/zeroj-verifier-plonk/src/main/java/org/zeroj/verifier/plonk/PlonkBLS12381Verifier.java +++ b/zeroj-verifier-plonk/src/main/java/org/zeroj/verifier/plonk/PlonkBLS12381Verifier.java @@ -2,19 +2,18 @@ import org.zeroj.api.*; import org.zeroj.backend.spi.BackendDescriptor; +import org.zeroj.backend.spi.EnvelopeBinding; import org.zeroj.backend.spi.ZkVerifier; import org.zeroj.bls12381.Bls12381Codecs; import org.zeroj.bls12381.ec.*; import org.zeroj.bls12381.field.*; import org.zeroj.codec.CodecException; -import org.zeroj.codec.CanonicalHash; import org.zeroj.bls12381.pairing.BLS12381Pairing; import org.zeroj.crypto.plonk.PlonKProverBLS381; import org.zeroj.crypto.transcript.FiatShamirTranscript; import java.math.BigInteger; import java.nio.charset.StandardCharsets; -import java.util.Arrays; import java.util.List; /** @@ -330,6 +329,11 @@ private void addG1(FiatShamirTranscript transcript, G1Point point, boolean compr } private VerificationResult validateEnvelopeMaterial(ZkProofEnvelope envelope, VerificationMaterial material) { + if (envelope == null) { + return VerificationResult.error( + VerificationResult.ReasonCode.MALFORMED_ENVELOPE, + "Proof envelope must not be null"); + } if (envelope.proofSystem() != ProofSystemId.PLONK) { return VerificationResult.error( VerificationResult.ReasonCode.UNSUPPORTED_PROOF_SYSTEM, @@ -340,27 +344,7 @@ private VerificationResult validateEnvelopeMaterial(ZkProofEnvelope envelope, Ve VerificationResult.ReasonCode.UNSUPPORTED_CURVE, "Expected BLS12-381 proof envelope"); } - if (material.proofSystemId() != envelope.proofSystem() - || material.curveId() != envelope.curve() - || !material.circuitId().equals(envelope.circuitId())) { - return VerificationResult.error( - VerificationResult.ReasonCode.VK_MISMATCH, - "Verification material does not match proof envelope"); - } - - byte[] actualVkHash = CanonicalHash.sha256(material.vkBytes()); - if (material.vkHash().isPresent() && !Arrays.equals(material.vkHash().orElseThrow(), actualVkHash)) { - return VerificationResult.error( - VerificationResult.ReasonCode.VK_MISMATCH, - "Verification material hash does not match VK bytes"); - } - if (envelope.vkRef() instanceof VerificationKeyRef.ByHash byHash - && !Arrays.equals(byHash.hash(), actualVkHash)) { - return VerificationResult.error( - VerificationResult.ReasonCode.VK_MISMATCH, - "Proof envelope VK hash does not match verification material"); - } - return null; + return EnvelopeBinding.validateBinding(envelope, material).orElse(null); } private void validateParsedMetadata(String proofProtocol, String proofCurve, String vkProtocol, String vkCurve) { diff --git a/zeroj-verifier-plonk/src/main/java/org/zeroj/verifier/plonk/PlonkBN254Verifier.java b/zeroj-verifier-plonk/src/main/java/org/zeroj/verifier/plonk/PlonkBN254Verifier.java index 288bb0fb..17813a25 100644 --- a/zeroj-verifier-plonk/src/main/java/org/zeroj/verifier/plonk/PlonkBN254Verifier.java +++ b/zeroj-verifier-plonk/src/main/java/org/zeroj/verifier/plonk/PlonkBN254Verifier.java @@ -10,7 +10,13 @@ import java.util.List; /** - * Pure Java PlonK verifier for BN254 — snarkjs compatible. + * Legacy pure Java PlonK verifier for BN254 — snarkjs compatible. + * + *

    SECURITY WARNING — LEGACY EXPERIMENTAL ONLY — UNSOUND AGAINST ADVERSARIAL INPUT: + * This verifier omits canonical coordinate, curve/subgroup, domain, and envelope-binding checks + * enforced by {@link PlonkBLS12381Verifier}. It is NOT registered via {@code ServiceLoader}, + * reports {@link #isAvailable()} as {@code false} unless {@link LegacyCurvePolicy#legacyBn254Enabled()} + * is explicitly enabled, and must only be used for trusted local off-chain experiments.

    * *

    Follows the exact snarkjs PlonK verification algorithm from * {@code snarkjs/src/plonk_verify.js} including the Keccak-256 Fiat-Shamir transcript.

    @@ -25,6 +31,11 @@ public class PlonkBN254Verifier implements ZkVerifier { @Override public BackendDescriptor descriptor() { return DESCRIPTOR; } + @Override + public boolean isAvailable() { + return LegacyCurvePolicy.legacyBn254Enabled(); + } + @Override public VerificationResult verify(ZkProofEnvelope envelope, VerificationMaterial material) { if (!LegacyCurvePolicy.legacyBn254Enabled()) { diff --git a/zeroj-verifier-plonk/src/test/java/org/zeroj/verifier/plonk/PlonkBN254VerifierTest.java b/zeroj-verifier-plonk/src/test/java/org/zeroj/verifier/plonk/PlonkBN254VerifierTest.java index fc106105..f7175ca1 100644 --- a/zeroj-verifier-plonk/src/test/java/org/zeroj/verifier/plonk/PlonkBN254VerifierTest.java +++ b/zeroj-verifier-plonk/src/test/java/org/zeroj/verifier/plonk/PlonkBN254VerifierTest.java @@ -139,6 +139,20 @@ void verify_malformedProof_returnsError() { assertEquals(VerificationResult.ReasonCode.INTERNAL_ERROR, result.reasonCode().orElse(null)); } + @Test + void isAvailableTracksPolicyAndNeverAppearsInServiceLoader() { + System.clearProperty(LegacyCurvePolicy.ALLOW_LEGACY_BN254_PROPERTY); + assertFalse(verifier.isAvailable(), "Legacy PlonkBN254Verifier must be unavailable by default"); + + enableLegacyBn254(); + assertTrue(verifier.isAvailable(), "Legacy PlonkBN254Verifier becomes available only when explicitly enabled"); + var discovered = java.util.ServiceLoader.load(org.zeroj.backend.spi.ZkVerifier.class).stream() + .map(p -> p.type().getName()) + .toList(); + assertFalse(discovered.contains(PlonkBN254Verifier.class.getName()), + "Legacy PlonkBN254Verifier must never be registered in META-INF/services"); + } + @Test void verify_sameProofTwice_deterministic() { enableLegacyBn254();