From b591fc81072d0e42e16771f2f9c646c039bcabdb Mon Sep 17 00:00:00 2001 From: Satya Date: Sat, 21 Nov 2026 09:10:54 +0800 Subject: [PATCH 1/3] Harden crypto, symbolic DSL, on-chain/JMT, CI, notices, and docs (ADR-0069) --- .github/workflows/heavy.yml | 2 + NOTICE | 17 ++ README.md | 41 +++-- ...0031-groth16-mpc-trusted-setup-ceremony.md | 7 +- ...nity-ic-profile-and-public-wire-binding.md | 6 +- ...lonk-v2-cardano-transcript-and-verifier.md | 73 ++++++++ www/src/content/docs/start/status.md | 13 +- .../main/java/org/zeroj/bbs/BbsService.java | 22 ++- .../java/org/zeroj/bbs/internal/BbsCodec.java | 3 +- .../org/zeroj/bbs/verifier/BbsZkVerifier.java | 60 ++++++- .../java/org/zeroj/bbs/BbsServiceTest.java | 46 +++++ .../org/zeroj/bls12381/Bls12381Codecs.java | 10 +- .../java/org/zeroj/bls12381/ec/G1Point.java | 7 +- .../zeroj/bls12381/ec/JacobianArith381.java | 8 +- .../bls12381/ec/JacobianArith381Test.java | 15 ++ .../java/org/zeroj/blst/ffm/BlstG1Msm.java | 157 +++++++++-------- .../java/org/zeroj/blst/ffm/BlstG2Msm.java | 135 +++++++++------ .../circuit/annotation/CircuitParam.java | 2 +- .../org/zeroj/circuit/annotation/ZkArray.java | 12 ++ .../org/zeroj/circuit/annotation/ZkBits.java | 15 +- .../org/zeroj/circuit/annotation/ZkBytes.java | 13 +- .../zeroj/circuit/annotation/ZkContext.java | 25 +++ .../annotation/ZkSymbolicTypesTest.java | 77 +++++++++ .../processor/CircuitAnnotationProcessor.java | 132 +++++++++++---- .../CircuitAnnotationProcessorTest.java | 89 ++++++++++ .../org/zeroj/circuit/CircuitAPIImpl.java | 48 +++++- .../src/main/java/org/zeroj/circuit/Gate.java | 9 +- .../main/java/org/zeroj/circuit/Signal.java | 5 + .../circuit/plonk/PlonKConstraintSystem.java | 10 +- .../java/org/zeroj/circuit/lib/Merkle.java | 23 +-- .../org/zeroj/circuit/lib/SignalMerkle.java | 14 +- .../circuit/lib/ed25519/Ed25519Point.java | 2 +- .../org/zeroj/circuit/lib/field/Fe25519.java | 43 ++++- .../circuit/lib/jubjub/InCircuitPedersen.java | 8 + .../lib/jubjub/InCircuitPedersenVector.java | 7 + .../org/zeroj/circuit/lib/zk/ZkPedersen.java | 4 + .../circuit/lib/jubjub/PedersenTest.java | 31 ++++ .../main/java/org/zeroj/codec/Halo2Codec.java | 16 +- .../java/org/zeroj/codec/Halo2CodecTest.java | 33 ++++ .../zeroj/crypto/groth16/Groth16Pipeline.java | 9 +- .../zeroj/crypto/groth16/Groth16PkMmap.java | 2 +- .../zeroj/crypto/groth16/Groth16PkStore.java | 33 +++- .../crypto/groth16/Groth16ProverBLS381.java | 20 ++- .../zeroj/crypto/groth16/SparsePointFile.java | 40 ++++- .../zeroj/crypto/kzg/KZGCommitmentBLS381.java | 17 +- .../org/zeroj/crypto/msm/FlatScalars.java | 11 +- .../zeroj/crypto/plonk/PlonKProverBLS381.java | 50 +++++- .../zeroj/crypto/plonk/PlonKSetupBLS381.java | 20 +++ .../crypto/setup/Groth16SetupBLS381.java | 98 +++++++---- .../zeroj/crypto/setup/Groth16SetupCache.java | 2 +- .../zeroj/crypto/setup/PowersOfTauBLS381.java | 6 +- .../org/zeroj/crypto/setup/SetupCacheIO.java | 11 +- .../java/org/zeroj/crypto/setup/SrsCache.java | 14 ++ .../transcript/FiatShamirTranscript.java | 6 +- .../zeroj/crypto/setup/SetupCacheTest.java | 68 +++++++- .../dsl/auction/SealedBidPureJavaE2ETest.java | 13 +- .../poseidon/ccl/PoseidonJmtReference.java | 158 ++++++++++++++++++ .../jmt/poseidon/ccl/PoseidonJmtTree.java | 4 +- .../PoseidonJmtSecurityRegressionTest.java | 19 +++ zeroj-onchain-julc/build.gradle | 40 ----- ...enticatedStateTransitionScriptFactory.java | 3 +- .../codec/Groth16VerificationKeyCodec.java | 32 +++- .../julc/groth16/codec/ProverToCardano.java | 4 + ...AuthenticatedStateTransitionValidator.java | 1 + ...roth16BLS12381TxOutRefBindingVerifier.java | 14 +- .../validator/Groth16BLS12381Verifier.java | 19 ++- .../PlonkBLS12381MultiInputParamVerifier.java | 6 + .../PlonkBLS12381MultiInputVerifier.java | 6 + .../validator/PlonkBLS12381Verifier.java | 5 + .../Groth16VerificationKeyCodecTest.java | 47 +++++- ...enticatedStateTransitionValidatorTest.java | 5 +- zeroj-tools/build.gradle | 2 + .../java/org/zeroj/ceremony/CeremonyCli.java | 22 ++- .../plonk/GnarkFiatShamirTranscript.java | 3 +- .../verifier/plonk/PlonkBLS12381Verifier.java | 12 +- 75 files changed, 1659 insertions(+), 403 deletions(-) create mode 100644 docs/adr/0069-plonk-v2-cardano-transcript-and-verifier.md create mode 100644 zeroj-codec/src/test/java/org/zeroj/codec/Halo2CodecTest.java diff --git a/.github/workflows/heavy.yml b/.github/workflows/heavy.yml index e64c8049..aadad0e3 100644 --- a/.github/workflows/heavy.yml +++ b/.github/workflows/heavy.yml @@ -19,9 +19,11 @@ on: branches: [ main ] paths: - 'zeroj-integration-tests/src/test/java/org/zeroj/examples/notes/**' + - 'zeroj-integration-tests/src/test/java/org/zeroj/it/sha2/**' - 'zeroj-integration-tests/build.gradle' - 'zeroj-circuit-lib/src/main/java/org/zeroj/circuit/lib/zk/**' - 'zeroj-circuit-lib/src/main/java/org/zeroj/circuit/lib/jubjub/**' + - 'zeroj-circuit-lib/src/main/java/org/zeroj/circuit/lib/hash/**' - '.github/workflows/heavy.yml' permissions: diff --git a/NOTICE b/NOTICE index c9e68f0c..ace1f5fe 100644 --- a/NOTICE +++ b/NOTICE @@ -61,6 +61,20 @@ https://github.com/dylibso/chicory Used only by the assurance/ WASM differential providers, which are outside the default build and are never published. +-------------------------------------------------------------------------- +Bouncy Castle — Cryptography Provider (bcprov-jdk18on) +-------------------------------------------------------------------------- +Copyright (c) 2000-2025 The Legion of the Bouncy Castle Inc. +Licensed under the Bouncy Castle License (MIT-style) +https://www.bouncycastle.org/licence.html + +-------------------------------------------------------------------------- +picocli — Command-Line Interface Framework +-------------------------------------------------------------------------- +Copyright (c) 2017-2024 Remko Popma +Licensed under the Apache License, Version 2.0 +https://picocli.info/ + -------------------------------------------------------------------------- Cardano Client Lib -------------------------------------------------------------------------- @@ -92,6 +106,9 @@ Shipped in a published artifact: Test data only (in no published artifact): + zeroj-bls12381/src/test/resources/rfc9380/ + RFC 9380 "Hashing to Elliptic Curves" test vectors (IETF Trust; + Revised BSD License) zeroj-bbs/src/test/resources/cfrg-bbs/ BBS draft-10 fixtures from decentralized-identity/bbs-signature (Apache License 2.0; the values are also in the IETF draft) diff --git a/README.md b/README.md index fd9462d6..f8d091ad 100644 --- a/README.md +++ b/README.md @@ -6,10 +6,10 @@ [![snapshot](https://img.shields.io/maven-metadata/v?metadataUrl=https%3A%2F%2Frepo.bloxbean.org%2Fmaven%2Fsnapshots%2Forg%2Fzeroj%2Fzeroj-crypto%2Fmaven-metadata.xml&strategy=latestProperty&label=snapshot)](#development-snapshots) -> ## **Preview Status** -> **ZeroJ** is currently in preview and under active development. Core functionality is available and usable for experimentation and testnet development, but some components and edge cases are still being implemented and hardened. +> ## **Research & Pre-Release Status** +> **ZeroJ** is experimental research software under active development. Components are labeled **Beta** (feature-complete and correctness-tested, testnet/evaluation only) or **Experimental** (opt-in, evolving) in the Support Matrix below. > -> ZeroJ has **not been externally audited**. APIs, serialization formats, and on-chain verifier scripts may change between releases. **Production use is not yet recommended.** +> ZeroJ has **not been externally audited**. APIs, serialization formats, and on-chain verifier scripts may change between releases. **Not for value-bearing or production/mainnet use.** Java-first zero-knowledge proof toolkit for Cardano. @@ -25,20 +25,20 @@ ZeroJ lets Java developers **define ZK circuits**, **generate proofs**, **verify ## Support Matrix -**Beta** means feature-complete and correctness-tested (3,500+ tests; the full -Groth16 flow is verified end-to-end on-chain against Yaci DevKit), but **not -externally audited and not for value-bearing/mainnet use**. **Experimental** -components are opt-in and may change or have known limitations. Statuses and -remaining production gates are tracked in +**Beta** means feature-complete and correctness-tested (including end-to-end +Groth16 verification on-chain against Yaci DevKit), but **not externally audited +and not for value-bearing/mainnet use** (tests are not a security or maturity +proof). **Experimental** components are opt-in and may change or have known +limitations. Statuses and remaining production gates are tracked in [ADR-0026](docs/adr/0026-production-readiness-review-and-remediation-plan.md). | Area | Components | Status | |------|-----------|--------| | Core proof model, codecs, verifier SPI/orchestrator | `zeroj-api`, `zeroj-codec`, `zeroj-backend-spi` | **Beta** | | Circuit definition (DSL, symbolic annotations, gadgets) | `zeroj-circuit-dsl`, `zeroj-circuit-annotation-*`, `zeroj-circuit-lib` ([per-gadget table](zeroj-circuit-lib/README.md)) | **Beta** | -| Groth16 BLS12-381 — pure Java prove + verify | `zeroj-crypto`, `zeroj-verifier-groth16` | **Beta** (production trusted setup requires an external snarkjs MPC ceremony; in-repo setup is dev-only and flag-gated) | -| Groth16 BLS12-381 — on-chain (Julc / Plutus V3) | `zeroj-onchain-julc` | **Beta — testnet only**, not value-bearing; bind `ScriptContext` in real validators (see `Groth16BLS12381TxOutRefBindingVerifier`) | -| PlonK BLS12-381 — pure Java prove + verify, `.ptau`/`.zkey` import | `zeroj-crypto`, `zeroj-verifier-plonk` | **Beta** | +| Groth16 BLS12-381 — pure Java prove + verify | `zeroj-crypto`, `zeroj-verifier-groth16` | **Beta** — proving is offline/isolated only (witness scalars are not heap-zeroized or constant-time in the JVM); production trusted setup requires an external snarkjs MPC ceremony (in-repo setup is dev-only and flag-gated) | +| Groth16 BLS12-381 — on-chain (Julc / Plutus V3) | `zeroj-onchain-julc` | **Beta — testnet only**, not value-bearing; bind `ScriptContext` in real validators (see `Groth16AuthenticatedStateTransitionValidator`) | +| PlonK BLS12-381 — pure Java prove + verify, `.ptau` import | `zeroj-crypto`, `zeroj-verifier-plonk` | **Experimental** — proving is offline/isolated only (witness scalars are not heap-zeroized or constant-time in the JVM) | | PlonK BLS12-381 — on-chain (Julc / Plutus V3) | `zeroj-onchain-julc` | **Experimental** — full KZG check implemented; labeled testnet trials only | | BBS (CFRG draft-10) — verification | `zeroj-bbs` | **Beta** (spec is an IRTF draft, not yet an RFC) | | BBS — issuance / proof generation | `zeroj-bbs` | **Beta with caveat** — offline/isolated only: no provider (pure Java or blst) has an evidenced side-channel contract ([ADR-0062](docs/adr/0062-bls12381-independent-review-and-remediation.md)) | @@ -58,7 +58,7 @@ remaining production gates are tracked in - **Multi-backend compilation** — one Java circuit can compile to R1CS for Groth16 or to PlonK ### Generate Proofs -- **Pure Java prover** (recommended) — Groth16 + PlonK for BLS12-381. Zero native dependencies. GraalVM compatible. Allocation-lean flat arithmetic, an `mmap`-able proving key, and a streaming trusted setup keep large circuits (millions of constraints) within commodity memory, no JNI (ADR-0029/0033/0034/0035). +- **Pure Java prover** (recommended) — Groth16 + PlonK for BLS12-381. Zero native dependencies (offline/isolated host model; witness scalars are not heap-zeroized or constant-time in the JVM). Allocation-lean flat arithmetic, an `mmap`-able proving key, and a streaming trusted setup keep large circuits (millions of constraints) within commodity memory, no JNI (ADR-0029/0033/0034/0035). (GraalVM `native-image` CI currently builds and verifies the `zeroj-ceremony` CLI; native-image proving is not yet CI-verified.) - **blst-accelerated prover backend** — optional, opt-in FFM-bound native MSM (`blst_p1s/p2s_mult_pippenger`); a faster Groth16 proving backend, bit-identical proofs. The MSM's `libblst` is built from source (no third-party wrapper) ([ADR-0029](docs/adr/0029-blst-accelerated-groth16-prover.md)). - **snarkjs CLI** — external CLI for circom-based circuits - **snarkjs key import** — import `.zkey` files, prove with the pure Java prover @@ -80,10 +80,6 @@ Reusable on-chain verifiers only verify the cryptographic proof statement. A real application validator must also bind replay protection, nullifiers, authorization, and any `ScriptContext` policy required by the business flow. -### Anchor on Cardano L1 -- 4 anchor patterns: proof hash, state root + proof hash, full verification ref, nullifier commitment -- CCL integration — fluent helpers for attaching proof metadata to transactions - ## Quick Start — Zero Dependencies Define a circuit, prove it, and verify — all in pure Java. @@ -204,7 +200,8 @@ The **pure Java prover and verifier require no optional dependencies**. ## Building ```bash -# Build the full repository, including opt-in WASM/native modules +# Build the default product surface (opt-in assurance WASM and benchmark modules require +# -PincludeAssurance or -PincludeBenchmarks) ./gradlew build # Build the core privacy path only @@ -251,6 +248,7 @@ The **pure Java prover and verifier require no optional dependencies**. | Module | Description | |--------|-------------| +| [`zeroj-bom-core`](zeroj-bom-core/) | Published BOM (Bill of Materials) for the default core product surface | | [`zeroj-api`](zeroj-api/) | Core proof model, envelopes, verification result types | | [`zeroj-codec`](zeroj-codec/) | Proof serialization — snarkjs JSON, CBOR, canonical hashing | | [`zeroj-backend-spi`](zeroj-backend-spi/) | Service Provider Interface for verification backends, plus verifier orchestration and backend routing | @@ -261,7 +259,9 @@ The **pure Java prover and verifier require no optional dependencies**. | [`zeroj-crypto-blst`](zeroj-crypto-blst/) | **Opt-in blst prover backend** — thin bridge wiring `zeroj-blst`'s native MSM into the `zeroj-crypto` prover SPI (keeps `zeroj-crypto` pure-Java by default; pure Java matches blst at large sizes since ADR-0033/0034) | | [`zeroj-tools`](zeroj-tools/) | Reusable operator tools and the `zeroj-ceremony` CLI — snarkjs-compatible Groth16 phase-2 contributor (`ZkeyContributor`), hash-to-G2 challenge derivation; embeddable in coordinator services and wallets | | [`zeroj-circuit-dsl`](zeroj-circuit-dsl/) | Java Circuit DSL — define circuits with CircuitSpec, compile to R1CS/PlonK | -| [`zeroj-circuit-lib`](zeroj-circuit-lib/) | Circuit standard library — Poseidon, MiMC, Merkle, Comparators, Binary, Mux, AliasCheck; in-circuit Blake2b / SHA-256 / SHA-512 / HMAC-SHA512 and Ed25519 / BIP32 / CIP-1852 key derivation; symbolic adapters; [per-gadget status](zeroj-circuit-lib/README.md#gadget-status) | +| [`zeroj-circuit-annotation-api`](zeroj-circuit-annotation-api/) | Symbolic circuit annotations (`@ZKCircuit`, `@Prove`, `@Public`, `@Secret`) and typed symbolic values (`ZkField`, `ZkBool`, `ZkUInt`, `ZkArray`, `ZkBits`, `ZkBytes`) | +| [`zeroj-circuit-annotation-processor`](zeroj-circuit-annotation-processor/) | Compile-time annotation processor generating typed `*Circuit` builders, schemas, and `Inputs` facades | +| [`zeroj-circuit-lib`](zeroj-circuit-lib/) | Circuit standard library — Poseidon, Merkle, Comparators, Binary, Mux; in-circuit Blake2b / SHA-256 / SHA-512 / HMAC-SHA512 and Ed25519 / BIP32 / CIP-1852 key derivation; symbolic adapters; [per-gadget status](zeroj-circuit-lib/README.md#gadget-status) | | [`zeroj-onchain-julc`](zeroj-onchain-julc/) | Reusable Plutus V3 on-chain verifiers and libraries via Julc; Groth16 is the primary supported path, PlonK BLS12-381 validators/libraries are experimental opt-in | #### Explicit Opt-In Product Modules @@ -283,7 +283,6 @@ documented independently; it does not mean untested. |--------|-------------| | [`zeroj-test-vectors`](zeroj-test-vectors/) | Shared test fixtures — pre-generated proofs and VKs | | [`zeroj-integration-tests`](zeroj-integration-tests/) | Cross-module security and end-to-end regressions (Groth16/PlonK E2E, tampering, invalid witness, snarkjs interop, Julc/Yaci on-chain) | -| [`zeroj-bom-core`](zeroj-bom-core/) | The single stable BOM for the default product surface | #### Opt-In Assurance and Benchmark Projects @@ -306,7 +305,7 @@ BloxBean Maven repository (`https://repo.bloxbean.org/maven/releases`), with the ```gradle dependencies { - implementation platform('org.zeroj:zeroj-bom-core:0.1.0') + implementation platform('org.zeroj:zeroj-bom-core:0.1.0-pre13') // Circuit definition + standard library implementation 'org.zeroj:zeroj-circuit-dsl' @@ -320,7 +319,7 @@ dependencies { implementation 'org.zeroj:zeroj-verifier-groth16' // Opt-in product artifacts are outside the stable BOM — give them a version - implementation 'org.zeroj:zeroj-verifier-plonk:0.1.0' + implementation 'org.zeroj:zeroj-verifier-plonk:0.1.0-pre13' // On-chain verification (Cardano Plutus V3) implementation 'org.zeroj:zeroj-onchain-julc' diff --git a/docs/adr/0031-groth16-mpc-trusted-setup-ceremony.md b/docs/adr/0031-groth16-mpc-trusted-setup-ceremony.md index b12832c0..1dd3fcc0 100644 --- a/docs/adr/0031-groth16-mpc-trusted-setup-ceremony.md +++ b/docs/adr/0031-groth16-mpc-trusted-setup-ceremony.md @@ -66,7 +66,7 @@ Java developers calling APIs — each role gets one command: |---|---|---|---| | `export-r1cs --circuit --out c.r1cs` | coordinator | compile the ZeroJ circuit → iden3 `.r1cs` (used by **both** options) | M4 | | `contribute in.zkey out.zkey` | contributor | Option B phase-2 contribution (entropy prompt + hash printout) | M5 | -| `verify c.r1cs pot.ptau final.zkey` | anyone | convenience wrapper; **independent check remains `snarkjs zkey verify`** | M5 | +| `verify c.r1cs pot.ptau final.zkey` | anyone | *not implemented in `zeroj-ceremony`* — use **`snarkjs zkey verify`** directly so verification remains completely independent | N/A | | `beacon in.zkey out.zkey --hash ` | coordinator | final beacon contribution | M5 | | `finalize final.zkey --pk-store ` | coordinator | import + persist via `Groth16PkStore`, export the VK for the validator | M2/M4 | @@ -99,7 +99,8 @@ Phase-2 contribution (BGM17): contributor samples random `d`, then - every **H** and **L** query point ← `d⁻¹·point` (the delta-divided sections), - appends a proof-of-knowledge of `d` (the s-pair construction) + running transcript hash, in exactly the snarkjs `.zkey` contributions-section layout, so `snarkjs zkey verify` accepts the -chain. CLI shape: `zeroj-ceremony contribute in.zkey out.zkey` (+ `verify`, `beacon`). +chain. CLI shape: `zeroj-ceremony contribute --in in.zkey --out out.zkey` (transcript verification +and final beacon remain in `snarkjs zkey verify` / `snarkjs zkey beacon`). **Honest cost estimate:** a contribution rescales ~77M G1 points (H+L) by one scalar — independent variable-base muls, embarrassingly parallel. Expected ~1 h-class per contribution at 19M on a @@ -155,7 +156,7 @@ that stays with the circuit's ceremony (minimum viable: coordinator contribution | M2 | `.zkey` import at 19M + `Groth16PkStore` integration | ownership-circuit-scale zkey imports within memory budget; persisted; warm prove works | | M3 | Phase-1 source decision (spike) | own-ptau vs Filecoin-conversion measured; one selected + documented | | M4 | **Option A runbook** | scripted, documented snarkjs ceremony (coordinator + contributor guides, transcript publication, beacon procedure); dry-run on a small circuit | -| M5 | **Option B contributor** | `zeroj-ceremony contribute/verify` producing snarkjs-verifiable contributions; cross-verified against snarkjs on the same transcript; timing measured at 19M | +| M5 | **Option B contributor** | `zeroj-ceremony contribute` producing snarkjs-verifiable contributions; independently verified with `snarkjs zkey verify` on the same transcript; timing measured at 19M | | M6 | Dry-run ceremony on the ownership circuit | ≥3 contributors (mixed A/B tooling on the same transcript), beacon, published transcript, `snarkjs zkey verify` green, imported key proves + verifies on-chain (testnet) | ## Results (2026-07-08) — M1–M6 delivered diff --git a/docs/adr/0045-groth16-infinity-ic-profile-and-public-wire-binding.md b/docs/adr/0045-groth16-infinity-ic-profile-and-public-wire-binding.md index a048b93f..b19248fa 100644 --- a/docs/adr/0045-groth16-infinity-ic-profile-and-public-wire-binding.md +++ b/docs/adr/0045-groth16-infinity-ic-profile-and-public-wire-binding.md @@ -87,9 +87,9 @@ therefore already consistent with the ADR-0025 profile. Only the native setup di - **Untrusted shape at setup time:** the relation (`constraints`, `numWires`, `numPublic`) is caller-supplied. As in issue #46, the setup must not weaken or silently reshape a relation; it must reject one it cannot produce a profile-conforming key for. -- **Untrusted at import time:** a `.zkey` file. `ZkeyPkStoreImporter` currently accepts an - infinity `IC` entry (`isOnCurve() || isInfinity()`); after this ADR it rejects it, matching - the verifier profile at the import boundary. +- **Untrusted at import/load time:** a `.zkey` file or cached/stored key bundle. + `ZkeyPkStoreImporter`, `Groth16SetupCache`, and `Groth16PkStore.load` all enforce the + verifier profile and reject any infinity `IC` entry at the import/load boundary. - **Secret:** `tau, alpha, beta, gamma, delta` in the dev setup (dev/test only, behind the ADR-0025 insecure-setup opt-in) and the prover blinders `r, s`. The new checks read only relation shape and the derived `IC` scalars; they do not introduce secret-dependent control diff --git a/docs/adr/0069-plonk-v2-cardano-transcript-and-verifier.md b/docs/adr/0069-plonk-v2-cardano-transcript-and-verifier.md new file mode 100644 index 00000000..80882e2a --- /dev/null +++ b/docs/adr/0069-plonk-v2-cardano-transcript-and-verifier.md @@ -0,0 +1,73 @@ +# ADR-0069: Future PlonK v2 Cardano Transcript, Single-Decode Verifier, and Parameter Surface + +- **Status:** Proposed +- **Date:** 2026-11-21 +- **Risk Classification:** R3 (Fiat-Shamir transcript, proof verification equation, on-chain Plutus V3 validator) +- **Related ADRs:** ADR-0010 (PlonK on-chain verifier), ADR-0022 (PlonK BLS12-381), ADR-0047 (snarkjs interop), ADR-0056 (Groth16 single-decode & MSM optimization), ADR-0066 (PlonK `.ptau` & `t3 = n + 6`) + +--- + +## Context + +ZeroJ's current PlonK BLS12-381 Cardano profiles (`COMPRESSED_G1` / `COMPRESSED_G1_MPI`) inherit snarkjs 0.7.6's unchained per-round Fiat-Shamir challenge derivation (including deriving `u` without chaining all prior transcript state) and decompress G1 proof/VK commitments multiple times on-chain (18 redundant decodes across verifier steps) while exposing redundant validator `@Param` values. + +Separately, the current `xiMinusOmegaInv` check in the on-chain verifier excludes the degenerate evaluation point `xi == omega` (where `X - xi * omega` / `xi - omega` vanishes); any future simplification must preserve that exact exclusion or prove an equivalent guard. + +Because changing the Fiat-Shamir transcript or `@Param` layout breaks interoperability with existing snarkjs 0.7.6 PlonK proofs and changes on-chain Plutus V3 script hashes, these improvements MUST be introduced as a versioned **v2 Cardano PlonK profile** while keeping the existing snarkjs-compatible v1 profile intact. + +--- + +## Threat Model & Trust Assumptions + +- **Adversarial prover:** Attempts to grind Fiat-Shamir challenges independently across rounds, exploit unchained transcript state (weak Fiat-Shamir / frozen-heart style attacks), substitute a proof across circuits/profiles/public-input arities, or exploit degenerate evaluation points (`xi in {0, 1, omega}` or `Z_H(xi) == 0`). +- **On-chain resource attacker:** Submits proofs sized to approach Plutus V3 CPU/memory execution budgets; eliminating redundant G1 decompressions directly increases safety margin under Cardano mainnet transaction budgets. +- **Trust assumptions:** Domain-separated Keccak-256 / Blake2b-256 (selected explicitly in the v2 wire profile) is modeled as a random oracle; the CRS (`tau*G1`, `tau*G2`) originates from an independently audited Powers of Tau ceremony. + +--- + +## Normative References + +- Gabizon, Williamson & Ciobotaru, *"PLONK: Permutations over Lagrange-bases for Oecumenical Noninteractive arguments of Knowledge"*, IACR ePrint 2019/953. +- Dao, Miller, Wright & Grubbs, *"Weak Fiat-Shamir Attacks on Modern Proof Systems"*, IEEE S&P 2023 (IACR ePrint 2023/691) — motivating full transcript chaining across every round including `u` and VK/public-input binding. +- CIP-0381 (Plutus V3 BLS12-381 primitives). +- ZeroJ ADR-0056 (single G1 decompression before arithmetic in Plutus V3 validators). + +--- + +## Proposed Security Invariants (v2 Profile) + +1. **I1 (Fully chained, domain-separated Fiat-Shamir transcript):** + - Initialize a single running sponge/hash state with an explicit v2 domain separator tag (`"zeroj-plonk-bls12381-v2"`), circuit VK commitment digest (`qM, qL, qR, qO, qC, s1, s2, s3`, `power`, `k1`, `k2`, `nPublic`), and length-prefixed public inputs. + - Absorb each round's compressed G1 commitments and evaluations in strict protocol order and chain every prior challenge into the next challenge derivation (`beta`, `gamma`, `alpha`, `zeta`, `v`, and **`u`** — never hashing standalone subsets). +2. **I2 (Single decompression per G1 point on-chain):** + - Decompress each compressed 48-byte G1 commitment in the VK and proof **once** via CIP-0381 `bls12_381_G1_uncompress` (which enforces length, canonical encoding, curve, and subgroup) and reuse the decompressed `G1Element` handles throughout linear combination and pairing evaluation, eliminating 18 redundant decodes. +3. **I3 (Degenerate challenge exclusion):** + - Preserve the explicit exclusion of `zeta == 0`, `zeta^n == 1` (`Z_H(zeta) == 0`), and `zeta == omega` (`xiMinusOmegaInv` check or direct equality rejection on `zeta` and `zeta * omega`), failing closed before division or inversion. +4. **I4 (Minimal, non-redundant `@Param` surface):** + - Audit and remove redundant derived `@Param` fields (e.g. values derivable cheaply from `power`/`omega` or folded into the precomputed VK digest) while documenting exact script-hash impact and binding all VK commitments into the v2 transcript. +5. **I5 (Strict v1/v2 profile separation):** + - Legacy snarkjs 0.7.6 v1 profiles remain unchanged for backward compatibility and cross-tool interop; v2 uses a distinct `proofFormat` identifier (`"zeroj-plonk-cardano-v2"`) so v1 and v2 proofs can never be confused. + +--- + +## Decision & Alternatives Considered + +- **Separate v2 profile vs. mutating v1 in place:** Mutating v1 would silently break snarkjs 0.7.6 interop and invalidate existing on-chain script hashes. Introducing a distinct v2 profile preserves v1 interop while allowing Cardano-native deployments to adopt strong Fiat-Shamir chaining and lower Plutus V3 CPU cost. +- **Keep `xiMinusOmegaInv` vs. removing it:** Removing the check without an equivalent `zeta != omega` guard would leave an unchecked zero denominator; v2 retains an explicit guard against `zeta in {0, 1, omega}` and `Z_H(zeta) == 0`. + +--- + +## Implementation Milestones (Future Work) + +- **M1:** Specify exact byte-level v2 transcript schedule and KAT vectors (independent reference script + pure-Java prover/verifier). +- **M2:** Implement `TranscriptEncoding.CARDANO_V2` in `PlonKProverBLS381` and `PlonkBLS12381Verifier` with negative transcript-tampering and degenerate-challenge tests. +- **M3:** Implement single-decode v2 Plutus V3 validator in `zeroj-onchain-julc`, benchmark CPU/memory reduction against v1 in Julc VM and Yaci DevKit, and audit minimal `@Param` set. +- **M4:** External cryptographic review before any non-experimental promotion. + +--- + +## Verification & Audit Gates + +- Independent Python/Rust reference transcript KATs matching Java and Plutus V3 byte-for-byte. +- Negative tests for challenge grinding, missing VK binding, `u` tampering, `zeta == 1`, `zeta == omega`, and cross-profile (`v1` vs `v2`) replay. +- Mandatory external cryptographic audit before promotion to production-safe status. diff --git a/www/src/content/docs/start/status.md b/www/src/content/docs/start/status.md index 164199ac..2f1058de 100644 --- a/www/src/content/docs/start/status.md +++ b/www/src/content/docs/start/status.md @@ -18,7 +18,7 @@ review says otherwise. | Label | Meaning in ZeroJ | |-------|------------------| -| **Beta** | Feature-complete and correctness-tested. The repository has more than 3,500 tests, and the full Groth16 flow is verified end-to-end on-chain against Yaci DevKit. **Not externally audited, and not for value-bearing or mainnet use.** | +| **Beta** | Feature-complete and correctness-tested, including end-to-end Groth16 verification against Yaci DevKit. **Not externally audited, and not for value-bearing or mainnet use.** | | **Beta, testnet only** | Beta, and additionally limited to test networks. Nothing of value should depend on it. | | **Beta with caveat** | Beta, with a specific known limitation you must design around. The caveat is named in the matrix. | | **Beta, opt-in** | Beta, but you have to add it explicitly; it's never pulled in by default. | @@ -66,7 +66,7 @@ alternative to Groth16, and these docs make no correctness or readiness claims f | Area | Modules | Status | |------|---------|--------| | BBS (IRTF CFRG draft-10): verification | `zeroj-bbs` | **Beta**. The spec is an IRTF draft, not yet an RFC. | -| BBS: issuance and proof generation | `zeroj-bbs` | **Beta with caveat**. The default pure-Java provider is not constant-time; prefer the blst provider for issuer keys. | +| BBS: issuance and proof generation | `zeroj-bbs` | **Beta with caveat**. Offline/isolated only: neither the pure-Java provider nor the blst provider has an evidenced constant-time side-channel contract in the JVM (see ADR-0062). | ### Commitments & encryption @@ -119,10 +119,11 @@ concretely for ZeroJ today: - **A valid proof isn't authorization.** The reusable on-chain verifiers only check the math. Your validator must still prevent replay, bind the proof to the transaction, track nullifiers, and enforce who may do what. See [Application security](/guides/verifying/application-security/). -- **No constant-time guarantee for Java code.** The BBS pure-Java provider uses fixed-schedule - arithmetic for secret scalars, but that is not a full JVM constant-time guarantee. For BBS issuer - keys, select the native blst provider. ZeroJ doesn't claim constant-time behavior for its Java - code. +- **No constant-time guarantee for Java/JVM secret paths.** Neither pure-Java secret operations + (proving, BBS issuance/proof generation, commitments, encryption) nor FFM calls into `libblst` + carry an evidenced constant-time or heap-zeroization guarantee in the JVM (see ADR-0062). Run + secret-bearing operations only on isolated/offline hosts where timing and memory side channels are + out of scope. - **PlonK is experimental,** off-chain and on-chain. - **APIs and coordinates can still change.** ZeroJ is pre-1.0. The move to `org.zeroj` in `0.1.0-pre12` is one example (see [Migration](/reference/migration/)). diff --git a/zeroj-bbs/src/main/java/org/zeroj/bbs/BbsService.java b/zeroj-bbs/src/main/java/org/zeroj/bbs/BbsService.java index 4184f369..67e0bb29 100644 --- a/zeroj-bbs/src/main/java/org/zeroj/bbs/BbsService.java +++ b/zeroj-bbs/src/main/java/org/zeroj/bbs/BbsService.java @@ -93,13 +93,29 @@ public BbsPresentation derivePresentation( return new BbsPresentation(proof, header, presentationHeader, revealedMessages); } + /** + * Verify a BBS selective-disclosure presentation. + * + *

Throws {@link BbsException} when the presentation's disclosed index structure is + * malformed (e.g., duplicate or out-of-range disclosed indices). Returns {@code false} + * on ciphersuite mismatch, invalid encodings, or cryptographic verification failure.

+ */ public boolean verifyPresentation(BbsPublicKey publicKey, BbsPresentation presentation) { + Objects.requireNonNull(publicKey, "publicKey required"); Objects.requireNonNull(presentation, "presentation required"); + if (publicKey.ciphersuite() != presentation.proof().ciphersuite() + || publicKey.ciphersuite() != provider.ciphersuite()) { + return false; + } + int hiddenCount = hiddenMessageCountFromProof(presentation.proof()); + if (hiddenCount < 0) { + return false; + } List revealed = presentation.revealedMessages().stream() .sorted(Comparator.comparingInt(BbsRevealedMessage::index)) .toList(); int[] indexes = revealed.stream().mapToInt(BbsRevealedMessage::index).toArray(); - validateDisclosedIndexes(indexes, hiddenMessageCountFromProof(presentation.proof()) + revealed.size()); + validateDisclosedIndexes(indexes, hiddenCount + revealed.size()); List messages = revealed.stream().map(BbsRevealedMessage::message).toList(); return provider.proofVerify( publicKey, @@ -128,6 +144,10 @@ private static int[] validateDisclosedIndexes(int[] indexes, int messageCount) { private static int hiddenMessageCountFromProof(BbsProof proof) { BbsCiphersuite ciphersuite = proof.ciphersuite(); int scalarBytes = proof.bytes().length - 3 * ciphersuite.g1Bytes(); + if (scalarBytes < 4 * ciphersuite.scalarBytes() + || scalarBytes % ciphersuite.scalarBytes() != 0) { + return -1; + } int scalarCount = scalarBytes / ciphersuite.scalarBytes(); return scalarCount - 4; } diff --git a/zeroj-bbs/src/main/java/org/zeroj/bbs/internal/BbsCodec.java b/zeroj-bbs/src/main/java/org/zeroj/bbs/internal/BbsCodec.java index aff639fa..a6c97933 100644 --- a/zeroj-bbs/src/main/java/org/zeroj/bbs/internal/BbsCodec.java +++ b/zeroj-bbs/src/main/java/org/zeroj/bbs/internal/BbsCodec.java @@ -236,7 +236,8 @@ public static List copyMessages(List messages) { Objects.requireNonNull(messages, "messages required"); List copy = new ArrayList<>(messages.size()); for (byte[] message : messages) { - copy.add(copy(message)); + Objects.requireNonNull(message, "message element required"); + copy.add(message.clone()); } return List.copyOf(copy); } 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..7942b710 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 @@ -12,21 +12,54 @@ import org.zeroj.bbs.BbsPublicKey; import org.zeroj.bbs.BbsService; +import java.util.EnumSet; +import java.util.Objects; +import java.util.Set; + /** * ZeroJ verifier adapter for CFRG BBS draft-10 presentations. + * + *

BBS presentations carry disclosed messages and presentation headers inside + * the CBOR {@code proofBytes} payload; {@link ZkProofEnvelope#publicInputs()} + * is not used by BBS and must be empty.

*/ public final class BbsZkVerifier implements ZkVerifier { private static final BackendDescriptor DESCRIPTOR = new BackendDescriptor(ProofSystemId.BBS, CurveId.BLS12_381, "bbs-bls12381-java"); private final BbsService service; + private final Set acceptedCiphersuites; + private final boolean allowPureJavaDispatch; + /** + * Default verifier accepting all supported CFRG BBS ciphersuites via pure-Java providers. + */ public BbsZkVerifier() { - this(BbsService.pureJava()); + this.service = BbsService.pureJava(); + this.acceptedCiphersuites = EnumSet.allOf(BbsCiphersuite.class); + this.allowPureJavaDispatch = true; } + /** + * Verifier pinned to the explicit {@link BbsService} and its configured ciphersuite + * (never silently downgrading a caller-configured provider to another provider or suite). + */ public BbsZkVerifier(BbsService service) { - this.service = java.util.Objects.requireNonNull(service, "BBS service required"); + this(service, EnumSet.of(Objects.requireNonNull(service, "BBS service required") + .provider().ciphersuite())); + } + + /** + * Verifier with an explicit accepted-ciphersuite policy. + */ + public BbsZkVerifier(BbsService service, Set acceptedCiphersuites) { + this.service = Objects.requireNonNull(service, "BBS service required"); + Objects.requireNonNull(acceptedCiphersuites, "acceptedCiphersuites required"); + if (acceptedCiphersuites.isEmpty()) { + throw new IllegalArgumentException("acceptedCiphersuites must not be empty"); + } + this.acceptedCiphersuites = EnumSet.copyOf(acceptedCiphersuites); + this.allowPureJavaDispatch = false; } @Override @@ -42,6 +75,11 @@ public VerificationResult verify(ZkProofEnvelope envelope, VerificationMaterial VerificationResult.ReasonCode.UNSUPPORTED_CURVE, "BBS verifier only supports BLS12-381"); } + if (envelope.publicInputs().size() != 0) { + return VerificationResult.error( + VerificationResult.ReasonCode.INVALID_PUBLIC_INPUTS, + "BBS envelopes must not carry field publicInputs; disclosed messages are encoded in proofBytes"); + } if (envelope.proofFormat().isPresent() && !BbsCiphersuite.DEFAULT_PROOF_FORMAT.equals(envelope.proofFormat().get())) { return VerificationResult.error( @@ -51,9 +89,21 @@ public VerificationResult verify(ZkProofEnvelope envelope, VerificationMaterial var presentation = BbsPresentationCodec.decode(envelope.proofBytes()); BbsCiphersuite ciphersuite = presentation.proof().ciphersuite(); - BbsService verifierService = service.provider().ciphersuite() == ciphersuite - ? service - : BbsService.pureJava(ciphersuite); + if (!acceptedCiphersuites.contains(ciphersuite)) { + return VerificationResult.error( + VerificationResult.ReasonCode.UNSUPPORTED_PROOF_SYSTEM, + "BBS ciphersuite is not accepted by verifier policy: " + ciphersuite); + } + BbsService verifierService; + if (service.provider().ciphersuite() == ciphersuite) { + verifierService = service; + } else if (allowPureJavaDispatch) { + verifierService = BbsService.pureJava(ciphersuite); + } else { + return VerificationResult.error( + VerificationResult.ReasonCode.UNSUPPORTED_PROOF_SYSTEM, + "Configured BBS service does not support presentation ciphersuite: " + ciphersuite); + } BbsPublicKey publicKey = new BbsPublicKey(material.vkBytes(), ciphersuite); boolean valid = verifierService.verifyPresentation(publicKey, presentation); return valid ? VerificationResult.cryptoValid() 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..a8d229f9 100644 --- a/zeroj-bbs/src/test/java/org/zeroj/bbs/BbsServiceTest.java +++ b/zeroj-bbs/src/test/java/org/zeroj/bbs/BbsServiceTest.java @@ -274,6 +274,52 @@ void serviceFactoryAcceptsExplicitBlsProvider() { assertTrue(bls.g2SecretScalarMulCalls > 0, "Selected BLS provider must be used for SkToPk"); } + @Test + void zkVerifierEnforcesSuitePolicyAndEmptyPublicInputsAndCodecRejectsNullMessage() { + BbsService sha256Service = BbsService.pureJava(BbsCiphersuite.BLS12381_SHA256); + BbsService shakeService = BbsService.pureJava(BbsCiphersuite.BLS12381_SHAKE256); + BbsKeyPair shakeKp = shakeService.keyPair(bytes("012345678901234567890123456789uv"), bytes("issuer")); + List messages = List.of(bytes("a"), bytes("b")); + BbsSignature sig = shakeService.sign(shakeKp.secretKey(), shakeKp.publicKey(), messages, bytes("hdr")); + BbsPresentation pres = shakeService.derivePresentation( + shakeKp.publicKey(), sig, messages, bytes("hdr"), bytes("nonce"), new int[]{0}); + + ZkProofEnvelope shakeEnv = ZkProofEnvelope.builder() + .proofSystem(ProofSystemId.BBS) + .curve(CurveId.BLS12_381) + .circuitId(new CircuitId("bbs-policy")) + .proofBytes(BbsPresentationCodec.encode(pres)) + .publicInputs(new PublicInputs(List.of())) + .vkRef(new VerificationKeyRef.ById("issuer")) + .proofFormat(BbsCiphersuite.DEFAULT_PROOF_FORMAT) + .build(); + VerificationMaterial shakeMat = VerificationMaterial.of( + shakeKp.publicKey().bytes(), ProofSystemId.BBS, CurveId.BLS12_381, new CircuitId("bbs-policy")); + + // Pinned SHA-256 verifier must NOT silently downgrade/dispatch to pure-Java SHAKE256. + var rejectedSuite = new BbsZkVerifier(sha256Service).verify(shakeEnv, shakeMat); + assertFalse(rejectedSuite.proofValid()); + + // Non-empty publicInputs must be rejected. + ZkProofEnvelope withPubInputs = ZkProofEnvelope.builder() + .proofSystem(ProofSystemId.BBS) + .curve(CurveId.BLS12_381) + .circuitId(new CircuitId("bbs-policy")) + .proofBytes(BbsPresentationCodec.encode(pres)) + .publicInputs(new PublicInputs(List.of(BigInteger.ONE))) + .vkRef(new VerificationKeyRef.ById("issuer")) + .proofFormat(BbsCiphersuite.DEFAULT_PROOF_FORMAT) + .build(); + var rejectedPub = new BbsZkVerifier().verify(withPubInputs, shakeMat); + assertFalse(rejectedPub.proofValid()); + + // BbsCodec.copyMessages must reject null message elements. + List withNull = new ArrayList<>(); + withNull.add(bytes("ok")); + withNull.add(null); + assertThrows(NullPointerException.class, () -> BbsCodec.copyMessages(withNull)); + } + @Test void octetsToProofAndVerifyPresentationRejectZeroAndOutOfRangeScalarsInEverySlot() { BbsService service = BbsService.pureJava(); diff --git a/zeroj-bls12381/src/main/java/org/zeroj/bls12381/Bls12381Codecs.java b/zeroj-bls12381/src/main/java/org/zeroj/bls12381/Bls12381Codecs.java index b7a05023..aaa7dfb2 100644 --- a/zeroj-bls12381/src/main/java/org/zeroj/bls12381/Bls12381Codecs.java +++ b/zeroj-bls12381/src/main/java/org/zeroj/bls12381/Bls12381Codecs.java @@ -32,13 +32,9 @@ public final class Bls12381Codecs { private Bls12381Codecs() {} public static byte[] scalarToLittleEndian32(BigInteger scalar) { - Objects.requireNonNull(scalar, "scalar required"); - if (scalar.signum() < 0 || scalar.compareTo(Bls12381Generators.SCALAR_FIELD_ORDER) >= 0) { - throw new IllegalArgumentException("Scalar is outside BLS12-381 Fr"); - } - byte[] be = fixedBigEndian(scalar, SCALAR_BYTES); - reverse(be); - return be; + byte[] out = scalarToBigEndian32(scalar); + reverse(out); + return out; } public static byte[] scalarToLittleEndian32Reduced(BigInteger scalar) { diff --git a/zeroj-bls12381/src/main/java/org/zeroj/bls12381/ec/G1Point.java b/zeroj-bls12381/src/main/java/org/zeroj/bls12381/ec/G1Point.java index 092bc510..ce3e861f 100644 --- a/zeroj-bls12381/src/main/java/org/zeroj/bls12381/ec/G1Point.java +++ b/zeroj-bls12381/src/main/java/org/zeroj/bls12381/ec/G1Point.java @@ -40,9 +40,10 @@ public boolean isValid() { /** Create from snarkjs projective [x, y, z] coordinates. */ public static G1Point fromProjective(BigInteger px, BigInteger py, BigInteger pz) { - if (pz.signum() == 0) return INFINITY; - if (pz.equals(BigInteger.ONE)) return new G1Point(Fp.of(px), Fp.of(py)); - var zInv = Fp.of(pz).inv(); + BigInteger zMod = pz.mod(Fp.P); + if (zMod.signum() == 0) return INFINITY; + if (zMod.equals(BigInteger.ONE)) return new G1Point(Fp.of(px), Fp.of(py)); + var zInv = Fp.of(zMod).inv(); return new G1Point(Fp.of(px).mul(zInv), Fp.of(py).mul(zInv)); } diff --git a/zeroj-bls12381/src/main/java/org/zeroj/bls12381/ec/JacobianArith381.java b/zeroj-bls12381/src/main/java/org/zeroj/bls12381/ec/JacobianArith381.java index 17938d0c..bf531e02 100644 --- a/zeroj-bls12381/src/main/java/org/zeroj/bls12381/ec/JacobianArith381.java +++ b/zeroj-bls12381/src/main/java/org/zeroj/bls12381/ec/JacobianArith381.java @@ -43,8 +43,12 @@ public static void copyPoint(long[] o, int oo, long[] a, int ao) { System.arraycopy(a, ao, o, oo, POINT_LONGS); } - /** Load an affine (x,y) into a Jacobian point (Z=1) at {@code o[oo..]}. */ + /** Load an affine (x,y) into a Jacobian point at {@code o[oo..]}, mapping (0, 0) to infinity. */ public static void fromAffine(long[] o, int oo, long[] ax, int axo, long[] ay, int ayo) { + if (FpArith381.isZero(ax, axo) && FpArith381.isZero(ay, ayo)) { + setInfinity(o, oo); + return; + } FpArith381.copy(o, X(oo), ax, axo); FpArith381.copy(o, Y(oo), ay, ayo); System.arraycopy(FP_ONE, 0, o, Z(oo), L); @@ -129,8 +133,8 @@ public static void add(long[] o, int oo, long[] a, int ao, long[] b, int bo, lon public static void addAffine(long[] o, int oo, long[] a, int ao, long[] ax, int axo, long[] ay, int ayo, long[] s) { - if (isInfinity(a, ao)) { fromAffine(o, oo, ax, axo, ay, ayo); return; } if (FpArith381.isZero(ax, axo) && FpArith381.isZero(ay, ayo)) { copyPoint(o, oo, a, ao); return; } + if (isInfinity(a, ao)) { fromAffine(o, oo, ax, axo, ay, ayo); return; } final int Z1Z1 = 0, Z1Z1Z1 = 6, U2 = 12, S2 = 18, H = 24, R = 30, HH = 36, HHH = 42, V = 48, T = 54, X3 = 60, Y3 = 66, Z3 = 72; diff --git a/zeroj-bls12381/src/test/java/org/zeroj/bls12381/ec/JacobianArith381Test.java b/zeroj-bls12381/src/test/java/org/zeroj/bls12381/ec/JacobianArith381Test.java index d66f87a0..731678b6 100644 --- a/zeroj-bls12381/src/test/java/org/zeroj/bls12381/ec/JacobianArith381Test.java +++ b/zeroj-bls12381/src/test/java/org/zeroj/bls12381/ec/JacobianArith381Test.java @@ -118,6 +118,21 @@ void specialCases() { assertSame("P + inf == P", j, o, 0); JacobianArith381.dbl(o, 0, inf, 0, s); assertNull(flatAffine(o, 0), "dbl(inf) == inf"); + + // (0, 0) affine infinity sentinel parity with JacobianG1BLS381 + long[] zeroCoord = new long[6]; + long[] fromZero = new long[18]; + JacobianArith381.fromAffine(fromZero, 0, zeroCoord, 0, zeroCoord, 0); + assertNull(flatAffine(fromZero, 0), "fromAffine(0, 0) must be infinity"); + assertTrue(JacobianArith381.isInfinity(fromZero, 0)); + + // addAffine(P, (0, 0)) == P + JacobianArith381.addAffine(o, 0, P, 0, zeroCoord, 0, zeroCoord, 0, s); + assertSame("addAffine(P, inf) == P", j, o, 0); + + // addAffine(inf, (0, 0)) == inf + JacobianArith381.addAffine(o, 0, inf, 0, zeroCoord, 0, zeroCoord, 0, s); + assertTrue(JacobianArith381.isInfinity(o, 0), "addAffine(inf, inf) must be infinity"); } @Test diff --git a/zeroj-blst/src/main/java/org/zeroj/blst/ffm/BlstG1Msm.java b/zeroj-blst/src/main/java/org/zeroj/blst/ffm/BlstG1Msm.java index 4d222831..9bd5468e 100644 --- a/zeroj-blst/src/main/java/org/zeroj/blst/ffm/BlstG1Msm.java +++ b/zeroj-blst/src/main/java/org/zeroj/blst/ffm/BlstG1Msm.java @@ -6,6 +6,7 @@ import java.lang.foreign.ValueLayout; import java.lang.invoke.MethodHandle; import java.math.BigInteger; +import java.util.Arrays; /** * Batched BLS12-381 G1 multi-scalar multiplication via blst's native Pippenger @@ -61,34 +62,42 @@ private BlstG1Msm() {} public static byte[] singleMul(byte[] uncompressedPoint, BigInteger scalar) { BlstMsmInputs.requireLength(uncompressedPoint, 96, 0); byte[] le = new byte[32]; - BlstMsmInputs.scalarLe(scalar, le); - return singleMulCore(uncompressedPoint, le, false); + try { + BlstMsmInputs.scalarLe(scalar, le); + return singleMulCore(uncompressedPoint, le, false); + } finally { + Arrays.fill(le, (byte) 0); + } } private static byte[] singleMulCore(byte[] encoded, byte[] le, boolean validateBase) { BlstMsmInputs.requireUncompressedFlags(encoded, 0); try (Arena a = Arena.ofConfined()) { - MemorySegment in = a.allocate(P1_AFFINE, LIMB_ALIGN); - MemorySegment.copy(encoded, 0, in, BYTE, 0, 96); - MemorySegment aff = a.allocate(P1_AFFINE, LIMB_ALIGN); - int err = (int) DESERIALIZE.invoke(aff, in); - if (err != 0) throw new IllegalArgumentException("deserialize err=" + err); - if (validateBase && !(boolean) IN_G1.invoke(aff)) { - throw new IllegalArgumentException("Point 0 is not in the G1 subgroup"); - } - MemorySegment jac = a.allocate(P1, LIMB_ALIGN); - FROM_AFFINE.invoke(jac, aff); MemorySegment sc = a.allocate(SCALAR); - MemorySegment.copy(le, 0, sc, BYTE, 0, 32); - MemorySegment ret = a.allocate(P1, LIMB_ALIGN); - P1_MULT.invoke(ret, jac, sc, NBITS); - MemorySegment retAff = a.allocate(P1_AFFINE, LIMB_ALIGN); - TO_AFFINE.invoke(retAff, ret); - MemorySegment out = a.allocate(P1_AFFINE, LIMB_ALIGN); - AFFINE_SERIALIZE.invoke(out, retAff); - byte[] r = new byte[96]; - MemorySegment.copy(out, BYTE, 0, r, 0, 96); - return r; + try { + MemorySegment in = a.allocate(P1_AFFINE, LIMB_ALIGN); + MemorySegment.copy(encoded, 0, in, BYTE, 0, 96); + MemorySegment aff = a.allocate(P1_AFFINE, LIMB_ALIGN); + int err = (int) DESERIALIZE.invoke(aff, in); + if (err != 0) throw new IllegalArgumentException("deserialize err=" + err); + if (validateBase && !(boolean) IN_G1.invoke(aff)) { + throw new IllegalArgumentException("Point 0 is not in the G1 subgroup"); + } + MemorySegment jac = a.allocate(P1, LIMB_ALIGN); + FROM_AFFINE.invoke(jac, aff); + MemorySegment.copy(le, 0, sc, BYTE, 0, 32); + MemorySegment ret = a.allocate(P1, LIMB_ALIGN); + P1_MULT.invoke(ret, jac, sc, NBITS); + MemorySegment retAff = a.allocate(P1_AFFINE, LIMB_ALIGN); + TO_AFFINE.invoke(retAff, ret); + MemorySegment out = a.allocate(P1_AFFINE, LIMB_ALIGN); + AFFINE_SERIALIZE.invoke(out, retAff); + byte[] r = new byte[96]; + MemorySegment.copy(out, BYTE, 0, r, 0, 96); + return r; + } finally { + sc.fill((byte) 0); + } } catch (RuntimeException e) { throw e; } catch (Throwable t) { throw new RuntimeException(t); } } @@ -178,60 +187,72 @@ private static byte[] msmCore(int n, G1Encoder points, ScalarEncoder scalars, bo // base with Z = 1, so an identity base (all-zero affine) corrupts the whole result. MemorySegment pts = a.allocate(P1_AFFINE * n, LIMB_ALIGN); MemorySegment scal = a.allocate(SCALAR * n); - MemorySegment inBuf = a.allocate(P1_AFFINE, LIMB_ALIGN); - int m = 0; - for (int i = 0; i < n; i++) { - points.encode(i, buf); - scalars.encode(i, sbuf); - BlstMsmInputs.requireUncompressedFlags(buf, i); - BlstMsmInputs.requireCanonicalScalar(sbuf, i); - MemorySegment.copy(buf, 0, inBuf, BYTE, 0, 96); - MemorySegment slot = pts.asSlice(m * P1_AFFINE, P1_AFFINE); - int err = (int) DESERIALIZE.invoke(slot, inBuf); - if (err != 0) throw new IllegalArgumentException("blst_p1_deserialize failed at " + i + " (err=" + err + ")"); - if ((buf[0] & 0x40) != 0) continue; // a well-formed identity encoding - if (validateBases && !(boolean) IN_G1.invoke(slot)) { - throw new IllegalArgumentException("Point " + i + " is not in the G1 subgroup"); + MemorySegment scratch = null; + try { + MemorySegment inBuf = a.allocate(P1_AFFINE, LIMB_ALIGN); + int m = 0; + for (int i = 0; i < n; i++) { + points.encode(i, buf); + scalars.encode(i, sbuf); + BlstMsmInputs.requireUncompressedFlags(buf, i); + BlstMsmInputs.requireCanonicalScalar(sbuf, i); + MemorySegment.copy(buf, 0, inBuf, BYTE, 0, 96); + MemorySegment slot = pts.asSlice(m * P1_AFFINE, P1_AFFINE); + int err = (int) DESERIALIZE.invoke(slot, inBuf); + if (err != 0) throw new IllegalArgumentException("blst_p1_deserialize failed at " + i + " (err=" + err + ")"); + if ((buf[0] & 0x40) != 0) continue; // a well-formed identity encoding + if (validateBases && !(boolean) IN_G1.invoke(slot)) { + throw new IllegalArgumentException("Point " + i + " is not in the G1 subgroup"); + } + MemorySegment.copy(sbuf, 0, scal, BYTE, m * SCALAR, 32); + m++; } - MemorySegment.copy(sbuf, 0, scal, BYTE, m * SCALAR, 32); - m++; - } - if (m == 0) return infinity(); - if (m == 1) { // pippenger is batch-only - byte[] base = new byte[96]; - AFFINE_SERIALIZE.invoke(inBuf, pts.asSlice(0, P1_AFFINE)); - MemorySegment.copy(inBuf, BYTE, 0, base, 0, 96); - byte[] le = new byte[32]; - MemorySegment.copy(scal, BYTE, 0, le, 0, 32); - return singleMulCore(base, le, false); - } - final int count = m; - - // points[]/scalars[] are arrays of n pointers into the contiguous buffers. - MemorySegment ptsPtr = a.allocate(ValueLayout.ADDRESS, count); - MemorySegment scalPtr = a.allocate(ValueLayout.ADDRESS, count); - for (int i = 0; i < count; i++) { - ptsPtr.setAtIndex(ValueLayout.ADDRESS, i, pts.asSlice(i * P1_AFFINE, P1_AFFINE)); - scalPtr.setAtIndex(ValueLayout.ADDRESS, i, scal.asSlice(i * SCALAR, SCALAR)); - } + if (m == 0) return infinity(); + if (m == 1) { // pippenger is batch-only + byte[] base = new byte[96]; + AFFINE_SERIALIZE.invoke(inBuf, pts.asSlice(0, P1_AFFINE)); + MemorySegment.copy(inBuf, BYTE, 0, base, 0, 96); + byte[] le = new byte[32]; + try { + MemorySegment.copy(scal, BYTE, 0, le, 0, 32); + return singleMulCore(base, le, false); + } finally { + Arrays.fill(le, (byte) 0); + } + } + final int count = m; - long scratchBytes = (long) SCRATCH_SIZEOF.invoke((long) count); - MemorySegment scratch = a.allocate(Math.max(8, scratchBytes), LIMB_ALIGN); - MemorySegment ret = a.allocate(P1, LIMB_ALIGN); - PIPPENGER.invoke(ret, ptsPtr, (long) count, scalPtr, NBITS, scratch); + // points[]/scalars[] are arrays of n pointers into the contiguous buffers. + MemorySegment ptsPtr = a.allocate(ValueLayout.ADDRESS, count); + MemorySegment scalPtr = a.allocate(ValueLayout.ADDRESS, count); + for (int i = 0; i < count; i++) { + ptsPtr.setAtIndex(ValueLayout.ADDRESS, i, pts.asSlice(i * P1_AFFINE, P1_AFFINE)); + scalPtr.setAtIndex(ValueLayout.ADDRESS, i, scal.asSlice(i * SCALAR, SCALAR)); + } - MemorySegment retAff = a.allocate(P1_AFFINE, LIMB_ALIGN); - TO_AFFINE.invoke(retAff, ret); - MemorySegment out = a.allocate(P1_AFFINE, LIMB_ALIGN); - AFFINE_SERIALIZE.invoke(out, retAff); + long scratchBytes = (long) SCRATCH_SIZEOF.invoke((long) count); + scratch = a.allocate(Math.max(8, scratchBytes), LIMB_ALIGN); + MemorySegment ret = a.allocate(P1, LIMB_ALIGN); + PIPPENGER.invoke(ret, ptsPtr, (long) count, scalPtr, NBITS, scratch); - byte[] result = new byte[96]; - MemorySegment.copy(out, BYTE, 0, result, 0, 96); - return result; + MemorySegment retAff = a.allocate(P1_AFFINE, LIMB_ALIGN); + TO_AFFINE.invoke(retAff, ret); + MemorySegment out = a.allocate(P1_AFFINE, LIMB_ALIGN); + AFFINE_SERIALIZE.invoke(out, retAff); + + byte[] result = new byte[96]; + MemorySegment.copy(out, BYTE, 0, result, 0, 96); + return result; + } finally { + scal.fill((byte) 0); + if (scratch != null) scratch.fill((byte) 0); + } } catch (RuntimeException e) { throw e; } catch (Throwable t) { throw new RuntimeException("blst G1 MSM failed", t); + } finally { + Arrays.fill(sbuf, (byte) 0); } } diff --git a/zeroj-blst/src/main/java/org/zeroj/blst/ffm/BlstG2Msm.java b/zeroj-blst/src/main/java/org/zeroj/blst/ffm/BlstG2Msm.java index c1b02258..0f15d68c 100644 --- a/zeroj-blst/src/main/java/org/zeroj/blst/ffm/BlstG2Msm.java +++ b/zeroj-blst/src/main/java/org/zeroj/blst/ffm/BlstG2Msm.java @@ -6,6 +6,7 @@ import java.lang.foreign.ValueLayout; import java.lang.invoke.MethodHandle; import java.math.BigInteger; +import java.util.Arrays; /** * Batched BLS12-381 G2 multi-scalar multiplication via blst's native Pippenger @@ -130,48 +131,64 @@ private static byte[] msmCore(int n, G2Encoder points, ScalarEncoder scalars, bo // Identity bases contribute nothing and are dropped (ADR-0062 F11; see BlstG1Msm). MemorySegment pts = a.allocate(P2_AFFINE * n, LIMB_ALIGN); MemorySegment scal = a.allocate(SCALAR * n); - MemorySegment inBuf = a.allocate(P2_AFFINE, LIMB_ALIGN); - int m = 0; - for (int i = 0; i < n; i++) { - points.encode(i, buf); - scalars.encode(i, sbuf); - BlstMsmInputs.requireUncompressedFlags(buf, i); - BlstMsmInputs.requireCanonicalScalar(sbuf, i); - MemorySegment.copy(buf, 0, inBuf, BYTE, 0, (int) P2_AFFINE); - MemorySegment slot = pts.asSlice(m * P2_AFFINE, P2_AFFINE); - int err = (int) DESERIALIZE.invoke(slot, inBuf); - if (err != 0) throw new IllegalArgumentException("blst_p2_deserialize failed at " + i + " (err=" + err + ")"); - if ((buf[0] & 0x40) != 0) continue; // a well-formed identity encoding - if (validateBases && !(boolean) IN_G2.invoke(slot)) { - throw new IllegalArgumentException("Point " + i + " is not in the G2 subgroup"); + MemorySegment scratch = null; + try { + MemorySegment inBuf = a.allocate(P2_AFFINE, LIMB_ALIGN); + int m = 0; + for (int i = 0; i < n; i++) { + points.encode(i, buf); + scalars.encode(i, sbuf); + BlstMsmInputs.requireUncompressedFlags(buf, i); + BlstMsmInputs.requireCanonicalScalar(sbuf, i); + MemorySegment.copy(buf, 0, inBuf, BYTE, 0, (int) P2_AFFINE); + MemorySegment slot = pts.asSlice(m * P2_AFFINE, P2_AFFINE); + int err = (int) DESERIALIZE.invoke(slot, inBuf); + if (err != 0) throw new IllegalArgumentException("blst_p2_deserialize failed at " + i + " (err=" + err + ")"); + if ((buf[0] & 0x40) != 0) continue; // a well-formed identity encoding + if (validateBases && !(boolean) IN_G2.invoke(slot)) { + throw new IllegalArgumentException("Point " + i + " is not in the G2 subgroup"); + } + MemorySegment.copy(sbuf, 0, scal, BYTE, m * SCALAR, 32); + m++; } - MemorySegment.copy(sbuf, 0, scal, BYTE, m * SCALAR, 32); - m++; - } - if (m == 0) return infinity(); - if (m == 1) { // pippenger is batch-only - byte[] base = new byte[(int) P2_AFFINE]; - AFFINE_SERIALIZE.invoke(inBuf, pts.asSlice(0, P2_AFFINE)); - MemorySegment.copy(inBuf, BYTE, 0, base, 0, (int) P2_AFFINE); - byte[] le = new byte[32]; - MemorySegment.copy(scal, BYTE, 0, le, 0, 32); - return singleMulCore(base, le, false); - } - final int count = m; + if (m == 0) return infinity(); + if (m == 1) { // pippenger is batch-only + byte[] base = new byte[(int) P2_AFFINE]; + AFFINE_SERIALIZE.invoke(inBuf, pts.asSlice(0, P2_AFFINE)); + MemorySegment.copy(inBuf, BYTE, 0, base, 0, (int) P2_AFFINE); + byte[] le = new byte[32]; + try { + MemorySegment.copy(scal, BYTE, 0, le, 0, 32); + return singleMulCore(base, le, false); + } finally { + Arrays.fill(le, (byte) 0); + } + } + final int count = m; - MemorySegment ptsPtr = a.allocate(ValueLayout.ADDRESS, count); - MemorySegment scalPtr = a.allocate(ValueLayout.ADDRESS, count); - for (int i = 0; i < count; i++) { - ptsPtr.setAtIndex(ValueLayout.ADDRESS, i, pts.asSlice(i * P2_AFFINE, P2_AFFINE)); - scalPtr.setAtIndex(ValueLayout.ADDRESS, i, scal.asSlice(i * SCALAR, SCALAR)); + MemorySegment ptsPtr = a.allocate(ValueLayout.ADDRESS, count); + MemorySegment scalPtr = a.allocate(ValueLayout.ADDRESS, count); + for (int i = 0; i < count; i++) { + ptsPtr.setAtIndex(ValueLayout.ADDRESS, i, pts.asSlice(i * P2_AFFINE, P2_AFFINE)); + scalPtr.setAtIndex(ValueLayout.ADDRESS, i, scal.asSlice(i * SCALAR, SCALAR)); + } + long scratchBytes = (long) SCRATCH_SIZEOF.invoke((long) count); + scratch = a.allocate(Math.max(8, scratchBytes), LIMB_ALIGN); + MemorySegment ret = a.allocate(P2, LIMB_ALIGN); + PIPPENGER.invoke(ret, ptsPtr, (long) count, scalPtr, NBITS, scratch); + + return serializeAffine(a, ret); + } finally { + scal.fill((byte) 0); + if (scratch != null) scratch.fill((byte) 0); } - long scratchBytes = (long) SCRATCH_SIZEOF.invoke((long) count); - MemorySegment scratch = a.allocate(Math.max(8, scratchBytes), LIMB_ALIGN); - MemorySegment ret = a.allocate(P2, LIMB_ALIGN); - PIPPENGER.invoke(ret, ptsPtr, (long) count, scalPtr, NBITS, scratch); - - return serializeAffine(a, ret); - } catch (RuntimeException e) { throw e; } catch (Throwable t) { throw new RuntimeException("blst G2 MSM failed", t); } + } catch (RuntimeException e) { + throw e; + } catch (Throwable t) { + throw new RuntimeException("blst G2 MSM failed", t); + } finally { + Arrays.fill(sbuf, (byte) 0); + } } /** @@ -181,28 +198,36 @@ private static byte[] msmCore(int n, G2Encoder points, ScalarEncoder scalars, bo public static byte[] singleMul(byte[] uncompressedPoint, BigInteger scalar) { BlstMsmInputs.requireLength(uncompressedPoint, (int) P2_AFFINE, 0); byte[] le = new byte[32]; - BlstMsmInputs.scalarLe(scalar, le); - return singleMulCore(uncompressedPoint, le, false); + try { + BlstMsmInputs.scalarLe(scalar, le); + return singleMulCore(uncompressedPoint, le, false); + } finally { + Arrays.fill(le, (byte) 0); + } } private static byte[] singleMulCore(byte[] encoded, byte[] le, boolean validateBase) { BlstMsmInputs.requireUncompressedFlags(encoded, 0); try (Arena a = Arena.ofConfined()) { - MemorySegment in = a.allocate(P2_AFFINE, LIMB_ALIGN); - MemorySegment.copy(encoded, 0, in, BYTE, 0, (int) P2_AFFINE); - MemorySegment aff = a.allocate(P2_AFFINE, LIMB_ALIGN); - int err = (int) DESERIALIZE.invoke(aff, in); - if (err != 0) throw new IllegalArgumentException("deserialize err=" + err); - if (validateBase && !(boolean) IN_G2.invoke(aff)) { - throw new IllegalArgumentException("Point 0 is not in the G2 subgroup"); - } - MemorySegment jac = a.allocate(P2, LIMB_ALIGN); - FROM_AFFINE.invoke(jac, aff); MemorySegment sc = a.allocate(SCALAR); - MemorySegment.copy(le, 0, sc, BYTE, 0, 32); - MemorySegment ret = a.allocate(P2, LIMB_ALIGN); - P2_MULT.invoke(ret, jac, sc, NBITS); - return serializeAffine(a, ret); + try { + MemorySegment in = a.allocate(P2_AFFINE, LIMB_ALIGN); + MemorySegment.copy(encoded, 0, in, BYTE, 0, (int) P2_AFFINE); + MemorySegment aff = a.allocate(P2_AFFINE, LIMB_ALIGN); + int err = (int) DESERIALIZE.invoke(aff, in); + if (err != 0) throw new IllegalArgumentException("deserialize err=" + err); + if (validateBase && !(boolean) IN_G2.invoke(aff)) { + throw new IllegalArgumentException("Point 0 is not in the G2 subgroup"); + } + MemorySegment jac = a.allocate(P2, LIMB_ALIGN); + FROM_AFFINE.invoke(jac, aff); + MemorySegment.copy(le, 0, sc, BYTE, 0, 32); + MemorySegment ret = a.allocate(P2, LIMB_ALIGN); + P2_MULT.invoke(ret, jac, sc, NBITS); + return serializeAffine(a, ret); + } finally { + sc.fill((byte) 0); + } } catch (RuntimeException e) { throw e; } catch (Throwable t) { throw new RuntimeException(t); } } diff --git a/zeroj-circuit-annotation-api/src/main/java/org/zeroj/circuit/annotation/CircuitParam.java b/zeroj-circuit-annotation-api/src/main/java/org/zeroj/circuit/annotation/CircuitParam.java index ecbf4b7b..24fa4f2f 100644 --- a/zeroj-circuit-annotation-api/src/main/java/org/zeroj/circuit/annotation/CircuitParam.java +++ b/zeroj-circuit-annotation-api/src/main/java/org/zeroj/circuit/annotation/CircuitParam.java @@ -8,7 +8,7 @@ /** * Marks a build-time value that changes circuit shape. */ -@Target({ElementType.FIELD, ElementType.PARAMETER}) +@Target({ElementType.PARAMETER}) @Retention(RetentionPolicy.SOURCE) public @interface CircuitParam { String value() default ""; diff --git a/zeroj-circuit-annotation-api/src/main/java/org/zeroj/circuit/annotation/ZkArray.java b/zeroj-circuit-annotation-api/src/main/java/org/zeroj/circuit/annotation/ZkArray.java index e173feba..a552f1fa 100644 --- a/zeroj-circuit-annotation-api/src/main/java/org/zeroj/circuit/annotation/ZkArray.java +++ b/zeroj-circuit-annotation-api/src/main/java/org/zeroj/circuit/annotation/ZkArray.java @@ -15,6 +15,18 @@ public final class ZkArray implements ZkValue { public ZkArray(List values) { Objects.requireNonNull(values, "values"); + Signal firstSignal = null; + for (T value : values) { + Objects.requireNonNull(value, "values element"); + for (Signal signal : value.signals()) { + Objects.requireNonNull(signal, "signal"); + if (firstSignal == null) { + firstSignal = signal; + } else if (!firstSignal.hasSameBuilder(signal)) { + throw new IllegalArgumentException("Symbolic values belong to different circuit builders"); + } + } + } this.values = List.copyOf(values); } diff --git a/zeroj-circuit-annotation-api/src/main/java/org/zeroj/circuit/annotation/ZkBits.java b/zeroj-circuit-annotation-api/src/main/java/org/zeroj/circuit/annotation/ZkBits.java index 8611decf..73096695 100644 --- a/zeroj-circuit-annotation-api/src/main/java/org/zeroj/circuit/annotation/ZkBits.java +++ b/zeroj-circuit-annotation-api/src/main/java/org/zeroj/circuit/annotation/ZkBits.java @@ -18,6 +18,16 @@ public ZkBits(List bits) { if (bits.isEmpty()) { throw new IllegalArgumentException("bits must not be empty"); } + Signal firstSignal = null; + for (ZkBool bit : bits) { + Objects.requireNonNull(bit, "bits element"); + Signal current = bit.signal(); + if (firstSignal == null) { + firstSignal = current; + } else if (!firstSignal.hasSameBuilder(current)) { + throw new IllegalArgumentException("Symbolic values belong to different circuit builders"); + } + } this.bits = List.copyOf(bits); } @@ -65,7 +75,10 @@ public ZkBool isEqual(ZkBits other) { } public void assertEqual(ZkBits other) { - isEqual(other).assertTrue(); + requireSameSize(other); + for (int i = 0; i < bits.size(); i++) { + bits.get(i).assertEqual(other.bits.get(i)); + } } @Override diff --git a/zeroj-circuit-annotation-api/src/main/java/org/zeroj/circuit/annotation/ZkBytes.java b/zeroj-circuit-annotation-api/src/main/java/org/zeroj/circuit/annotation/ZkBytes.java index 96a16d2c..a177a65c 100644 --- a/zeroj-circuit-annotation-api/src/main/java/org/zeroj/circuit/annotation/ZkBytes.java +++ b/zeroj-circuit-annotation-api/src/main/java/org/zeroj/circuit/annotation/ZkBytes.java @@ -18,10 +18,18 @@ public ZkBytes(List bytes) { if (bytes.isEmpty()) { throw new IllegalArgumentException("bytes must not be empty"); } + Signal firstSignal = null; for (ZkUInt value : bytes) { + Objects.requireNonNull(value, "bytes element"); if (value.bits() != 8) { throw new IllegalArgumentException("bytes must contain only 8-bit ZkUInt values"); } + Signal current = value.signal(); + if (firstSignal == null) { + firstSignal = current; + } else if (!firstSignal.hasSameBuilder(current)) { + throw new IllegalArgumentException("Symbolic values belong to different circuit builders"); + } } this.bytes = List.copyOf(bytes); } @@ -70,7 +78,10 @@ public ZkBool isEqual(ZkBytes other) { } public void assertEqual(ZkBytes other) { - isEqual(other).assertTrue(); + requireSameSize(other); + for (int i = 0; i < bytes.size(); i++) { + bytes.get(i).assertEqual(other.bytes.get(i)); + } } @Override diff --git a/zeroj-circuit-annotation-api/src/main/java/org/zeroj/circuit/annotation/ZkContext.java b/zeroj-circuit-annotation-api/src/main/java/org/zeroj/circuit/annotation/ZkContext.java index 6bad06a2..6421fa42 100644 --- a/zeroj-circuit-annotation-api/src/main/java/org/zeroj/circuit/annotation/ZkContext.java +++ b/zeroj-circuit-annotation-api/src/main/java/org/zeroj/circuit/annotation/ZkContext.java @@ -36,6 +36,31 @@ public ZkField constant(BigInteger value) { return ZkField.wrap(this, builder.constant(value)); } + public ZkBool constantBool(boolean value) { + return ZkBool.trusted(this, builder.constant(value ? 1L : 0L)); + } + + public ZkUInt constantUInt(long value, int bits) { + if (bits <= 0 || bits > ZkUInt.MAX_BITS) { + throw new IllegalArgumentException("bits must be in [1, " + ZkUInt.MAX_BITS + "], got " + bits); + } + if (value < 0 || (bits < 63 && value >= (1L << bits))) { + throw new IllegalArgumentException("constantUInt value out of range for " + bits + " bits"); + } + return ZkUInt.trusted(this, builder.constant(value), bits); + } + + public ZkUInt constantUInt(BigInteger value, int bits) { + Objects.requireNonNull(value, "value"); + if (bits <= 0 || bits > ZkUInt.MAX_BITS) { + throw new IllegalArgumentException("bits must be in [1, " + ZkUInt.MAX_BITS + "], got " + bits); + } + if (value.signum() < 0 || value.bitLength() > bits) { + throw new IllegalArgumentException("constantUInt value out of range for " + bits + " bits"); + } + return ZkUInt.trusted(this, builder.constant(value), bits); + } + public ZkField field(Signal signal) { return ZkField.wrap(this, signal); } diff --git a/zeroj-circuit-annotation-api/src/test/java/org/zeroj/circuit/annotation/ZkSymbolicTypesTest.java b/zeroj-circuit-annotation-api/src/test/java/org/zeroj/circuit/annotation/ZkSymbolicTypesTest.java index 4001b7c4..e84be41d 100644 --- a/zeroj-circuit-annotation-api/src/test/java/org/zeroj/circuit/annotation/ZkSymbolicTypesTest.java +++ b/zeroj-circuit-annotation-api/src/test/java/org/zeroj/circuit/annotation/ZkSymbolicTypesTest.java @@ -511,4 +511,81 @@ void apiGuardrailsRejectInvalidShapeParameters() { .defineSignals(c -> ZkUInt.secret(c, "a", ZkUInt.MAX_BITS) .lt(ZkUInt.secret(c, "b", ZkUInt.MAX_BITS)))); } + + @Test + void contextConstantsContainerSingleBuilderAndBls12381AdversarialR1cs() { + // ZkContext.constantBool & constantUInt + range bounds + linear ZkBytes/ZkBits assertEqual on BLS12-381. + var circuit = CircuitBuilder.create("zk-const-and-linear-eq") + .publicVar("byte_0").publicVar("byte_1") + .secretVar("sbyte_0").secretVar("sbyte_1") + .secretVar("bit_0").secretVar("bit_1") + .defineSignals(c -> { + var zk = new ZkContext(c); + var pubBytes = ZkBytes.publicInput(c, "byte", 2); + var secBytes = ZkBytes.secret(c, "sbyte", 2); + pubBytes.assertEqual(secBytes); + + var secBits = ZkBits.secret(c, "bit", 2); + var expectedBits = new ZkBits(List.of(zk.constantBool(true), zk.constantBool(false))); + secBits.assertEqual(expectedBits); + + zk.constantUInt(255L, 8).assertEqual(pubBytes.get(0)); + assertThrows(IllegalArgumentException.class, () -> zk.constantUInt(-1L, 8)); + assertThrows(IllegalArgumentException.class, () -> zk.constantUInt(256L, 8)); + assertThrows(IllegalArgumentException.class, () -> zk.constantUInt(BigInteger.valueOf(256), 8)); + }); + + var validInputs = Map.of( + "byte_0", List.of(BigInteger.valueOf(255)), + "byte_1", List.of(BigInteger.valueOf(42)), + "sbyte_0", List.of(BigInteger.valueOf(255)), + "sbyte_1", List.of(BigInteger.valueOf(42)), + "bit_0", List.of(BigInteger.ONE), + "bit_1", List.of(BigInteger.ZERO)); + BigInteger[] witness = circuit.calculateWitness(validInputs, CurveId.BLS12_381); + var r1cs = circuit.compileR1CS(CurveId.BLS12_381); + org.junit.jupiter.api.Assertions.assertTrue( + satisfiesR1cs(r1cs, witness), "Honest BLS12-381 witness must satisfy R1CS"); + + // Adversarial R1CS witness tampering: flip one witness wire and verify R1CS rejects it. + BigInteger[] tampered = witness.clone(); + tampered[2] = BigInteger.valueOf(43); // pub byte_1 != sec sbyte_1 + org.junit.jupiter.api.Assertions.assertFalse( + satisfiesR1cs(r1cs, tampered), "Tampered BLS12-381 witness must fail R1CS"); + + // Container constructors must reject elements from different builders. + ZkUInt[] foreignByte = new ZkUInt[1]; + ZkBool[] foreignBit = new ZkBool[1]; + CircuitBuilder.create("foreign-b") + .secretVar("fb").secretVar("fbit") + .defineSignals(c -> { + foreignByte[0] = ZkUInt.secret(c, "fb", 8); + foreignBit[0] = ZkBool.secret(c, "fbit"); + }); + CircuitBuilder.create("local-b") + .secretVar("lb").secretVar("lbit") + .defineSignals(c -> { + var localByte = ZkUInt.secret(c, "lb", 8); + var localBit = ZkBool.secret(c, "lbit"); + assertThrows(IllegalArgumentException.class, () -> new ZkBytes(List.of(localByte, foreignByte[0]))); + assertThrows(IllegalArgumentException.class, () -> new ZkBits(List.of(localBit, foreignBit[0]))); + assertThrows(IllegalArgumentException.class, () -> new ZkArray<>(List.of(localByte, foreignByte[0]))); + }); + } + + private static boolean satisfiesR1cs(org.zeroj.circuit.r1cs.R1CSConstraintSystem r1cs, BigInteger[] witness) { + BigInteger p = r1cs.fieldConfig().prime(); + for (var c : r1cs.constraints()) { + BigInteger a = BigInteger.ZERO; + for (var e : c.a().entrySet()) a = a.add(e.getValue().multiply(witness[e.getKey()])).mod(p); + BigInteger b = BigInteger.ZERO; + for (var e : c.b().entrySet()) b = b.add(e.getValue().multiply(witness[e.getKey()])).mod(p); + BigInteger cv = BigInteger.ZERO; + for (var e : c.c().entrySet()) cv = cv.add(e.getValue().multiply(witness[e.getKey()])).mod(p); + if (!a.multiply(b).mod(p).equals(cv)) { + return false; + } + } + return true; + } } diff --git a/zeroj-circuit-annotation-processor/src/main/java/org/zeroj/circuit/annotation/processor/CircuitAnnotationProcessor.java b/zeroj-circuit-annotation-processor/src/main/java/org/zeroj/circuit/annotation/processor/CircuitAnnotationProcessor.java index 72f00993..e187c2ed 100644 --- a/zeroj-circuit-annotation-processor/src/main/java/org/zeroj/circuit/annotation/processor/CircuitAnnotationProcessor.java +++ b/zeroj-circuit-annotation-processor/src/main/java/org/zeroj/circuit/annotation/processor/CircuitAnnotationProcessor.java @@ -32,11 +32,14 @@ import java.io.Writer; import java.util.ArrayList; import java.util.Comparator; +import java.util.HashMap; import java.util.HashSet; +import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; +import java.util.regex.Pattern; import java.util.stream.Collectors; /** @@ -85,6 +88,10 @@ private void generate(TypeElement sourceType) throws IOException { throw new GenerationException(sourceType, "Nested @ZKCircuit classes are not supported in Phase 4"); } + if (sourceType.getModifiers().contains(Modifier.ABSTRACT)) { + throw new GenerationException(sourceType, + "Abstract @ZKCircuit classes are not supported"); + } List proveMethods = sourceType.getEnclosedElements().stream() .filter(e -> e.getKind() == ElementKind.METHOD) @@ -100,6 +107,10 @@ private void generate(TypeElement sourceType) throws IOException { throw new GenerationException(proveMethod, "@Prove method must be visible to generated code"); } + if (!proveMethod.getThrownTypes().isEmpty()) { + throw new GenerationException(proveMethod, + "@Prove method must not declare a throws clause"); + } validateReturnType(proveMethod); List circuitParams = circuitParams(sourceType, proveMethod); @@ -176,7 +187,8 @@ private List circuitParams(TypeElement sourceType, Executable + "String, BigInteger, or enum"); } params.add(new CircuitParamModel(name, parameter.getSimpleName().toString(), - parameter.asType().toString(), isIntegerCircuitParam(parameter.asType()))); + parameter.asType().toString(), isIntegerCircuitParam(parameter.asType()), + isBoxedInteger(parameter.asType()))); } return params; } @@ -220,6 +232,9 @@ private List inputs(TypeElement sourceType, ExecutableElement proveM } if (parameter.getAnnotation(Public.class) != null || parameter.getAnnotation(Secret.class) != null) { parameterInputs.add(parameterInput(parameter, circuitParams)); + } else { + throw new GenerationException(parameter, + "@Prove parameters must be ZkContext or annotated with @Public or @Secret"); } } @@ -241,6 +256,9 @@ private List inputs(TypeElement sourceType, ExecutableElement proveM } private InputModel fieldInput(VariableElement field, Map circuitParams) { + if (field.getModifiers().contains(Modifier.STATIC)) { + throw new GenerationException(field, "Static symbolic input fields are not supported"); + } if (field.getModifiers().contains(Modifier.PRIVATE)) { throw new GenerationException(field, "Private symbolic input fields are not supported in Phase 4"); } @@ -347,7 +365,7 @@ private SizeModel sizeModel(VariableElement element, int literal, String paramNa if (literal <= 0) { throw new GenerationException(element, label + " value must be positive"); } - return new SizeModel(Integer.toString(literal), false, ""); + return new SizeModel(Integer.toString(literal), false, "", false); } CircuitParamModel param = circuitParams.get(paramName); @@ -355,7 +373,7 @@ private SizeModel sizeModel(VariableElement element, int literal, String paramNa throw new GenerationException(element, label + " \"" + paramName + "\" must reference an integer @CircuitParam"); } - return new SizeModel(param.javaName(), true, param.name()); + return new SizeModel(param.javaName(), true, param.name(), param.boxedInt()); } private List orderInputs(List inputs) { @@ -390,7 +408,7 @@ private void validateInputNames(List inputs) { } Set flattenedNames = new HashSet<>(); - Map flattenedOwners = new java.util.HashMap<>(); + Map flattenedOwners = new HashMap<>(); for (InputModel input : inputs) { if (isFixedVector(input.valueKind())) { if (hasLiteralShape(input)) { @@ -411,7 +429,9 @@ private void validateInputNames(List inputs) { } } - for (InputModel array : inputs.stream().filter(i -> isFixedVector(i.valueKind())).toList()) { + for (InputModel array : inputs.stream() + .filter(i -> isFixedVector(i.valueKind()) && !hasLiteralShape(i)) + .toList()) { for (InputModel other : inputs.stream().filter(i -> i != array).toList()) { if (mayOverlapParameterizedFlattenedName(array, other.baseName())) { throw new GenerationException(null, @@ -455,7 +475,7 @@ private List literalFlattenedNames(InputModel input) { } private boolean mayOverlapParameterizedFlattenedName(InputModel array, String otherBaseName) { - String prefix = java.util.regex.Pattern.quote(array.baseName()); + String prefix = Pattern.quote(array.baseName()); if (isNestedArray(array)) { return otherBaseName.matches(prefix + "_\\d+.*"); } @@ -500,7 +520,7 @@ private String render(TypeElement sourceType, String packageName, String sourceS String zkLocal = uniqueLocalName("__zeroj", usedLocalNames); String loopLocal = uniqueLocalName("__zerojIndex", usedLocalNames); String innerLoopLocal = uniqueLocalName("__zerojInnerIndex", usedLocalNames); - Map inputLocals = new java.util.LinkedHashMap<>(); + Map inputLocals = new LinkedHashMap<>(); for (int i = 0; i < inputs.size(); i++) { inputLocals.put(inputs.get(i), uniqueLocalName("__zerojInput" + i, usedLocalNames)); } @@ -551,7 +571,7 @@ private String render(TypeElement sourceType, String packageName, String sourceS .append(") {\n"); renderFixedSizeParamGuards(out, inputs, " "); if (needsInstance) { - out.append(" var ").append(instanceLocal).append(" = new ").append(sourceSimpleName).append("(") + out.append(" var ").append(instanceLocal).append(" = new ").append(sourceType.getQualifiedName()).append("(") .append(circuitParams.stream().map(CircuitParamModel::javaName).collect(Collectors.joining(", "))) .append(");\n"); } @@ -599,30 +619,31 @@ private String render(TypeElement sourceType, String packageName, String sourceS out.append("\n private static String circuitName(") .append(renderParamSignature(circuitParams)) .append(") {\n") - .append(" String ").append(nameLocal).append(" = ") - .append(hasNameTemplate ? "CIRCUIT_NAME_TEMPLATE" : "CIRCUIT_NAME") - .append(";\n"); + .append(" String ").append(nameLocal).append(" = "); if (hasNameTemplate) { - for (CircuitParamModel param : circuitParams) { - out.append(" ").append(nameLocal).append(" = ").append(nameLocal) - .append(".replace(\"{").append(param.name()).append("}\", circuitParamDisplayValue(") - .append(param.javaName()).append("));\n"); - } + out.append(renderSinglePassTemplateExpression(nameTemplate, circuitParams)); + } else { + out.append("CIRCUIT_NAME"); } - out.append(" return ").append(nameLocal).append(" + circuitParamSuffix(") + out.append(";\n") + .append(" return ").append(nameLocal).append(" + circuitParamSuffix(") .append(renderParamNames(circuitParams)) .append(");\n") .append(" }\n"); + Set suffixLocals = new HashSet<>( + circuitParams.stream().map(CircuitParamModel::javaName).toList()); + String suffixLocal = uniqueLocalName("__zerojSuffix", suffixLocals); out.append("\n private static String circuitParamSuffix(") .append(renderParamSignature(circuitParams)) .append(") {\n") - .append(" String suffix = \"\";\n"); + .append(" String ").append(suffixLocal).append(" = \"\";\n"); for (CircuitParamModel param : circuitParams) { - out.append(" suffix = suffix + \"--").append(param.name()).append("-\" + circuitParamValue(") + out.append(" ").append(suffixLocal).append(" = ").append(suffixLocal) + .append(" + \"--").append(param.name()).append("-\" + circuitParamValue(") .append(param.javaName()).append(");\n"); } - out.append(" return suffix;\n") + out.append(" return ").append(suffixLocal).append(";\n") .append(" }\n"); out.append("\n private static String circuitParamDisplayValue(Object value) {\n") @@ -707,30 +728,51 @@ private void renderSchemaAndInputs(StringBuilder out, List ci .append(" if (schema == null) {\n") .append(" throw new NullPointerException(\"schema\");\n") .append(" }\n") - .append(" String circuitName = circuit.constraintGraph().name();\n") + .append(" var graph = circuit.constraintGraph();\n") + .append(" String circuitName = graph.name();\n") .append(" if (!circuitName.equals(schema.name())) {\n") .append(" throw new IllegalArgumentException(\"Circuit name \" + circuitName\n") .append(" + \" does not match generated input schema \" + schema.name());\n") .append(" }\n") + .append(" List publicNames = graph.publicInputs().stream()\n") + .append(" .map(v -> v.name()).toList();\n") + .append(" if (!publicNames.equals(schema.publicInputs().names())) {\n") + .append(" throw new IllegalArgumentException(\"Circuit public inputs \"\n") + .append(" + \"do not match generated input schema \" + schema.name());\n") + .append(" }\n") + .append(" List secretNames = graph.secretInputs().stream()\n") + .append(" .map(v -> v.name()).toList();\n") + .append(" if (!secretNames.equals(schema.secretInputs().names())) {\n") + .append(" throw new IllegalArgumentException(\"Circuit secret inputs \"\n") + .append(" + \"do not match generated input schema \" + schema.name());\n") + .append(" }\n") .append(" }\n"); renderInputsClass(out, inputs); } private void renderFixedSizeParamGuards(StringBuilder out, List inputs, String indent) { - Map sizeParams = new java.util.LinkedHashMap<>(); + Map sizeParams = new LinkedHashMap<>(); for (InputModel input : inputs) { if (input.size() != null && input.size().fromCircuitParam()) { - sizeParams.putIfAbsent(input.size().expression(), input.size().paramName()); + sizeParams.putIfAbsent(input.size().expression(), input.size()); } if (input.innerSize() != null && input.innerSize().fromCircuitParam()) { - sizeParams.putIfAbsent(input.innerSize().expression(), input.innerSize().paramName()); + sizeParams.putIfAbsent(input.innerSize().expression(), input.innerSize()); } } - for (Map.Entry entry : sizeParams.entrySet()) { + for (Map.Entry entry : sizeParams.entrySet()) { + SizeModel size = entry.getValue(); + if (size.nullable()) { + out.append(indent).append("if (").append(entry.getKey()).append(" == null) {\n") + .append(indent).append(" throw new IllegalArgumentException(") + .append(stringLiteral("@FixedSize(param = \"" + size.paramName() + "\") must not be null")) + .append(");\n") + .append(indent).append("}\n"); + } out.append(indent).append("if (").append(entry.getKey()).append(" <= 0) {\n") .append(indent).append(" throw new IllegalArgumentException(") - .append(stringLiteral("@FixedSize(param = \"" + entry.getValue() + "\") must be positive")) + .append(stringLiteral("@FixedSize(param = \"" + size.paramName() + "\") must be positive")) .append(");\n") .append(indent).append("}\n"); } @@ -1028,16 +1070,13 @@ private String proveCall(TypeElement sourceType, ExecutableElement proveMethod, List args = new ArrayList<>(); for (VariableElement parameter : proveMethod.getParameters()) { - if (parameter.getAnnotation(CircuitParam.class) != null) { - CircuitParam annotation = parameter.getAnnotation(CircuitParam.class); - args.add(annotation.value().isBlank() ? parameter.getSimpleName().toString() : annotation.value()); - } else if (isType(parameter.asType(), ZK_CONTEXT)) { + if (isType(parameter.asType(), ZK_CONTEXT)) { args.add(zkLocal); } else { InputModel input = byJavaName.get(parameter.getSimpleName().toString()); if (input == null) { throw new GenerationException(parameter, - "@Prove parameters must be ZkContext, @CircuitParam, or symbolic inputs"); + "@Prove parameters must be ZkContext or symbolic inputs"); } args.add(inputLocals.get(input)); } @@ -1045,6 +1084,29 @@ private String proveCall(TypeElement sourceType, ExecutableElement proveMethod, return receiver + "." + proveMethod.getSimpleName() + "(" + String.join(", ", args) + ")"; } + private String renderSinglePassTemplateExpression(String nameTemplate, List circuitParams) { + Map byName = circuitParams.stream() + .collect(Collectors.toMap(CircuitParamModel::name, p -> p)); + List parts = new ArrayList<>(); + int index = 0; + while (index < nameTemplate.length()) { + int start = nameTemplate.indexOf('{', index); + if (start < 0) { + parts.add(stringLiteral(nameTemplate.substring(index))); + break; + } + if (start > index) { + parts.add(stringLiteral(nameTemplate.substring(index, start))); + } + int end = nameTemplate.indexOf('}', start + 1); + String placeholder = nameTemplate.substring(start + 1, end); + CircuitParamModel param = byName.get(placeholder); + parts.add("circuitParamDisplayValue(" + param.javaName() + ")"); + index = end + 1; + } + return parts.isEmpty() ? "\"\"" : String.join(" + ", parts); + } + private void validateNameTemplate(List circuitParams, String nameTemplate) { if (circuitParams.isEmpty() || nameTemplate.isBlank()) { return; @@ -1166,6 +1228,10 @@ private boolean isIntegerCircuitParam(TypeMirror type) { return type.getKind() == TypeKind.INT || erasure(type).equals("java.lang.Integer"); } + private boolean isBoxedInteger(TypeMirror type) { + return type.getKind() != TypeKind.INT && erasure(type).equals("java.lang.Integer"); + } + private boolean isSupportedCircuitParamType(TypeMirror type) { return switch (type.getKind()) { case BOOLEAN, BYTE, SHORT, INT, LONG, CHAR -> true; @@ -1320,9 +1386,9 @@ private enum ValueKind { BYTES } - private record CircuitParamModel(String name, String javaName, String type, boolean intLike) {} + private record CircuitParamModel(String name, String javaName, String type, boolean intLike, boolean boxedInt) {} - private record SizeModel(String expression, boolean fromCircuitParam, String paramName) {} + private record SizeModel(String expression, boolean fromCircuitParam, String paramName, boolean nullable) {} private record InputModel( String javaName, diff --git a/zeroj-circuit-annotation-processor/src/test/java/org/zeroj/circuit/annotation/processor/CircuitAnnotationProcessorTest.java b/zeroj-circuit-annotation-processor/src/test/java/org/zeroj/circuit/annotation/processor/CircuitAnnotationProcessorTest.java index c092ac8b..8cf8e2bc 100644 --- a/zeroj-circuit-annotation-processor/src/test/java/org/zeroj/circuit/annotation/processor/CircuitAnnotationProcessorTest.java +++ b/zeroj-circuit-annotation-processor/src/test/java/org/zeroj/circuit/annotation/processor/CircuitAnnotationProcessorTest.java @@ -1342,6 +1342,95 @@ ZkBool prove(@Secret ZkBool ok) { assertTrue(unknown.diagnosticsText().contains("references unknown @CircuitParam: other")); } + @Test + void processorRejectsAbstractThrowsStaticFieldAndUnannotatedProveParamAndHandlesBoxedIntegerSinglePassTemplate() + throws Exception { + var abstractCircuit = compile("test.AbstractCircuit", """ + package test; + import org.zeroj.circuit.annotation.*; + @ZKCircuit + public abstract class AbstractCircuit { + @Prove ZkBool prove(@Public ZkBool ok) { return ok; } + } + """); + assertFalse(abstractCircuit.success()); + assertTrue(abstractCircuit.diagnosticsText().contains("Abstract @ZKCircuit")); + + var throwsCircuit = compile("test.ThrowsCircuit", """ + package test; + import org.zeroj.circuit.annotation.*; + @ZKCircuit + public class ThrowsCircuit { + @Prove ZkBool prove(@Public ZkBool ok) throws Exception { return ok; } + } + """); + assertFalse(throwsCircuit.success()); + assertTrue(throwsCircuit.diagnosticsText().contains("throws")); + + var staticFieldCircuit = compile("test.StaticFieldCircuit", """ + package test; + import org.zeroj.circuit.annotation.*; + @ZKCircuit + public class StaticFieldCircuit { + @Public static ZkBool ok; + @Prove ZkBool prove() { return ok; } + } + """); + assertFalse(staticFieldCircuit.success()); + assertTrue(staticFieldCircuit.diagnosticsText().contains("Static symbolic input fields")); + + var unannotatedParam = compile("test.UnannotatedParamCircuit", """ + package test; + import org.zeroj.circuit.annotation.*; + @ZKCircuit + public class UnannotatedParamCircuit { + @Public ZkBool ok; + @Prove ZkBool prove(ZkField extra) { return ok; } + } + """); + assertFalse(unannotatedParam.success()); + assertTrue(unannotatedParam.diagnosticsText().contains("@Prove parameters must be ZkContext")); + + // Boxed Integer @FixedSize param null check + single-pass template + param named "suffix" + var singlePass = compile("test.SinglePassAndBoxed", """ + package test; + import org.zeroj.circuit.annotation.*; + @ZKCircuit(nameTemplate = "c-{suffix}-{tag}") + public class SinglePassAndBoxed { + public SinglePassAndBoxed( + @CircuitParam("suffix") Integer suffix, + @CircuitParam("tag") String tag) {} + @Prove ZkBool prove( + @Secret @FixedSize(param = "suffix") ZkArray items, + @Public ZkBool ok) { + return ok; + } + } + """); + assertTrue(singlePass.success(), singlePass.diagnosticsText()); + Class gen = singlePass.load("test.SinglePassAndBoxedCircuit"); + var nullEx = assertThrows(java.lang.reflect.InvocationTargetException.class, + () -> gen.getMethod("build", Integer.class, String.class).invoke(null, null, "x")); + assertTrue(nullEx.getCause() instanceof IllegalArgumentException); + assertTrue(nullEx.getCause().getMessage().contains("must not be null")); + + // Single-pass template: if tag contains "{suffix}", it must NOT be substituted again. + var schema = (ZkCircuitSchema) gen.getMethod("schema", Integer.class, String.class) + .invoke(null, 2, "{suffix}"); + assertTrue(schema.name().startsWith("c-2-{suffix}--"), "got: " + schema.name()); + + // validateCircuit must reject a different circuit with the same name but different inputs. + var inputsObj = gen.getMethod("inputs", Integer.class, String.class).invoke(null, 2, "{suffix}"); + CircuitBuilder fakeSameName = CircuitBuilder.create(schema.name()) + .publicVar("wrong_pub") + .define(api -> {}); + var mismatchEx = assertThrows(java.lang.reflect.InvocationTargetException.class, + () -> gen.getMethod("calculateWitness", CircuitBuilder.class, inputsObj.getClass(), CurveId.class) + .invoke(null, fakeSameName, inputsObj, CurveId.BLS12_381)); + assertTrue(mismatchEx.getCause() instanceof IllegalArgumentException); + assertTrue(mismatchEx.getCause().getMessage().contains("public inputs")); + } + private Compilation compile(String className, String source) throws Exception { var compiler = ToolProvider.getSystemJavaCompiler(); assertNotNull(compiler, "Tests require a JDK, not a JRE"); diff --git a/zeroj-circuit-dsl/src/main/java/org/zeroj/circuit/CircuitAPIImpl.java b/zeroj-circuit-dsl/src/main/java/org/zeroj/circuit/CircuitAPIImpl.java index 3cd468a7..fcc1472a 100644 --- a/zeroj-circuit-dsl/src/main/java/org/zeroj/circuit/CircuitAPIImpl.java +++ b/zeroj-circuit-dsl/src/main/java/org/zeroj/circuit/CircuitAPIImpl.java @@ -219,10 +219,56 @@ private Variable newIntermediate() { } @Override - public Variable[] hintN(Gate.HintKind kind, java.math.BigInteger[] params, int numOutputs, Variable[] inputs) { + public Variable[] hintN(Gate.HintKind kind, BigInteger[] params, int numOutputs, Variable[] inputs) { // Hoist the lifecycle guard: with zero outputs newIntermediate() is never called, so // relying on its guard would let a post-build HintN mutate the snapshotted gate list. requireNotFrozen(); + Objects.requireNonNull(kind, "kind"); + Objects.requireNonNull(params, "params"); + Objects.requireNonNull(inputs, "inputs"); + if (numOutputs < 0) { + throw new IllegalArgumentException("numOutputs must be non-negative"); + } + for (int i = 0; i < params.length; i++) { + if (params[i] == null) { + throw new IllegalArgumentException("hintN params[" + i + "] must not be null"); + } + } + for (int i = 0; i < inputs.length; i++) { + Variable v = inputs[i]; + if (v == null || v.id() < 0 || v.id() >= nextId) { + throw new IllegalArgumentException("hintN inputs[" + i + "] is not a wire of this circuit"); + } + } + switch (kind) { + case MUL_MOD_REDUCE -> { + if (params.length != 4) { + throw new IllegalArgumentException("MUL_MOD_REDUCE requires 4 params [modulus, radixBits, numLimbsAB, numLimbsQ]"); + } + int radixBits = params[1].intValueExact(); + int nAB = params[2].intValueExact(); + int nQ = params[3].intValueExact(); + if (params[0].signum() <= 0 || radixBits <= 0 || nAB <= 0 || nQ <= 0) { + throw new IllegalArgumentException("MUL_MOD_REDUCE params must be positive"); + } + if (inputs.length != 2 * nAB || numOutputs != nQ + nAB) { + throw new IllegalArgumentException("MUL_MOD_REDUCE input/output counts do not match limb params"); + } + } + case INV_MOD -> { + if (params.length != 3) { + throw new IllegalArgumentException("INV_MOD requires 3 params [modulus, radixBits, numLimbs]"); + } + int radixBits = params[1].intValueExact(); + int numLimbs = params[2].intValueExact(); + if (params[0].signum() <= 0 || radixBits <= 0 || numLimbs <= 0) { + throw new IllegalArgumentException("INV_MOD params must be positive"); + } + if (inputs.length != numLimbs || numOutputs != numLimbs) { + throw new IllegalArgumentException("INV_MOD input/output counts do not match numLimbs"); + } + } + } var outputs = new Variable[numOutputs]; for (int i = 0; i < numOutputs; i++) outputs[i] = newIntermediate(); gates.add(new Gate.HintN(outputs, kind, inputs.clone(), params.clone())); diff --git a/zeroj-circuit-dsl/src/main/java/org/zeroj/circuit/Gate.java b/zeroj-circuit-dsl/src/main/java/org/zeroj/circuit/Gate.java index 0bfd3660..ad42c5d1 100644 --- a/zeroj-circuit-dsl/src/main/java/org/zeroj/circuit/Gate.java +++ b/zeroj-circuit-dsl/src/main/java/org/zeroj/circuit/Gate.java @@ -71,10 +71,11 @@ enum HintKind { /** * Non-native modular-reduction advice for {@code a·b mod m}. Given operand limbs, supplies * the quotient and remainder of the integer product. Layout — params: {@code [modulus, - * radixBits, numLimbs]}; inputs: {@code numLimbs} a-limbs then {@code numLimbs} b-limbs - * (radix 2^radixBits, little-endian); outputs: {@code numLimbs} q-limbs then {@code numLimbs} - * r-limbs where {@code a·b = q·modulus + r}, {@code 0 <= r < modulus}. The hint is - * unconstrained here — the caller MUST range-check q,r and enforce the identity + r= numWires + || add.wireB() < 0 || add.wireB() >= numWires + || add.outputWire() < 0 || add.outputWire() >= numWires) { + throw new IllegalArgumentException("PlonK addition references wire index outside [0, " + numWires + ")"); + } BigInteger a = extended[add.wireA()]; BigInteger b = extended[add.wireB()]; - if (a == null) a = BigInteger.ZERO; - if (b == null) b = BigInteger.ZERO; + if (a == null || b == null) { + throw new IllegalArgumentException("PlonK witness is missing required wire value for virtual addition"); + } extended[add.outputWire()] = add.factorA().multiply(a).add(add.factorB().multiply(b)).mod(p); } return extended; diff --git a/zeroj-circuit-lib/src/main/java/org/zeroj/circuit/lib/Merkle.java b/zeroj-circuit-lib/src/main/java/org/zeroj/circuit/lib/Merkle.java index 8c2dc78e..4510cd25 100644 --- a/zeroj-circuit-lib/src/main/java/org/zeroj/circuit/lib/Merkle.java +++ b/zeroj-circuit-lib/src/main/java/org/zeroj/circuit/lib/Merkle.java @@ -33,22 +33,7 @@ public interface HashFunction { public static void verifyProof(CircuitAPI api, Variable leaf, Variable root, Variable[] siblings, Variable[] pathBits, HashFunction hashFn) { - if (siblings.length != pathBits.length) { - throw new IllegalArgumentException("siblings and pathBits must have equal length"); - } - - Variable current = leaf; - for (int i = 0; i < siblings.length; i++) { - api.assertBoolean(pathBits[i]); - - // If pathBit == 0: current is left, sibling is right - // If pathBit == 1: sibling is left, current is right - var left = api.select(pathBits[i], siblings[i], current); - var right = api.select(pathBits[i], current, siblings[i]); - - current = hashFn.hash(api, left, right); - } - + Variable current = computeRoot(api, leaf, siblings, pathBits, hashFn); api.assertEqual(current, root); } @@ -58,6 +43,12 @@ public static void verifyProof(CircuitAPI api, Variable leaf, Variable root, public static Variable computeRoot(CircuitAPI api, Variable leaf, Variable[] siblings, Variable[] pathBits, HashFunction hashFn) { + if (siblings == null || pathBits == null) { + throw new IllegalArgumentException("siblings and pathBits must not be null"); + } + if (siblings.length != pathBits.length) { + throw new IllegalArgumentException("siblings and pathBits must have equal length"); + } Variable current = leaf; for (int i = 0; i < siblings.length; i++) { api.assertBoolean(pathBits[i]); diff --git a/zeroj-circuit-lib/src/main/java/org/zeroj/circuit/lib/SignalMerkle.java b/zeroj-circuit-lib/src/main/java/org/zeroj/circuit/lib/SignalMerkle.java index 5d329532..bea0ae39 100644 --- a/zeroj-circuit-lib/src/main/java/org/zeroj/circuit/lib/SignalMerkle.java +++ b/zeroj-circuit-lib/src/main/java/org/zeroj/circuit/lib/SignalMerkle.java @@ -25,13 +25,7 @@ public interface HashFn { */ public static void verifyProof(SignalBuilder c, Signal leaf, Signal root, Signal[] siblings, Signal[] pathBits, HashFn hashFn) { - Signal current = leaf; - for (int i = 0; i < siblings.length; i++) { - pathBits[i].assertBoolean(); - Signal left = pathBits[i].select(siblings[i], current); - Signal right = pathBits[i].select(current, siblings[i]); - current = hashFn.hash(c, left, right); - } + Signal current = computeRoot(c, leaf, siblings, pathBits, hashFn); c.assertEqual(current, root); } @@ -40,6 +34,12 @@ public static void verifyProof(SignalBuilder c, Signal leaf, Signal root, */ public static Signal computeRoot(SignalBuilder c, Signal leaf, Signal[] siblings, Signal[] pathBits, HashFn hashFn) { + if (siblings == null || pathBits == null) { + throw new IllegalArgumentException("siblings and pathBits must not be null"); + } + if (siblings.length != pathBits.length) { + throw new IllegalArgumentException("siblings and pathBits must have equal length"); + } Signal current = leaf; for (int i = 0; i < siblings.length; i++) { pathBits[i].assertBoolean(); diff --git a/zeroj-circuit-lib/src/main/java/org/zeroj/circuit/lib/ed25519/Ed25519Point.java b/zeroj-circuit-lib/src/main/java/org/zeroj/circuit/lib/ed25519/Ed25519Point.java index afb1f597..0e373f5c 100644 --- a/zeroj-circuit-lib/src/main/java/org/zeroj/circuit/lib/ed25519/Ed25519Point.java +++ b/zeroj-circuit-lib/src/main/java/org/zeroj/circuit/lib/ed25519/Ed25519Point.java @@ -163,7 +163,7 @@ private static Ed25519Point muxTree(CircuitAPI api, Ed25519Point[] table, Variab * Returns 32 field-element bytes in [0,255], ready to feed to {@code Blake2b}. */ public Variable[] encode() { - Fe25519 zInv = Fe25519.USE_HINT_INVERSE ? z.inverseHint() : z.inverse(); + Fe25519 zInv = Fe25519.hintConfig(api).useHintInverse() ? z.inverseHint() : z.inverse(); Fe25519 ax = x.mul(zInv).canonical(); Fe25519 ay = y.mul(zInv).canonical(); diff --git a/zeroj-circuit-lib/src/main/java/org/zeroj/circuit/lib/field/Fe25519.java b/zeroj-circuit-lib/src/main/java/org/zeroj/circuit/lib/field/Fe25519.java index 15aba08e..a40fc878 100644 --- a/zeroj-circuit-lib/src/main/java/org/zeroj/circuit/lib/field/Fe25519.java +++ b/zeroj-circuit-lib/src/main/java/org/zeroj/circuit/lib/field/Fe25519.java @@ -5,6 +5,10 @@ import org.zeroj.circuit.Variable; import java.math.BigInteger; +import java.util.Collections; +import java.util.Map; +import java.util.Objects; +import java.util.WeakHashMap; /** * In-circuit non-native field arithmetic over the Ed25519 base field @@ -137,30 +141,51 @@ public static BigInteger[] toLimbValues(BigInteger value) { /** (this - other) mod p, normalized. */ public Fe25519 sub(Fe25519 other) { return subLazy(other).reduce(); } + /** Per-circuit hint configuration for {@link Fe25519} arithmetic (avoids global static mutation). */ + public record HintConfig(boolean useHintMul, boolean useHintInverse) {} + + private static final Map CIRCUIT_HINTS = + Collections.synchronizedMap(new WeakHashMap<>()); + + /** Configure hint usage for a single {@link CircuitAPI} instance without mutating global state. */ + public static void configureHints(CircuitAPI api, HintConfig config) { + Objects.requireNonNull(api, "api"); + Objects.requireNonNull(config, "config"); + CIRCUIT_HINTS.put(api, config); + } + + /** Effective hint configuration for {@code api} (per-circuit override or global default). */ + public static HintConfig hintConfig(CircuitAPI api) { + HintConfig configured = api != null ? CIRCUIT_HINTS.get(api) : null; + return configured != null ? configured : new HintConfig(USE_HINT_MUL, USE_HINT_INVERSE); + } + /** * ADR-0028 Phase C opt-in: when {@code true}, {@link #mul} routes through the hint-based * {@link #mulHint}. AUDIT-GATED — do not enable in production until the hint path's * integer-identity argument is externally audited (ADR-0028 pillar 5). Default {@code false} - * keeps the deterministic path. Used by tests to measure/validate the wired end-to-end circuit. + * keeps the deterministic path. + * + * @deprecated Prefer per-circuit {@link #configureHints(CircuitAPI, HintConfig)} to avoid + * cross-thread global mutable state. */ + @Deprecated public static volatile boolean USE_HINT_MUL = false; /** * ADR-0028: when {@code true} (the default), {@link Ed25519Point#encode}-style inversions * route through the hint-based {@link #inverseHint} (~380× cheaper than the Fermat - * {@link #inverse}). Enabled by default because the inverse hint is trivially sound and - * standard practice: its check {@code a·a⁻¹ == 1} uniquely pins the inverse (adversarially - * reviewed, no forgery), and it uses the deterministic mul, so it is independent of the - * audit-gated CRT-mul. + * {@link #inverse}). * - *

To disable (fully-deterministic Fermat inverse, zero advice in the circuit) set - * {@code Fe25519.USE_HINT_INVERSE = false} before building the circuit.

+ * @deprecated Prefer per-circuit {@link #configureHints(CircuitAPI, HintConfig)} to avoid + * cross-thread global mutable state. */ + @Deprecated public static volatile boolean USE_HINT_INVERSE = true; - /** (this * other) mod p, normalized. Routes to {@link #mulHint} when {@link #USE_HINT_MUL}. */ + /** (this * other) mod p, normalized. Routes to {@link #mulHint} when enabled for this circuit. */ public Fe25519 mul(Fe25519 other) { - return USE_HINT_MUL ? mulHint(other) : mulDeterministic(other); + return hintConfig(api).useHintMul() ? mulHint(other) : mulDeterministic(other); } /** Deterministic schoolbook multiply (the frozen reference path; never uses advice). */ diff --git a/zeroj-circuit-lib/src/main/java/org/zeroj/circuit/lib/jubjub/InCircuitPedersen.java b/zeroj-circuit-lib/src/main/java/org/zeroj/circuit/lib/jubjub/InCircuitPedersen.java index 5ce99970..3995b8cf 100644 --- a/zeroj-circuit-lib/src/main/java/org/zeroj/circuit/lib/jubjub/InCircuitPedersen.java +++ b/zeroj-circuit-lib/src/main/java/org/zeroj/circuit/lib/jubjub/InCircuitPedersen.java @@ -128,6 +128,10 @@ public static InCircuitJubjub.Point commit(CircuitAPI api, api.requireOwned(blinding); validateValueWidth(value.width()); validateBlindingWidth(blinding.width()); + if (value.source().id() == blinding.source().id()) { + throw new IllegalArgumentException("wire " + blinding.source().id() + + " is used as both the value and the blinding (ADR-0051 D2)"); + } api.requireNotPublicOrConstant(blinding.source()); api.requireHidingRange(blinding.source(), BLINDING_BITS); InCircuitJubjub.Point vG = InCircuitJubjub.scalarMulFixedBase( @@ -155,6 +159,10 @@ public static InCircuitJubjub.Point commit(CircuitAPI api, Objects.requireNonNull(value, "value"); Objects.requireNonNull(blinding, "blinding"); validateValueWidth(valueBits); + if (value.id() == blinding.id()) { + throw new IllegalArgumentException("wire " + blinding.id() + + " is used as both the value and the blinding (ADR-0051 D2)"); + } api.requireNotPublicOrConstant(blinding); api.requireHidingRange(blinding, BLINDING_BITS); Variable[] valueBitVector = api.toBinary(value, valueBits); diff --git a/zeroj-circuit-lib/src/main/java/org/zeroj/circuit/lib/jubjub/InCircuitPedersenVector.java b/zeroj-circuit-lib/src/main/java/org/zeroj/circuit/lib/jubjub/InCircuitPedersenVector.java index 376217e0..6679dd57 100644 --- a/zeroj-circuit-lib/src/main/java/org/zeroj/circuit/lib/jubjub/InCircuitPedersenVector.java +++ b/zeroj-circuit-lib/src/main/java/org/zeroj/circuit/lib/jubjub/InCircuitPedersenVector.java @@ -59,6 +59,13 @@ public static InCircuitJubjub.Point commit(CircuitAPI api, throw new IllegalArgumentException("blinding width must be exactly " + InCircuitPedersen.BLINDING_BITS + ", got " + blinding.width() + " (ADR-0051 D2)"); } + int blindingWireId = blinding.source().id(); + for (int i = 0; i < values.size(); i++) { + if (values.get(i).source().id() == blindingWireId) { + throw new IllegalArgumentException("wire " + blindingWireId + + " is used as both value[" + i + "] and the blinding (ADR-0051 D2)"); + } + } api.requireNotPublicOrConstant(blinding.source()); api.requireHidingRange(blinding.source(), InCircuitPedersen.BLINDING_BITS); diff --git a/zeroj-circuit-lib/src/main/java/org/zeroj/circuit/lib/zk/ZkPedersen.java b/zeroj-circuit-lib/src/main/java/org/zeroj/circuit/lib/zk/ZkPedersen.java index d7ec8ee2..38bb8edc 100644 --- a/zeroj-circuit-lib/src/main/java/org/zeroj/circuit/lib/zk/ZkPedersen.java +++ b/zeroj-circuit-lib/src/main/java/org/zeroj/circuit/lib/zk/ZkPedersen.java @@ -48,6 +48,10 @@ private ZkPedersen() {} */ public static ZkJubjubPoint commit(ZkContext zk, ZkUInt value, ZkUInt blinding) { validateScalarInputs(zk, value, blinding); + if (value.signal().variable().id() == blinding.signal().variable().id()) { + throw new IllegalArgumentException("wire " + blinding.signal().variable().id() + + " is used as both the value and the blinding (ADR-0051 D2)"); + } // Mint (or retrieve) both owned decompositions at their actual widths FIRST, so the // canonicality check below is satisfied from the range cache rather than emitting a // second, wider decomposition. diff --git a/zeroj-circuit-lib/src/test/java/org/zeroj/circuit/lib/jubjub/PedersenTest.java b/zeroj-circuit-lib/src/test/java/org/zeroj/circuit/lib/jubjub/PedersenTest.java index 00ec4e8f..40f72cbe 100644 --- a/zeroj-circuit-lib/src/test/java/org/zeroj/circuit/lib/jubjub/PedersenTest.java +++ b/zeroj-circuit-lib/src/test/java/org/zeroj/circuit/lib/jubjub/PedersenTest.java @@ -2,7 +2,10 @@ import org.zeroj.api.CurveId; import org.zeroj.circuit.CircuitBuilder; +import org.zeroj.circuit.annotation.ZkContext; +import org.zeroj.circuit.annotation.ZkUInt; import org.zeroj.circuit.lib.poseidon.PoseidonParamsBLS12_381T5; +import org.zeroj.circuit.lib.zk.ZkPedersen; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -266,4 +269,32 @@ void t5_firstMds_matchesSage() { assertEquals(expected, PoseidonParamsBLS12_381T5.INSTANCE.m()[0], "BLS12-381 t=5 MDS[0][0] must match hadeshash Sage script output"); } + + @Test + @DisplayName("InCircuitPedersen and ZkPedersen reject value and blinding sharing the same wire") + void pedersenRejectsSharedValueAndBlindingWire() { + assertThrows(IllegalArgumentException.class, () -> CircuitBuilder.create("pedersen-shared-var") + .secretVar("x") + .define(api -> { + var x = api.var("x"); + InCircuitPedersen.commit(api, x, 64, x); + })); + + assertThrows(IllegalArgumentException.class, () -> CircuitBuilder.create("pedersen-shared-decomp") + .secretVar("x") + .define(api -> { + var x = api.var("x"); + var d1 = api.decompose(x, 250); + var d2 = api.decompose(x, 250); + InCircuitPedersen.commit(api, d1, d2); + })); + + assertThrows(IllegalArgumentException.class, () -> CircuitBuilder.create("pedersen-shared-zk") + .secretVar("x") + .defineSignals(c -> { + var zk = new ZkContext(c); + var x = ZkUInt.secret(c, "x", 250); + ZkPedersen.commit(zk, x, x); + })); + } } diff --git a/zeroj-codec/src/main/java/org/zeroj/codec/Halo2Codec.java b/zeroj-codec/src/main/java/org/zeroj/codec/Halo2Codec.java index 46cdc65e..c07610c6 100644 --- a/zeroj-codec/src/main/java/org/zeroj/codec/Halo2Codec.java +++ b/zeroj-codec/src/main/java/org/zeroj/codec/Halo2Codec.java @@ -126,15 +126,15 @@ public static boolean wasVerified(String json) { } private static CurveId detectCurve(JsonNode root) { - if (root.has("curve")) { - String curve = root.get("curve").asText(); - try { - return CurveId.fromValue(curve); - } catch (IllegalArgumentException e) { - // Fall through to default - } + if (root == null || !root.has("curve") || !root.get("curve").isTextual()) { + throw new CodecException("Missing required 'curve' field in Halo2 result JSON"); + } + String curve = root.get("curve").asText(); + try { + return CurveId.fromValue(curve); + } catch (IllegalArgumentException e) { + throw new CodecException("Unsupported curve in Halo2 result JSON: " + curve, e); } - return CurveId.PALLAS; // default for Halo2 IPA } private static PublicInputs parsePublicInputs(JsonNode root) { diff --git a/zeroj-codec/src/test/java/org/zeroj/codec/Halo2CodecTest.java b/zeroj-codec/src/test/java/org/zeroj/codec/Halo2CodecTest.java new file mode 100644 index 00000000..255bd6fd --- /dev/null +++ b/zeroj-codec/src/test/java/org/zeroj/codec/Halo2CodecTest.java @@ -0,0 +1,33 @@ +package org.zeroj.codec; + +import org.junit.jupiter.api.Test; +import org.zeroj.api.CircuitId; +import org.zeroj.api.CurveId; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +class Halo2CodecTest { + + @Test + void detectCurveFailsClosedWhenMissingOrUnsupported() { + CircuitId cid = new CircuitId("halo2-test"); + assertThrows(CodecException.class, + () -> Halo2Codec.toEnvelopeFromJson("{\"proof\":\"AA==\",\"publicInputs\":[]}", cid)); + assertThrows(CodecException.class, + () -> Halo2Codec.toEnvelopeFromJson("{\"proof\":\"AA==\",\"publicInputs\":[],\"curve\":\"unknown\"}", cid)); + assertThrows(CodecException.class, + () -> Halo2Codec.toEnvelopeFromJson("{\"proof\":\"AA==\",\"curve\":\"not-a-curve\"}", "[]", cid)); + } + + @Test + void parseAcceptsExplicitSupportedCurves() { + CircuitId cid = new CircuitId("halo2-test"); + var pallas = Halo2Codec.toEnvelopeFromJson( + "{\"proof\":\"AA==\",\"publicInputs\":[\"1\"],\"curve\":\"pallas\"}", cid); + assertEquals(CurveId.PALLAS, pallas.curve()); + var bls = Halo2Codec.toEnvelopeFromJson( + "{\"proof\":\"AA==\",\"publicInputs\":[\"2\"],\"curve\":\"" + CurveId.BLS12_381.value() + "\"}", cid); + assertEquals(CurveId.BLS12_381, bls.curve()); + } +} diff --git a/zeroj-crypto/src/main/java/org/zeroj/crypto/groth16/Groth16Pipeline.java b/zeroj-crypto/src/main/java/org/zeroj/crypto/groth16/Groth16Pipeline.java index 14fc31ff..5e95032b 100644 --- a/zeroj-crypto/src/main/java/org/zeroj/crypto/groth16/Groth16Pipeline.java +++ b/zeroj-crypto/src/main/java/org/zeroj/crypto/groth16/Groth16Pipeline.java @@ -3,6 +3,7 @@ import org.zeroj.api.R1CSFlat; import org.zeroj.api.R1CSFlatIO; import org.zeroj.api.R1CSValidation; +import org.zeroj.api.TrustedSetupPolicy; import org.zeroj.bls12381.field.MontFr381; import org.zeroj.crypto.msm.FlatScalars; import org.zeroj.crypto.setup.Groth16SetupBLS381; @@ -65,7 +66,9 @@ public static final class Compiled { public Compiled(R1CSFlat flat, int numConstraints, int numWires, int numPublic) { if (flat == null) throw new NullPointerException("flat"); - if (numConstraints < 1) throw new IllegalArgumentException("numConstraints must be >= 1"); + if (numConstraints < 1 || numConstraints > (1 << 30)) { + throw new IllegalArgumentException("numConstraints must be in [1, 2^30]"); + } if (numWires < 1) throw new IllegalArgumentException("numWires must be >= 1"); if (numPublic < 0 || numPublic >= numWires) { throw new IllegalArgumentException("numPublic must be in [0, numWires)"); @@ -143,6 +146,9 @@ public static Dims parseFingerprint(String fp) { public record Dims(int numConstraints, int numWires, int numPublic) { /** FFT domain: next power of two ≥ constraint count (min 4), as the setup computes it. */ public int domain() { + if (numConstraints < 1 || numConstraints > (1 << 30)) { + throw new IllegalArgumentException("numConstraints must be in [1, 2^30]"); + } int d = Integer.highestOneBit(numConstraints); if (d < numConstraints) d <<= 1; return Math.max(d, 4); @@ -185,6 +191,7 @@ public static Groth16SetupBLS381.SetupResult setup(Compiled cc, BigInteger tau, */ public static Groth16SetupBLS381.SetupResult setup(Compiled cc, BigInteger tau, Path dir, boolean sparse, Progress progress) throws IOException { + TrustedSetupPolicy.requireInsecureTrustedSetupEnabled(); // ADR-0045 S1 (native setup only): every public wire, the constant wire included, must be // bound by the relation itself — a native key has no snarkjs binding rows. Checked here so // the failure happens before the r1cs.bin cache or any store file exists; setupToStore diff --git a/zeroj-crypto/src/main/java/org/zeroj/crypto/groth16/Groth16PkMmap.java b/zeroj-crypto/src/main/java/org/zeroj/crypto/groth16/Groth16PkMmap.java index de417cd6..6b266d97 100644 --- a/zeroj-crypto/src/main/java/org/zeroj/crypto/groth16/Groth16PkMmap.java +++ b/zeroj-crypto/src/main/java/org/zeroj/crypto/groth16/Groth16PkMmap.java @@ -80,7 +80,7 @@ public static Groth16PkMmap materialize(Groth16ProvingKeyBLS381 pk, Path dir) th * risks OOM / heavy GC. Native (mmap) memory is not counted against {@code -Xmx}. */ public static boolean shouldEngage(Groth16ProvingKeyBLS381 pk, double headroomFraction) { - long g1Bytes = (long) (pk.pointsA().length + pk.pointsB1().length + long g1Bytes = ((long) pk.pointsA().length + pk.pointsB1().length + pk.pointsH().length + pk.pointsL().length) * Long.BYTES; long maxHeap = Runtime.getRuntime().maxMemory(); return g1Bytes > headroomFraction * maxHeap; diff --git a/zeroj-crypto/src/main/java/org/zeroj/crypto/groth16/Groth16PkStore.java b/zeroj-crypto/src/main/java/org/zeroj/crypto/groth16/Groth16PkStore.java index f2fdba5f..d54f63c1 100644 --- a/zeroj-crypto/src/main/java/org/zeroj/crypto/groth16/Groth16PkStore.java +++ b/zeroj-crypto/src/main/java/org/zeroj/crypto/groth16/Groth16PkStore.java @@ -2,6 +2,7 @@ import org.zeroj.bls12381.ec.JacobianG1BLS381.AffineG1; import org.zeroj.bls12381.ec.JacobianG2BLS381.AffineG2; +import org.zeroj.bls12381.field.Fp; import org.zeroj.bls12381.field.MontFp2_381; import org.zeroj.bls12381.field.MontFp381; import org.zeroj.crypto.msm.G2AffineReader; @@ -176,9 +177,15 @@ public static Loaded load(Path dir, String expectedManifestSha256) throws IOExce AffineG1 alphaG1, betaG1, deltaG1; AffineG2 betaG2, deltaG2, gammaG2; AffineG1[] ic = new AffineG1[numIc]; try (var aux = dis(dir.resolve("aux.bin"))) { - alphaG1 = getG1(aux); betaG1 = getG1(aux); deltaG1 = getG1(aux); - betaG2 = getG2(aux); deltaG2 = getG2(aux); gammaG2 = getG2(aux); - for (int i = 0; i < numIc; i++) ic[i] = getG1(aux); + alphaG1 = requireNonInfinityG1(getG1(aux), "alphaG1"); + betaG1 = requireNonInfinityG1(getG1(aux), "betaG1"); + deltaG1 = requireNonInfinityG1(getG1(aux), "deltaG1"); + betaG2 = requireNonInfinityG2(getG2(aux), "betaG2"); + deltaG2 = requireNonInfinityG2(getG2(aux), "deltaG2"); + gammaG2 = requireNonInfinityG2(getG2(aux), "gammaG2"); + for (int i = 0; i < numIc; i++) { + ic[i] = requireNonInfinityG1(getG1(aux), "IC[" + i + "]"); + } } Arena arena = Arena.ofShared(); @@ -289,10 +296,28 @@ private static void putFp(DataOutputStream o, MontFp381 v) throws IOException { o.write(b); } + private static AffineG1 requireNonInfinityG1(AffineG1 p, String label) throws IOException { + if (p == null || p.isInfinity() || !p.isOnCurve()) { + throw new IOException("Groth16 " + label + " must be a non-infinity point on BLS12-381 G1"); + } + return p; + } + + private static AffineG2 requireNonInfinityG2(AffineG2 p, String label) throws IOException { + if (p == null || p.isInfinity() || !p.isOnCurve()) { + throw new IOException("Groth16 " + label + " must be a non-infinity point on BLS12-381 G2"); + } + return p; + } + private static MontFp381 getFp(DataInputStream in) throws IOException { byte[] b = new byte[FP_BYTES]; in.readFully(b); - return MontFp381.fromBigInteger(new BigInteger(1, b)); + BigInteger v = new BigInteger(1, b); + if (v.compareTo(Fp.P) >= 0) { + throw new IOException("Non-canonical BLS12-381 Fp coordinate in Groth16 aux.bin"); + } + return MontFp381.fromBigInteger(v); } private static void putG1(DataOutputStream o, AffineG1 p) throws IOException { putFp(o, p.x()); putFp(o, p.y()); } diff --git a/zeroj-crypto/src/main/java/org/zeroj/crypto/groth16/Groth16ProverBLS381.java b/zeroj-crypto/src/main/java/org/zeroj/crypto/groth16/Groth16ProverBLS381.java index 5e679ae4..b4810705 100644 --- a/zeroj-crypto/src/main/java/org/zeroj/crypto/groth16/Groth16ProverBLS381.java +++ b/zeroj-crypto/src/main/java/org/zeroj/crypto/groth16/Groth16ProverBLS381.java @@ -590,8 +590,26 @@ private static void requireFftDomain(int domainSize, long rows) { */ private static void requireKeyDimensions(Groth16ProvingKeyBLS381 pk, G1Readers readers, G2AffineReader b2, FlatScalars witness, FlatScalars hCoeffs) { + if (pk == null) throw new IllegalArgumentException("Proving key must not be null"); + if (readers == null) throw new IllegalArgumentException("Proving key readers must not be null"); + if (witness == null || witness.count() == 0) throw new IllegalArgumentException("Witness must not be null or empty"); + if (hCoeffs == null) throw new IllegalArgumentException("H coefficients must not be null"); + long[] w0 = new long[4]; + witness.copyLimbs(0, w0, 0); + if (w0[0] != 1L || w0[1] != 0L || w0[2] != 0L || w0[3] != 0L) { + throw new IllegalArgumentException("witness[0] must be 1"); + } + if (pk.alphaG1() == null || pk.alphaG1().isInfinity() || !pk.alphaG1().isOnCurve()) + throw new IllegalArgumentException("Proving key alphaG1 is not on curve"); + if (pk.betaG1() == null || pk.betaG1().isInfinity() || !pk.betaG1().isOnCurve()) + throw new IllegalArgumentException("Proving key betaG1 is not on curve"); + if (pk.betaG2() == null || pk.betaG2().isInfinity() || !pk.betaG2().isOnCurve()) + throw new IllegalArgumentException("Proving key betaG2 is not on curve"); + if (pk.deltaG1() == null || pk.deltaG1().isInfinity() || !pk.deltaG1().isOnCurve()) + throw new IllegalArgumentException("Proving key deltaG1 is not on curve"); + if (pk.deltaG2() == null || pk.deltaG2().isInfinity() || !pk.deltaG2().isOnCurve()) + throw new IllegalArgumentException("Proving key deltaG2 is not on curve"); int n = witness.count(); - if (n == 0) throw new IllegalArgumentException("Witness must not be empty"); if (pk.numPublic() < 0 || pk.numPublic() >= n) { throw new IllegalArgumentException("proving key numPublic (" + pk.numPublic() + ") must be in [0, witness count " + n + ")"); diff --git a/zeroj-crypto/src/main/java/org/zeroj/crypto/groth16/SparsePointFile.java b/zeroj-crypto/src/main/java/org/zeroj/crypto/groth16/SparsePointFile.java index 3c0843fd..d683556b 100644 --- a/zeroj-crypto/src/main/java/org/zeroj/crypto/groth16/SparsePointFile.java +++ b/zeroj-crypto/src/main/java/org/zeroj/crypto/groth16/SparsePointFile.java @@ -87,17 +87,39 @@ public static final class Index { final long ptsOff; public Index(MemorySegment seg) { + if (seg == null) throw new NullPointerException("seg"); + if (seg.byteSize() < 32L) { + throw new IllegalArgumentException("ZJSP sparse point file is truncated"); + } this.seg = seg; if (seg.get(LE_INT, 0) != MAGIC || seg.get(LE_INT, 4) != VERSION) throw new IllegalArgumentException("not a ZJSP v1 sparse point file"); this.stride = seg.get(LE_INT, 8); + if (this.stride != 96 && this.stride != 192) { + throw new IllegalArgumentException("unsupported ZJSP stride: " + this.stride); + } if (seg.get(LE_INT, 12) != BLOCK) throw new IllegalArgumentException("unsupported block size"); this.count = seg.get(LE_LONG, 16); this.nnz = seg.get(LE_LONG, 24); - long words = (count + 63) >>> 6; - this.rankOff = 32 + words * 8; + if (this.count < 0L || this.count > Integer.MAX_VALUE + || this.nnz < 0L || this.nnz > this.count) { + throw new IllegalArgumentException( + "invalid ZJSP counts: count=" + this.count + ", nnz=" + this.nnz); + } + long words = (count + 63L) >>> 6; + this.rankOff = 32L + words * 8L; this.ptsOff = pointsOffset(count); + long expectedSize; + try { + expectedSize = Math.addExact(this.ptsOff, Math.multiplyExact(this.nnz, (long) this.stride)); + } catch (ArithmeticException e) { + throw new IllegalArgumentException("ZJSP file size overflow", e); + } + if (seg.byteSize() != expectedSize) { + throw new IllegalArgumentException( + "ZJSP segment size mismatch: expected " + expectedSize + ", got " + seg.byteSize()); + } } public int count() { return (int) count; } @@ -126,7 +148,12 @@ long rank(int i) { public static final class SparseG1Reader implements PippengerFlatBLS381.G1AffineReader { private final Index idx; - public SparseG1Reader(MemorySegment seg) { this.idx = new Index(seg); } + public SparseG1Reader(MemorySegment seg) { + this.idx = new Index(seg); + if (this.idx.stride != 96) { + throw new IllegalArgumentException("Expected G1 sparse stride 96, got " + this.idx.stride); + } + } @Override public int count() { return idx.count(); } @@ -144,7 +171,12 @@ public static final class SparseG1Reader implements PippengerFlatBLS381.G1Affine public static final class SparseG2Reader implements G2AffineReader { private final Index idx; - public SparseG2Reader(MemorySegment seg) { this.idx = new Index(seg); } + public SparseG2Reader(MemorySegment seg) { + this.idx = new Index(seg); + if (this.idx.stride != 192) { + throw new IllegalArgumentException("Expected G2 sparse stride 192, got " + this.idx.stride); + } + } @Override public int count() { return idx.count(); } diff --git a/zeroj-crypto/src/main/java/org/zeroj/crypto/kzg/KZGCommitmentBLS381.java b/zeroj-crypto/src/main/java/org/zeroj/crypto/kzg/KZGCommitmentBLS381.java index 2b27db6f..2ea8cb80 100644 --- a/zeroj-crypto/src/main/java/org/zeroj/crypto/kzg/KZGCommitmentBLS381.java +++ b/zeroj-crypto/src/main/java/org/zeroj/crypto/kzg/KZGCommitmentBLS381.java @@ -49,7 +49,18 @@ public static JacobianG1BLS381 openingProof(AffineG1[] srsG1, MontFr381[] coeffs public static MontFr381[] syntheticDivision(MontFr381[] coeffs, MontFr381 z, MontFr381 v) { int n = coeffs.length; - if (n <= 1) return new MontFr381[]{MontFr381.ZERO}; + if (n == 0) { + if (!v.isZero()) { + throw new IllegalArgumentException("Polynomial does not evaluate to claimed value at z (non-zero remainder)"); + } + return new MontFr381[]{MontFr381.ZERO}; + } + if (n == 1) { + if (!coeffs[0].sub(v).isZero()) { + throw new IllegalArgumentException("Polynomial does not evaluate to claimed value at z (non-zero remainder)"); + } + return new MontFr381[]{MontFr381.ZERO}; + } MontFr381[] f = new MontFr381[n]; System.arraycopy(coeffs, 0, f, 0, n); @@ -60,6 +71,10 @@ public static MontFr381[] syntheticDivision(MontFr381[] coeffs, MontFr381 z, Mon for (int i = n - 3; i >= 0; i--) { q[i] = f[i + 1].add(z.mul(q[i + 1])); } + MontFr381 remainder = f[0].add(z.mul(q[0])); + if (!remainder.isZero()) { + throw new IllegalArgumentException("Polynomial does not evaluate to claimed value at z (non-zero remainder)"); + } return q; } } diff --git a/zeroj-crypto/src/main/java/org/zeroj/crypto/msm/FlatScalars.java b/zeroj-crypto/src/main/java/org/zeroj/crypto/msm/FlatScalars.java index f2d315b9..99e488dc 100644 --- a/zeroj-crypto/src/main/java/org/zeroj/crypto/msm/FlatScalars.java +++ b/zeroj-crypto/src/main/java/org/zeroj/crypto/msm/FlatScalars.java @@ -61,8 +61,17 @@ public static FlatScalars packConsuming(BigInteger[] values, int n) { return new FlatScalars(limbs, 0, n); } - /** Wrap already-canonical limbs (value {@code i} at {@code i*4}; caller must not mutate). */ + /** + * Wrap already-canonical little-endian Fr limbs (value {@code i} at {@code i*4}; caller must + * ensure every 4-limb value is strictly reduced {@code 0 <= v < r} and must not mutate the + * array after wrapping). + */ public static FlatScalars wrap(long[] canonicalLimbs, int count) { + if (canonicalLimbs == null) throw new NullPointerException("canonicalLimbs"); + if (count < 0 || (long) count * 4L > canonicalLimbs.length) { + throw new IllegalArgumentException("canonicalLimbs length " + canonicalLimbs.length + + " is smaller than required " + ((long) count * 4L)); + } return new FlatScalars(canonicalLimbs, 0, count); } diff --git a/zeroj-crypto/src/main/java/org/zeroj/crypto/plonk/PlonKProverBLS381.java b/zeroj-crypto/src/main/java/org/zeroj/crypto/plonk/PlonKProverBLS381.java index a51768bf..feff1ce7 100644 --- a/zeroj-crypto/src/main/java/org/zeroj/crypto/plonk/PlonKProverBLS381.java +++ b/zeroj-crypto/src/main/java/org/zeroj/crypto/plonk/PlonKProverBLS381.java @@ -35,6 +35,7 @@ private PlonKProverBLS381() {} private static final BigInteger FR = MontFr381.modulus(); private static final int MIN_DOMAIN_SIZE = 8; private static final int MAX_DOMAIN_POWER = 24; + private static final int MAX_BLINDER_RESAMPLES = 8; public static final int MAX_CARDANO_MPI_PUBLIC_INPUTS = 8; public static final String CARDANO_MPI_PROFILE_TAG = "zeroj-plonk-bls12381-cardano-mpi-v1-json"; @@ -69,9 +70,7 @@ public static PlonKProofBLS381 prove(PlonKProvingKeyBLS381 pk, MontFr381[] wireA if (rng == null) { throw new IllegalArgumentException("SecureRandom must not be null"); } - MontFr381[] b = new MontFr381[11]; - for (int i = 0; i < 11; i++) b[i] = randomFr(rng); - return proveInternal(pk, wireA, wireB, wireC, pubInputs, b, TranscriptEncoding.UNCOMPRESSED_AFFINE); + return proveWithResampling(pk, wireA, wireB, wireC, pubInputs, rng, TranscriptEncoding.UNCOMPRESSED_AFFINE); } /** @@ -97,9 +96,7 @@ public static PlonKProofBLS381 proveCardano(PlonKProvingKeyBLS381 pk, MontFr381[ throw new IllegalArgumentException("SecureRandom must not be null"); } requireCardanoV1PublicInputs(pubInputs); - MontFr381[] b = new MontFr381[11]; - for (int i = 0; i < 11; i++) b[i] = randomFr(rng); - return proveInternal(pk, wireA, wireB, wireC, pubInputs, b, TranscriptEncoding.COMPRESSED_G1); + return proveWithResampling(pk, wireA, wireB, wireC, pubInputs, rng, TranscriptEncoding.COMPRESSED_G1); } /** @@ -124,9 +121,32 @@ public static PlonKProofBLS381 proveCardanoMpi(PlonKProvingKeyBLS381 pk, MontFr3 throw new IllegalArgumentException("SecureRandom must not be null"); } requireCardanoMpiPublicInputs(pubInputs); - MontFr381[] b = new MontFr381[11]; - for (int i = 0; i < 11; i++) b[i] = randomFr(rng); - return proveInternal(pk, wireA, wireB, wireC, pubInputs, b, TranscriptEncoding.COMPRESSED_G1_MPI); + return proveWithResampling(pk, wireA, wireB, wireC, pubInputs, rng, TranscriptEncoding.COMPRESSED_G1_MPI); + } + + private static PlonKProofBLS381 proveWithResampling( + PlonKProvingKeyBLS381 pk, MontFr381[] wireA, MontFr381[] wireB, MontFr381[] wireC, + BigInteger[] pubInputs, SecureRandom rng, TranscriptEncoding encoding) { + DegenerateProofException last = null; + for (int attempt = 0; attempt < MAX_BLINDER_RESAMPLES; attempt++) { + MontFr381[] b = new MontFr381[11]; + for (int i = 0; i < 11; i++) b[i] = randomFr(rng); + try { + return proveInternal(pk, wireA, wireB, wireC, pubInputs, b, encoding); + } catch (DegenerateProofException e) { + last = e; + } + } + throw new IllegalStateException( + "PlonK prove aborted after " + MAX_BLINDER_RESAMPLES + + " blinding attempts due to degenerate challenge or infinity commitment", + last); + } + + private static final class DegenerateProofException extends IllegalStateException { + private DegenerateProofException(String message) { + super(message); + } } /** Prove without blinding (for debugging). */ @@ -200,6 +220,9 @@ private static PlonKProofBLS381 proveInternal(PlonKProvingKeyBLS381 pk, MontFr38 var den = aEvals[i].add(beta.mul(pk.s1()[i])).add(gamma) .mul(bEvals[i].add(beta.mul(pk.s2()[i])).add(gamma)) .mul(cEvals[i].add(beta.mul(pk.s3()[i])).add(gamma)); + if (den.isZero()) { + throw new DegenerateProofException("PlonK permutation denominator vanished at row " + i); + } zEvals[i + 1] = zEvals[i].mul(num).mul(den.inverse()); wi = wi.mul(omega); } @@ -401,6 +424,9 @@ private static PlonKProofBLS381 proveInternal(PlonKProvingKeyBLS381 pk, MontFr38 MontFr381 zetaN = zeta; for (int i = 1; i < n; i++) zetaN = zetaN.mul(zeta); MontFr381 zh = zetaN.sub(MontFr381.ONE); + if (zh.isZero() || zeta.equals(MontFr381.ONE)) { + throw new DegenerateProofException("PlonK challenge zeta lies inside the evaluation domain"); + } MontFr381 l1Zeta = zh.mul(MontFr381.fromLong(n).mul(zeta.sub(MontFr381.ONE)).inverse()); zCoeffInR = zCoeffInR.add(alpha2.mul(l1Zeta)); @@ -461,6 +487,12 @@ private static PlonKProofBLS381 proveInternal(PlonKProvingKeyBLS381 pk, MontFr38 var commitWxiw = KZGCommitmentBLS381.openingProof(srs, zBlind, zetaOmega, MontFr381.fromBigInteger(evalZw)).toAffine(); + if (commitA.isInfinity() || commitB.isInfinity() || commitC.isInfinity() + || commitZ.isInfinity() || commitT1.isInfinity() || commitT2.isInfinity() + || commitT3.isInfinity() || commitWxi.isInfinity() || commitWxiw.isInfinity()) { + throw new DegenerateProofException("PlonK proof commitment cancelled to the point at infinity"); + } + return new PlonKProofBLS381( commitA, commitB, commitC, commitZ, commitT1, commitT2, commitT3, diff --git a/zeroj-crypto/src/main/java/org/zeroj/crypto/plonk/PlonKSetupBLS381.java b/zeroj-crypto/src/main/java/org/zeroj/crypto/plonk/PlonKSetupBLS381.java index 11b804cd..31e2f831 100644 --- a/zeroj-crypto/src/main/java/org/zeroj/crypto/plonk/PlonKSetupBLS381.java +++ b/zeroj-crypto/src/main/java/org/zeroj/crypto/plonk/PlonKSetupBLS381.java @@ -14,6 +14,7 @@ import org.zeroj.crypto.poly.FieldFFTBLS381; import java.math.BigInteger; +import java.util.BitSet; import java.util.Objects; /** @@ -191,6 +192,7 @@ private static void validateSetupInputs( validateSigma("sigmaA", sigmaA, numGates); validateSigma("sigmaB", sigmaB, numGates); validateSigma("sigmaC", sigmaC, numGates); + validateSigmaBijection(sigmaA, sigmaB, sigmaC, numGates); validateSrs(srs, domainSize); } @@ -221,6 +223,24 @@ private static void validateSigma(String name, int[] sigma, int numGates) { } } + private static void validateSigmaBijection(int[] sigmaA, int[] sigmaB, int[] sigmaC, int numGates) { + int totalPositions = 3 * numGates; + BitSet seen = new BitSet(totalPositions); + markSigmaTargets(seen, sigmaA); + markSigmaTargets(seen, sigmaB); + markSigmaTargets(seen, sigmaC); + } + + private static void markSigmaTargets(BitSet seen, int[] sigma) { + for (int target : sigma) { + if (seen.get(target)) { + throw new IllegalArgumentException( + "PlonK sigma permutation is not a bijection: duplicate target " + target); + } + seen.set(target); + } + } + private static void validateSrs(PtauImporterBLS381.SRS srs, int domainSize) { Objects.requireNonNull(srs, "srs"); AffineG1[] tauG1 = srs.tauG1(); diff --git a/zeroj-crypto/src/main/java/org/zeroj/crypto/setup/Groth16SetupBLS381.java b/zeroj-crypto/src/main/java/org/zeroj/crypto/setup/Groth16SetupBLS381.java index 82816492..ba49e7d6 100644 --- a/zeroj-crypto/src/main/java/org/zeroj/crypto/setup/Groth16SetupBLS381.java +++ b/zeroj-crypto/src/main/java/org/zeroj/crypto/setup/Groth16SetupBLS381.java @@ -88,6 +88,7 @@ public final class Groth16SetupBLS381 { private Groth16SetupBLS381() {} private static final BigInteger FR = MontFr381.modulus(); + private static final int MAX_CONSTRAINTS = 1 << 29; /** * Generate a Groth16 proving key from R1CS constraints and known tau. @@ -126,6 +127,10 @@ public static SetupResult setup(List constraints, int numWires, + "Use snarkjs multi-party ceremony for production."); int nConstraints = constraints.size(); + if (nConstraints > MAX_CONSTRAINTS) { + throw new IllegalArgumentException("nConstraints (" + nConstraints + + ") exceeds maximum supported Groth16 setup size (" + MAX_CONSTRAINTS + ")"); + } // Domain size: next power of 2 >= nConstraints int domainSize = Integer.highestOneBit(nConstraints); @@ -133,14 +138,21 @@ public static SetupResult setup(List constraints, int numWires, if (domainSize < 4) domainSize = 4; int logN = Integer.numberOfTrailingZeros(domainSize); - BigInteger gammaInv = gamma.modInverse(FR); - BigInteger deltaInv = delta.modInverse(FR); + final BigInteger tauVal = requireValidSetupScalar(tau, "tau"); + final BigInteger alphaVal = requireValidSetupScalar(alpha, "alpha"); + final BigInteger betaVal = requireValidSetupScalar(beta, "beta"); + final BigInteger gammaVal = requireValidSetupScalar(gamma, "gamma"); + final BigInteger deltaVal = requireValidSetupScalar(delta, "delta"); + requireTauOutsideDomain(tauVal, domainSize); + + BigInteger gammaInv = gammaVal.modInverse(FR); + BigInteger deltaInv = deltaVal.modInverse(FR); // Compute omega (primitive domainSize-th root of unity) MontFr381 omega = FieldFFTBLS381.rootOfUnity(logN); // Compute Lagrange basis evaluations at tau: L_i(tau) = (tau^N - 1) / (N * (tau - omega^i)) - BigInteger tauN = tau.modPow(BigInteger.valueOf(domainSize), FR); + BigInteger tauN = tauVal.modPow(BigInteger.valueOf(domainSize), FR); BigInteger zh = tauN.subtract(BigInteger.ONE).mod(FR); // tau^N - 1 BigInteger nInv = BigInteger.valueOf(domainSize).modInverse(FR); @@ -155,7 +167,7 @@ public static SetupResult setup(List constraints, int numWires, final BigInteger[] lagrange = new BigInteger[domainSize]; java.util.stream.IntStream.range(0, domainSize).parallel().forEach(i -> { // L_i(tau) = omega^i * (tau^N - 1) / (N * (tau - omega^i)) - BigInteger diff = tau.subtract(omegaPows[i]).mod(FR); + BigInteger diff = tauVal.subtract(omegaPows[i]).mod(FR); lagrange[i] = (diff.signum() == 0) ? BigInteger.ONE : omegaPows[i].multiply(zhNInv).mod(FR).multiply(diff.modInverse(FR)).mod(FR); }); @@ -180,17 +192,17 @@ public static SetupResult setup(List constraints, int numWires, // ADR-0045 S2: the public-query scalars (beta*u_s + alpha*v_s + w_s)/gamma are checked for // zero here, before any point is generated, so a key the verifiers would reject is never // built (and a large relation fails in seconds rather than after the MSM work). - BigInteger[] icScalars = publicQueryScalars(us, vs, ws, numPublic, alpha, beta, gammaInv); + BigInteger[] icScalars = publicQueryScalars(us, vs, ws, numPublic, alphaVal, betaVal, gammaInv); // Compute group elements var g1 = JacobianG1BLS381.GENERATOR; var g2 = JacobianG2BLS381.GENERATOR; - AffineG1 alphaG1 = FixedBaseG1BLS381.mulAffine(alpha); - AffineG1 betaG1 = FixedBaseG1BLS381.mulAffine(beta); - AffineG2 betaG2 = g2.scalarMul(beta).toAffine(); - AffineG1 deltaG1 = FixedBaseG1BLS381.mulAffine(delta); - AffineG2 deltaG2 = g2.scalarMul(delta).toAffine(); + AffineG1 alphaG1 = FixedBaseG1BLS381.mulAffine(alphaVal); + AffineG1 betaG1 = FixedBaseG1BLS381.mulAffine(betaVal); + AffineG2 betaG2 = g2.scalarMul(betaVal).toAffine(); + AffineG1 deltaG1 = FixedBaseG1BLS381.mulAffine(deltaVal); + AffineG2 deltaG2 = g2.scalarMul(deltaVal).toAffine(); // ADR-0029 M5a: the per-wire scalar-muls are independent (each writes its own slot), so run // them in parallel across cores. This — not blst — is the setup-time lever: blst's speedup is @@ -218,7 +230,7 @@ public static SetupResult setup(List constraints, int numWires, long[] pointsL = new long[Math.max(0, numPrivate) * Groth16ProvingKeyBLS381.G1_STRIDE]; java.util.stream.IntStream.range(0, numPrivate).parallel().forEach(j -> { int s = numPublic + 1 + j; - BigInteger lVal = beta.multiply(us[s]).add(alpha.multiply(vs[s])).add(ws[s]) + BigInteger lVal = betaVal.multiply(us[s]).add(alphaVal.multiply(vs[s])).add(ws[s]) .multiply(deltaInv).mod(FR); Groth16ProvingKeyBLS381.writeG1(pointsL, j, lVal.signum() == 0 ? AffineG1.INFINITY : FixedBaseG1BLS381.mulAffine(lVal)); @@ -229,7 +241,7 @@ public static SetupResult setup(List constraints, int numWires, int domainSize2 = 2 * domainSize; MontFr381 omega2 = FieldFFTBLS381.rootOfUnity(logN + 1); // primitive 2N-th root BigInteger omega2Bi = omega2.toBigInteger(); - BigInteger tauN2 = tau.modPow(BigInteger.valueOf(domainSize2), FR); + BigInteger tauN2 = tauVal.modPow(BigInteger.valueOf(domainSize2), FR); BigInteger zh2 = tauN2.subtract(BigInteger.ONE).mod(FR); BigInteger nInv2 = BigInteger.valueOf(domainSize2).modInverse(FR); @@ -239,7 +251,7 @@ public static SetupResult setup(List constraints, int numWires, int lagIdx = 2 * i + 1; // odd index // omega2^lagIdx BigInteger omegaPow = omega2Bi.modPow(BigInteger.valueOf(lagIdx), FR); - BigInteger diff = tau.subtract(omegaPow).mod(FR); + BigInteger diff = tauVal.subtract(omegaPow).mod(FR); BigInteger hLagrange; if (diff.signum() == 0) { hLagrange = BigInteger.ONE; @@ -254,7 +266,7 @@ public static SetupResult setup(List constraints, int numWires, }); // Verification key components: gamma_G2 and IC points - AffineG2 gammaG2 = g2.scalarMul(gamma).toAffine(); + AffineG2 gammaG2 = g2.scalarMul(gammaVal).toAffine(); // IC[s] = (beta*u_s + alpha*v_s + w_s) / gamma * G1 for public wires s = 0..numPublic // (scalars pre-checked nonzero by publicQueryScalars — never AffineG1.INFINITY, ADR-0045) @@ -295,6 +307,23 @@ static BigInteger[] publicQueryScalars(BigInteger[] us, BigInteger[] vs, BigInte * cancelled its public-query combination, an event of probability on the order of * {@code N/r}. The key is not produced; a re-run with fresh randomness resolves it. */ + private static BigInteger requireValidSetupScalar(BigInteger value, String name) { + if (value == null) { + throw new IllegalArgumentException(name + " must not be null"); + } + BigInteger reduced = value.mod(FR); + if (reduced.signum() == 0) { + throw new IllegalArgumentException(name + " must be non-zero modulo Fr"); + } + return reduced; + } + + private static void requireTauOutsideDomain(BigInteger tau, int domainSize) { + if (tau.modPow(BigInteger.valueOf(2L * domainSize), FR).equals(BigInteger.ONE)) { + throw new IllegalArgumentException("tau must not be a 2N-th root of unity for domain size " + domainSize); + } + } + private static IllegalStateException zeroPublicQuery(int s, int numPublic) { return new IllegalStateException("Groth16 setup aborted: the public-query scalar for public wire " + s + " (of " + numPublic + ") is zero, so IC[" + s + "] would be the point at infinity, which every" @@ -371,22 +400,33 @@ public static SetupResult setupToStore(R1CSFlat flat, + "Use snarkjs multi-party ceremony for production."); int nConstraints = flat.rows(); + if (nConstraints > MAX_CONSTRAINTS) { + throw new IllegalArgumentException("nConstraints (" + nConstraints + + ") exceeds maximum supported Groth16 setup size (" + MAX_CONSTRAINTS + ")"); + } int domainSize = Integer.highestOneBit(nConstraints); if (domainSize < nConstraints) domainSize <<= 1; if (domainSize < 4) domainSize = 4; int logN = Integer.numberOfTrailingZeros(domainSize); final int domain = domainSize; - BigInteger gammaInv = gamma.modInverse(FR); - BigInteger deltaInv = delta.modInverse(FR); + final BigInteger tauVal = requireValidSetupScalar(tau, "tau"); + final BigInteger alphaVal = requireValidSetupScalar(alpha, "alpha"); + final BigInteger betaVal = requireValidSetupScalar(beta, "beta"); + final BigInteger gammaVal = requireValidSetupScalar(gamma, "gamma"); + final BigInteger deltaVal = requireValidSetupScalar(delta, "delta"); + requireTauOutsideDomain(tauVal, domain); + + BigInteger gammaInv = gammaVal.modInverse(FR); + BigInteger deltaInv = deltaVal.modInverse(FR); // ---- Lagrange basis L_i(tau) as flat Montgomery limbs; omega powers are walked // per-chunk (omega^lo by modPow, then one multiply per step) — no boxed arrays. BigInteger omegaBi = FieldFFTBLS381.rootOfUnity(logN).toBigInteger(); - BigInteger tauN = tau.modPow(BigInteger.valueOf(domain), FR); + BigInteger tauN = tauVal.modPow(BigInteger.valueOf(domain), FR); BigInteger zhNInv = tauN.subtract(BigInteger.ONE).mod(FR) .multiply(BigInteger.valueOf(domain).modInverse(FR)).mod(FR); - long[] lagMont = computeLagrangeMont(domain, tau, omegaBi, zhNInv); + long[] lagMont = computeLagrangeMont(domain, tauVal, omegaBi, zhNInv); // ---- QAP evaluations u_s/v_s/w_s(tau) as flat Montgomery limbs (ADR-0035 M2): // one pass over the CSR rows, dictionary Montgomery-converted once. @@ -426,15 +466,15 @@ public static SetupResult setupToStore(R1CSFlat flat, // ---- single points + VK bits (tiny) var g2 = JacobianG2BLS381.GENERATOR; - AffineG1 alphaG1 = FixedBaseG1BLS381.mulAffine(alpha); - AffineG1 betaG1 = FixedBaseG1BLS381.mulAffine(beta); - AffineG2 betaG2 = g2.scalarMul(beta).toAffine(); - AffineG1 deltaG1 = FixedBaseG1BLS381.mulAffine(delta); - AffineG2 deltaG2 = g2.scalarMul(delta).toAffine(); - AffineG2 gammaG2 = g2.scalarMul(gamma).toAffine(); - - long[] alphaMont = MontFr381.fromBigInteger(alpha).toLimbs(); - long[] betaMont = MontFr381.fromBigInteger(beta).toLimbs(); + AffineG1 alphaG1 = FixedBaseG1BLS381.mulAffine(alphaVal); + AffineG1 betaG1 = FixedBaseG1BLS381.mulAffine(betaVal); + AffineG2 betaG2 = g2.scalarMul(betaVal).toAffine(); + AffineG1 deltaG1 = FixedBaseG1BLS381.mulAffine(deltaVal); + AffineG2 deltaG2 = g2.scalarMul(deltaVal).toAffine(); + AffineG2 gammaG2 = g2.scalarMul(gammaVal).toAffine(); + + long[] alphaMont = MontFr381.fromBigInteger(alphaVal).toLimbs(); + long[] betaMont = MontFr381.fromBigInteger(betaVal).toLimbs(); long[] deltaInvMont = MontFr381.fromBigInteger(deltaInv).toLimbs(); long[] gammaInvMont = MontFr381.fromBigInteger(gammaInv).toLimbs(); @@ -534,7 +574,7 @@ public static SetupResult setupToStore(R1CSFlat flat, MontFr381 omega2 = FieldFFTBLS381.rootOfUnity(logN + 1); BigInteger omega2Bi = omega2.toBigInteger(); BigInteger omega2Sq = omega2Bi.multiply(omega2Bi).mod(FR); - BigInteger tauN2 = tau.modPow(BigInteger.valueOf(2L * domain), FR); + BigInteger tauN2 = tauVal.modPow(BigInteger.valueOf(2L * domain), FR); BigInteger zh2NInv2 = tauN2.subtract(BigInteger.ONE).mod(FR) .multiply(BigInteger.valueOf(2L * domain).modInverse(FR)).mod(FR); // H is dense by nature (its Lagrange values are never zero for a random tau), so its @@ -572,7 +612,7 @@ public static SetupResult setupToStore(R1CSFlat flat, boolean zeroDiff = false; for (int k = 0; k < m; k++) { omPows[k] = omPow; - diffs[k] = tau.subtract(omPow).mod(FR); + diffs[k] = tauVal.subtract(omPow).mod(FR); if (diffs[k].signum() == 0) zeroDiff = true; omPow = omPow.multiply(omega2Sq).mod(FR); } diff --git a/zeroj-crypto/src/main/java/org/zeroj/crypto/setup/Groth16SetupCache.java b/zeroj-crypto/src/main/java/org/zeroj/crypto/setup/Groth16SetupCache.java index ea9b7a56..9904e241 100644 --- a/zeroj-crypto/src/main/java/org/zeroj/crypto/setup/Groth16SetupCache.java +++ b/zeroj-crypto/src/main/java/org/zeroj/crypto/setup/Groth16SetupCache.java @@ -183,6 +183,6 @@ private static void validateGroth16SetupPoints( SetupCacheIO.validateG2Array((org.zeroj.bls12381.ec.JacobianG2BLS381.AffineG2[]) pointsB2, true, "Groth16 pointsB2"); SetupCacheIO.validateG1Array((org.zeroj.bls12381.ec.JacobianG1BLS381.AffineG1[]) pointsH, true, "Groth16 pointsH"); SetupCacheIO.validateG1Array((org.zeroj.bls12381.ec.JacobianG1BLS381.AffineG1[]) pointsL, true, "Groth16 pointsL"); - SetupCacheIO.validateG1Array((org.zeroj.bls12381.ec.JacobianG1BLS381.AffineG1[]) ic, true, "Groth16 IC"); + SetupCacheIO.validateG1Array((org.zeroj.bls12381.ec.JacobianG1BLS381.AffineG1[]) ic, false, "Groth16 IC"); } } diff --git a/zeroj-crypto/src/main/java/org/zeroj/crypto/setup/PowersOfTauBLS381.java b/zeroj-crypto/src/main/java/org/zeroj/crypto/setup/PowersOfTauBLS381.java index e7c8e161..36510b40 100644 --- a/zeroj-crypto/src/main/java/org/zeroj/crypto/setup/PowersOfTauBLS381.java +++ b/zeroj-crypto/src/main/java/org/zeroj/crypto/setup/PowersOfTauBLS381.java @@ -44,9 +44,9 @@ private PowersOfTauBLS381() {} */ public static PtauImporterBLS381.SRS generate(int power) { TrustedSetupPolicy.requireInsecureTrustedSetupEnabled(); - if (power < 4 || power > 32) - throw new IllegalArgumentException("Power must be in [4, 32], got " + power - + " (minimum 4 required for PlonK domain size >= 8)"); + if (power < 4 || power > 28) + throw new IllegalArgumentException("Power must be in [4, 28], got " + power + + " (minimum 4 for PlonK domain >= 8; max 28 so 2^(power+1) + 1 fits in a Java array)"); System.err.println("WARNING: Single-party Powers of Tau generation (BLS12-381) — " + "for DEVELOPMENT and TESTING only. " diff --git a/zeroj-crypto/src/main/java/org/zeroj/crypto/setup/SetupCacheIO.java b/zeroj-crypto/src/main/java/org/zeroj/crypto/setup/SetupCacheIO.java index 3de93ad0..b5525f9b 100644 --- a/zeroj-crypto/src/main/java/org/zeroj/crypto/setup/SetupCacheIO.java +++ b/zeroj-crypto/src/main/java/org/zeroj/crypto/setup/SetupCacheIO.java @@ -234,7 +234,8 @@ static BigInteger readScalar(DataInputStream in, String label) throws IOExceptio byte[] bytes = new byte[len]; in.readFully(bytes); BigInteger value = new BigInteger(bytes); - if (value.signum() < 0 || value.compareTo(MontFr381.modulus()) >= 0) { + if (value.signum() < 0 || value.compareTo(MontFr381.modulus()) >= 0 + || !Arrays.equals(bytes, value.toByteArray())) { throw new IOException(label + " must be a canonical BLS12-381 scalar"); } return value; @@ -316,11 +317,13 @@ static void validateG2Array(AffineG2[] points, boolean allowInfinity, String lab } static void validateBls12381Srs(AffineG1[] tauG1, AffineG2[] tauG2, int power) throws IOException { - if (power < 1 || power > 32) { + if (power < 1 || power > 28) { throw new IOException("Invalid BLS12-381 SRS power: " + power); } - if (tauG1.length == 0) { - throw new IOException("BLS12-381 SRS contains no G1 powers"); + long minG1 = (1L << power) + 1L; + if (tauG1.length < minG1) { + throw new IOException("BLS12-381 SRS G1 power count " + tauG1.length + + " is smaller than required minimum " + minG1 + " for power " + power); } if (tauG2.length < 2) { throw new IOException("BLS12-381 SRS must contain at least two G2 powers"); diff --git a/zeroj-crypto/src/main/java/org/zeroj/crypto/setup/SrsCache.java b/zeroj-crypto/src/main/java/org/zeroj/crypto/setup/SrsCache.java index 080eba6c..4e6b4c77 100644 --- a/zeroj-crypto/src/main/java/org/zeroj/crypto/setup/SrsCache.java +++ b/zeroj-crypto/src/main/java/org/zeroj/crypto/setup/SrsCache.java @@ -38,6 +38,7 @@ static void saveBls12381InsecureDevSrsWithTau(PtauImporterBLS381.SRS srs, Path p if (srs.tauScalar() == null) { throw new IOException("SRS does not contain a tau scalar"); } + verifyTauMatchesG1(srs.tauScalar(), srs.tauG1()); saveBls12381Srs(srs, path, true); setOwnerOnlyPermissions(path); } @@ -63,14 +64,27 @@ public static PtauImporterBLS381.SRS loadBls12381Srs(Path path) throws IOExcepti BigInteger tau = null; if (in.readBoolean()) { + TrustedSetupPolicy.requireInsecureTrustedSetupEnabled(); tau = SetupCacheIO.readScalar(in, "tau scalar"); } SetupCacheIO.validateBls12381Srs(tauG1, tauG2, power); + if (tau != null) { + verifyTauMatchesG1(tau, tauG1); + } return new PtauImporterBLS381.SRS(tauG1, tauG2, power, tau); }); } + private static void verifyTauMatchesG1(BigInteger tau, AffineG1[] tauG1) throws IOException { + if (tau.signum() <= 0 || tauG1 == null || tauG1.length < 2) { + throw new IOException("SRS tau scalar is invalid or missing tau*G1"); + } + if (!FixedBaseG1BLS381.mulAffine(tau).equals(tauG1[1])) { + throw new IOException("SRS tau scalar does not match tau*G1"); + } + } + private static void saveBls12381Srs(PtauImporterBLS381.SRS srs, Path path, boolean includeTau) throws IOException { SetupCacheIO.validateBls12381Srs(srs.tauG1(), srs.tauG2(), srs.power()); SetupCacheIO.writeCacheFile(path, SetupCacheIO.TYPE_BLS12381_SRS, out -> { diff --git a/zeroj-crypto/src/main/java/org/zeroj/crypto/transcript/FiatShamirTranscript.java b/zeroj-crypto/src/main/java/org/zeroj/crypto/transcript/FiatShamirTranscript.java index 9f35c833..571c5089 100644 --- a/zeroj-crypto/src/main/java/org/zeroj/crypto/transcript/FiatShamirTranscript.java +++ b/zeroj-crypto/src/main/java/org/zeroj/crypto/transcript/FiatShamirTranscript.java @@ -139,10 +139,12 @@ public BigInteger getChallenge() { /** Alias for {@link #getChallenge()}. */ public BigInteger squeezeChallenge() { return getChallenge(); } - /** Squeeze a non-zero challenge. */ + /** Squeeze a non-zero challenge; fails closed if the transcript hashes to zero. */ public BigInteger squeezeNonZeroChallenge() { BigInteger c = getChallenge(); - // In practice Keccak-256 output mod Fr is never zero + if (c.signum() == 0) { + throw new IllegalStateException("Fiat-Shamir transcript squeezed zero challenge"); + } return c; } diff --git a/zeroj-crypto/src/test/java/org/zeroj/crypto/setup/SetupCacheTest.java b/zeroj-crypto/src/test/java/org/zeroj/crypto/setup/SetupCacheTest.java index a312a320..231984e4 100644 --- a/zeroj-crypto/src/test/java/org/zeroj/crypto/setup/SetupCacheTest.java +++ b/zeroj-crypto/src/test/java/org/zeroj/crypto/setup/SetupCacheTest.java @@ -2,12 +2,18 @@ import org.zeroj.api.CurveId; import org.zeroj.api.R1CSConstraint; +import org.zeroj.api.R1CSFlat; import org.zeroj.api.TrustedSetupPolicy; +import org.zeroj.bls12381.field.MontFr381; import org.zeroj.circuit.CircuitBuilder; +import org.zeroj.crypto.groth16.Groth16Keys; +import org.zeroj.crypto.groth16.Groth16Pipeline; import org.zeroj.crypto.groth16.Groth16ProvingKeyBLS381; +import org.zeroj.crypto.kzg.KZGCommitmentBLS381; import org.zeroj.crypto.plonk.PlonKProvingKeyBLS381; import org.zeroj.crypto.plonk.PlonKSetupBLS381; import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assumptions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; @@ -79,17 +85,71 @@ void tamperedSrsCacheIsRejected() throws Exception { } @Test - void insecureTrustedSetupRequiresExplicitOptIn() { + void insecureTrustedSetupRequiresExplicitOptInAcrossAllSites() throws Exception { + Assumptions.assumeFalse( + "true".equalsIgnoreCase(System.getenv(TrustedSetupPolicy.ALLOW_INSECURE_TRUSTED_SETUP_ENV)), + "Environment variable overrides system property"); + + // Prepare valid fixtures while opt-in is enabled. + var srs = PowersOfTauBLS381.generate(4); + Path srsWithTau = tempDir.resolve("srs-with-tau.insecure"); + Groth16SetupCache.saveBls12381InsecureDevSrsWithTau(srs, srsWithTau); + var constraints = List.of( + new R1CSConstraint(Map.of(2, BigInteger.ONE), Map.of(3, BigInteger.ONE), Map.of(1, BigInteger.ONE)), + new R1CSConstraint(Map.of(0, BigInteger.ONE), Map.of(0, BigInteger.ONE), Map.of(0, BigInteger.ONE))); + var flatBuilder = R1CSFlat.builder(); + for (var c : constraints) flatBuilder.add(c.a(), c.b(), c.c()); + var flat = flatBuilder.build(); + var compiled = new Groth16Pipeline.Compiled(flat, constraints.size(), 4, 1); + try { System.clearProperty(TrustedSetupPolicy.ALLOW_INSECURE_TRUSTED_SETUP_PROPERTY); - if (!"true".equalsIgnoreCase(System.getenv(TrustedSetupPolicy.ALLOW_INSECURE_TRUSTED_SETUP_ENV))) { - assertThrows(IllegalStateException.class, () -> PowersOfTauBLS381.generate(4)); - } + assertThrows(IllegalStateException.class, () -> PowersOfTauBLS381.generate(4)); + assertThrows(IllegalStateException.class, + () -> Groth16SetupBLS381.setup(constraints, 4, 1, srs.tauScalar())); + assertThrows(IllegalStateException.class, + () -> Groth16SetupBLS381.setupToStore(flat, 4, 1, srs.tauScalar(), tempDir.resolve("store-1"))); + assertThrows(IllegalStateException.class, + () -> Groth16SetupCache.saveBls12381InsecureDevSrsWithTau(srs, tempDir.resolve("srs-2.insecure"))); + assertThrows(IllegalStateException.class, + () -> Groth16SetupCache.loadBls12381Srs(srsWithTau)); + Path pipelineDir = tempDir.resolve("pipeline-denied"); + assertThrows(IllegalStateException.class, + () -> Groth16Pipeline.setup(compiled, srs.tauScalar(), pipelineDir, false)); + org.junit.jupiter.api.Assertions.assertFalse(Files.exists(pipelineDir), + "Groth16Pipeline.setup must fail before creating output directory"); + assertThrows(IllegalStateException.class, + () -> Groth16Keys.setupInMemory(constraints, 4, 1, srs.tauScalar())); } finally { restoreProperty(TrustedSetupPolicy.ALLOW_INSECURE_TRUSTED_SETUP_PROPERTY, previousInsecureTrustedSetup); } } + @Test + void setupAndKzgHardeningRejectsInvalidPowerNonBijectiveSigmaAndNonZeroRemainder() { + assertThrows(IllegalArgumentException.class, () -> PowersOfTauBLS381.generate(29)); + + // KZG syntheticDivision must reject a claimed evaluation with non-zero remainder. + MontFr381[] poly = {MontFr381.fromLong(3), MontFr381.fromLong(2), MontFr381.fromLong(1)}; // x^2 + 2x + 3 + MontFr381 z = MontFr381.fromLong(5); // p(5) = 25 + 10 + 3 = 38 + assertThrows(IllegalArgumentException.class, + () -> KZGCommitmentBLS381.syntheticDivision(poly, z, MontFr381.fromLong(39))); + var q = KZGCommitmentBLS381.syntheticDivision(poly, z, MontFr381.fromLong(38)); + assertEquals(2, q.length); + + // PlonKSetupBLS381 must reject non-bijective sigma permutations. + var srs = PowersOfTauBLS381.generate(4); + BigInteger[][] selectors = { + {BigInteger.ONE, BigInteger.ZERO, BigInteger.ZERO, BigInteger.ZERO, BigInteger.ZERO}, + {BigInteger.ZERO, BigInteger.ZERO, BigInteger.ZERO, BigInteger.ZERO, BigInteger.ZERO} + }; + int[] dupSigmaA = {0, 0}; // duplicate target 0 + int[] sigmaB = {2, 3}; + int[] sigmaC = {4, 5}; + assertThrows(IllegalArgumentException.class, + () -> PlonKSetupBLS381.setup(2, 0, selectors, dupSigmaA, sigmaB, sigmaC, 4, srs)); + } + @Test void groth16SetupCacheRoundTripsBls381() throws Exception { var constraints = List.of( diff --git a/zeroj-integration-tests/src/test/java/org/zeroj/examples/dsl/auction/SealedBidPureJavaE2ETest.java b/zeroj-integration-tests/src/test/java/org/zeroj/examples/dsl/auction/SealedBidPureJavaE2ETest.java index 00c3d562..b2e03302 100644 --- a/zeroj-integration-tests/src/test/java/org/zeroj/examples/dsl/auction/SealedBidPureJavaE2ETest.java +++ b/zeroj-integration-tests/src/test/java/org/zeroj/examples/dsl/auction/SealedBidPureJavaE2ETest.java @@ -18,19 +18,18 @@ import static org.junit.jupiter.api.Assertions.*; /** - * Full-stack E2E: Java DSL circuit → pure Java BLS12-381 prove → off-chain verify → Julc VM on-chain verify. + * Off-chain E2E: Java DSL circuit → pure Java BLS12-381 prove → off-chain pairing verify. * *

DEV/TEST path (this test)

*

Uses single-party {@code PowersOfTauBLS381.generate(10)} — toxic waste is known. * DO NOT use this setup for production.

* *

PRODUCTION path

+ *

Production Groth16 keys must come from an independently verified BLS12-381 multi-party + * ceremony (e.g., {@code snarkjs groth16 setup} + {@code zkey contribute} + {@code zkey beacon} + * + {@code zkey verify}). Production {@code .ptau} files never expose {@code tau}.

*
- * // Option A: Import .ptau from MPC ceremony (Hermez, PPOT)
- * var srs = PtauImporterBLS381.importPtau(new FileInputStream("hermez_pot20.ptau"));
- * var setup = Groth16SetupBLS381.setup(constraints, numWires, numPublic, srs.tauScalar());
- *
- * // Option B: Import snarkjs .zkey (from multi-party ceremony)
+ * // Import snarkjs .zkey (from an independently verified BLS12-381 MPC ceremony)
  * var zkeyData = ZkeyImporterBLS381.importZkeyFull(Files.readAllBytes(Path.of("circuit.zkey")));
  * var proof = Groth16ProverBLS381.prove(zkeyData.provingKey(), witness, ...);
  * 
@@ -38,7 +37,7 @@ class SealedBidPureJavaE2ETest { /** - * Pure Java end-to-end: circuit → prove → off-chain pairing verify → Julc VM on-chain verify. + * Pure Java end-to-end: circuit → prove → off-chain pairing verify. */ @Test void devTau_sealedBid_fullStack() { diff --git a/zeroj-jmt-poseidon/src/main/java/org/zeroj/merkle/jmt/poseidon/ccl/PoseidonJmtReference.java b/zeroj-jmt-poseidon/src/main/java/org/zeroj/merkle/jmt/poseidon/ccl/PoseidonJmtReference.java index 1d79f308..b6d7e87b 100644 --- a/zeroj-jmt-poseidon/src/main/java/org/zeroj/merkle/jmt/poseidon/ccl/PoseidonJmtReference.java +++ b/zeroj-jmt-poseidon/src/main/java/org/zeroj/merkle/jmt/poseidon/ccl/PoseidonJmtReference.java @@ -1,10 +1,21 @@ package org.zeroj.merkle.jmt.poseidon.ccl; +import co.nstant.in.cbor.CborDecoder; +import co.nstant.in.cbor.model.Array; +import co.nstant.in.cbor.model.ByteString; +import co.nstant.in.cbor.model.DataItem; +import com.bloxbean.cardano.vds.jmt.JmtEncoding; +import com.bloxbean.cardano.vds.jmt.JmtInternalNode; +import com.bloxbean.cardano.vds.jmt.JmtLeafNode; +import com.bloxbean.cardano.vds.jmt.JmtNode; import com.bloxbean.cardano.vds.jmt.JmtProof; import org.zeroj.merkle.jmt.poseidon.profile.PoseidonJmtCommitments; import org.zeroj.merkle.jmt.poseidon.profile.PoseidonJmtHash; +import java.io.ByteArrayInputStream; import java.security.MessageDigest; +import java.util.ArrayList; +import java.util.List; /** Independent object-proof traversal for the Poseidon JMT v1 statement. */ public final class PoseidonJmtReference { @@ -93,6 +104,153 @@ public static boolean verify( } } + private static final int MAX_WIRE_BYTES = 1_048_576; + + /** + * Independent wire-proof verification for the Poseidon JMT v1 statement. + * + *

Decodes the CBOR classic JMT proof array, enforces v1 non-compressed + * step-by-step path traversal without skipped levels, validates canonical + * Poseidon field digests, and recomputes the root via + * {@link PoseidonJmtCommitments}.

+ */ + public static boolean verifyWire( + byte[] expectedRoot, + byte[] key, + byte[] expectedValue, + boolean including, + byte[] proofWire) { + if (expectedRoot == null || key == null || proofWire == null + || proofWire.length > MAX_WIRE_BYTES + || including != (expectedValue != null)) { + return false; + } + try { + PoseidonJmtHash.decode(expectedRoot); + byte[] queryKeyHash = PoseidonJmtHash.digest(key); + int[] queryPath = PoseidonJmtHash.nibbles(queryKeyHash); + + List top = new CborDecoder(new ByteArrayInputStream(proofWire)).decode(); + if (top.size() != 1 || !(top.get(0) instanceof Array array)) { + return false; + } + List items = array.getDataItems(); + if (items.size() > queryPath.length + 1) { + return false; + } + + List nodes = new ArrayList<>(items.size()); + for (DataItem item : items) { + if (!(item instanceof ByteString bs)) { + return false; + } + nodes.add(JmtEncoding.decode(bs.getBytes())); + } + + if (nodes.isEmpty()) { + return !including && equal(expectedRoot, PoseidonJmtCommitments.empty()); + } + + List branches = new ArrayList<>(nodes.size()); + JmtLeafNode terminalLeaf = null; + boolean missingBranchTerminal = false; + for (int depth = 0; depth < nodes.size(); depth++) { + JmtNode node = nodes.get(depth); + boolean isLast = depth == nodes.size() - 1; + if (node instanceof JmtInternalNode internal) { + if (internal.compressedPath() != null || depth >= queryPath.length) { + return false; + } + int bit = (internal.bitmap() >>> queryPath[depth]) & 1; + branches.add(internal); + if (bit == 0) { + if (!isLast) { + return false; + } + missingBranchTerminal = true; + } + } else if (node instanceof JmtLeafNode leaf) { + if (!isLast) { + return false; + } + terminalLeaf = leaf; + } else { + return false; + } + } + + byte[] current; + if (terminalLeaf != null) { + byte[] leafKey = terminalLeaf.keyHash(); + byte[] leafValue = terminalLeaf.valueHash(); + PoseidonJmtHash.decode(leafKey); + PoseidonJmtHash.decode(leafValue); + if (including) { + if (!equal(queryKeyHash, leafKey)) return false; + byte[] expectedValueHash = PoseidonJmtHash.digest(expectedValue); + if (!equal(expectedValueHash, leafValue)) return false; + } else { + if (equal(queryKeyHash, leafKey)) return false; + int[] conflictingPath = PoseidonJmtHash.nibbles(leafKey); + for (int i = 0; i < branches.size(); i++) { + if (conflictingPath[i] != queryPath[i]) return false; + } + } + current = PoseidonJmtCommitments.leaf(leafKey, leafValue); + } else if (missingBranchTerminal) { + if (including) { + return false; + } + current = null; + } else { + return false; + } + + for (int depth = branches.size() - 1; depth >= 0; depth--) { + JmtInternalNode internal = branches.get(depth); + byte[][] children = unpackChildren(internal); + if (children == null) { + return false; + } + int slot = queryPath[depth]; + if (missingBranchTerminal && depth == branches.size() - 1) { + if (children[slot] != null) { + return false; + } + } else { + if (children[slot] == null || !equal(children[slot], current)) { + return false; + } + } + current = PoseidonJmtCommitments.branch(children); + } + return equal(expectedRoot, current); + } catch (Exception malformed) { + return false; + } + } + + private static byte[][] unpackChildren(JmtInternalNode internal) { + int bitmap = internal.bitmap(); + byte[][] packed = internal.childHashes(); + if (packed == null || packed.length != Integer.bitCount(bitmap & 0xFFFF)) { + return null; + } + byte[][] children = new byte[16][]; + int cursor = 0; + for (int i = 0; i < 16; i++) { + if (((bitmap >>> i) & 1) != 0) { + byte[] hash = packed[cursor++]; + if (hash == null) { + return null; + } + PoseidonJmtHash.decode(hash); + children[i] = hash.clone(); + } + } + return children; + } + private static boolean equal(byte[] left, byte[] right) { return left != null && right != null && MessageDigest.isEqual(left, right); } diff --git a/zeroj-jmt-poseidon/src/main/java/org/zeroj/merkle/jmt/poseidon/ccl/PoseidonJmtTree.java b/zeroj-jmt-poseidon/src/main/java/org/zeroj/merkle/jmt/poseidon/ccl/PoseidonJmtTree.java index bd1ec18e..c72de66c 100644 --- a/zeroj-jmt-poseidon/src/main/java/org/zeroj/merkle/jmt/poseidon/ccl/PoseidonJmtTree.java +++ b/zeroj-jmt-poseidon/src/main/java/org/zeroj/merkle/jmt/poseidon/ccl/PoseidonJmtTree.java @@ -110,7 +110,9 @@ public boolean verifyProofWire( } try { PoseidonJmtHash.decode(expectedRoot); - return delegate.verifyProofWire( + return PoseidonJmtReference.verifyWire( + expectedRoot, key, expectedValue, including, proofWire) + && delegate.verifyProofWire( expectedRoot, key, expectedValue, including, proofWire); } catch (RuntimeException malformed) { return false; diff --git a/zeroj-jmt-poseidon/src/test/java/org/zeroj/merkle/jmt/poseidon/ccl/PoseidonJmtSecurityRegressionTest.java b/zeroj-jmt-poseidon/src/test/java/org/zeroj/merkle/jmt/poseidon/ccl/PoseidonJmtSecurityRegressionTest.java index f99275c2..9e7d7794 100644 --- a/zeroj-jmt-poseidon/src/test/java/org/zeroj/merkle/jmt/poseidon/ccl/PoseidonJmtSecurityRegressionTest.java +++ b/zeroj-jmt-poseidon/src/test/java/org/zeroj/merkle/jmt/poseidon/ccl/PoseidonJmtSecurityRegressionTest.java @@ -1,6 +1,10 @@ package org.zeroj.merkle.jmt.poseidon.ccl; +import co.nstant.in.cbor.CborEncoder; +import co.nstant.in.cbor.model.Array; +import co.nstant.in.cbor.model.ByteString; import com.bloxbean.cardano.vds.core.NibblePath; +import com.bloxbean.cardano.vds.jmt.JmtInternalNode; import com.bloxbean.cardano.vds.jmt.JmtProof; import com.bloxbean.cardano.vds.jmt.JmtProofVerifier; import com.bloxbean.cardano.vds.jmt.store.InMemoryJmtStore; @@ -8,6 +12,7 @@ import org.zeroj.merkle.jmt.poseidon.profile.PoseidonJmtHash; import org.junit.jupiter.api.Test; +import java.io.ByteArrayOutputStream; import java.lang.reflect.Method; import java.nio.charset.StandardCharsets; import java.util.LinkedHashMap; @@ -91,6 +96,20 @@ void rejectsGapRelabelingThatCouldForgeAbsenceForPresentKey() throws Exception { new PoseidonJmtHashFunction(), new PoseidonJmtCommitmentScheme())); assertFalse(new PoseidonJmtTree(new InMemoryJmtStore()) .verifyNonInclusionProof(root, key, forged)); + + // Wire-level equivalent: compressedPath on an internal node attempting to skip depth 0. + int bitmap = 1 << path[0]; + var compressedInternal = JmtInternalNode.of( + bitmap, new byte[][]{children[path[0]]}, new byte[]{(byte) path[0]}); + Array wireArr = new Array(); + wireArr.add(new ByteString(compressedInternal.encode())); + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + new CborEncoder(baos).encode(wireArr); + byte[] forgedWire = baos.toByteArray(); + + assertFalse(PoseidonJmtReference.verifyWire(root, key, null, false, forgedWire)); + assertFalse(new PoseidonJmtTree(new InMemoryJmtStore()) + .verifyProofWire(root, key, null, false, forgedWire)); } private static JmtProof nonInclusionEmpty(List steps) throws Exception { diff --git a/zeroj-onchain-julc/build.gradle b/zeroj-onchain-julc/build.gradle index 55c5b0ff..a5a9421a 100644 --- a/zeroj-onchain-julc/build.gradle +++ b/zeroj-onchain-julc/build.gradle @@ -97,46 +97,6 @@ test { } } -//tasks.named('bundleJulcSources') { -// mustRunAfter tasks.named('processResources') -// -// doLast { -// def sourceRoot = layout.buildDirectory.dir('resources/main/META-INF/plutus-sources').get().asFile -// def sources = new TreeSet(fileTree(sourceRoot) { -// include '**/*.java' -// }.files.collect { file -> -// sourceRoot.toPath().relativize(file.toPath()).toString().replace(File.separatorChar, '/' as char) -// }) -// -// configurations.compileClasspath.files.findAll { it.name.endsWith('.jar') }.each { jar -> -// zipTree(jar).matching { -// include 'META-INF/plutus-sources/index.txt' -// }.files.each { indexFile -> -// indexFile.eachLine { line -> -// def entry = line.trim() -// if (entry.endsWith('.java')) { -// sources.add(entry) -// } -// } -// } -// } -// -// if (!sources.isEmpty()) { -// def index = new File(sourceRoot, 'index.txt') -// index.parentFile.mkdirs() -// index.text = sources.join('\n') + '\n' -// } -// } -//} -// -//tasks.named('compileTestJava') { -// dependsOn tasks.named('bundleJulcSources') -//} -// -//tasks.named('javadoc') { -// dependsOn tasks.named('bundleJulcSources') -//} - publishing { publications { mavenJava(MavenPublication) { diff --git a/zeroj-onchain-julc/src/main/java/org/zeroj/onchain/julc/groth16/codec/Groth16AuthenticatedStateTransitionScriptFactory.java b/zeroj-onchain-julc/src/main/java/org/zeroj/onchain/julc/groth16/codec/Groth16AuthenticatedStateTransitionScriptFactory.java index 6c05f1de..97cb92be 100644 --- a/zeroj-onchain-julc/src/main/java/org/zeroj/onchain/julc/groth16/codec/Groth16AuthenticatedStateTransitionScriptFactory.java +++ b/zeroj-onchain-julc/src/main/java/org/zeroj/onchain/julc/groth16/codec/Groth16AuthenticatedStateTransitionScriptFactory.java @@ -48,8 +48,7 @@ public final class Groth16AuthenticatedStateTransitionScriptFactory { Set.of( AuthenticatedStateCircuitManifest.Operation.VALUE_UPDATE, AuthenticatedStateCircuitManifest.Operation.INSERT_EMPTY, - AuthenticatedStateCircuitManifest.Operation.INSERT_DIFFERENT_LEAF, - AuthenticatedStateCircuitManifest.Operation.DELETE); + AuthenticatedStateCircuitManifest.Operation.INSERT_DIFFERENT_LEAF); private Groth16AuthenticatedStateTransitionScriptFactory() {} diff --git a/zeroj-onchain-julc/src/main/java/org/zeroj/onchain/julc/groth16/codec/Groth16VerificationKeyCodec.java b/zeroj-onchain-julc/src/main/java/org/zeroj/onchain/julc/groth16/codec/Groth16VerificationKeyCodec.java index efee1f8a..45fef9d7 100644 --- a/zeroj-onchain-julc/src/main/java/org/zeroj/onchain/julc/groth16/codec/Groth16VerificationKeyCodec.java +++ b/zeroj-onchain-julc/src/main/java/org/zeroj/onchain/julc/groth16/codec/Groth16VerificationKeyCodec.java @@ -1,5 +1,9 @@ package org.zeroj.onchain.julc.groth16.codec; +import org.zeroj.bls12381.Bls12381Codecs; +import org.zeroj.bls12381.ec.G1Point; +import org.zeroj.bls12381.ec.G2Point; + import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.charset.StandardCharsets; @@ -66,16 +70,34 @@ public static SnarkjsToCardano.VkCompressed decode(byte[] encoded) { if (expected != encoded.length) { throw new IllegalArgumentException("Groth16 verification-key length does not match IC count"); } - byte[] alpha = take(input, G1_BYTES); - byte[] beta = take(input, G2_BYTES); - byte[] gamma = take(input, G2_BYTES); - byte[] delta = take(input, G2_BYTES); + byte[] alpha = requireNonInfinityG1("alpha", take(input, G1_BYTES)); + byte[] beta = requireNonInfinityG2("beta", take(input, G2_BYTES)); + byte[] gamma = requireNonInfinityG2("gamma", take(input, G2_BYTES)); + byte[] delta = requireNonInfinityG2("delta", take(input, G2_BYTES)); List ic = new ArrayList<>(icCount); - for (int index = 0; index < icCount; index++) ic.add(take(input, G1_BYTES)); + for (int index = 0; index < icCount; index++) { + ic.add(requireNonInfinityG1("ic[" + index + "]", take(input, G1_BYTES))); + } if (input.hasRemaining()) throw new IllegalArgumentException("trailing verification-key bytes"); return new SnarkjsToCardano.VkCompressed(alpha, beta, gamma, delta, List.copyOf(ic)); } + private static byte[] requireNonInfinityG1(String name, byte[] bytes) { + G1Point point = Bls12381Codecs.g1FromCompressed(bytes); + if (point.isInfinity()) { + throw new IllegalArgumentException("Groth16 verification key " + name + " must not be infinity"); + } + return bytes; + } + + private static byte[] requireNonInfinityG2(String name, byte[] bytes) { + G2Point point = Bls12381Codecs.g2FromCompressed(bytes); + if (point.isInfinity()) { + throw new IllegalArgumentException("Groth16 verification key " + name + " must not be infinity"); + } + return bytes; + } + private static void requireLength(String name, byte[] value, int expected) { if (value == null || value.length != expected) { throw new IllegalArgumentException(name + " must be " + expected + " bytes"); diff --git a/zeroj-onchain-julc/src/main/java/org/zeroj/onchain/julc/groth16/codec/ProverToCardano.java b/zeroj-onchain-julc/src/main/java/org/zeroj/onchain/julc/groth16/codec/ProverToCardano.java index c9cbb669..4f54f222 100644 --- a/zeroj-onchain-julc/src/main/java/org/zeroj/onchain/julc/groth16/codec/ProverToCardano.java +++ b/zeroj-onchain-julc/src/main/java/org/zeroj/onchain/julc/groth16/codec/ProverToCardano.java @@ -3,6 +3,7 @@ import org.zeroj.bls12381.Bls12381Codecs; import org.zeroj.bls12381.ec.JacobianG1BLS381; import org.zeroj.bls12381.ec.JacobianG2BLS381; +import org.zeroj.bls12381.field.Fp; import org.zeroj.crypto.groth16.Groth16ProofBLS381; import org.zeroj.crypto.groth16.Groth16Keys; import org.zeroj.crypto.setup.Groth16SetupBLS381; @@ -120,6 +121,9 @@ public static SnarkjsToCardano.VkCompressed compressVk(Groth16Keys keys) { * Write a field element as 48-byte big-endian into buffer at offset. */ private static void writeFp(byte[] buf, int offset, BigInteger value) { + if (value == null || value.signum() < 0 || value.compareTo(Fp.P) >= 0) { + throw new IllegalArgumentException("Field element is outside BLS12-381 Fp [0, p)"); + } byte[] bytes = value.toByteArray(); int srcStart = Math.max(0, bytes.length - FP_SIZE); int count = Math.min(bytes.length, FP_SIZE); diff --git a/zeroj-onchain-julc/src/main/java/org/zeroj/onchain/julc/groth16/validator/Groth16AuthenticatedStateTransitionValidator.java b/zeroj-onchain-julc/src/main/java/org/zeroj/onchain/julc/groth16/validator/Groth16AuthenticatedStateTransitionValidator.java index 778861b6..5ea1049f 100644 --- a/zeroj-onchain-julc/src/main/java/org/zeroj/onchain/julc/groth16/validator/Groth16AuthenticatedStateTransitionValidator.java +++ b/zeroj-onchain-julc/src/main/java/org/zeroj/onchain/julc/groth16/validator/Groth16AuthenticatedStateTransitionValidator.java @@ -87,6 +87,7 @@ public static boolean validate( || !hasStateToken(continuingOutput) || !Builtins.equalsData( continuingOutput.value(), ownInput.resolved().value()) + || !continuingOutput.referenceScript().isEmpty() || !hasInlineStateDatum( continuingOutput, transition.newRoot(), diff --git a/zeroj-onchain-julc/src/main/java/org/zeroj/onchain/julc/groth16/validator/Groth16BLS12381TxOutRefBindingVerifier.java b/zeroj-onchain-julc/src/main/java/org/zeroj/onchain/julc/groth16/validator/Groth16BLS12381TxOutRefBindingVerifier.java index 53543308..6ff3859b 100644 --- a/zeroj-onchain-julc/src/main/java/org/zeroj/onchain/julc/groth16/validator/Groth16BLS12381TxOutRefBindingVerifier.java +++ b/zeroj-onchain-julc/src/main/java/org/zeroj/onchain/julc/groth16/validator/Groth16BLS12381TxOutRefBindingVerifier.java @@ -15,11 +15,17 @@ /** * Groth16 BLS12-381 verifier that binds the proof statement to the UTxO being spent. * + *

SECURITY WARNING — DEMONSTRATION ONLY (CANNOT GUARD A REAL UTxO): + * Binding the proof to {@code txOutRef} prevents replaying the same proof on a + * different UTxO, but this validator does not constrain signers, + * outputs, value preservation, recipient addresses, or state transitions — any + * party who observes a valid proof in the mempool can front-run the transaction + * and redirect the spent funds. Do not use this validator to guard real value; + * embed {@link Groth16BLS12381Lib} in an application validator that binds + * signers, outputs, value, nullifiers, and business-policy invariants.

+ * *

The first public input must be - * {@code blake2b_256(spentTxId || spentOutputIndex32) mod Fr}. This is only an - * example policy: production validators should bind the statement to the - * application-specific signer, datum, value, output, nullifier, or authorization - * fields they require.

+ * {@code blake2b_256(spentTxId || spentOutputIndex32) mod Fr}.

*/ @SpendingValidator public class Groth16BLS12381TxOutRefBindingVerifier { diff --git a/zeroj-onchain-julc/src/main/java/org/zeroj/onchain/julc/groth16/validator/Groth16BLS12381Verifier.java b/zeroj-onchain-julc/src/main/java/org/zeroj/onchain/julc/groth16/validator/Groth16BLS12381Verifier.java index 1a1caecf..9fd7fcf4 100644 --- a/zeroj-onchain-julc/src/main/java/org/zeroj/onchain/julc/groth16/validator/Groth16BLS12381Verifier.java +++ b/zeroj-onchain-julc/src/main/java/org/zeroj/onchain/julc/groth16/validator/Groth16BLS12381Verifier.java @@ -8,15 +8,22 @@ /** * On-chain Groth16 BLS12-381 verifier as a Plutus V3 spending validator. - *

- * Verification key points are baked in at deploy time. The full IC vector is + * + *

SECURITY WARNING — NOT FOR VALUE-BEARING UTxOs: This standalone + * validator performs cryptographic proof verification only and ignores + * {@code ScriptContext} (no signer, output, value, replay, or nullifier checks). + * Do not lock funds under this validator directly; compose + * {@link Groth16BLS12381Lib} into an application-bound validator that enforces + * full transaction and state-transition authorization.

+ * + *

Verification key points are baked in at deploy time. The full IC vector is * passed as a Plutus list parameter, so this verifier supports any public-input - * count for Groth16 circuits over BLS12-381. - *

- * Datum: list of public input integers in verification-key schema order. + * count for Groth16 circuits over BLS12-381.

+ * + *

Datum: list of public input integers in verification-key schema order. * Redeemer: compressed Groth16 proof points. * Parameter {@code vkIc}: list of compressed G1 IC points, where - * {@code len(vkIc) == len(publicInputs) + 1}. + * {@code len(vkIc) == len(publicInputs) + 1}.

*/ @SpendingValidator public class Groth16BLS12381Verifier { diff --git a/zeroj-onchain-julc/src/main/java/org/zeroj/onchain/julc/plonk/validator/PlonkBLS12381MultiInputParamVerifier.java b/zeroj-onchain-julc/src/main/java/org/zeroj/onchain/julc/plonk/validator/PlonkBLS12381MultiInputParamVerifier.java index 1a2e305f..661fdb13 100644 --- a/zeroj-onchain-julc/src/main/java/org/zeroj/onchain/julc/plonk/validator/PlonkBLS12381MultiInputParamVerifier.java +++ b/zeroj-onchain-julc/src/main/java/org/zeroj/onchain/julc/plonk/validator/PlonkBLS12381MultiInputParamVerifier.java @@ -10,6 +10,12 @@ /** * Cardano-profile BLS12-381 PlonK verifier with script-parameter public inputs. + * + *

SECURITY WARNING — NOT FOR VALUE-BEARING UTxOs: This standalone + * validator performs cryptographic proof verification only and ignores + * {@code ScriptContext} (no signer, output, value, replay, or nullifier checks). + * Do not lock funds under this validator directly; compose + * {@link PlonkBLS12381Lib} into an application-bound validator.

*/ @SpendingValidator public class PlonkBLS12381MultiInputParamVerifier { diff --git a/zeroj-onchain-julc/src/main/java/org/zeroj/onchain/julc/plonk/validator/PlonkBLS12381MultiInputVerifier.java b/zeroj-onchain-julc/src/main/java/org/zeroj/onchain/julc/plonk/validator/PlonkBLS12381MultiInputVerifier.java index 03e35455..6545c12a 100644 --- a/zeroj-onchain-julc/src/main/java/org/zeroj/onchain/julc/plonk/validator/PlonkBLS12381MultiInputVerifier.java +++ b/zeroj-onchain-julc/src/main/java/org/zeroj/onchain/julc/plonk/validator/PlonkBLS12381MultiInputVerifier.java @@ -11,6 +11,12 @@ /** * Cardano-profile BLS12-381 PlonK verifier for bounded datum-supplied * multi-public-input circuits. + * + *

SECURITY WARNING — NOT FOR VALUE-BEARING UTxOs: This standalone + * validator performs cryptographic proof verification only and ignores + * {@code ScriptContext} (no signer, output, value, replay, or nullifier checks). + * Do not lock funds under this validator directly; compose + * {@link PlonkBLS12381Lib} into an application-bound validator.

*/ @SpendingValidator public class PlonkBLS12381MultiInputVerifier { diff --git a/zeroj-onchain-julc/src/main/java/org/zeroj/onchain/julc/plonk/validator/PlonkBLS12381Verifier.java b/zeroj-onchain-julc/src/main/java/org/zeroj/onchain/julc/plonk/validator/PlonkBLS12381Verifier.java index f6a04b61..e49ae244 100644 --- a/zeroj-onchain-julc/src/main/java/org/zeroj/onchain/julc/plonk/validator/PlonkBLS12381Verifier.java +++ b/zeroj-onchain-julc/src/main/java/org/zeroj/onchain/julc/plonk/validator/PlonkBLS12381Verifier.java @@ -11,6 +11,11 @@ /** * Cardano-profile BLS12-381 PlonK verifier for one-public-input circuits. * + *

SECURITY WARNING — NOT FOR VALUE-BEARING UTxOs: This standalone + * validator performs cryptographic proof verification only and ignores + * {@code ScriptContext} (no signer, output, value, replay, or nullifier checks). + * Do not lock funds under this validator directly.

+ * *

The cryptographic verifier is implemented in {@link PlonkBLS12381Lib} so * application validators can reuse the same reviewed pairing-check logic while * adding their own ScriptContext policy.

diff --git a/zeroj-onchain-julc/src/test/java/org/zeroj/onchain/julc/groth16/codec/Groth16VerificationKeyCodecTest.java b/zeroj-onchain-julc/src/test/java/org/zeroj/onchain/julc/groth16/codec/Groth16VerificationKeyCodecTest.java index b1bfb252..f7e05983 100644 --- a/zeroj-onchain-julc/src/test/java/org/zeroj/onchain/julc/groth16/codec/Groth16VerificationKeyCodecTest.java +++ b/zeroj-onchain-julc/src/test/java/org/zeroj/onchain/julc/groth16/codec/Groth16VerificationKeyCodecTest.java @@ -1,7 +1,12 @@ package org.zeroj.onchain.julc.groth16.codec; import org.junit.jupiter.api.Test; +import org.zeroj.bls12381.Bls12381Codecs; +import org.zeroj.bls12381.Bls12381Generators; +import org.zeroj.bls12381.ec.G1Point; +import org.zeroj.bls12381.ec.G2Point; +import java.math.BigInteger; import java.nio.ByteBuffer; import java.util.Arrays; import java.util.List; @@ -13,9 +18,7 @@ class Groth16VerificationKeyCodecTest { @Test void canonicalEncodingRoundTripsAndRejectsNonCanonicalLengths() { - var key = new SnarkjsToCardano.VkCompressed( - filled(48, 1), filled(96, 2), filled(96, 3), filled(96, 4), - List.of(filled(48, 5), filled(48, 6))); + var key = validKey(); byte[] encoded = Groth16VerificationKeyCodec.encode(key); var decoded = Groth16VerificationKeyCodec.decode(encoded); @@ -45,6 +48,44 @@ void canonicalEncodingRoundTripsAndRejectsNonCanonicalLengths() { new byte[47], key.beta(), key.gamma(), key.delta(), key.ic()))); } + @Test + void decodeRejectsInfinityAndInvalidCompressedPoints() { + var valid = validKey(); + byte[] g1Inf = Bls12381Codecs.g1ToCompressed(G1Point.INFINITY); + byte[] g2Inf = Bls12381Codecs.g2ToCompressed(G2Point.INFINITY); + + var infAlpha = new SnarkjsToCardano.VkCompressed(g1Inf, valid.beta(), valid.gamma(), valid.delta(), valid.ic()); + assertThrows(IllegalArgumentException.class, + () -> Groth16VerificationKeyCodec.decode(Groth16VerificationKeyCodec.encode(infAlpha))); + + var infBeta = new SnarkjsToCardano.VkCompressed(valid.alpha(), g2Inf, valid.gamma(), valid.delta(), valid.ic()); + assertThrows(IllegalArgumentException.class, + () -> Groth16VerificationKeyCodec.decode(Groth16VerificationKeyCodec.encode(infBeta))); + + var infIc = new SnarkjsToCardano.VkCompressed( + valid.alpha(), valid.beta(), valid.gamma(), valid.delta(), List.of(valid.ic().get(0), g1Inf)); + assertThrows(IllegalArgumentException.class, + () -> Groth16VerificationKeyCodec.decode(Groth16VerificationKeyCodec.encode(infIc))); + + var garbage = new SnarkjsToCardano.VkCompressed( + filled(48, 1), valid.beta(), valid.gamma(), valid.delta(), valid.ic()); + assertThrows(IllegalArgumentException.class, + () -> Groth16VerificationKeyCodec.decode(Groth16VerificationKeyCodec.encode(garbage))); + } + + private static SnarkjsToCardano.VkCompressed validKey() { + G1Point g1 = Bls12381Generators.G1; + G2Point g2 = Bls12381Generators.G2; + return new SnarkjsToCardano.VkCompressed( + Bls12381Codecs.g1ToCompressed(g1.scalarMul(BigInteger.valueOf(2))), + Bls12381Codecs.g2ToCompressed(g2.scalarMul(BigInteger.valueOf(3))), + Bls12381Codecs.g2ToCompressed(g2.scalarMul(BigInteger.valueOf(5))), + Bls12381Codecs.g2ToCompressed(g2.scalarMul(BigInteger.valueOf(7))), + List.of( + Bls12381Codecs.g1ToCompressed(g1.scalarMul(BigInteger.valueOf(11))), + Bls12381Codecs.g1ToCompressed(g1.scalarMul(BigInteger.valueOf(13))))); + } + private static byte[] filled(int length, int value) { byte[] output = new byte[length]; Arrays.fill(output, (byte) value); diff --git a/zeroj-onchain-julc/src/test/java/org/zeroj/onchain/julc/groth16/validator/Groth16AuthenticatedStateTransitionValidatorTest.java b/zeroj-onchain-julc/src/test/java/org/zeroj/onchain/julc/groth16/validator/Groth16AuthenticatedStateTransitionValidatorTest.java index 3fd1803a..6c7a2e9b 100644 --- a/zeroj-onchain-julc/src/test/java/org/zeroj/onchain/julc/groth16/validator/Groth16AuthenticatedStateTransitionValidatorTest.java +++ b/zeroj-onchain-julc/src/test/java/org/zeroj/onchain/julc/groth16/validator/Groth16AuthenticatedStateTransitionValidatorTest.java @@ -266,7 +266,9 @@ private PlutusData context(Mutation mutation, byte[] acceptedRelease) { } else { outputValue = STATE_VALUE; } - TxOut continuingOutput = txOut(continuingAddress, outputValue, outputDatum); + TxOut continuingOutput = mutation == Mutation.OUTPUT_REFERENCE_SCRIPT + ? new TxOut(continuingAddress, outputValue, outputDatum, Optional.of(ScriptHash.of(SCRIPT_HASH))) + : txOut(continuingAddress, outputValue, outputDatum); PlutusData argumentDatum = stateDatum(argumentRoot, argumentVersion); PlutusData redeemer = PlutusData.constr(0, @@ -397,6 +399,7 @@ private enum Mutation { OUTPUT_NO_DATUM, OUTPUT_TOKEN, OUTPUT_VALUE, + OUTPUT_REFERENCE_SCRIPT, MINT, MISSING_SIGNER, NO_CONTINUING_OUTPUT, diff --git a/zeroj-tools/build.gradle b/zeroj-tools/build.gradle index 9f3b1e0c..522860c1 100644 --- a/zeroj-tools/build.gradle +++ b/zeroj-tools/build.gradle @@ -125,6 +125,8 @@ tasks.register('nativeDistZip', Zip) { filePermissions { unix(0755) } } from("${rootDir}/docs/ceremony/USER-GUIDE.md") { rename { 'README.md' } } + from("${rootDir}/LICENSE") + from("${rootDir}/NOTICE") } } diff --git a/zeroj-tools/src/main/java/org/zeroj/ceremony/CeremonyCli.java b/zeroj-tools/src/main/java/org/zeroj/ceremony/CeremonyCli.java index 5854c297..1ce81980 100644 --- a/zeroj-tools/src/main/java/org/zeroj/ceremony/CeremonyCli.java +++ b/zeroj-tools/src/main/java/org/zeroj/ceremony/CeremonyCli.java @@ -68,12 +68,25 @@ static class ExportR1cs implements Callable { @Override public Integer call() throws Exception { - ClassLoader loader = CeremonyCli.class.getClassLoader(); + if (circuitJar != null && !Files.isReadable(circuitJar)) { + System.err.println("Cannot read jar: " + circuitJar); + return 2; + } + CircuitBuilder builder; if (circuitJar != null) { - if (!Files.isReadable(circuitJar)) { System.err.println("Cannot read jar: " + circuitJar); return 2; } - loader = new URLClassLoader(new URL[]{circuitJar.toUri().toURL()}, loader); + try (URLClassLoader jarLoader = new URLClassLoader( + new URL[]{circuitJar.toUri().toURL()}, CeremonyCli.class.getClassLoader())) { + builder = loadCircuit(circuit, jarLoader); + exportCircuit(builder); + } + } else { + builder = loadCircuit(circuit, CeremonyCli.class.getClassLoader()); + exportCircuit(builder); } - CircuitBuilder builder = loadCircuit(circuit, loader); + return 0; + } + + private void exportCircuit(CircuitBuilder builder) throws Exception { System.out.println("Compiling circuit " + circuit + " (BLS12-381) ..."); long t0 = System.nanoTime(); R1CSConstraintSystem r1cs = builder.compileR1CS(CurveId.BLS12_381); @@ -83,7 +96,6 @@ public Integer call() throws Exception { R1csExporter.export(r1cs.constraints(), r1cs.numWires(), r1cs.numPublicInputs(), out); System.out.printf("Wrote %s (%,d bytes)%n", out, Files.size(out)); System.out.println("Next: snarkjs groth16 setup " + out.getFileName() + " key_0000.zkey"); - return 0; } } diff --git a/zeroj-verifier-plonk/src/main/java/org/zeroj/verifier/plonk/GnarkFiatShamirTranscript.java b/zeroj-verifier-plonk/src/main/java/org/zeroj/verifier/plonk/GnarkFiatShamirTranscript.java index c3bffe89..83352fc5 100644 --- a/zeroj-verifier-plonk/src/main/java/org/zeroj/verifier/plonk/GnarkFiatShamirTranscript.java +++ b/zeroj-verifier-plonk/src/main/java/org/zeroj/verifier/plonk/GnarkFiatShamirTranscript.java @@ -1,6 +1,7 @@ package org.zeroj.verifier.plonk; import java.math.BigInteger; +import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; @@ -88,7 +89,7 @@ public BigInteger computeChallenge(String challengeName) { MessageDigest sha256 = MessageDigest.getInstance("SHA-256"); // 1. Write challenge name - sha256.update(challengeName.getBytes()); + sha256.update(challengeName.getBytes(StandardCharsets.UTF_8)); // 2. Write previous challenge hash (if not the first challenge) if (state.position != 0) { 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..11e822aa 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 @@ -195,6 +195,9 @@ public VerificationResult verify(ZkProofEnvelope envelope, VerificationMaterial xin = xin.multiply(xin).mod(Fr); } BigInteger zh = xin.subtract(BigInteger.ONE).mod(Fr); + if (zh.signum() == 0) { + return VerificationResult.proofInvalid("PlonK BLS12-381 challenge is inside the evaluation domain"); + } // Step 3: Lagrange evaluations for public input positions. BigInteger nBI = BigInteger.valueOf(n); @@ -377,15 +380,16 @@ private void validateParsedMetadata(String proofProtocol, String proofCurve, Str } private void validateVkShape(int nPublic, int power) { - if (nPublic < 0 || nPublic > MAX_PUBLIC_INPUTS) { + if (power <= 0 || power > MAX_DOMAIN_POWER) { throw new VerificationInputException( VerificationResult.ReasonCode.MALFORMED_ENVELOPE, - "Invalid PlonK BLS12-381 public input count"); + "Invalid PlonK BLS12-381 domain size"); } - if (power <= 0 || power > MAX_DOMAIN_POWER) { + int domainSize = 1 << power; + if (nPublic < 0 || nPublic > MAX_PUBLIC_INPUTS || nPublic > domainSize) { throw new VerificationInputException( VerificationResult.ReasonCode.MALFORMED_ENVELOPE, - "Invalid PlonK BLS12-381 domain size"); + "Invalid PlonK BLS12-381 public input count"); } } From a62a18d4bc6cfc18a7fa7863e48afa4d79bbaac2 Mon Sep 17 00:00:00 2001 From: Satya Date: Sat, 21 Nov 2026 11:54:37 +0800 Subject: [PATCH 2/3] Address PR #126 review feedback: bounded CBOR, VK/store/rank validation, SRS compat, and tests --- NOTICE | 18 +- ...0031-groth16-mpc-trusted-setup-ceremony.md | 4 +- ...0-julc-pre17-org-julclang-and-typed-bls.md | 2 +- ...lonk-v2-cardano-transcript-and-verifier.md | 18 +- .../annotation/ZkSymbolicTypesTest.java | 11 +- .../CircuitAnnotationProcessorTest.java | 5 +- .../org/zeroj/circuit/CircuitAPIImpl.java | 33 +++- .../circuit/lib/field/Fe25519HintTest.java | 46 +++++ .../circuit/lib/jubjub/PedersenTest.java | 30 ++- .../zeroj/crypto/groth16/Groth16Pipeline.java | 11 +- .../zeroj/crypto/groth16/Groth16PkStore.java | 9 + .../crypto/groth16/Groth16ProverBLS381.java | 3 + .../zeroj/crypto/groth16/SparsePointFile.java | 30 +++ .../crypto/setup/Groth16SetupBLS381.java | 32 +++- .../org/zeroj/crypto/setup/SetupCacheIO.java | 10 +- .../crypto/groth16/Groth16PkStoreTest.java | 135 ++++++++++++++ .../zeroj/crypto/setup/SetupCacheTest.java | 109 ++++++++++- .../poseidon/ccl/PoseidonJmtReference.java | 171 +++++++++++++++--- .../PoseidonJmtSecurityRegressionTest.java | 47 +++++ zeroj-onchain-julc/README.md | 2 +- ...enticatedStateTransitionScriptFactory.java | 1 + .../codec/Groth16VerificationKeyCodec.java | 28 ++- .../Groth16VerificationKeyCodecTest.java | 61 +++++-- ...enticatedStateTransitionValidatorTest.java | 55 +++++- zeroj-tools/build.gradle | 4 + 25 files changed, 772 insertions(+), 103 deletions(-) diff --git a/NOTICE b/NOTICE index ace1f5fe..a4309ba5 100644 --- a/NOTICE +++ b/NOTICE @@ -64,10 +64,26 @@ default build and are never published. -------------------------------------------------------------------------- Bouncy Castle — Cryptography Provider (bcprov-jdk18on) -------------------------------------------------------------------------- -Copyright (c) 2000-2025 The Legion of the Bouncy Castle Inc. +Copyright (c) 2000-2023 The Legion of the Bouncy Castle Inc. (https://www.bouncycastle.org) Licensed under the Bouncy Castle License (MIT-style) https://www.bouncycastle.org/licence.html +Permission is hereby granted, free of charge, to any person obtaining a copy of this software +and associated documentation files (the "Software"), to deal in the Software without restriction, +including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, +and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial +portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. + -------------------------------------------------------------------------- picocli — Command-Line Interface Framework -------------------------------------------------------------------------- diff --git a/docs/adr/0031-groth16-mpc-trusted-setup-ceremony.md b/docs/adr/0031-groth16-mpc-trusted-setup-ceremony.md index 1dd3fcc0..981b1178 100644 --- a/docs/adr/0031-groth16-mpc-trusted-setup-ceremony.md +++ b/docs/adr/0031-groth16-mpc-trusted-setup-ceremony.md @@ -65,9 +65,9 @@ Java developers calling APIs — each role gets one command: | command | who | what | milestone | |---|---|---|---| | `export-r1cs --circuit --out c.r1cs` | coordinator | compile the ZeroJ circuit → iden3 `.r1cs` (used by **both** options) | M4 | -| `contribute in.zkey out.zkey` | contributor | Option B phase-2 contribution (entropy prompt + hash printout) | M5 | +| `contribute --in in.zkey --out out.zkey` | contributor | Option B phase-2 contribution (entropy prompt + hash printout) | M5 | | `verify c.r1cs pot.ptau final.zkey` | anyone | *not implemented in `zeroj-ceremony`* — use **`snarkjs zkey verify`** directly so verification remains completely independent | N/A | -| `beacon in.zkey out.zkey --hash ` | coordinator | final beacon contribution | M5 | +| `beacon` | coordinator | *not implemented in `zeroj-ceremony`* — use **`snarkjs zkey beacon`** for the final beacon contribution | N/A | | `finalize final.zkey --pk-store ` | coordinator | import + persist via `Groth16PkStore`, export the VK for the validator | M2/M4 | Same module family later hosts the planned end-user proving CLI (seed phrase → ownership proof) — diff --git a/docs/adr/0050-julc-pre17-org-julclang-and-typed-bls.md b/docs/adr/0050-julc-pre17-org-julclang-and-typed-bls.md index 635ad98f..13bfcd05 100644 --- a/docs/adr/0050-julc-pre17-org-julclang-and-typed-bls.md +++ b/docs/adr/0050-julc-pre17-org-julclang-and-typed-bls.md @@ -358,7 +358,7 @@ ZeroJ upgrades `julcVersion` from `0.1.0-pre18` to `0.1.0-pre22` alongside [ADR- |---|---:|---| | `Groth16BLS12381Verifier` | 1,117 | `59f37dc68c0dd3a9f1aeeef7dbbdc3b57ab7acf0e75ddb28d1385db6` | | `Groth16BLS12381TxOutRefBindingVerifier` | 1,325 | `5c2f90090a78275d2b5eb26195bfeeebf9633daec452e01deef01b13` | -| `Groth16AuthenticatedStateTransitionValidator` | 2,817 | `46c77c445f4d16b156797d05aee6964f9c93d7446dd4f12d26824d4d` | +| `Groth16AuthenticatedStateTransitionValidator` | 2,845 | `5192732cf2c70ce2f03859f1e9f728d986f6a0e1c18e1a1ab86f8eb2` | | `PlonkBLS12381Verifier` | 4,262 | `7e36f398c0d0c1d3f141563c4766118cb6ea1496dfaab269fc30b2de` | | `PlonkBLS12381MultiInputVerifier` | 4,668 | `4172c86d5e8e8e69dfd91f92776176b567c4c2200108dc98273d4a1e` | | `PlonkBLS12381MultiInputParamVerifier` | 4,707 | `7e78ad1bbf6ef553a4401fab1025250f14e3f5271816bcc8a732f38f` | diff --git a/docs/adr/0069-plonk-v2-cardano-transcript-and-verifier.md b/docs/adr/0069-plonk-v2-cardano-transcript-and-verifier.md index 80882e2a..3a4896f4 100644 --- a/docs/adr/0069-plonk-v2-cardano-transcript-and-verifier.md +++ b/docs/adr/0069-plonk-v2-cardano-transcript-and-verifier.md @@ -9,9 +9,9 @@ ## Context -ZeroJ's current PlonK BLS12-381 Cardano profiles (`COMPRESSED_G1` / `COMPRESSED_G1_MPI`) inherit snarkjs 0.7.6's unchained per-round Fiat-Shamir challenge derivation (including deriving `u` without chaining all prior transcript state) and decompress G1 proof/VK commitments multiple times on-chain (18 redundant decodes across verifier steps) while exposing redundant validator `@Param` values. +ZeroJ's current PlonK BLS12-381 Cardano profiles (`COMPRESSED_G1` / `COMPRESSED_G1_MPI`) follow snarkjs 0.7.6's Fiat-Shamir challenge derivation, which binds the VK and public inputs into `beta` and chains `gamma`, `alpha`, `zeta`, and `v` through the preceding challenge, but derives the multipoint opening challenge `u` solely from `(Wxi, Wxiw)` without chaining the prior transcript state (`plonk_verify.js:267-270`). On-chain, `PlonkBLS12381Lib` also calls `bls12_381_G1_uncompress` 19 times across its verifier helpers (decompressing the proof and VK G1 commitments repeatedly instead of once per point) and exposes redundant validator `@Param` values. -Separately, the current `xiMinusOmegaInv` check in the on-chain verifier excludes the degenerate evaluation point `xi == omega` (where `X - xi * omega` / `xi - omega` vanishes); any future simplification must preserve that exact exclusion or prove an equivalent guard. +Separately, the current `xiMinusOmegaInv` check in the v1 on-chain verifier (`PlonkBLS12381Lib`) excludes `zeta == omega` (where `zeta - omega == 0`), alongside `zeta != 1` and the public-input positions checked via supplied inverses, whereas the off-chain `PlonkBLS12381Verifier` checks `Z_H(zeta) = zeta^n - 1 != 0` directly (which implies `zeta != 1` and `zeta != omega` because `omega^n == 1`). Unifying the on-chain check onto `Z_H(zeta) != 0` and eliminating redundant decompressions is batched into the versioned v2 profile rather than mutating v1 in place, to avoid an unversioned v1 Plutus V3 script-hash change. Because changing the Fiat-Shamir transcript or `@Param` layout breaks interoperability with existing snarkjs 0.7.6 PlonK proofs and changes on-chain Plutus V3 script hashes, these improvements MUST be introduced as a versioned **v2 Cardano PlonK profile** while keeping the existing snarkjs-compatible v1 profile intact. @@ -37,14 +37,14 @@ Because changing the Fiat-Shamir transcript or `@Param` layout breaks interopera ## Proposed Security Invariants (v2 Profile) 1. **I1 (Fully chained, domain-separated Fiat-Shamir transcript):** - - Initialize a single running sponge/hash state with an explicit v2 domain separator tag (`"zeroj-plonk-bls12381-v2"`), circuit VK commitment digest (`qM, qL, qR, qO, qC, s1, s2, s3`, `power`, `k1`, `k2`, `nPublic`), and length-prefixed public inputs. + - Initialize a single running sponge/hash state with an explicit v2 domain separator tag (`"zeroj-plonk-bls12381-v2"`), circuit VK commitment digest (`qM, qL, qR, qO, qC, s1, s2, s3`, canonical 96-byte compressed G2 opening key `X2 = tau * G2`, `power`, `k1`, `k2`, `nPublic`), and length-prefixed public inputs. - Absorb each round's compressed G1 commitments and evaluations in strict protocol order and chain every prior challenge into the next challenge derivation (`beta`, `gamma`, `alpha`, `zeta`, `v`, and **`u`** — never hashing standalone subsets). 2. **I2 (Single decompression per G1 point on-chain):** - - Decompress each compressed 48-byte G1 commitment in the VK and proof **once** via CIP-0381 `bls12_381_G1_uncompress` (which enforces length, canonical encoding, curve, and subgroup) and reuse the decompressed `G1Element` handles throughout linear combination and pairing evaluation, eliminating 18 redundant decodes. + - Decompress each compressed 48-byte G1 commitment in the VK and proof **once** via CIP-0381 `bls12_381_G1_uncompress` (which enforces length, canonical encoding, curve, and subgroup) and reuse the decompressed `G1Element` handles throughout linear combination and pairing evaluation, eliminating repeated G1 decompressions across the 19 current call sites in `PlonkBLS12381Lib`. 3. **I3 (Degenerate challenge exclusion):** - - Preserve the explicit exclusion of `zeta == 0`, `zeta^n == 1` (`Z_H(zeta) == 0`), and `zeta == omega` (`xiMinusOmegaInv` check or direct equality rejection on `zeta` and `zeta * omega`), failing closed before division or inversion. + - Preserve the explicit fail-closed exclusion of `zeta == 0`, `zeta^n == 1` (`Z_H(zeta) == 0`), and `zeta == omega` (`zeta - omega == 0`) before any division or inversion. Because `omega` is a primitive `n`-th root of unity (`omega^n == 1`), rejecting `Z_H(zeta) == 0` subsumes `zeta == 1`, `zeta == omega`, and every other domain point `omega^i` (closing the v1 off-chain vs. on-chain gap where `PlonkBLS12381Verifier` checks `Z_H(zeta) != 0` while v1 `PlonkBLS12381Lib` checks only `zeta != 1`, `zeta != omega`, and public-input positions via inverses). 4. **I4 (Minimal, non-redundant `@Param` surface):** - - Audit and remove redundant derived `@Param` fields (e.g. values derivable cheaply from `power`/`omega` or folded into the precomputed VK digest) while documenting exact script-hash impact and binding all VK commitments into the v2 transcript. + - Audit and remove redundant derived `@Param` fields (e.g. values derivable cheaply from `power`/`omega` or folded into the precomputed VK digest) while documenting exact script-hash impact and binding all VK commitments (including `X2`) into the v2 transcript. 5. **I5 (Strict v1/v2 profile separation):** - Legacy snarkjs 0.7.6 v1 profiles remain unchanged for backward compatibility and cross-tool interop; v2 uses a distinct `proofFormat` identifier (`"zeroj-plonk-cardano-v2"`) so v1 and v2 proofs can never be confused. @@ -53,13 +53,13 @@ Because changing the Fiat-Shamir transcript or `@Param` layout breaks interopera ## Decision & Alternatives Considered - **Separate v2 profile vs. mutating v1 in place:** Mutating v1 would silently break snarkjs 0.7.6 interop and invalidate existing on-chain script hashes. Introducing a distinct v2 profile preserves v1 interop while allowing Cardano-native deployments to adopt strong Fiat-Shamir chaining and lower Plutus V3 CPU cost. -- **Keep `xiMinusOmegaInv` vs. removing it:** Removing the check without an equivalent `zeta != omega` guard would leave an unchecked zero denominator; v2 retains an explicit guard against `zeta in {0, 1, omega}` and `Z_H(zeta) == 0`. +- **Keep `xiMinusOmegaInv` vs. replacing with `Z_H(zeta) != 0`:** Removing `xiMinusOmegaInv` without an equivalent `zeta != omega` guard would leave an unchecked zero denominator; v2 explicitly enforces `zeta != 0` and `Z_H(zeta) != 0` (which implies `zeta != omega` and rejects every domain root). --- ## Implementation Milestones (Future Work) -- **M1:** Specify exact byte-level v2 transcript schedule and KAT vectors (independent reference script + pure-Java prover/verifier). +- **M1:** Specify exact byte-level v2 transcript schedule and independent KAT vectors (reference script + pure-Java prover/verifier), including VK-binding vectors (covering `X2`) and challenge-boundary vectors (`zeta in {0, 1, omega}` and `Z_H(zeta) == 0`). - **M2:** Implement `TranscriptEncoding.CARDANO_V2` in `PlonKProverBLS381` and `PlonkBLS12381Verifier` with negative transcript-tampering and degenerate-challenge tests. - **M3:** Implement single-decode v2 Plutus V3 validator in `zeroj-onchain-julc`, benchmark CPU/memory reduction against v1 in Julc VM and Yaci DevKit, and audit minimal `@Param` set. - **M4:** External cryptographic review before any non-experimental promotion. @@ -69,5 +69,5 @@ Because changing the Fiat-Shamir transcript or `@Param` layout breaks interopera ## Verification & Audit Gates - Independent Python/Rust reference transcript KATs matching Java and Plutus V3 byte-for-byte. -- Negative tests for challenge grinding, missing VK binding, `u` tampering, `zeta == 1`, `zeta == omega`, and cross-profile (`v1` vs `v2`) replay. +- Negative tests for challenge grinding, missing VK or `X2` binding, `u` tampering, `zeta in {0, 1, omega}`, `Z_H(zeta) == 0`, and cross-profile (`v1` vs `v2`) replay. - Mandatory external cryptographic audit before promotion to production-safe status. diff --git a/zeroj-circuit-annotation-api/src/test/java/org/zeroj/circuit/annotation/ZkSymbolicTypesTest.java b/zeroj-circuit-annotation-api/src/test/java/org/zeroj/circuit/annotation/ZkSymbolicTypesTest.java index e84be41d..70d2e03c 100644 --- a/zeroj-circuit-annotation-api/src/test/java/org/zeroj/circuit/annotation/ZkSymbolicTypesTest.java +++ b/zeroj-circuit-annotation-api/src/test/java/org/zeroj/circuit/annotation/ZkSymbolicTypesTest.java @@ -6,6 +6,7 @@ import org.zeroj.api.VerificationKeyRef; import org.zeroj.circuit.CircuitBuilder; import org.zeroj.circuit.Signal; +import org.zeroj.circuit.r1cs.R1CSConstraintSystem; import org.junit.jupiter.api.Test; import java.math.BigInteger; @@ -14,8 +15,10 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; class ZkSymbolicTypesTest { @@ -544,14 +547,12 @@ void contextConstantsContainerSingleBuilderAndBls12381AdversarialR1cs() { "bit_1", List.of(BigInteger.ZERO)); BigInteger[] witness = circuit.calculateWitness(validInputs, CurveId.BLS12_381); var r1cs = circuit.compileR1CS(CurveId.BLS12_381); - org.junit.jupiter.api.Assertions.assertTrue( - satisfiesR1cs(r1cs, witness), "Honest BLS12-381 witness must satisfy R1CS"); + assertTrue(satisfiesR1cs(r1cs, witness), "Honest BLS12-381 witness must satisfy R1CS"); // Adversarial R1CS witness tampering: flip one witness wire and verify R1CS rejects it. BigInteger[] tampered = witness.clone(); tampered[2] = BigInteger.valueOf(43); // pub byte_1 != sec sbyte_1 - org.junit.jupiter.api.Assertions.assertFalse( - satisfiesR1cs(r1cs, tampered), "Tampered BLS12-381 witness must fail R1CS"); + assertFalse(satisfiesR1cs(r1cs, tampered), "Tampered BLS12-381 witness must fail R1CS"); // Container constructors must reject elements from different builders. ZkUInt[] foreignByte = new ZkUInt[1]; @@ -573,7 +574,7 @@ void contextConstantsContainerSingleBuilderAndBls12381AdversarialR1cs() { }); } - private static boolean satisfiesR1cs(org.zeroj.circuit.r1cs.R1CSConstraintSystem r1cs, BigInteger[] witness) { + private static boolean satisfiesR1cs(R1CSConstraintSystem r1cs, BigInteger[] witness) { BigInteger p = r1cs.fieldConfig().prime(); for (var c : r1cs.constraints()) { BigInteger a = BigInteger.ZERO; diff --git a/zeroj-circuit-annotation-processor/src/test/java/org/zeroj/circuit/annotation/processor/CircuitAnnotationProcessorTest.java b/zeroj-circuit-annotation-processor/src/test/java/org/zeroj/circuit/annotation/processor/CircuitAnnotationProcessorTest.java index 8cf8e2bc..e96c3020 100644 --- a/zeroj-circuit-annotation-processor/src/test/java/org/zeroj/circuit/annotation/processor/CircuitAnnotationProcessorTest.java +++ b/zeroj-circuit-annotation-processor/src/test/java/org/zeroj/circuit/annotation/processor/CircuitAnnotationProcessorTest.java @@ -22,6 +22,7 @@ import javax.tools.SimpleJavaFileObject; import javax.tools.StandardJavaFileManager; import javax.tools.ToolProvider; +import java.lang.reflect.InvocationTargetException; import java.math.BigInteger; import java.net.URI; import java.net.URLClassLoader; @@ -1409,7 +1410,7 @@ public SinglePassAndBoxed( """); assertTrue(singlePass.success(), singlePass.diagnosticsText()); Class gen = singlePass.load("test.SinglePassAndBoxedCircuit"); - var nullEx = assertThrows(java.lang.reflect.InvocationTargetException.class, + var nullEx = assertThrows(InvocationTargetException.class, () -> gen.getMethod("build", Integer.class, String.class).invoke(null, null, "x")); assertTrue(nullEx.getCause() instanceof IllegalArgumentException); assertTrue(nullEx.getCause().getMessage().contains("must not be null")); @@ -1424,7 +1425,7 @@ public SinglePassAndBoxed( CircuitBuilder fakeSameName = CircuitBuilder.create(schema.name()) .publicVar("wrong_pub") .define(api -> {}); - var mismatchEx = assertThrows(java.lang.reflect.InvocationTargetException.class, + var mismatchEx = assertThrows(InvocationTargetException.class, () -> gen.getMethod("calculateWitness", CircuitBuilder.class, inputsObj.getClass(), CurveId.class) .invoke(null, fakeSameName, inputsObj, CurveId.BLS12_381)); assertTrue(mismatchEx.getCause() instanceof IllegalArgumentException); diff --git a/zeroj-circuit-dsl/src/main/java/org/zeroj/circuit/CircuitAPIImpl.java b/zeroj-circuit-dsl/src/main/java/org/zeroj/circuit/CircuitAPIImpl.java index fcc1472a..d51ed2d4 100644 --- a/zeroj-circuit-dsl/src/main/java/org/zeroj/circuit/CircuitAPIImpl.java +++ b/zeroj-circuit-dsl/src/main/java/org/zeroj/circuit/CircuitAPIImpl.java @@ -245,11 +245,19 @@ public Variable[] hintN(Gate.HintKind kind, BigInteger[] params, int numOutputs, if (params.length != 4) { throw new IllegalArgumentException("MUL_MOD_REDUCE requires 4 params [modulus, radixBits, numLimbsAB, numLimbsQ]"); } - int radixBits = params[1].intValueExact(); - int nAB = params[2].intValueExact(); - int nQ = params[3].intValueExact(); - if (params[0].signum() <= 0 || radixBits <= 0 || nAB <= 0 || nQ <= 0) { - throw new IllegalArgumentException("MUL_MOD_REDUCE params must be positive"); + int radixBits; + int nAB; + int nQ; + try { + radixBits = params[1].intValueExact(); + nAB = params[2].intValueExact(); + nQ = params[3].intValueExact(); + } catch (ArithmeticException e) { + throw new IllegalArgumentException("MUL_MOD_REDUCE limb params must fit in a 32-bit int", e); + } + if (params[0].signum() <= 0 || radixBits <= 0 || radixBits > MAX_SAFE_BITS || nAB <= 0 || nQ <= 0) { + throw new IllegalArgumentException( + "MUL_MOD_REDUCE params must be positive and radixBits <= " + MAX_SAFE_BITS); } if (inputs.length != 2 * nAB || numOutputs != nQ + nAB) { throw new IllegalArgumentException("MUL_MOD_REDUCE input/output counts do not match limb params"); @@ -259,10 +267,17 @@ public Variable[] hintN(Gate.HintKind kind, BigInteger[] params, int numOutputs, if (params.length != 3) { throw new IllegalArgumentException("INV_MOD requires 3 params [modulus, radixBits, numLimbs]"); } - int radixBits = params[1].intValueExact(); - int numLimbs = params[2].intValueExact(); - if (params[0].signum() <= 0 || radixBits <= 0 || numLimbs <= 0) { - throw new IllegalArgumentException("INV_MOD params must be positive"); + int radixBits; + int numLimbs; + try { + radixBits = params[1].intValueExact(); + numLimbs = params[2].intValueExact(); + } catch (ArithmeticException e) { + throw new IllegalArgumentException("INV_MOD limb params must fit in a 32-bit int", e); + } + if (params[0].signum() <= 0 || radixBits <= 0 || radixBits > MAX_SAFE_BITS || numLimbs <= 0) { + throw new IllegalArgumentException( + "INV_MOD params must be positive and radixBits <= " + MAX_SAFE_BITS); } if (inputs.length != numLimbs || numOutputs != numLimbs) { throw new IllegalArgumentException("INV_MOD input/output counts do not match numLimbs"); diff --git a/zeroj-circuit-lib/src/test/java/org/zeroj/circuit/lib/field/Fe25519HintTest.java b/zeroj-circuit-lib/src/test/java/org/zeroj/circuit/lib/field/Fe25519HintTest.java index 786d3028..6ea2f666 100644 --- a/zeroj-circuit-lib/src/test/java/org/zeroj/circuit/lib/field/Fe25519HintTest.java +++ b/zeroj-circuit-lib/src/test/java/org/zeroj/circuit/lib/field/Fe25519HintTest.java @@ -103,6 +103,52 @@ void constraintCount_mulHint_reported() { assertTrue(c > 0 && c < 8051, "mulHint should be cheaper than deterministic mul: " + c); } + @Test + void configureHintsOverridesSingleCircuitWithoutMutatingGlobalDefault() { + BigInteger a = randFe(); + BigInteger b = randFe(); + BigInteger expected = a.multiply(b).mod(P); + BigInteger[] al = Fe25519.toLimbValues(a); + BigInteger[] bl = Fe25519.toLimbValues(b); + BigInteger[] el = Fe25519.toLimbValues(expected); + + var hintCircuit = CircuitBuilder.create("fe25519-per-circuit-hint"); + var defaultCircuit = CircuitBuilder.create("fe25519-default-det"); + for (int i = 0; i < 5; i++) { + hintCircuit.secretVar("a" + i).secretVar("b" + i).publicVar("e" + i); + defaultCircuit.secretVar("a" + i).secretVar("b" + i).publicVar("e" + i); + } + hintCircuit.define(api -> { + Fe25519.configureHints(api, new Fe25519.HintConfig(true, true)); + Variable[] av = new Variable[5], bv = new Variable[5]; + for (int i = 0; i < 5; i++) { av[i] = api.var("a" + i); bv[i] = api.var("b" + i); } + Variable[] rl = Fe25519.ofLimbsTrusted(api, av).mul(Fe25519.ofLimbsTrusted(api, bv)).canonical().limbs(); + for (int i = 0; i < 5; i++) api.assertEqual(rl[i], api.var("e" + i)); + }); + defaultCircuit.define(api -> { + Variable[] av = new Variable[5], bv = new Variable[5]; + for (int i = 0; i < 5; i++) { av[i] = api.var("a" + i); bv[i] = api.var("b" + i); } + Variable[] rl = Fe25519.ofLimbsTrusted(api, av).mul(Fe25519.ofLimbsTrusted(api, bv)).canonical().limbs(); + for (int i = 0; i < 5; i++) api.assertEqual(rl[i], api.var("e" + i)); + }); + + int hintConstraints = hintCircuit.compileR1CS(CurveId.BLS12_381).numConstraints(); + int defaultConstraints = defaultCircuit.compileR1CS(CurveId.BLS12_381).numConstraints(); + assertTrue(hintConstraints < defaultConstraints, + "Per-circuit hint config should route mul() through mulHint: hint=" + + hintConstraints + ", default=" + defaultConstraints); + assertFalse(Fe25519.hintConfig(null).useHintMul(), "Global default must remain unchanged"); + + Map> inputs = new HashMap<>(); + for (int i = 0; i < 5; i++) { + inputs.put("a" + i, List.of(al[i])); + inputs.put("b" + i, List.of(bl[i])); + inputs.put("e" + i, List.of(el[i])); + } + assertDoesNotThrow(() -> hintCircuit.calculateWitness(inputs, CurveId.BLS12_381)); + assertDoesNotThrow(() -> defaultCircuit.calculateWitness(inputs, CurveId.BLS12_381)); + } + // ------------------------------------------------------------------ // 2. Soundness: adversarial (q, r) fed to mulFromQR must be REJECTED // ------------------------------------------------------------------ diff --git a/zeroj-circuit-lib/src/test/java/org/zeroj/circuit/lib/jubjub/PedersenTest.java b/zeroj-circuit-lib/src/test/java/org/zeroj/circuit/lib/jubjub/PedersenTest.java index 40f72cbe..ac0b0760 100644 --- a/zeroj-circuit-lib/src/test/java/org/zeroj/circuit/lib/jubjub/PedersenTest.java +++ b/zeroj-circuit-lib/src/test/java/org/zeroj/circuit/lib/jubjub/PedersenTest.java @@ -271,30 +271,46 @@ void t5_firstMds_matchesSage() { } @Test - @DisplayName("InCircuitPedersen and ZkPedersen reject value and blinding sharing the same wire") + @DisplayName("InCircuitPedersen, InCircuitPedersenVector, and ZkPedersen reject value and blinding sharing the same wire") void pedersenRejectsSharedValueAndBlindingWire() { - assertThrows(IllegalArgumentException.class, () -> CircuitBuilder.create("pedersen-shared-var") + var ex1 = assertThrows(IllegalArgumentException.class, () -> CircuitBuilder.create("pedersen-shared-var") .secretVar("x") .define(api -> { var x = api.var("x"); InCircuitPedersen.commit(api, x, 64, x); })); + assertTrue(ex1.getMessage().contains("blinding"), "unexpected message: " + ex1.getMessage()); - assertThrows(IllegalArgumentException.class, () -> CircuitBuilder.create("pedersen-shared-decomp") + var ex2 = assertThrows(IllegalArgumentException.class, () -> CircuitBuilder.create("pedersen-shared-decomp") .secretVar("x") .define(api -> { var x = api.var("x"); - var d1 = api.decompose(x, 250); - var d2 = api.decompose(x, 250); + var d1 = api.decompose(x, InCircuitPedersen.BLINDING_BITS); + var d2 = api.decompose(x, InCircuitPedersen.BLINDING_BITS); InCircuitPedersen.commit(api, d1, d2); })); + assertTrue(ex2.getMessage().contains("both the value and the blinding"), + "expected same-wire rejection, got: " + ex2.getMessage()); - assertThrows(IllegalArgumentException.class, () -> CircuitBuilder.create("pedersen-shared-zk") + var ex3 = assertThrows(IllegalArgumentException.class, () -> CircuitBuilder.create("pedersen-shared-zk") .secretVar("x") .defineSignals(c -> { var zk = new ZkContext(c); - var x = ZkUInt.secret(c, "x", 250); + var x = ZkUInt.secret(c, "x", InCircuitPedersen.BLINDING_BITS); ZkPedersen.commit(zk, x, x); })); + assertTrue(ex3.getMessage().contains("both the value and the blinding"), + "expected same-wire rejection, got: " + ex3.getMessage()); + + var ex4 = assertThrows(IllegalArgumentException.class, () -> CircuitBuilder.create("pedersen-vec-shared") + .secretVar("x") + .define(api -> { + var x = api.var("x"); + var d1 = api.decompose(x, 64); + var d2 = api.decompose(x, InCircuitPedersen.BLINDING_BITS); + InCircuitPedersenVector.commit(api, List.of(d1), d2); + })); + assertTrue(ex4.getMessage().contains("both value[0] and the blinding"), + "expected same-wire rejection, got: " + ex4.getMessage()); } } diff --git a/zeroj-crypto/src/main/java/org/zeroj/crypto/groth16/Groth16Pipeline.java b/zeroj-crypto/src/main/java/org/zeroj/crypto/groth16/Groth16Pipeline.java index 5e95032b..4d443be7 100644 --- a/zeroj-crypto/src/main/java/org/zeroj/crypto/groth16/Groth16Pipeline.java +++ b/zeroj-crypto/src/main/java/org/zeroj/crypto/groth16/Groth16Pipeline.java @@ -66,8 +66,9 @@ public static final class Compiled { public Compiled(R1CSFlat flat, int numConstraints, int numWires, int numPublic) { if (flat == null) throw new NullPointerException("flat"); - if (numConstraints < 1 || numConstraints > (1 << 30)) { - throw new IllegalArgumentException("numConstraints must be in [1, 2^30]"); + if (numConstraints < 1 || numConstraints > Groth16SetupBLS381.MAX_CONSTRAINTS) { + throw new IllegalArgumentException( + "numConstraints must be in [1, " + Groth16SetupBLS381.MAX_CONSTRAINTS + "]"); } if (numWires < 1) throw new IllegalArgumentException("numWires must be >= 1"); if (numPublic < 0 || numPublic >= numWires) { @@ -146,8 +147,9 @@ public static Dims parseFingerprint(String fp) { public record Dims(int numConstraints, int numWires, int numPublic) { /** FFT domain: next power of two ≥ constraint count (min 4), as the setup computes it. */ public int domain() { - if (numConstraints < 1 || numConstraints > (1 << 30)) { - throw new IllegalArgumentException("numConstraints must be in [1, 2^30]"); + if (numConstraints < 1 || numConstraints > Groth16SetupBLS381.MAX_CONSTRAINTS) { + throw new IllegalArgumentException( + "numConstraints must be in [1, " + Groth16SetupBLS381.MAX_CONSTRAINTS + "]"); } int d = Integer.highestOneBit(numConstraints); if (d < numConstraints) d <<= 1; @@ -197,6 +199,7 @@ public static Groth16SetupBLS381.SetupResult setup(Compiled cc, BigInteger tau, // the failure happens before the r1cs.bin cache or any store file exists; setupToStore // re-checks it at its own ingress. R1CSValidation.requirePublicWiresConstrained(cc.flat(), cc.numPublic(), MontFr381.modulus()); + Groth16SetupBLS381.validateSetupParameters(cc.numConstraints(), tau); Files.createDirectories(dir); Path cache = dir.resolve(R1CS_CACHE); try { diff --git a/zeroj-crypto/src/main/java/org/zeroj/crypto/groth16/Groth16PkStore.java b/zeroj-crypto/src/main/java/org/zeroj/crypto/groth16/Groth16PkStore.java index d54f63c1..f05448db 100644 --- a/zeroj-crypto/src/main/java/org/zeroj/crypto/groth16/Groth16PkStore.java +++ b/zeroj-crypto/src/main/java/org/zeroj/crypto/groth16/Groth16PkStore.java @@ -1,6 +1,9 @@ package org.zeroj.crypto.groth16; +import org.zeroj.bls12381.ec.G1Point; +import org.zeroj.bls12381.ec.JacobianG1BLS381; import org.zeroj.bls12381.ec.JacobianG1BLS381.AffineG1; +import org.zeroj.bls12381.ec.JacobianG2BLS381; import org.zeroj.bls12381.ec.JacobianG2BLS381.AffineG2; import org.zeroj.bls12381.field.Fp; import org.zeroj.bls12381.field.MontFp2_381; @@ -300,6 +303,9 @@ private static AffineG1 requireNonInfinityG1(AffineG1 p, String label) throws IO if (p == null || p.isInfinity() || !p.isOnCurve()) { throw new IOException("Groth16 " + label + " must be a non-infinity point on BLS12-381 G1"); } + if (!JacobianG1BLS381.fromAffine(p.x(), p.y()).scalarMul(G1Point.R).isInfinity()) { + throw new IOException("Groth16 " + label + " is not in the BLS12-381 G1 prime-order subgroup"); + } return p; } @@ -307,6 +313,9 @@ private static AffineG2 requireNonInfinityG2(AffineG2 p, String label) throws IO if (p == null || p.isInfinity() || !p.isOnCurve()) { throw new IOException("Groth16 " + label + " must be a non-infinity point on BLS12-381 G2"); } + if (!JacobianG2BLS381.fromAffine(p.x(), p.y()).scalarMul(G1Point.R).isInfinity()) { + throw new IOException("Groth16 " + label + " is not in the BLS12-381 G2 prime-order subgroup"); + } return p; } diff --git a/zeroj-crypto/src/main/java/org/zeroj/crypto/groth16/Groth16ProverBLS381.java b/zeroj-crypto/src/main/java/org/zeroj/crypto/groth16/Groth16ProverBLS381.java index b4810705..66f7514c 100644 --- a/zeroj-crypto/src/main/java/org/zeroj/crypto/groth16/Groth16ProverBLS381.java +++ b/zeroj-crypto/src/main/java/org/zeroj/crypto/groth16/Groth16ProverBLS381.java @@ -236,6 +236,9 @@ private static ProofPoints computeProofPoints( Groth16ProvingKeyBLS381 pk, G1Readers readers, ProverBackend backend, FlatScalars witness, FlatScalars hCoeffs, BigInteger r, BigInteger s) { + if (readers == null) { + throw new IllegalArgumentException("Proving key readers must not be null"); + } G2AffineReader b2 = readers.b2() != null ? readers.b2() : new G2AffineReader.HeapG2Reader(pk.pointsB2()); requireKeyDimensions(pk, readers, b2, witness, hCoeffs); diff --git a/zeroj-crypto/src/main/java/org/zeroj/crypto/groth16/SparsePointFile.java b/zeroj-crypto/src/main/java/org/zeroj/crypto/groth16/SparsePointFile.java index d683556b..bbd80d29 100644 --- a/zeroj-crypto/src/main/java/org/zeroj/crypto/groth16/SparsePointFile.java +++ b/zeroj-crypto/src/main/java/org/zeroj/crypto/groth16/SparsePointFile.java @@ -120,6 +120,36 @@ public Index(MemorySegment seg) { throw new IllegalArgumentException( "ZJSP segment size mismatch: expected " + expectedSize + ", got " + seg.byteSize()); } + validateBitmapAndRanks(words); + } + + private void validateBitmapAndRanks(long words) { + int remBits = (int) (count & 63L); + long running = 0L; + long block = 0L; + for (long w = 0L; w < words; w++) { + if ((w & 7L) == 0L) { + long storedRank = Integer.toUnsignedLong(seg.get(LE_INT, rankOff + block * 4L)); + if (storedRank != running) { + throw new IllegalArgumentException( + "ZJSP rank mismatch at block " + block + ": stored " + storedRank + + " != computed " + running); + } + block++; + } + long word = seg.get(LE_LONG, 32L + w * 8L); + if (w == words - 1L && remBits != 0) { + long trailingMask = ~((1L << remBits) - 1L); + if ((word & trailingMask) != 0L) { + throw new IllegalArgumentException("ZJSP bitmap has set bits beyond logical count"); + } + } + running += Long.bitCount(word); + } + if (running != nnz) { + throw new IllegalArgumentException( + "ZJSP bitmap popcount (" + running + ") does not match header nnz (" + nnz + ")"); + } } public int count() { return (int) count; } diff --git a/zeroj-crypto/src/main/java/org/zeroj/crypto/setup/Groth16SetupBLS381.java b/zeroj-crypto/src/main/java/org/zeroj/crypto/setup/Groth16SetupBLS381.java index ba49e7d6..d65c7c51 100644 --- a/zeroj-crypto/src/main/java/org/zeroj/crypto/setup/Groth16SetupBLS381.java +++ b/zeroj-crypto/src/main/java/org/zeroj/crypto/setup/Groth16SetupBLS381.java @@ -88,7 +88,7 @@ public final class Groth16SetupBLS381 { private Groth16SetupBLS381() {} private static final BigInteger FR = MontFr381.modulus(); - private static final int MAX_CONSTRAINTS = 1 << 29; + public static final int MAX_CONSTRAINTS = 1 << 29; /** * Generate a Groth16 proving key from R1CS constraints and known tau. @@ -307,6 +307,29 @@ static BigInteger[] publicQueryScalars(BigInteger[] us, BigInteger[] vs, BigInte * cancelled its public-query combination, an event of probability on the order of * {@code N/r}. The key is not produced; a re-run with fresh randomness resolves it. */ + private static IllegalStateException zeroPublicQuery(int s, int numPublic) { + return new IllegalStateException("Groth16 setup aborted: the public-query scalar for public wire " + s + + " (of " + numPublic + ") is zero, so IC[" + s + "] would be the point at infinity, which every" + + " verifier profile rejects (ADR-0045). The relation binds the wire; the sampled setup" + + " randomness cancelled its combination (probability ~N/r). Re-run setup with fresh randomness."); + } + + /** + * Validate Groth16 setup constraint count and {@code tau} before creating directories or + * allocating key buffers. + */ + public static void validateSetupParameters(int nConstraints, BigInteger tau) { + if (nConstraints < 1 || nConstraints > MAX_CONSTRAINTS) { + throw new IllegalArgumentException("nConstraints (" + nConstraints + + ") must be in [1, " + MAX_CONSTRAINTS + "]"); + } + int domainSize = Integer.highestOneBit(nConstraints); + if (domainSize < nConstraints) domainSize <<= 1; + if (domainSize < 4) domainSize = 4; + BigInteger tauVal = requireValidSetupScalar(tau, "tau"); + requireTauOutsideDomain(tauVal, domainSize); + } + private static BigInteger requireValidSetupScalar(BigInteger value, String name) { if (value == null) { throw new IllegalArgumentException(name + " must not be null"); @@ -324,13 +347,6 @@ private static void requireTauOutsideDomain(BigInteger tau, int domainSize) { } } - private static IllegalStateException zeroPublicQuery(int s, int numPublic) { - return new IllegalStateException("Groth16 setup aborted: the public-query scalar for public wire " + s - + " (of " + numPublic + ") is zero, so IC[" + s + "] would be the point at infinity, which every" - + " verifier profile rejects (ADR-0045). The relation binds the wire; the sampled setup" - + " randomness cancelled its combination (probability ~N/r). Re-run setup with fresh randomness."); - } - /** * Setup result containing both proving key and verification key components. * diff --git a/zeroj-crypto/src/main/java/org/zeroj/crypto/setup/SetupCacheIO.java b/zeroj-crypto/src/main/java/org/zeroj/crypto/setup/SetupCacheIO.java index b5525f9b..d0bc3ed6 100644 --- a/zeroj-crypto/src/main/java/org/zeroj/crypto/setup/SetupCacheIO.java +++ b/zeroj-crypto/src/main/java/org/zeroj/crypto/setup/SetupCacheIO.java @@ -317,13 +317,15 @@ static void validateG2Array(AffineG2[] points, boolean allowInfinity, String lab } static void validateBls12381Srs(AffineG1[] tauG1, AffineG2[] tauG2, int power) throws IOException { - if (power < 1 || power > 28) { + if (power < 1 || power > 32) { throw new IOException("Invalid BLS12-381 SRS power: " + power); } - long minG1 = (1L << power) + 1L; - if (tauG1.length < minG1) { + if (tauG1.length < 2) { + throw new IOException("BLS12-381 SRS must contain at least two G1 powers"); + } + if (power <= 29 && tauG1.length > (2L << power) + 1L) { throw new IOException("BLS12-381 SRS G1 power count " + tauG1.length - + " is smaller than required minimum " + minG1 + " for power " + power); + + " exceeds ceremony power " + power); } if (tauG2.length < 2) { throw new IOException("BLS12-381 SRS must contain at least two G2 powers"); diff --git a/zeroj-crypto/src/test/java/org/zeroj/crypto/groth16/Groth16PkStoreTest.java b/zeroj-crypto/src/test/java/org/zeroj/crypto/groth16/Groth16PkStoreTest.java index e3c28652..c79b2c31 100644 --- a/zeroj-crypto/src/test/java/org/zeroj/crypto/groth16/Groth16PkStoreTest.java +++ b/zeroj-crypto/src/test/java/org/zeroj/crypto/groth16/Groth16PkStoreTest.java @@ -2,6 +2,10 @@ import org.zeroj.api.R1CSConstraint; import org.zeroj.api.TrustedSetupPolicy; +import org.zeroj.bls12381.ec.G1Point; +import org.zeroj.bls12381.ec.G2Point; +import org.zeroj.bls12381.field.Fp; +import org.zeroj.bls12381.field.Fp2; import org.zeroj.bls12381.field.MontFr381; import org.zeroj.crypto.setup.Groth16SetupBLS381; import org.zeroj.crypto.setup.PowersOfTauBLS381; @@ -9,9 +13,16 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; +import java.io.IOException; +import java.lang.foreign.Arena; +import java.lang.foreign.MemorySegment; +import java.lang.foreign.ValueLayout; import java.math.BigInteger; +import java.nio.ByteOrder; +import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; +import java.util.Arrays; import java.util.List; import java.util.Map; @@ -75,4 +86,128 @@ void saveLoad_roundTrips_proofBitIdentical(@TempDir Path dir) throws Exception { assertEquals(sr.ic()[0].x().toBigInteger(), loaded.ic()[0].x().toBigInteger(), "ic[0].x"); } } + + @Test + void loadRejectsOffSubgroupOffCurveInfinityAndNonCanonicalAuxPoints(@TempDir Path dir) throws Exception { + var cons = chain(8); + BigInteger tau = PowersOfTauBLS381.generate(5).tauScalar(); + var sr = Groth16SetupBLS381.setup(cons, 10, 1, tau); + Groth16PkStore.save(sr, dir); + Path auxPath = dir.resolve("aux.bin"); + byte[] validAux = Files.readAllBytes(auxPath); + + // Positive control: untouched store loads cleanly. + try (var ok = Groth16PkStore.load(dir)) { + assertEquals(sr.ic().length, ok.ic().length); + } + + // 1. G1 off-subgroup torsion point (0, 2) in alphaG1 (offset 0). + G1Point g1Torsion = new G1Point(Fp.ZERO, Fp.of(2)); + assertTrue(g1Torsion.isOnCurve()); + assertFalse(g1Torsion.isInSubgroup()); + byte[] g1SubgroupBad = validAux.clone(); + writeBe48(g1SubgroupBad, 0, BigInteger.ZERO); + writeBe48(g1SubgroupBad, 48, BigInteger.TWO); + Files.write(auxPath, g1SubgroupBad); + assertThrows(IOException.class, () -> Groth16PkStore.load(dir)); + + // 2. G2 off-subgroup torsion point in gammaG2 (offset 672 = 3*96 + 2*192). + Fp2 x2 = Fp2.of(Fp.ZERO, Fp.ONE); + Fp2 y2 = x2.square().mul(x2).add(Fp2.of(Fp.of(4), Fp.of(4))).sqrt().orElseThrow(); + G2Point g2Torsion = new G2Point(x2, y2); + assertTrue(g2Torsion.isOnCurve()); + assertFalse(g2Torsion.isInSubgroup()); + byte[] g2SubgroupBad = validAux.clone(); + writeBe48(g2SubgroupBad, 672, x2.c0().value()); + writeBe48(g2SubgroupBad, 720, x2.c1().value()); + writeBe48(g2SubgroupBad, 768, y2.c0().value()); + writeBe48(g2SubgroupBad, 816, y2.c1().value()); + Files.write(auxPath, g2SubgroupBad); + assertThrows(IOException.class, () -> Groth16PkStore.load(dir)); + + // 3. Infinity IC[0] (96 zero bytes at offset 864 = 3*96 + 3*192). + byte[] infIc = validAux.clone(); + Arrays.fill(infIc, 864, 960, (byte) 0); + Files.write(auxPath, infIc); + assertThrows(IOException.class, () -> Groth16PkStore.load(dir)); + + // 4. Off-curve G1 (1, 1) in betaG1 (offset 96). + byte[] offCurve = validAux.clone(); + writeBe48(offCurve, 96, BigInteger.ONE); + writeBe48(offCurve, 144, BigInteger.ONE); + Files.write(auxPath, offCurve); + assertThrows(IOException.class, () -> Groth16PkStore.load(dir)); + + // 5. Non-canonical Fp coordinate (x + p) in alphaG1 (offset 0). + byte[] nonCanonical = validAux.clone(); + BigInteger canonicalX = new BigInteger(1, Arrays.copyOfRange(validAux, 0, 48)); + writeBe48(nonCanonical, 0, canonicalX.add(Fp.P)); + Files.write(auxPath, nonCanonical); + assertThrows(IOException.class, () -> Groth16PkStore.load(dir)); + } + + @Test + void sparsePointFileIndexValidatesMultiBlockBitmapAndRanks() { + int count = 1200; // 3 blocks (512 + 512 + 176), 19 bitmap words with 48 trailing bits in last word + int words = (count + 63) >>> 6; + long[] bitmap = new long[words]; + long nnz = 0; + for (int i = 0; i < count; i += 3) { + bitmap[i >>> 6] |= 1L << (i & 63); + nnz++; + } + long fileSize = SparsePointFile.fileSize(count, nnz, 96); + long rankOff = 32L + (long) words * 8L; + var leInt = ValueLayout.JAVA_INT_UNALIGNED.withOrder(ByteOrder.LITTLE_ENDIAN); + var leLong = ValueLayout.JAVA_LONG_UNALIGNED.withOrder(ByteOrder.LITTLE_ENDIAN); + + try (Arena arena = Arena.ofConfined()) { + MemorySegment valid = arena.allocate(fileSize); + SparsePointFile.writeIndex(valid, bitmap, count, nnz, 96); + + // Positive control: valid multi-block index passes validation and returns exact ranks. + var idx = new SparsePointFile.Index(valid); + assertEquals(count, idx.count()); + long expectedRank = 0; + for (int i = 0; i < count; i++) { + boolean present = (i % 3) == 0; + assertEquals(present, idx.present(i), "present(" + i + ")"); + if (present) { + assertEquals(expectedRank++, idx.rank(i), "rank(" + i + ")"); + } + } + + // Negative 1: same-length tampered block rank (block 1 rank incremented by 1). + MemorySegment badRank = arena.allocate(fileSize); + MemorySegment.copy(valid, 0, badRank, 0, fileSize); + badRank.set(leInt, rankOff + 4L, badRank.get(leInt, rankOff + 4L) + 1); + assertThrows(IllegalArgumentException.class, () -> new SparsePointFile.Index(badRank)); + + // Negative 2: same-length tampered bitmap bit (popcount != header nnz). + MemorySegment badPopcount = arena.allocate(fileSize); + MemorySegment.copy(valid, 0, badPopcount, 0, fileSize); + long lastWordOff = 32L + (long) (words - 1) * 8L; + badPopcount.set(leLong, lastWordOff, badPopcount.get(leLong, lastWordOff) ^ 1L); + assertThrows(IllegalArgumentException.class, () -> new SparsePointFile.Index(badPopcount)); + + // Negative 3: trailing bitmap bit >= count set while clearing an in-range bit in the same + // final word so total popcount still equals nnz and all earlier block ranks still match. + MemorySegment badTrailingBit = arena.allocate(fileSize); + MemorySegment.copy(valid, 0, badTrailingBit, 0, fileSize); + long lastWord = badTrailingBit.get(leLong, lastWordOff); + long clearedBit = Long.lowestOneBit(lastWord); + assertTrue(clearedBit != 0L, "final word must have at least one set in-range bit"); + long trailingBit = 1L << (count & 63); + badTrailingBit.set(leLong, lastWordOff, (lastWord ^ clearedBit) | trailingBit); + assertThrows(IllegalArgumentException.class, () -> new SparsePointFile.Index(badTrailingBit)); + } + } + + private static void writeBe48(byte[] dst, int offset, BigInteger value) { + byte[] raw = value.toByteArray(); + Arrays.fill(dst, offset, offset + 48, (byte) 0); + int srcPos = raw.length > 48 ? raw.length - 48 : 0; + int len = Math.min(raw.length, 48); + System.arraycopy(raw, srcPos, dst, offset + 48 - len, len); + } } diff --git a/zeroj-crypto/src/test/java/org/zeroj/crypto/setup/SetupCacheTest.java b/zeroj-crypto/src/test/java/org/zeroj/crypto/setup/SetupCacheTest.java index 231984e4..ab8801ea 100644 --- a/zeroj-crypto/src/test/java/org/zeroj/crypto/setup/SetupCacheTest.java +++ b/zeroj-crypto/src/test/java/org/zeroj/crypto/setup/SetupCacheTest.java @@ -10,22 +10,32 @@ import org.zeroj.crypto.groth16.Groth16Pipeline; import org.zeroj.crypto.groth16.Groth16ProvingKeyBLS381; import org.zeroj.crypto.kzg.KZGCommitmentBLS381; +import org.zeroj.crypto.msm.FlatScalars; import org.zeroj.crypto.plonk.PlonKProvingKeyBLS381; import org.zeroj.crypto.plonk.PlonKSetupBLS381; +import org.zeroj.crypto.plonk.PtauImporterBLS381; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assumptions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; -import java.nio.file.Files; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.IOException; import java.math.BigInteger; +import java.nio.file.Files; import java.nio.file.Path; +import java.util.Arrays; import java.util.List; import java.util.Map; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; @@ -81,7 +91,7 @@ void tamperedSrsCacheIsRejected() throws Exception { bytes[bytes.length - 1] ^= 0x01; Files.write(path, bytes); - assertThrows(java.io.IOException.class, () -> Groth16SetupCache.loadBls12381Srs(path)); + assertThrows(IOException.class, () -> Groth16SetupCache.loadBls12381Srs(path)); } @Test @@ -116,7 +126,7 @@ void insecureTrustedSetupRequiresExplicitOptInAcrossAllSites() throws Exception Path pipelineDir = tempDir.resolve("pipeline-denied"); assertThrows(IllegalStateException.class, () -> Groth16Pipeline.setup(compiled, srs.tauScalar(), pipelineDir, false)); - org.junit.jupiter.api.Assertions.assertFalse(Files.exists(pipelineDir), + assertFalse(Files.exists(pipelineDir), "Groth16Pipeline.setup must fail before creating output directory"); assertThrows(IllegalStateException.class, () -> Groth16Keys.setupInMemory(constraints, 4, 1, srs.tauScalar())); @@ -196,6 +206,99 @@ void plonkProvingKeyCacheRoundTripsBls381() throws Exception { assertPlonkProvingKeyEquals(pk, loaded); } + @Test + void partialPrefixSrsCacheRoundTripsAndSupportsPlonkSetup() throws Exception { + var full = PowersOfTauBLS381.generate(4); + + // Partial 14-point prefix (e.g. domainSize=8 + 6) of a power-4 ceremony round-trips cleanly. + var partial14 = new PtauImporterBLS381.SRS( + Arrays.copyOf(full.tauG1(), 14), full.tauG2(), full.power(), null); + Path path14 = tempDir.resolve("srs-partial-14.bin"); + Groth16SetupCache.saveBls12381Srs(partial14, path14); + var loaded14 = Groth16SetupCache.loadBls12381Srs(path14); + assertEquals(4, loaded14.power()); + assertEquals(14, loaded14.tauG1().length); + assertArrayEquals(partial14.tauG1(), loaded14.tauG1()); + assertArrayEquals(partial14.tauG2(), loaded14.tauG2()); + + // Partial 16-point prefix (< 2^(power+1) = 32) round-trips and feeds PlonKSetupBLS381.setup. + var partial16 = new PtauImporterBLS381.SRS( + Arrays.copyOf(full.tauG1(), 16), full.tauG2(), full.power(), null); + Path path16 = tempDir.resolve("srs-partial-16.bin"); + Groth16SetupCache.saveBls12381Srs(partial16, path16); + var loaded16 = Groth16SetupCache.loadBls12381Srs(path16); + assertEquals(16, loaded16.tauG1().length); + + var circuit = CircuitBuilder.create("plonk-partial-srs") + .publicVar("c").secretVar("a").secretVar("b") + .define(api -> api.assertEqual(api.mul(api.var("a"), api.var("b")), api.var("c"))); + var plonk = circuit.compilePlonK(CurveId.BLS12_381); + BigInteger[][] gateSelectors = new BigInteger[plonk.numGates()][5]; + for (int i = 0; i < plonk.numGates(); i++) { + var row = plonk.gateRows().get(i); + gateSelectors[i] = new BigInteger[]{row.qL(), row.qR(), row.qO(), row.qM(), row.qC()}; + } + var pk = PlonKSetupBLS381.setup(plonk.numGates(), plonk.numPublicInputs(), gateSelectors, + plonk.sigmaA(), plonk.sigmaB(), plonk.sigmaC(), plonk.numWires(), loaded16); + assertNotNull(pk); + } + + @Test + void srsCacheRejectsTauMismatchAndNonMinimalScalarEncoding() throws Exception { + var srs = PowersOfTauBLS381.generate(4); + BigInteger wrongTau = srs.tauScalar().add(BigInteger.ONE).mod(MontFr381.modulus()); + var mismatchedSrs = new PtauImporterBLS381.SRS(srs.tauG1(), srs.tauG2(), srs.power(), wrongTau); + + assertThrows(IOException.class, + () -> Groth16SetupCache.saveBls12381InsecureDevSrsWithTau(mismatchedSrs, tempDir.resolve("bad-save.bin"))); + + Path forgedPath = tempDir.resolve("forged-tau.bin"); + SetupCacheIO.writeCacheFile(forgedPath, SetupCacheIO.TYPE_BLS12381_SRS, out -> { + out.writeInt(srs.power()); + SetupCacheIO.writeG1Array(out, srs.tauG1()); + SetupCacheIO.writeG2Array(out, srs.tauG2()); + out.writeBoolean(true); + SetupCacheIO.writeScalar(out, wrongTau, "tau scalar"); + }); + assertThrows(IOException.class, () -> Groth16SetupCache.loadBls12381Srs(forgedPath)); + + // Non-minimal big-endian two's-complement scalar encoding (extra leading zero byte on 1). + ByteArrayOutputStream nonMinimal = new ByteArrayOutputStream(); + try (var out = new DataOutputStream(nonMinimal)) { + out.writeInt(2); + out.write(new byte[]{0x00, 0x01}); + } + assertThrows(IOException.class, () -> SetupCacheIO.readScalar( + new DataInputStream(new ByteArrayInputStream(nonMinimal.toByteArray())), "test")); + } + + @Test + void groth16SetupAndPipelineRejectDegenerateTauAndFlatScalarsWrapRejectsBadBounds() { + var constraints = List.of( + new R1CSConstraint(Map.of(2, BigInteger.ONE), Map.of(3, BigInteger.ONE), Map.of(1, BigInteger.ONE)), + new R1CSConstraint(Map.of(0, BigInteger.ONE), Map.of(0, BigInteger.ONE), Map.of(0, BigInteger.ONE))); + var flatBuilder = R1CSFlat.builder(); + for (var c : constraints) flatBuilder.add(c.a(), c.b(), c.c()); + var flat = flatBuilder.build(); + var compiled = new Groth16Pipeline.Compiled(flat, constraints.size(), 4, 1); + + // tau == 0 and tau == 1 (a 2N-th root of unity) must both be rejected before directory creation. + for (BigInteger badTau : List.of(BigInteger.ZERO, BigInteger.ONE)) { + assertThrows(IllegalArgumentException.class, + () -> Groth16SetupBLS381.setup(constraints, 4, 1, badTau)); + Path dir = tempDir.resolve("bad-tau-" + badTau); + assertThrows(IllegalArgumentException.class, + () -> Groth16Pipeline.setup(compiled, badTau, dir, false)); + assertFalse(Files.exists(dir), "Groth16Pipeline.setup must fail before creating directory for bad tau"); + } + + // FlatScalars.wrap bounds validation. + assertThrows(IllegalArgumentException.class, () -> FlatScalars.wrap(new long[4], -1)); + assertThrows(IllegalArgumentException.class, () -> FlatScalars.wrap(new long[3], 1)); + assertThrows(IllegalArgumentException.class, () -> FlatScalars.wrap(new long[4], 2)); + assertEquals(1, FlatScalars.wrap(new long[4], 1).count()); + } + private static void assertGroth16SetupEquals( Groth16SetupBLS381.SetupResult expected, Groth16SetupBLS381.SetupResult actual) { diff --git a/zeroj-jmt-poseidon/src/main/java/org/zeroj/merkle/jmt/poseidon/ccl/PoseidonJmtReference.java b/zeroj-jmt-poseidon/src/main/java/org/zeroj/merkle/jmt/poseidon/ccl/PoseidonJmtReference.java index b6d7e87b..5641f652 100644 --- a/zeroj-jmt-poseidon/src/main/java/org/zeroj/merkle/jmt/poseidon/ccl/PoseidonJmtReference.java +++ b/zeroj-jmt-poseidon/src/main/java/org/zeroj/merkle/jmt/poseidon/ccl/PoseidonJmtReference.java @@ -1,9 +1,5 @@ package org.zeroj.merkle.jmt.poseidon.ccl; -import co.nstant.in.cbor.CborDecoder; -import co.nstant.in.cbor.model.Array; -import co.nstant.in.cbor.model.ByteString; -import co.nstant.in.cbor.model.DataItem; import com.bloxbean.cardano.vds.jmt.JmtEncoding; import com.bloxbean.cardano.vds.jmt.JmtInternalNode; import com.bloxbean.cardano.vds.jmt.JmtLeafNode; @@ -11,10 +7,11 @@ import com.bloxbean.cardano.vds.jmt.JmtProof; import org.zeroj.merkle.jmt.poseidon.profile.PoseidonJmtCommitments; import org.zeroj.merkle.jmt.poseidon.profile.PoseidonJmtHash; +import org.zeroj.merkle.jmt.poseidon.profile.PoseidonJmtProfile; -import java.io.ByteArrayInputStream; import java.security.MessageDigest; import java.util.ArrayList; +import java.util.Arrays; import java.util.List; /** Independent object-proof traversal for the Poseidon JMT v1 statement. */ @@ -105,14 +102,17 @@ public static boolean verify( } private static final int MAX_WIRE_BYTES = 1_048_576; + private static final int MAX_INTERNAL_NODE_ITEMS = 2 + 16; // tag + bitmap + up to 16 child hashes + private static final int MAX_NODE_BYTES = 1024; // v1 internal node with 16 x 32B hashes is ~550B /** * Independent wire-proof verification for the Poseidon JMT v1 statement. * - *

Decodes the CBOR classic JMT proof array, enforces v1 non-compressed - * step-by-step path traversal without skipped levels, validates canonical - * Poseidon field digests, and recomputes the root via - * {@link PoseidonJmtCommitments}.

+ *

Parses the CBOR classic JMT proof array iteratively with strict depth, + * count, and remaining-length bounds (RFC 8949 §10) before calling the CCL + * node decoder, enforces v1 non-compressed step-by-step path traversal + * without skipped levels, validates canonical Poseidon field digests, and + * recomputes the root via {@link PoseidonJmtCommitments}.

*/ public static boolean verifyWire( byte[] expectedRoot, @@ -121,6 +121,7 @@ public static boolean verifyWire( boolean including, byte[] proofWire) { if (expectedRoot == null || key == null || proofWire == null + || proofWire.length == 0 || proofWire.length > MAX_WIRE_BYTES || including != (expectedValue != null)) { return false; @@ -130,22 +131,10 @@ public static boolean verifyWire( byte[] queryKeyHash = PoseidonJmtHash.digest(key); int[] queryPath = PoseidonJmtHash.nibbles(queryKeyHash); - List top = new CborDecoder(new ByteArrayInputStream(proofWire)).decode(); - if (top.size() != 1 || !(top.get(0) instanceof Array array)) { + List nodes = decodeBoundedWireNodes(proofWire, queryPath.length + 1); + if (nodes == null) { return false; } - List items = array.getDataItems(); - if (items.size() > queryPath.length + 1) { - return false; - } - - List nodes = new ArrayList<>(items.size()); - for (DataItem item : items) { - if (!(item instanceof ByteString bs)) { - return false; - } - nodes.add(JmtEncoding.decode(bs.getBytes())); - } if (nodes.isEmpty()) { return !including && equal(expectedRoot, PoseidonJmtCommitments.empty()); @@ -251,6 +240,142 @@ private static byte[][] unpackChildren(JmtInternalNode internal) { return children; } + /** + * Iterative, zero-recursion bounded CBOR parser for the v1 Classic JMT proof wire schema: + * a single definite-length CBOR array of at most {@code maxNodes} definite-length byte strings, + * each containing a flat v1 node array validated before calling {@link JmtEncoding#decode}. + */ + private static List decodeBoundedWireNodes(byte[] wire, int maxNodes) { + int[] cursor = {0}; + long countLong = readDefiniteHeader(wire, cursor, 4); // major 4 = array + if (countLong < 0 || countLong > maxNodes) { + return null; + } + int count = (int) countLong; + List nodes = new ArrayList<>(count); + for (int i = 0; i < count; i++) { + long lenLong = readDefiniteHeader(wire, cursor, 2); // major 2 = byte string + if (lenLong <= 0 || lenLong > MAX_NODE_BYTES || lenLong > wire.length - cursor[0]) { + return null; + } + int len = (int) lenLong; + int start = cursor[0]; + cursor[0] = start + len; + if (!isValidFlatV1NodeCbor(wire, start, len)) { + return null; + } + byte[] nodeBytes = Arrays.copyOfRange(wire, start, start + len); + nodes.add(JmtEncoding.decode(nodeBytes)); + } + if (cursor[0] != wire.length) { + return null; + } + return nodes; + } + + /** + * Validates that {@code wire[offset..offset+length)} is a single flat definite-length CBOR + * array matching either a v1 JMT internal node (tag + bitmap + popcount(bitmap) 32-byte + * child hashes, no compressed path) or a v1 JMT leaf node (tag + 32-byte keyHash + 32-byte + * valueHash), with zero nested containers and zero trailing bytes. + */ + private static boolean isValidFlatV1NodeCbor(byte[] wire, int offset, int length) { + int end = offset + length; + int[] cursor = {offset}; + long itemCountLong = readDefiniteHeader(wire, cursor, end, 4); // major 4 = array + if (itemCountLong < 2 || itemCountLong > MAX_INTERNAL_NODE_ITEMS) { + return false; + } + int itemCount = (int) itemCountLong; + // Item 0: 1-byte node tag ByteString + long tagLen = readDefiniteHeader(wire, cursor, end, 2); + if (tagLen != 1 || cursor[0] >= end) { + return false; + } + int tag = wire[cursor[0]++] & 0xFF; + if (tag == 0) { + // Internal node (v1 non-compressed): [tag(1B), bitmap(uint 0..65535), childHash_0..k(32B each)] + long bitmap = readDefiniteHeader(wire, cursor, end, 0); // major 0 = unsigned int + if (bitmap < 0 || bitmap > 0xFFFFL) { + return false; + } + int expectedHashes = Integer.bitCount((int) bitmap); + if (itemCount != 2 + expectedHashes) { + return false; + } + for (int i = 0; i < expectedHashes; i++) { + long hashLen = readDefiniteHeader(wire, cursor, end, 2); + if (hashLen != PoseidonJmtProfile.DIGEST_BYTES || hashLen > end - cursor[0]) { + return false; + } + cursor[0] += (int) hashLen; + } + return cursor[0] == end; + } else if (tag == 1) { + // Leaf node: [tag(1B), keyHash(32B), valueHash(32B)] + if (itemCount != 3) { + return false; + } + for (int i = 0; i < 2; i++) { + long hashLen = readDefiniteHeader(wire, cursor, end, 2); + if (hashLen != PoseidonJmtProfile.DIGEST_BYTES || hashLen > end - cursor[0]) { + return false; + } + cursor[0] += (int) hashLen; + } + return cursor[0] == end; + } + return false; + } + + private static long readDefiniteHeader(byte[] data, int[] cursor, int expectedMajor) { + return readDefiniteHeader(data, cursor, data.length, expectedMajor); + } + + private static long readDefiniteHeader(byte[] data, int[] cursor, int end, int expectedMajor) { + int pos = cursor[0]; + if (pos >= end) { + return -1; + } + int initial = data[pos++] & 0xFF; + int major = initial >>> 5; + int ai = initial & 0x1F; + if (major != expectedMajor) { + return -1; + } + long value; + if (ai < 24) { + value = ai; + } else if (ai == 24) { + if (pos + 1 > end) return -1; + value = data[pos++] & 0xFFL; + } else if (ai == 25) { + if (pos + 2 > end) return -1; + value = ((data[pos] & 0xFFL) << 8) | (data[pos + 1] & 0xFFL); + pos += 2; + } else if (ai == 26) { + if (pos + 4 > end) return -1; + value = ((data[pos] & 0xFFL) << 24) + | ((data[pos + 1] & 0xFFL) << 16) + | ((data[pos + 2] & 0xFFL) << 8) + | (data[pos + 3] & 0xFFL); + pos += 4; + } else if (ai == 27) { + if (pos + 8 > end) return -1; + long v = 0; + for (int i = 0; i < 8; i++) { + v = (v << 8) | (data[pos++] & 0xFFL); + } + if (v < 0) return -1; // reject > Long.MAX_VALUE + value = v; + } else { + // Reject reserved additional info (28..30) and indefinite-length (31) + return -1; + } + cursor[0] = pos; + return value; + } + private static boolean equal(byte[] left, byte[] right) { return left != null && right != null && MessageDigest.isEqual(left, right); } diff --git a/zeroj-jmt-poseidon/src/test/java/org/zeroj/merkle/jmt/poseidon/ccl/PoseidonJmtSecurityRegressionTest.java b/zeroj-jmt-poseidon/src/test/java/org/zeroj/merkle/jmt/poseidon/ccl/PoseidonJmtSecurityRegressionTest.java index 9e7d7794..2e742400 100644 --- a/zeroj-jmt-poseidon/src/test/java/org/zeroj/merkle/jmt/poseidon/ccl/PoseidonJmtSecurityRegressionTest.java +++ b/zeroj-jmt-poseidon/src/test/java/org/zeroj/merkle/jmt/poseidon/ccl/PoseidonJmtSecurityRegressionTest.java @@ -15,6 +15,7 @@ import java.io.ByteArrayOutputStream; import java.lang.reflect.Method; import java.nio.charset.StandardCharsets; +import java.util.Arrays; import java.util.LinkedHashMap; import java.util.List; @@ -112,6 +113,52 @@ void rejectsGapRelabelingThatCouldForgeAbsenceForPresentKey() throws Exception { .verifyProofWire(root, key, null, false, forgedWire)); } + @Test + void wireProofRejectsDeepCborNestingOverCountAndNestedNodeCbor() throws Exception { + var tree = new PoseidonJmtTree(new InMemoryJmtStore()); + var entries = new LinkedHashMap(); + entries.put(bytes("k1"), bytes("v1")); + entries.put(bytes("k2"), bytes("v2")); + var commit = tree.put(1, entries); + + // Positive controls: honest inclusion and non-inclusion wire proofs verify cleanly. + byte[] inclusionWire = tree.getProofWire(bytes("k1"), 1).orElseThrow(); + byte[] nonInclusionWire = tree.getProofWire(bytes("missing"), 1).orElseThrow(); + assertTrue(tree.verifyProofWire(commit.rootHash(), bytes("k1"), bytes("v1"), true, inclusionWire)); + assertTrue(tree.verifyProofWire(commit.rootHash(), bytes("missing"), null, false, nonInclusionWire)); + + // 1. Deeply nested top-level CBOR (300 KB of 1-element array headers 0x81) must return + // false without StackOverflowError. + byte[] deepTopLevel = new byte[300_000]; + Arrays.fill(deepTopLevel, (byte) 0x81); + assertFalse(PoseidonJmtReference.verifyWire(commit.rootHash(), bytes("k1"), bytes("v1"), true, deepTopLevel)); + assertFalse(tree.verifyProofWire(commit.rootHash(), bytes("k1"), bytes("v1"), true, deepTopLevel)); + + // 2. Top-level array exceeding max 65 node entries must return false. + Array overCount = new Array(); + for (int i = 0; i < 66; i++) { + overCount.add(new ByteString(new byte[4])); + } + ByteArrayOutputStream overBaos = new ByteArrayOutputStream(); + new CborEncoder(overBaos).encode(overCount); + assertFalse(PoseidonJmtReference.verifyWire( + commit.rootHash(), bytes("k1"), bytes("v1"), true, overBaos.toByteArray())); + + // 3. Nested CBOR inside a node byte string must be rejected before JmtEncoding.decode. + byte[] deepNode = new byte[10_000]; + Arrays.fill(deepNode, (byte) 0x81); + Array embeddedDeep = new Array(); + embeddedDeep.add(new ByteString(deepNode)); + ByteArrayOutputStream embeddedBaos = new ByteArrayOutputStream(); + new CborEncoder(embeddedBaos).encode(embeddedDeep); + assertFalse(PoseidonJmtReference.verifyWire( + commit.rootHash(), bytes("k1"), bytes("v1"), true, embeddedBaos.toByteArray())); + + // 4. Trailing bytes after a valid wire proof must return false. + byte[] trailing = Arrays.copyOf(inclusionWire, inclusionWire.length + 1); + assertFalse(PoseidonJmtReference.verifyWire(commit.rootHash(), bytes("k1"), bytes("v1"), true, trailing)); + } + private static JmtProof nonInclusionEmpty(List steps) throws Exception { Method factory = JmtProof.class.getDeclaredMethod("nonInclusionEmpty", List.class); factory.setAccessible(true); diff --git a/zeroj-onchain-julc/README.md b/zeroj-onchain-julc/README.md index dac17a13..1e42c11c 100644 --- a/zeroj-onchain-julc/README.md +++ b/zeroj-onchain-julc/README.md @@ -20,7 +20,7 @@ V3. |---------|----------|--------|-------| | `org.zeroj.onchain.julc.groth16.validator` | `Groth16BLS12381Verifier` | Working crypto-only validator | Default BLS12-381 Groth16 spending validator using Plutus V3 BLS builtins; supports arbitrary public-input counts, but does not bind `ScriptContext` | | `org.zeroj.onchain.julc.groth16.validator` | `Groth16BLS12381TxOutRefBindingVerifier` | Working bound validator example | Binds the first public input to `blake2b_256(spentTxId || spentOutputIndex32) mod Fr` to reject proof replay across UTxOs | -| `org.zeroj.onchain.julc.groth16.validator` | `Groth16AuthenticatedStateTransitionValidator` | Experimental representative state-transition validator | Derives old/new roots from the spent and single continuing state-token UTxO, enforces version increment, signer, value/token conservation and no mint, and verifies one operation-specific Groth16 proof | +| `org.zeroj.onchain.julc.groth16.validator` | `Groth16AuthenticatedStateTransitionValidator` | Experimental representative state-transition validator | Derives old/new roots from the spent and single continuing state-token UTxO, enforces version increment, signer, value/token conservation, empty continuing reference script, and no mint, and verifies one operation-specific Groth16 proof | | `org.zeroj.onchain.julc.groth16.codec` | `Groth16AuthenticatedStateTransitionScriptFactory`, `Groth16VerificationKeyCodec` | Experimental fail-closed release tooling | Binds exact circuit/manifest/R1CS/VK, audited validator-template digest, compiler profile, applied Plutus V3 script hash, typed network, state token/signer, and external one-shot genesis attestation | | `org.zeroj.onchain.julc.groth16.lib` | `Groth16BLS12381Lib` | Working on-chain library | Reusable `@OnchainLibrary` proof verification helper for custom validators | | `org.zeroj.onchain.julc.groth16.codec` | `SnarkjsToCardano`, `ProverToCardano` | Working off-chain helpers | Convert snarkjs and ZeroJ Groth16 artifacts to Cardano-compatible compressed bytes and Plutus data shapes | diff --git a/zeroj-onchain-julc/src/main/java/org/zeroj/onchain/julc/groth16/codec/Groth16AuthenticatedStateTransitionScriptFactory.java b/zeroj-onchain-julc/src/main/java/org/zeroj/onchain/julc/groth16/codec/Groth16AuthenticatedStateTransitionScriptFactory.java index 97cb92be..eb848b1b 100644 --- a/zeroj-onchain-julc/src/main/java/org/zeroj/onchain/julc/groth16/codec/Groth16AuthenticatedStateTransitionScriptFactory.java +++ b/zeroj-onchain-julc/src/main/java/org/zeroj/onchain/julc/groth16/codec/Groth16AuthenticatedStateTransitionScriptFactory.java @@ -77,6 +77,7 @@ public static AppliedScript apply( // Snapshot every caller-owned byte array before validating or applying it. All subsequent // identity and script operations use only these snapshots. SnarkjsToCardano.VkCompressed key = snapshot(verificationKey); + Groth16VerificationKeyCodec.validate(key); byte[] policyId = snapshot("statePolicyId", statePolicyId); byte[] tokenName = snapshot("stateTokenName", stateTokenName); byte[] signer = snapshot("authorizedSigner", authorizedSigner); diff --git a/zeroj-onchain-julc/src/main/java/org/zeroj/onchain/julc/groth16/codec/Groth16VerificationKeyCodec.java b/zeroj-onchain-julc/src/main/java/org/zeroj/onchain/julc/groth16/codec/Groth16VerificationKeyCodec.java index 45fef9d7..d01b000d 100644 --- a/zeroj-onchain-julc/src/main/java/org/zeroj/onchain/julc/groth16/codec/Groth16VerificationKeyCodec.java +++ b/zeroj-onchain-julc/src/main/java/org/zeroj/onchain/julc/groth16/codec/Groth16VerificationKeyCodec.java @@ -31,6 +31,22 @@ public final class Groth16VerificationKeyCodec { private Groth16VerificationKeyCodec() {} public static byte[] encode(SnarkjsToCardano.VkCompressed key) { + validate(key); + List ic = List.copyOf(key.ic()); + int size = Math.toIntExact(Math.addExact( + FIXED_BYTES, Math.multiplyExact((long) ic.size(), G1_BYTES))); + ByteBuffer output = ByteBuffer.allocate(size).order(ByteOrder.BIG_ENDIAN); + output.put(MAGIC).putInt(ic.size()); + output.put(key.alpha()).put(key.beta()).put(key.gamma()).put(key.delta()); + for (byte[] point : ic) output.put(point); + return output.array(); + } + + /** + * Validate that every point in {@code key} has canonical compressed length, lies on BLS12-381 + * G1/G2, is in the prime-order subgroup, and is not the point at infinity. + */ + public static void validate(SnarkjsToCardano.VkCompressed key) { Objects.requireNonNull(key, "key"); requireLength("alpha", key.alpha(), G1_BYTES); requireLength("beta", key.beta(), G2_BYTES); @@ -40,16 +56,14 @@ public static byte[] encode(SnarkjsToCardano.VkCompressed key) { if (ic.isEmpty() || ic.size() > MAX_IC_POINTS) { throw new IllegalArgumentException("IC count must be in [1, " + MAX_IC_POINTS + "]"); } + requireNonInfinityG1("alpha", key.alpha()); + requireNonInfinityG2("beta", key.beta()); + requireNonInfinityG2("gamma", key.gamma()); + requireNonInfinityG2("delta", key.delta()); for (int index = 0; index < ic.size(); index++) { requireLength("ic[" + index + "]", ic.get(index), G1_BYTES); + requireNonInfinityG1("ic[" + index + "]", ic.get(index)); } - int size = Math.toIntExact(Math.addExact( - FIXED_BYTES, Math.multiplyExact((long) ic.size(), G1_BYTES))); - ByteBuffer output = ByteBuffer.allocate(size).order(ByteOrder.BIG_ENDIAN); - output.put(MAGIC).putInt(ic.size()); - output.put(key.alpha()).put(key.beta()).put(key.gamma()).put(key.delta()); - for (byte[] point : ic) output.put(point); - return output.array(); } public static SnarkjsToCardano.VkCompressed decode(byte[] encoded) { diff --git a/zeroj-onchain-julc/src/test/java/org/zeroj/onchain/julc/groth16/codec/Groth16VerificationKeyCodecTest.java b/zeroj-onchain-julc/src/test/java/org/zeroj/onchain/julc/groth16/codec/Groth16VerificationKeyCodecTest.java index f7e05983..c94fb150 100644 --- a/zeroj-onchain-julc/src/test/java/org/zeroj/onchain/julc/groth16/codec/Groth16VerificationKeyCodecTest.java +++ b/zeroj-onchain-julc/src/test/java/org/zeroj/onchain/julc/groth16/codec/Groth16VerificationKeyCodecTest.java @@ -5,15 +5,20 @@ import org.zeroj.bls12381.Bls12381Generators; import org.zeroj.bls12381.ec.G1Point; import org.zeroj.bls12381.ec.G2Point; +import org.zeroj.bls12381.field.Fp; +import org.zeroj.bls12381.field.Fp2; import java.math.BigInteger; import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.List; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; class Groth16VerificationKeyCodecTest { @Test @@ -49,28 +54,54 @@ void canonicalEncodingRoundTripsAndRejectsNonCanonicalLengths() { } @Test - void decodeRejectsInfinityAndInvalidCompressedPoints() { + void encodeAndDecodeRejectInfinityOffSubgroupAndInvalidCompressedPoints() { var valid = validKey(); byte[] g1Inf = Bls12381Codecs.g1ToCompressed(G1Point.INFINITY); byte[] g2Inf = Bls12381Codecs.g2ToCompressed(G2Point.INFINITY); - var infAlpha = new SnarkjsToCardano.VkCompressed(g1Inf, valid.beta(), valid.gamma(), valid.delta(), valid.ic()); - assertThrows(IllegalArgumentException.class, - () -> Groth16VerificationKeyCodec.decode(Groth16VerificationKeyCodec.encode(infAlpha))); + G1Point g1Torsion = new G1Point(Fp.ZERO, Fp.of(2)); + assertTrue(g1Torsion.isOnCurve()); + assertFalse(g1Torsion.isInSubgroup()); + byte[] g1OffSubgroup = Bls12381Codecs.g1ToCompressed(g1Torsion); - var infBeta = new SnarkjsToCardano.VkCompressed(valid.alpha(), g2Inf, valid.gamma(), valid.delta(), valid.ic()); - assertThrows(IllegalArgumentException.class, - () -> Groth16VerificationKeyCodec.decode(Groth16VerificationKeyCodec.encode(infBeta))); + Fp2 x2 = Fp2.of(Fp.ZERO, Fp.ONE); + Fp2 y2 = x2.square().mul(x2).add(Fp2.of(Fp.of(4), Fp.of(4))).sqrt().orElseThrow(); + G2Point g2Torsion = new G2Point(x2, y2); + assertTrue(g2Torsion.isOnCurve()); + assertFalse(g2Torsion.isInSubgroup()); + byte[] g2OffSubgroup = Bls12381Codecs.g2ToCompressed(g2Torsion); - var infIc = new SnarkjsToCardano.VkCompressed( - valid.alpha(), valid.beta(), valid.gamma(), valid.delta(), List.of(valid.ic().get(0), g1Inf)); - assertThrows(IllegalArgumentException.class, - () -> Groth16VerificationKeyCodec.decode(Groth16VerificationKeyCodec.encode(infIc))); + List badKeys = List.of( + new SnarkjsToCardano.VkCompressed(g1Inf, valid.beta(), valid.gamma(), valid.delta(), valid.ic()), + new SnarkjsToCardano.VkCompressed(valid.alpha(), g2Inf, valid.gamma(), valid.delta(), valid.ic()), + new SnarkjsToCardano.VkCompressed(valid.alpha(), valid.beta(), valid.gamma(), valid.delta(), + List.of(valid.ic().get(0), g1Inf)), + new SnarkjsToCardano.VkCompressed(filled(48, 1), valid.beta(), valid.gamma(), valid.delta(), valid.ic()), + new SnarkjsToCardano.VkCompressed(g1OffSubgroup, valid.beta(), valid.gamma(), valid.delta(), valid.ic()), + new SnarkjsToCardano.VkCompressed(valid.alpha(), g2OffSubgroup, valid.gamma(), valid.delta(), valid.ic()) + ); - var garbage = new SnarkjsToCardano.VkCompressed( - filled(48, 1), valid.beta(), valid.gamma(), valid.delta(), valid.ic()); - assertThrows(IllegalArgumentException.class, - () -> Groth16VerificationKeyCodec.decode(Groth16VerificationKeyCodec.encode(garbage))); + for (var bad : badKeys) { + assertThrows(IllegalArgumentException.class, () -> Groth16VerificationKeyCodec.encode(bad)); + byte[] rawWire = rawEncodeUnchecked(bad); + assertThrows(IllegalArgumentException.class, () -> Groth16VerificationKeyCodec.decode(rawWire)); + } + } + + private static byte[] rawEncodeUnchecked(SnarkjsToCardano.VkCompressed key) { + byte[] magic = "ZJG1VK01".getBytes(StandardCharsets.US_ASCII); + int size = magic.length + 4 + 48 + 3 * 96 + key.ic().size() * 48; + ByteBuffer buf = ByteBuffer.allocate(size); + buf.put(magic); + buf.putInt(key.ic().size()); + buf.put(key.alpha()); + buf.put(key.beta()); + buf.put(key.gamma()); + buf.put(key.delta()); + for (byte[] p : key.ic()) { + buf.put(p); + } + return buf.array(); } private static SnarkjsToCardano.VkCompressed validKey() { diff --git a/zeroj-onchain-julc/src/test/java/org/zeroj/onchain/julc/groth16/validator/Groth16AuthenticatedStateTransitionValidatorTest.java b/zeroj-onchain-julc/src/test/java/org/zeroj/onchain/julc/groth16/validator/Groth16AuthenticatedStateTransitionValidatorTest.java index 6c7a2e9b..2287809a 100644 --- a/zeroj-onchain-julc/src/test/java/org/zeroj/onchain/julc/groth16/validator/Groth16AuthenticatedStateTransitionValidatorTest.java +++ b/zeroj-onchain-julc/src/test/java/org/zeroj/onchain/julc/groth16/validator/Groth16AuthenticatedStateTransitionValidatorTest.java @@ -21,6 +21,8 @@ import org.julclang.testkit.ScriptContextTestBuilder; import org.julclang.testkit.TestDataBuilder; import org.zeroj.api.AuthenticatedStateCircuitManifest; +import org.zeroj.bls12381.Bls12381Codecs; +import org.zeroj.bls12381.ec.G1Point; import org.zeroj.onchain.julc.groth16.codec.Groth16AuthenticatedStateTransitionScriptFactory; import org.zeroj.onchain.julc.groth16.codec.Groth16VerificationKeyCodec; import org.zeroj.onchain.julc.groth16.codec.SnarkjsToCardano; @@ -29,9 +31,12 @@ import java.io.IOException; import java.math.BigInteger; +import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; import java.util.ArrayList; import java.util.Arrays; +import java.util.HexFormat; import java.util.List; import java.util.Optional; @@ -199,6 +204,39 @@ void releaseFactoryBindsManifestKeyPolicyAndAppliedScriptWithoutCircularIdentity } } + @Test + void releaseFactoryRejectsInvalidVerificationKeyEvenWhenManifestHashMatches() throws Exception { + Program template = compileValidator(Groth16AuthenticatedStateTransitionValidator.class) + .program(); + String templateSha256 = Groth16AuthenticatedStateTransitionScriptFactory + .unappliedValidatorSha256(template); + var genesis = new Groth16AuthenticatedStateTransitionScriptFactory + .StateTokenGenesisAttestation(GENESIS_TX_ID, 0, GENESIS_EVIDENCE); + + // Positive control: valid VK applies cleanly. + var validManifest = transitionManifest(vk); + String validFingerprint = validManifest.dimensionFingerprint() + "-r" + validManifest.r1csSha256(); + assertTrue(Groth16AuthenticatedStateTransitionScriptFactory.apply( + template, templateSha256, validManifest.canonicalSha256(), validManifest, validFingerprint, vk, + STATE_POLICY_BYTES, STATE_TOKEN_BYTES, AUTHORIZED_SIGNER, genesis).flatProgram().length > 0); + + // Negative: VK with infinity IC point whose raw ZJG1VK01 bytes match the manifest hash + // must still be rejected by ScriptFactory.apply(). + byte[] g1Inf = Bls12381Codecs.g1ToCompressed(G1Point.INFINITY); + var badVk = new SnarkjsToCardano.VkCompressed( + vk.alpha(), vk.beta(), vk.gamma(), vk.delta(), + List.of(vk.ic().get(0), vk.ic().get(1), g1Inf)); + byte[] rawBadVkBytes = rawVkBytesUnchecked(badVk); + String badKeySha = HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(rawBadVkBytes)); + var badManifest = transitionManifestWithKeySha(badKeySha); + String badFingerprint = badManifest.dimensionFingerprint() + "-r" + badManifest.r1csSha256(); + + assertThrows(IllegalArgumentException.class, + () -> Groth16AuthenticatedStateTransitionScriptFactory.apply( + template, templateSha256, badManifest.canonicalSha256(), badManifest, badFingerprint, badVk, + STATE_POLICY_BYTES, STATE_TOKEN_BYTES, AUTHORIZED_SIGNER, genesis)); + } + private Program appliedProgram(byte[] release, SnarkjsToCardano.VkCompressed key) { return compileValidator(Groth16AuthenticatedStateTransitionValidator.class) .program() @@ -354,8 +392,21 @@ private static String loadResource(String path) throws IOException { private static AuthenticatedStateCircuitManifest transitionManifest( SnarkjsToCardano.VkCompressed key) throws Exception { byte[] encodedKey = Groth16VerificationKeyCodec.encode(key); - String keySha = java.util.HexFormat.of().formatHex( - java.security.MessageDigest.getInstance("SHA-256").digest(encodedKey)); + String keySha = HexFormat.of().formatHex( + MessageDigest.getInstance("SHA-256").digest(encodedKey)); + return transitionManifestWithKeySha(keySha); + } + + private static byte[] rawVkBytesUnchecked(SnarkjsToCardano.VkCompressed key) { + byte[] magic = "ZJG1VK01".getBytes(StandardCharsets.US_ASCII); + ByteBuffer buf = ByteBuffer.allocate(magic.length + 4 + 48 + 3 * 96 + key.ic().size() * 48); + buf.put(magic).putInt(key.ic().size()) + .put(key.alpha()).put(key.beta()).put(key.gamma()).put(key.delta()); + for (byte[] p : key.ic()) buf.put(p); + return buf.array(); + } + + private static AuthenticatedStateCircuitManifest transitionManifestWithKeySha(String keySha) { return new AuthenticatedStateCircuitManifest( AuthenticatedStateCircuitManifest.SCHEMA_VERSION, "zeroj-mpf-v1-value-update-s8-p2", diff --git a/zeroj-tools/build.gradle b/zeroj-tools/build.gradle index 522860c1..97e3e8d8 100644 --- a/zeroj-tools/build.gradle +++ b/zeroj-tools/build.gradle @@ -74,6 +74,9 @@ tasks.register('fatJar', Jar) { dependsOn configurations.runtimeClasspath from sourceSets.main.output from { configurations.runtimeClasspath.collect { it.isDirectory() ? it : zipTree(it) } } + from("${rootDir}/LICENSE") { into 'META-INF' } + from("${rootDir}/NOTICE") { into 'META-INF' } + from("${rootDir}/licenses/Apache-2.0.txt") { into 'META-INF/licenses' } // BC jar signatures don't survive repacking (we use the lightweight digest API, not the JCE provider) exclude 'META-INF/*.SF', 'META-INF/*.DSA', 'META-INF/*.RSA', 'META-INF/versions/*/OSGI-INF/**' } @@ -127,6 +130,7 @@ tasks.register('nativeDistZip', Zip) { from("${rootDir}/docs/ceremony/USER-GUIDE.md") { rename { 'README.md' } } from("${rootDir}/LICENSE") from("${rootDir}/NOTICE") + from("${rootDir}/licenses/Apache-2.0.txt") { into 'licenses' } } } From 6d8de174b9f6400e39899f2f9922a20d77f2e310 Mon Sep 17 00:00:00 2001 From: Satya Date: Sat, 21 Nov 2026 16:26:47 +0800 Subject: [PATCH 3/3] Preserve 1-point tau-free SRS cache, snapshot JMT wire & VK encode bytes, note ADR-0050 baseline --- ...0-julc-pre17-org-julclang-and-typed-bls.md | 2 + .../org/zeroj/crypto/setup/SetupCacheIO.java | 4 +- .../zeroj/crypto/setup/SetupCacheTest.java | 18 ++++++++ .../poseidon/ccl/PoseidonJmtReference.java | 27 +++++++++--- .../jmt/poseidon/ccl/PoseidonJmtTree.java | 14 ++++-- .../codec/Groth16VerificationKeyCodec.java | 44 ++++++++++++------- .../Groth16VerificationKeyCodecTest.java | 7 ++- ...enticatedStateTransitionValidatorTest.java | 2 +- 8 files changed, 87 insertions(+), 31 deletions(-) diff --git a/docs/adr/0050-julc-pre17-org-julclang-and-typed-bls.md b/docs/adr/0050-julc-pre17-org-julclang-and-typed-bls.md index 13bfcd05..c8e1cbe2 100644 --- a/docs/adr/0050-julc-pre17-org-julclang-and-typed-bls.md +++ b/docs/adr/0050-julc-pre17-org-julclang-and-typed-bls.md @@ -363,6 +363,8 @@ ZeroJ upgrades `julcVersion` from `0.1.0-pre18` to `0.1.0-pre22` alongside [ADR- | `PlonkBLS12381MultiInputVerifier` | 4,668 | `4172c86d5e8e8e69dfd91f92776176b567c4c2200108dc98273d4a1e` | | `PlonkBLS12381MultiInputParamVerifier` | 4,707 | `7e78ad1bbf6ef553a4401fab1025250f14e3f5271816bcc8a732f38f` | +Note: `Groth16AuthenticatedStateTransitionValidator` was originally `2,817` bytes (`46c77c445f4d16b156797d05aee6964f9c93d7446dd4f12d26824d4d`) under the initial `0.1.0-pre22` migration and was updated in place to `2,845` bytes (`5192732cf2c70ce2f03859f1e9f728d986f6a0e1c18e1a1ab86f8eb2`) when the `continuingOutput.referenceScript().isEmpty()` guard was added. + Downstream validators embedding `BbsProofVerify`, `PedersenG1Lib`, `Groth16BLS12381Lib`, or `PlonkBLS12381Lib` (including `zeroj-integration-tests` example validators and `zeroj-usecases` validators) also receive regenerated UPLC bytes and new script hashes. ## Open questions diff --git a/zeroj-crypto/src/main/java/org/zeroj/crypto/setup/SetupCacheIO.java b/zeroj-crypto/src/main/java/org/zeroj/crypto/setup/SetupCacheIO.java index d0bc3ed6..ad10064f 100644 --- a/zeroj-crypto/src/main/java/org/zeroj/crypto/setup/SetupCacheIO.java +++ b/zeroj-crypto/src/main/java/org/zeroj/crypto/setup/SetupCacheIO.java @@ -320,8 +320,8 @@ static void validateBls12381Srs(AffineG1[] tauG1, AffineG2[] tauG2, int power) t if (power < 1 || power > 32) { throw new IOException("Invalid BLS12-381 SRS power: " + power); } - if (tauG1.length < 2) { - throw new IOException("BLS12-381 SRS must contain at least two G1 powers"); + if (tauG1.length < 1) { + throw new IOException("BLS12-381 SRS must contain at least one G1 power"); } if (power <= 29 && tauG1.length > (2L << power) + 1L) { throw new IOException("BLS12-381 SRS G1 power count " + tauG1.length diff --git a/zeroj-crypto/src/test/java/org/zeroj/crypto/setup/SetupCacheTest.java b/zeroj-crypto/src/test/java/org/zeroj/crypto/setup/SetupCacheTest.java index ab8801ea..092a7700 100644 --- a/zeroj-crypto/src/test/java/org/zeroj/crypto/setup/SetupCacheTest.java +++ b/zeroj-crypto/src/test/java/org/zeroj/crypto/setup/SetupCacheTest.java @@ -210,6 +210,24 @@ void plonkProvingKeyCacheRoundTripsBls381() throws Exception { void partialPrefixSrsCacheRoundTripsAndSupportsPlonkSetup() throws Exception { var full = PowersOfTauBLS381.generate(4); + // Generator-only 1-point tau-free prefix (e.g. maxPoints=1 import) round-trips cleanly, + // while saving a 1-point SRS with a retained tau scalar is still rejected. + var partial1 = new PtauImporterBLS381.SRS( + Arrays.copyOf(full.tauG1(), 1), full.tauG2(), full.power(), null); + Path path1 = tempDir.resolve("srs-partial-1.bin"); + Groth16SetupCache.saveBls12381Srs(partial1, path1); + var loaded1 = Groth16SetupCache.loadBls12381Srs(path1); + assertEquals(4, loaded1.power()); + assertEquals(1, loaded1.tauG1().length); + assertNull(loaded1.tauScalar()); + assertArrayEquals(partial1.tauG1(), loaded1.tauG1()); + assertArrayEquals(partial1.tauG2(), loaded1.tauG2()); + + var partial1WithTau = new PtauImporterBLS381.SRS( + Arrays.copyOf(full.tauG1(), 1), full.tauG2(), full.power(), full.tauScalar()); + assertThrows(IOException.class, () -> Groth16SetupCache.saveBls12381InsecureDevSrsWithTau( + partial1WithTau, tempDir.resolve("srs-partial-1-tau.bin"))); + // Partial 14-point prefix (e.g. domainSize=8 + 6) of a power-4 ceremony round-trips cleanly. var partial14 = new PtauImporterBLS381.SRS( Arrays.copyOf(full.tauG1(), 14), full.tauG2(), full.power(), null); diff --git a/zeroj-jmt-poseidon/src/main/java/org/zeroj/merkle/jmt/poseidon/ccl/PoseidonJmtReference.java b/zeroj-jmt-poseidon/src/main/java/org/zeroj/merkle/jmt/poseidon/ccl/PoseidonJmtReference.java index 5641f652..0040380d 100644 --- a/zeroj-jmt-poseidon/src/main/java/org/zeroj/merkle/jmt/poseidon/ccl/PoseidonJmtReference.java +++ b/zeroj-jmt-poseidon/src/main/java/org/zeroj/merkle/jmt/poseidon/ccl/PoseidonJmtReference.java @@ -101,18 +101,19 @@ public static boolean verify( } } - private static final int MAX_WIRE_BYTES = 1_048_576; + static final int MAX_WIRE_BYTES = 1_048_576; private static final int MAX_INTERNAL_NODE_ITEMS = 2 + 16; // tag + bitmap + up to 16 child hashes private static final int MAX_NODE_BYTES = 1024; // v1 internal node with 16 x 32B hashes is ~550B /** * Independent wire-proof verification for the Poseidon JMT v1 statement. * - *

Parses the CBOR classic JMT proof array iteratively with strict depth, - * count, and remaining-length bounds (RFC 8949 §10) before calling the CCL - * node decoder, enforces v1 non-compressed step-by-step path traversal - * without skipped levels, validates canonical Poseidon field digests, and - * recomputes the root via {@link PoseidonJmtCommitments}.

+ *

Bounds and snapshots caller-owned byte arrays at ingress, parses the + * CBOR classic JMT proof array iteratively with strict depth, count, and + * remaining-length bounds (RFC 8949 §10) before calling the CCL node + * decoder on the same private bytes, enforces v1 non-compressed step-by-step + * path traversal without skipped levels, validates canonical Poseidon field + * digests, and recomputes the root via {@link PoseidonJmtCommitments}.

*/ public static boolean verifyWire( byte[] expectedRoot, @@ -126,6 +127,20 @@ public static boolean verifyWire( || including != (expectedValue != null)) { return false; } + return verifyWireSnapshot( + expectedRoot.clone(), + key.clone(), + expectedValue == null ? null : expectedValue.clone(), + including, + proofWire.clone()); + } + + static boolean verifyWireSnapshot( + byte[] expectedRoot, + byte[] key, + byte[] expectedValue, + boolean including, + byte[] proofWire) { try { PoseidonJmtHash.decode(expectedRoot); byte[] queryKeyHash = PoseidonJmtHash.digest(key); diff --git a/zeroj-jmt-poseidon/src/main/java/org/zeroj/merkle/jmt/poseidon/ccl/PoseidonJmtTree.java b/zeroj-jmt-poseidon/src/main/java/org/zeroj/merkle/jmt/poseidon/ccl/PoseidonJmtTree.java index c72de66c..8168d81b 100644 --- a/zeroj-jmt-poseidon/src/main/java/org/zeroj/merkle/jmt/poseidon/ccl/PoseidonJmtTree.java +++ b/zeroj-jmt-poseidon/src/main/java/org/zeroj/merkle/jmt/poseidon/ccl/PoseidonJmtTree.java @@ -105,15 +105,21 @@ public boolean verifyProofWire( boolean including, byte[] proofWire) { if (expectedRoot == null || key == null || proofWire == null + || proofWire.length == 0 + || proofWire.length > PoseidonJmtReference.MAX_WIRE_BYTES || including != (expectedValue != null)) { return false; } + byte[] rootSnapshot = expectedRoot.clone(); + byte[] keySnapshot = key.clone(); + byte[] valueSnapshot = expectedValue == null ? null : expectedValue.clone(); + byte[] wireSnapshot = proofWire.clone(); try { - PoseidonJmtHash.decode(expectedRoot); - return PoseidonJmtReference.verifyWire( - expectedRoot, key, expectedValue, including, proofWire) + PoseidonJmtHash.decode(rootSnapshot); + return PoseidonJmtReference.verifyWireSnapshot( + rootSnapshot, keySnapshot, valueSnapshot, including, wireSnapshot) && delegate.verifyProofWire( - expectedRoot, key, expectedValue, including, proofWire); + rootSnapshot, keySnapshot, valueSnapshot, including, wireSnapshot); } catch (RuntimeException malformed) { return false; } diff --git a/zeroj-onchain-julc/src/main/java/org/zeroj/onchain/julc/groth16/codec/Groth16VerificationKeyCodec.java b/zeroj-onchain-julc/src/main/java/org/zeroj/onchain/julc/groth16/codec/Groth16VerificationKeyCodec.java index d01b000d..9dc366e8 100644 --- a/zeroj-onchain-julc/src/main/java/org/zeroj/onchain/julc/groth16/codec/Groth16VerificationKeyCodec.java +++ b/zeroj-onchain-julc/src/main/java/org/zeroj/onchain/julc/groth16/codec/Groth16VerificationKeyCodec.java @@ -31,13 +31,13 @@ public final class Groth16VerificationKeyCodec { private Groth16VerificationKeyCodec() {} public static byte[] encode(SnarkjsToCardano.VkCompressed key) { - validate(key); - List ic = List.copyOf(key.ic()); + SnarkjsToCardano.VkCompressed validated = snapshotAndValidate(key); + List ic = validated.ic(); int size = Math.toIntExact(Math.addExact( FIXED_BYTES, Math.multiplyExact((long) ic.size(), G1_BYTES))); ByteBuffer output = ByteBuffer.allocate(size).order(ByteOrder.BIG_ENDIAN); output.put(MAGIC).putInt(ic.size()); - output.put(key.alpha()).put(key.beta()).put(key.gamma()).put(key.delta()); + output.put(validated.alpha()).put(validated.beta()).put(validated.gamma()).put(validated.delta()); for (byte[] point : ic) output.put(point); return output.array(); } @@ -47,23 +47,35 @@ public static byte[] encode(SnarkjsToCardano.VkCompressed key) { * G1/G2, is in the prime-order subgroup, and is not the point at infinity. */ public static void validate(SnarkjsToCardano.VkCompressed key) { + snapshotAndValidate(key); + } + + private static SnarkjsToCardano.VkCompressed snapshotAndValidate(SnarkjsToCardano.VkCompressed key) { Objects.requireNonNull(key, "key"); - requireLength("alpha", key.alpha(), G1_BYTES); - requireLength("beta", key.beta(), G2_BYTES); - requireLength("gamma", key.gamma(), G2_BYTES); - requireLength("delta", key.delta(), G2_BYTES); - List ic = List.copyOf(Objects.requireNonNull(key.ic(), "ic")); - if (ic.isEmpty() || ic.size() > MAX_IC_POINTS) { + List rawIc = List.copyOf(Objects.requireNonNull(key.ic(), "ic")); + if (rawIc.isEmpty() || rawIc.size() > MAX_IC_POINTS) { throw new IllegalArgumentException("IC count must be in [1, " + MAX_IC_POINTS + "]"); } - requireNonInfinityG1("alpha", key.alpha()); - requireNonInfinityG2("beta", key.beta()); - requireNonInfinityG2("gamma", key.gamma()); - requireNonInfinityG2("delta", key.delta()); - for (int index = 0; index < ic.size(); index++) { - requireLength("ic[" + index + "]", ic.get(index), G1_BYTES); - requireNonInfinityG1("ic[" + index + "]", ic.get(index)); + byte[] alpha = snapshot("alpha", key.alpha(), G1_BYTES); + byte[] beta = snapshot("beta", key.beta(), G2_BYTES); + byte[] gamma = snapshot("gamma", key.gamma(), G2_BYTES); + byte[] delta = snapshot("delta", key.delta(), G2_BYTES); + requireNonInfinityG1("alpha", alpha); + requireNonInfinityG2("beta", beta); + requireNonInfinityG2("gamma", gamma); + requireNonInfinityG2("delta", delta); + List ic = new ArrayList<>(rawIc.size()); + for (int index = 0; index < rawIc.size(); index++) { + byte[] point = snapshot("ic[" + index + "]", rawIc.get(index), G1_BYTES); + requireNonInfinityG1("ic[" + index + "]", point); + ic.add(point); } + return new SnarkjsToCardano.VkCompressed(alpha, beta, gamma, delta, List.copyOf(ic)); + } + + private static byte[] snapshot(String name, byte[] value, int expected) { + requireLength(name, value, expected); + return value.clone(); } public static SnarkjsToCardano.VkCompressed decode(byte[] encoded) { diff --git a/zeroj-onchain-julc/src/test/java/org/zeroj/onchain/julc/groth16/codec/Groth16VerificationKeyCodecTest.java b/zeroj-onchain-julc/src/test/java/org/zeroj/onchain/julc/groth16/codec/Groth16VerificationKeyCodecTest.java index c94fb150..e19534a7 100644 --- a/zeroj-onchain-julc/src/test/java/org/zeroj/onchain/julc/groth16/codec/Groth16VerificationKeyCodecTest.java +++ b/zeroj-onchain-julc/src/test/java/org/zeroj/onchain/julc/groth16/codec/Groth16VerificationKeyCodecTest.java @@ -84,12 +84,15 @@ void encodeAndDecodeRejectInfinityOffSubgroupAndInvalidCompressedPoints() { for (var bad : badKeys) { assertThrows(IllegalArgumentException.class, () -> Groth16VerificationKeyCodec.encode(bad)); byte[] rawWire = rawEncodeUnchecked(bad); - assertThrows(IllegalArgumentException.class, () -> Groth16VerificationKeyCodec.decode(rawWire)); + IllegalArgumentException decodeEx = assertThrows( + IllegalArgumentException.class, () -> Groth16VerificationKeyCodec.decode(rawWire)); + assertFalse(decodeEx.getMessage().contains("magic"), + "raw wire test must exercise point validation, got: " + decodeEx.getMessage()); } } private static byte[] rawEncodeUnchecked(SnarkjsToCardano.VkCompressed key) { - byte[] magic = "ZJG1VK01".getBytes(StandardCharsets.US_ASCII); + byte[] magic = "ZJG16VK1".getBytes(StandardCharsets.US_ASCII); int size = magic.length + 4 + 48 + 3 * 96 + key.ic().size() * 48; ByteBuffer buf = ByteBuffer.allocate(size); buf.put(magic); diff --git a/zeroj-onchain-julc/src/test/java/org/zeroj/onchain/julc/groth16/validator/Groth16AuthenticatedStateTransitionValidatorTest.java b/zeroj-onchain-julc/src/test/java/org/zeroj/onchain/julc/groth16/validator/Groth16AuthenticatedStateTransitionValidatorTest.java index 2287809a..4e222cb2 100644 --- a/zeroj-onchain-julc/src/test/java/org/zeroj/onchain/julc/groth16/validator/Groth16AuthenticatedStateTransitionValidatorTest.java +++ b/zeroj-onchain-julc/src/test/java/org/zeroj/onchain/julc/groth16/validator/Groth16AuthenticatedStateTransitionValidatorTest.java @@ -398,7 +398,7 @@ private static AuthenticatedStateCircuitManifest transitionManifest( } private static byte[] rawVkBytesUnchecked(SnarkjsToCardano.VkCompressed key) { - byte[] magic = "ZJG1VK01".getBytes(StandardCharsets.US_ASCII); + byte[] magic = "ZJG16VK1".getBytes(StandardCharsets.US_ASCII); ByteBuffer buf = ByteBuffer.allocate(magic.length + 4 + 48 + 3 * 96 + key.ic().size() * 48); buf.put(magic).putInt(key.ic().size()) .put(key.alpha()).put(key.beta()).put(key.gamma()).put(key.delta());