diff --git a/docs/adr/0068-dsl-plonk-scaling-mpf-and-gadget-hardening.md b/docs/adr/0068-dsl-plonk-scaling-mpf-and-gadget-hardening.md
new file mode 100644
index 00000000..403d7582
--- /dev/null
+++ b/docs/adr/0068-dsl-plonk-scaling-mpf-and-gadget-hardening.md
@@ -0,0 +1,112 @@
+# ADR-0068: Circuit DSL Soundness, PlonK Scaling, Poseidon MPF Canonicality, and Gadget Hardening
+
+- **Status:** Proposed
+- **Date:** 2026-11-21
+- **Risk Classification:** R2 (security-sensitive circuit soundness, witness validation, SRS verification, and state-tree conformance)
+- **Related ADRs:** ADR-0022 (PlonK BLS12-381), ADR-0025 (Legacy BN254 opt-in gating), ADR-0037 / ADR-0038 (DSL range & ownership soundness), ADR-0063 (Direct Boolean lowering), ADR-0065 (`arrayAccess` bounds), ADR-0066 (BLS12-381 PlonK `.ptau` & `t3 = n + 6` SRS sizing)
+
+---
+
+## Context
+
+Seven related correctness, soundness, and scaling defects span the circuit DSL, symbolic annotation layer, BLS12-381 PlonK setup/prover, Poseidon MPF circuits, and standard-library gadgets:
+
+1. **`ZkUInt.sub` 253-bit underflow wrap-around on BN254.** `ZkUInt.MAX_BITS` is `253`, and `ZkUInt.sub` constrains `a - b` to `max(a.bits, b.bits)` bits without capping at `252`. On BN254 (`r ≈ 2^253.57`), `2^254 > r`, so `0 - (2^253 - 1) ≡ r - (2^253 - 1) < 2^253` satisfies the 253-bit range check and wraps around silently. The comment on `CircuitAPIImpl.MAX_SAFE_BITS` also conflates decomposition uniqueness (`2^bits < p`, 253 bits on BN254) with difference-underflow safety (`2^(bits+1) <= p`, 252 bits on BN254).
+2. **PlonK BLS12-381 $O(n^2)$ loops and duplicated $O(n)$ SRS pairings.** `PlonKProverBLS381.cosetEval` calls linear `powFr(shift, i)` inside an $O(n)$ loop and computes `zeta^n` in $O(n)$ multiplications; `PlonKSetupBLS381` calls linear `evalOmegaPow` inside its domain loop and `decodeSigmaTarget`; both `PtauImporterBLS381` and `PlonKSetupBLS381` independently execute `count - 1` sequential two-pairing checks (`O(n)` pairings performed twice across import + setup).
+3. **Raw `CircuitAPI.{xor,and,or,not,fromBinary}` booleanity and width guards.** Raw `xor`, `and`, `or`, and `not` rely on a Javadoc precondition that operands are `{0, 1}` without enforcing `assertBoolean`, while `fromBinary` has no upper bit-width guard against field wrap-around. Naively enforcing `assertBoolean` without tracking derived-boolean wires would inflate circuits that chain boolean expressions.
+4. **Witness input validation gaps and BN254-hardcoded `Groth16Prover.validateWitness`.** `WitnessCalculator` silently reduces out-of-range and negative inputs modulo `p`, ignores unknown input keys, and ignores extra entries in input value lists. `ZkInputMap` and generated `Inputs` setters accept negative or out-of-type values. There is no curve-generic public `verifyWitness` helper in `zeroj-circuit-dsl`, while the public `Groth16Prover.validateWitness` hard-codes `MontFr254.modulus()`, lacks `LegacyCurvePolicy` gating, and skips wire-0 / bounds / canonical checks.
+5. **Poseidon MPF `< Fr` key-path canonicality and `Step.fork` nibble validation.** `docs/merkle/poseidon-authenticated-state-v1.md` requires every 32-byte decoded key to be canonical (`< Fr`) rather than reduced, and host `PoseidonMpfHash.digestToNibbles` rejects `>= Fr`, but `ZkMpf.requireKeyPath` only checks that each of the 64 nibbles is 4-bit (`0..15`), allowing non-canonical `>= Fr` nibble paths (such as `64 × 0xF`) in-circuit. `PoseidonMpfCodec.Step.fork` checks `prefix.length <= 64` but does not validate that each prefix byte is a nibble in `[0, 15]`.
+6. **Standard-library gadget defects and foreign `ZkBool` ownership.**
+ - `Binary.rotateLeft` and `SignalBinary.rotateLeft` rotate LSB-first bit arrays in the right-shift direction (`(i + n) % len`) and throw `ArrayIndexOutOfBoundsException` for negative `n`; `Binary.shiftRight` accepts negative `n` and can overflow `i + n`.
+ - `AliasCheck` claims circomlib `< p` canonicality enforcement, but delegates to `toBinary(value, nBits)`, which throws at 254/255 bits and checks `< 2^nBits` (rejecting ~72.4% of valid BLS12-381 scalars at `nBits = 253`).
+ - `PoseidonN` left-folds 2-input Poseidon without domain/arity separation (`PoseidonN(x) == Poseidon(x, 0) == PoseidonN(x, 0)`, `PoseidonN(a, b, c) == Poseidon(Poseidon(a, b), c)`) while claiming circomlib `Poseidon(nInputs)` equivalence.
+ - `CircuitAnnotationProcessor` invokes `.assertTrue()` on a `@Prove` method's returned `ZkBool` without checking that the returned signal belongs to the circuit's own `ZkContext`.
+
+---
+
+## Threat Model & Trust Assumptions
+
+- **Malicious prover:** Controls all private witness values and can bypass `WitnessCalculator` to feed arbitrary field elements directly to a prover, attempting to satisfy under-constrained arithmetic (`ZkUInt.sub` underflow, unvalidated raw boolean ops, non-canonical MPF key paths, or circuits whose `@Prove` assertion was silently emitted into a foreign builder).
+- **Untrusted SRS / `.ptau` / MPF wire proof inputs:** A corrupted SRS with valid individual subgroup points can still violate `tauG1[i] == tau * tauG1[i-1]` unless consistency is verified. Untrusted MPF CBOR proofs can carry non-nibble fork prefix bytes.
+- **Misconfigured caller:** A caller passing negative/out-of-range inputs, unknown keys, or a BLS12-381 witness to BN254-hardcoded `Groth16Prover.validateWitness` must receive an explicit failure rather than silent modular wrap-around or false validation.
+- **Trust assumptions:** `SecureRandom` supplies unbiased field challenges for batched SRS consistency checks. Circuit-level key regeneration is required for any deployed MPF circuit because enforcing `< Fr` changes the R1CS constraint set and canonical digest.
+
+---
+
+## Normative References
+
+- **BN254 scalar field order:** `r = 21888242871839275222246405745257275088548364400416034343698204186575808495617` (`2^253 < r < 2^254`).
+- **BLS12-381 scalar field order:** `r = 52435875175126190479447740508185965837690552500527637822603658699938581184513` (`2^254 < r < 2^255`).
+- **Batched pairing RLC (Schwartz-Zippel over `F_r`):**
+ - Primary references: Bellare, Garay & Rabin, *"Fast Batch Verification for Modular Exponentiation and Digital Signatures"* (EUROCRYPT 1998, LNCS 1403); Bowe, Gabizon & Miers, *"Scalable Multi-party Computation for zk-SNARK Parameters in the Random Beacon Model"* (IACR ePrint 2017/1050, §2.2 Powers of Tau ratio check).
+ - **Fixed-input-before-challenge assumption:** All G1/G2 SRS points are copied into a private caller-isolated snapshot (`PlonKSetupBLS381` / `PtauImporterBLS381`) *before* subgroup checks or drawing the `SecureRandom` challenge `r in F_r \ {0}`, and that same private snapshot is used for every KZG commitment and stored in the returned `PlonKProvingKeyBLS381`.
+ - For fixed validated prime-order subgroup points `P_0..P_{m}` in `G1` and `G2, tau*G2` in `G2`, checking `e(sum_{j=0}^{m-1} r^j P_{j+1}, G2) == e(sum_{j=0}^{m-1} r^j P_j, tau*G2)` fails to detect an inconsistent SRS with probability at most `(m - 1) / (r - 1) < 2^{-230}` for `m <= 2^24 + 6`.
+- **ZeroJ Poseidon Authenticated State v1 specification:** `docs/merkle/poseidon-authenticated-state-v1.md` (Proof normalization invariant #8: every field decoded from 32 bytes is canonical rather than reduced).
+- **ADR-0025 / ADR-0037 / ADR-0038 / ADR-0063 / ADR-0066.**
+
+---
+
+## Security Invariants
+
+1. **I1 (Subtraction non-underflow):** `ZkUInt.sub(other)` rejects `max(bits, other.bits) >= MAX_BITS` (`>= 253`), ensuring `2^(width + 1) <= p` on every supported curve (BN254, BLS12-381, Pallas).
+2. **I2 (SRS consistency soundness & caller-isolated snapshot):** `PlonKSetupBLS381.setup` copies the required `domainSize + 6` G1 prefix and 2 G2 anchors into private arrays at entry before validation, uses those same private arrays for every KZG commitment and inside the returned `PlonKProvingKeyBLS381`, and never re-reads caller-visible arrays. Every SRS accepted by `PtauImporterBLS381` or `PlonKSetupBLS381` has validated generator anchors, validated non-infinity prime-order subgroup points, and passes the `SecureRandom`-challenged batched pairing check on its pinned snapshot. Reusing a `PtauImporterBLS381`-verified `SRS` in `PlonKSetupBLS381` skips redundant subgroup/pairing work **only** when element-by-element equality of the pinned snapshot against the recorded import snapshot confirms zero post-import mutation.
+3. **I3 (Booleanity enforcement without bloat):** `CircuitAPIImpl` records provably-boolean wires (`oneWire`, exact constants `0` and `1`, `isZero` / `isEqual`, `lessThan`, `decompose` bits, and outputs of `xor`/`and`/`or`/`not`) in `booleanWires`, enforces `assertBoolean` on operands of `xor`, `and`, `or`, and `not`, and bounds `fromBinary` to `1 <= bits.length <= MAX_SAFE_BITS`. Non-boolean constants (`2`, `p - 1`, etc.) remain excluded from `booleanWires` so explicit `assertBoolean(constant(2))` still fails.
+4. **I4 (Canonical witness & input validation with secret redaction):**
+ - `WitnessCalculator` rejects null maps, unknown input keys, null values, multi-value lists (`size != 1`), and non-canonical values (`< 0` or `>= p`) rather than silently reducing modulo `p`.
+ - `ZkInputMap` and generated `Inputs` setters enforce non-negative / declared type ranges (`BOOL`/`BITS`: `{0, 1}`, `BYTES`: `[0, 255]`, `UINT(bits)`: `[0, 2^bits)`, `FIELD`: `[0, p)` at curve-bound validation).
+ - `R1CSConstraintSystem.verifyWitness` provides curve-generic R1CS witness verification checking wire-0 `== 1`, canonical `[0, prime)`, bounds, and every constraint `(A·w)(B·w) ≡ C·w (mod prime)`.
+ - `Groth16Prover.validateWitness` is `@Deprecated(forRemoval = true)`, gated behind `LegacyCurvePolicy.requireLegacyBn254Enabled()`, and enforces bounds, wire-0 `== 1`, and canonical BN254 scalars.
+ - All validation exceptions report only the signal name, wire index, constraint index, and failed rule — never witness values or witness-derived linear-combination evaluations.
+5. **I5 (MPF canonical `< Fr` key paths & nibble-checked forks):** `ZkMpf.requireKeyPath` (and `ZkMpfProof` leaf key paths) constrain the 64-nibble big-endian key path to be strictly less than `FieldConfig.BLS12_381.prime()`. `PoseidonMpfCodec.Step.fork` rejects `prefix.length > 64`, negative `skip`, `neighborNibble` outside `[0, 15]`, or any prefix byte outside `[0, 15]`.
+6. **I6 (Correct bit rotation, honest range/hash semantics, and `@Prove` ownership):**
+ - `Binary.rotateLeft` and `SignalBinary.rotateLeft` rotate LSB-first bit vectors left (`result[i] = bits[(i - floorMod(n, len) + len) % len]`), rejecting null/empty arrays; `Binary.shiftRight` rejects `n < 0` and avoids integer overflow.
+ - `RangeCheck` replaces `AliasCheck` (`@Deprecated(forRemoval = true)`) with accurate `< 2^nBits` semantics.
+ - `PoseidonN` null-checks inputs and documents fixed-arity-only non-circomlib semantics and collision caveats.
+ - `CircuitAnnotationProcessor` checks `Objects.requireNonNull` and `__zeroj.requireSignal(__zerojResult.signal())` before calling `.assertTrue()` on a `@Prove` return value.
+
+---
+
+## Decision & Alternatives Considered
+
+- **Batched SRS pairing vs. per-index pairing:** Per-index pairing is $O(n)$ pairings (seconds to minutes at medium powers). A single `SecureRandom` RLC reduces pairing cost to $O(1)$ (2 Miller loops + 1 final exponentiation) with `< 2^{-230}` soundness error, while a snapshot-verified `WeakHashMap` avoids duplicating work when `PlonKSetupBLS381.setup` consumes an unmodified `PtauImporterBLS381.SRS`.
+ - *Alternative rejected:* Trusting a mutable boolean flag on `SRS` without snapshot comparison — rejected because `SRS.tauG1()` is a mutable array that callers could tamper with after import.
+- **Caching derived booleans in `CircuitAPIImpl` vs. forcing `assertBoolean` inside `fromBinary`:** SHA-256 and SHA-512 gadgets construct `ch`/`maj` using direct arithmetic (`mul`/`add`/`sub`) and pass those wires to `fromBinary`. Calling `assertBoolean` inside `fromBinary` would add ~4,096 redundant constraints per SHA block. Instead, enforcing `assertBoolean` on `xor`/`and`/`or`/`not` (backed by `booleanWires` propagation) protects raw boolean callers with zero bloat on proven booleans, while `fromBinary` enforces the `1..MAX_SAFE_BITS` width guard.
+- **Strict canonical `WitnessCalculator` by default vs. opt-in overload:** Silent `.mod(p)` hides prover-vs-verifier public-input mismatches because BLS12-381 verifiers fail closed on `>= r`. Making canonical `[0, p)` enforcement the default closes the mismatch class completely.
+- **Deprecating `AliasCheck` and `Groth16Prover.validateWitness` vs. immediate deletion:** Keeping source-compatible deprecated facades with clear replacements (`RangeCheck` and `R1CSConstraintSystem.verifyWitness`) preserves existing API surface contracts (including `Groth16ProverApiSurfaceTest`) while blocking unsafe use (`LegacyCurvePolicy` gate on `validateWitness`).
+
+---
+
+## Compatibility & Migration Notes
+
+- **Poseidon MPF circuit keys (breaking R1CS change):** Enforcing `< Fr` on `keyPath` (and `leafKeyPath`) adds constraints and changes the canonical R1CS SHA-256 digests for all MPF templates (`inclusion`, `non-inclusion-*`, `value-update`, `insert-*`, `full-semantics-*`). Existing deployments must recompile MPF circuits and regenerate proving/verifying keys.
+- **Derived-boolean deduplication (breaking R1CS change for affected circuits):** Recording provably-boolean outputs (`oneWire`, exact `0`/`1` constants, `isZero`/`isEqual`, `xor`/`and`/`or`/`not`) in `CircuitAPIImpl.booleanWires` eliminates redundant `AssertBoolean` rows in circuits that later select on or re-assert those wires (for example, `-1` row on `ZkJubjubPoint.assertInPrimeOrderSubgroup` and `-160` rows on `zeroj-jmt-v1-insert-different-leaf-s8-p2`). Recompile and regenerate keys for affected circuits.
+- **Poseidon MPF terminal-fork exclusion limitation:** In `ZkMpf`, full-semantics non-inclusion fails closed on terminal-fork steps (`valid && forkKind && lastValid`) because CCL's terminal-fork wire proof omits an authenticated commitment for the skipped branch. For a fixed absent key on an unchanged trie, the proof path is deterministic, so that absent key cannot be proven non-included under the current MPF full-semantics or branch-only templates (branch-only templates cover only branch-only empty-child and different-leaf shapes). Callers requiring total non-inclusion over arbitrary authenticated trie states should use the `zeroj-jmt-poseidon` templates (which have no compressed fork steps) or wait for a future MPF witness format that authenticates terminal-fork commitments.
+- **`Binary.rotateLeft` / `SignalBinary.rotateLeft`:** Previously rotated in the opposite (right) direction; callers expecting LSB-first circular left rotation now get the mathematically correct result.
+- **`WitnessCalculator` / `ZkInputMap`:** Negative inputs, values `>= p`, unknown keys, and multi-element input lists now throw `IllegalArgumentException` instead of being silently reduced or ignored.
+- **`PlonKProvingKeyBLS381.srsG1()`:** Now stores the pinned `domainSize + 6` SRS prefix validated by `PlonKSetupBLS381.setup` rather than retaining the caller's entire full-ceremony G1 array.
+- **`Groth16Prover.validateWitness`:** Now requires legacy BN254 opt-in (`LegacyCurvePolicy`) and is scheduled for removal; migrate to `R1CSConstraintSystem.verifyWitness`.
+
+---
+
+## Implementation Milestones
+
+1. **M1:** Cap `ZkUInt.sub` at `<= 252` bits, clarify `CircuitAPIImpl.MAX_SAFE_BITS` Javadoc, add BN254 & BLS12-381 regression tests.
+2. **M2:** Eliminate PlonK $O(n^2)$ exponent loops (`cosetEval`, `powFr`, `zetaN`, `PlonKSetupBLS381` precomputed `omegaPows`) and introduce `SrsConsistencyBLS381` batched RLC pairing check with snapshot-checked reuse across `PtauImporterBLS381` and `PlonKSetupBLS381`.
+3. **M3:** Propagate derived-boolean tracking in `CircuitAPIImpl`, enforce operand booleanity in `xor`/`and`/`or`/`not`, and add `1..MAX_SAFE_BITS` width guard on `fromBinary`.
+4. **M4:** Enforce canonical input validation in `WitnessCalculator`, `ZkInputMap`, and generated `Inputs`; add curve-generic `R1CSConstraintSystem.verifyWitness`; deprecate, gate, and harden `Groth16Prover.validateWitness`.
+5. **M5:** Enforce `< Fr` key-path canonicality in `ZkMpf`, validate nibble range in `PoseidonMpfCodec.Step.fork`, update pinned MPF R1CS profiles, and document the unsupported MPF terminal-fork exclusion case accurately.
+6. **M6:** Fix `Binary`/`SignalBinary.rotateLeft` and `Binary.shiftRight`, add `RangeCheck` & deprecate `AliasCheck`, harden/document `PoseidonN`, and check returned `ZkBool` ownership in `CircuitAnnotationProcessor`.
+
+---
+
+## Verification & Test-Vector Strategy
+
+- **Negative soundness tests:** BN254 253-bit `ZkUInt.sub` rejection + 252-bit underflow rejection on BN254 & BLS12-381; raw non-boolean witness injection into `xor`/`and`/`or`/`not` rejected by R1CS; `fromBinary` empty and `> 253` width rejection; non-canonical MPF `64 × 0xF` and `Fr` key paths rejected by R1CS; non-nibble fork prefix bytes rejected by `Step.fork` & CBOR decode; foreign-builder and null `@Prove` `ZkBool` return rejection.
+- **PlonK scaling & interop:** Synthetic corrupted SRS (single tampered G1 power, swapped G1 power, wrong generator anchor, mutated post-import `SRS`) rejected by batched RLC check; live `snarkjs@0.7.6` `.ptau -> setup -> prove -> verify` interop remains green.
+- **Witness & gadget correctness:** Unknown keys, multi-value lists, negative and `>= p` inputs rejected by `WitnessCalculator` and `ZkInputMap`/`Inputs`; `R1CSConstraintSystem.verifyWitness` verified on both BLS12-381 and BN254 with tampered wire-0, out-of-range scalar, wrong length, and broken constraint; integer-value tests for `Binary.rotateLeft`, `SignalBinary.rotateLeft`, `Binary.shiftRight`, `RangeCheck`, `PoseidonN`.
+
+---
+
+## Production & Audit Gates
+
+- This ADR does **not** promote any module to production-safe status. External cryptographic review of the DSL constraint lowering, PlonK prover/setup, and Poseidon MPF circuits remains mandatory before value-bearing or mainnet deployment.
diff --git a/docs/merkle/poseidon-authenticated-state-v1.md b/docs/merkle/poseidon-authenticated-state-v1.md
index b8d5902f..a0dda26d 100644
--- a/docs/merkle/poseidon-authenticated-state-v1.md
+++ b/docs/merkle/poseidon-authenticated-state-v1.md
@@ -201,7 +201,7 @@ or transaction binding.
|---|---|---|---|
| `zeroj-mpf-v1-inclusion-sN-p1` | `root` | normalized inclusion path, value commitment | some canonical MPF v1 key path maps to the value commitment under `root` |
| `zeroj-mpf-v1-non-inclusion-empty-sN-p1` | `root` | query path and authenticated empty-child path | the query path reaches an authenticated empty child under `root` |
-| `zeroj-mpf-v1-non-inclusion-different-leaf-sN-p1` | `root` | query path, conflicting leaf and authenticated path | an authenticated different leaf proves the query path absent; terminal forks fail closed |
+| `zeroj-mpf-v1-non-inclusion-different-leaf-sN-p1` | `root` | query path, conflicting leaf and authenticated path | an authenticated different leaf proves the query path absent; terminal forks fail closed (unsupported under current MPF witness format; use JMT v1 templates for total non-inclusion) |
| `zeroj-mpf-v1-value-update-sN-p2` | `oldRoot,newRoot` | one key path, old/new values, shared path | only the value commitment at the authenticated path changes |
| `zeroj-mpf-v1-insert-empty-sN-p2` | `oldRoot,newRoot` | authenticated empty-child absence plus canonical rewrite | insertion into an authenticated empty child transforms the roots |
| `zeroj-mpf-v1-insert-different-leaf-sN-p2` | `oldRoot,newRoot` | authenticated conflicting leaf plus canonical rewrite | insertion beside an authenticated different leaf transforms the roots |
diff --git a/zeroj-circuit-annotation-api/src/main/java/org/zeroj/circuit/annotation/ZkInputMap.java b/zeroj-circuit-annotation-api/src/main/java/org/zeroj/circuit/annotation/ZkInputMap.java
index f3688b21..8ad0f43a 100644
--- a/zeroj-circuit-annotation-api/src/main/java/org/zeroj/circuit/annotation/ZkInputMap.java
+++ b/zeroj-circuit-annotation-api/src/main/java/org/zeroj/circuit/annotation/ZkInputMap.java
@@ -1,24 +1,33 @@
package org.zeroj.circuit.annotation;
+import org.zeroj.api.CurveId;
import org.zeroj.api.PublicInputs;
+import org.zeroj.circuit.FieldConfig;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collections;
+import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
+import java.util.Set;
/**
* Ordered witness input accumulator used by generated input builders.
*/
public final class ZkInputMap {
+ private static final BigInteger MAX_BYTE = BigInteger.valueOf(255);
+
private final Map> values = new LinkedHashMap<>();
public ZkInputMap put(String name, BigInteger value) {
Objects.requireNonNull(name, "name");
Objects.requireNonNull(value, "value");
+ if (value.signum() < 0) {
+ throw new IllegalArgumentException("Input " + name + " must be non-negative");
+ }
values.put(name, List.of(value));
return this;
}
@@ -27,6 +36,17 @@ public ZkInputMap put(String name, long value) {
return put(name, BigInteger.valueOf(value));
}
+ /**
+ * Validate {@code value} against {@code schemaInput}'s declared type/bit-width bounds and
+ * record it under {@code signalName}.
+ */
+ public ZkInputMap putChecked(ZkCircuitSchema.Input schemaInput, String signalName, BigInteger value) {
+ Objects.requireNonNull(schemaInput, "schemaInput");
+ Objects.requireNonNull(signalName, "signalName");
+ requireInSchemaRange(schemaInput, signalName, value);
+ return put(signalName, value);
+ }
+
public ZkInputMap putArray(String baseName, List inputValues) {
Objects.requireNonNull(baseName, "baseName");
Objects.requireNonNull(inputValues, "inputValues");
@@ -36,6 +56,19 @@ public ZkInputMap putArray(String baseName, List inputValues) {
return this;
}
+ /**
+ * Validate every element against {@code schemaInput}'s declared type/bit-width bounds before
+ * storing any entry.
+ */
+ public ZkInputMap putArrayChecked(ZkCircuitSchema.Input schemaInput, List inputValues) {
+ Objects.requireNonNull(schemaInput, "schemaInput");
+ Objects.requireNonNull(inputValues, "inputValues");
+ for (int i = 0; i < inputValues.size(); i++) {
+ requireInSchemaRange(schemaInput, schemaInput.name() + "_" + i, inputValues.get(i));
+ }
+ return putArray(schemaInput.name(), inputValues);
+ }
+
public ZkInputMap putNestedArray(String baseName, List extends List> inputValues) {
Objects.requireNonNull(baseName, "baseName");
Objects.requireNonNull(inputValues, "inputValues");
@@ -49,6 +82,110 @@ public ZkInputMap putNestedArray(String baseName, List extends List> inputValues) {
+ Objects.requireNonNull(schemaInput, "schemaInput");
+ Objects.requireNonNull(inputValues, "inputValues");
+ for (int row = 0; row < inputValues.size(); row++) {
+ List rowValues = Objects.requireNonNull(inputValues.get(row),
+ "inputValues[" + row + "]");
+ for (int col = 0; col < rowValues.size(); col++) {
+ requireInSchemaRange(schemaInput,
+ schemaInput.name() + "_" + row + "_" + col,
+ rowValues.get(col));
+ }
+ }
+ return putNestedArray(schemaInput.name(), inputValues);
+ }
+
+ /**
+ * Validate that every input declared by {@code schema} is present, no unknown keys exist,
+ * every value satisfies its declared type/bit-width bounds, and every value is canonical in
+ * {@code [0, p)} for {@code curve}.
+ */
+ public void validate(ZkCircuitSchema schema, CurveId curve) {
+ Objects.requireNonNull(schema, "schema");
+ Objects.requireNonNull(curve, "curve");
+ validate(schema, FieldConfig.forCurve(curve));
+ }
+
+ /**
+ * Validate all inputs against {@code schema} and {@code field}'s canonical range {@code [0, p)}.
+ */
+ public void validate(ZkCircuitSchema schema, FieldConfig field) {
+ Objects.requireNonNull(schema, "schema");
+ Objects.requireNonNull(field, "field");
+ BigInteger prime = field.prime();
+ Set expectedSignals = new HashSet<>();
+ for (ZkCircuitSchema.Input input : schema.inputs()) {
+ for (String signalName : input.signalNames()) {
+ expectedSignals.add(signalName);
+ List vals = values.get(signalName);
+ if (vals == null || vals.isEmpty()) {
+ throw new IllegalStateException("Missing input: " + signalName);
+ }
+ if (vals.size() != 1) {
+ throw new IllegalArgumentException(
+ "Input " + signalName + " must have exactly 1 value, got " + vals.size());
+ }
+ BigInteger value = vals.getFirst();
+ requireInSchemaRange(input, signalName, value);
+ if (value.compareTo(prime) >= 0) {
+ throw new IllegalArgumentException(
+ "Input " + signalName + " is not canonical for " + field.name()
+ + " (expected < p)");
+ }
+ }
+ }
+ for (String key : values.keySet()) {
+ if (!expectedSignals.contains(key)) {
+ throw new IllegalArgumentException("Unknown input not declared in schema: " + key);
+ }
+ }
+ }
+
+ public static void requireInSchemaRange(
+ ZkCircuitSchema.Input schemaInput,
+ String signalName,
+ BigInteger value) {
+ Objects.requireNonNull(schemaInput, "schemaInput");
+ Objects.requireNonNull(signalName, "signalName");
+ Objects.requireNonNull(value, signalName);
+ if (value.signum() < 0) {
+ throw new IllegalArgumentException(
+ "Input " + signalName + " must be non-negative");
+ }
+ switch (schemaInput.kind()) {
+ case BOOL, BITS -> {
+ if (value.compareTo(BigInteger.ONE) > 0) {
+ throw new IllegalArgumentException(
+ "Input " + signalName + " must be 0 or 1");
+ }
+ }
+ case BYTES -> {
+ if (value.compareTo(MAX_BYTE) > 0) {
+ throw new IllegalArgumentException(
+ "Input " + signalName + " must be in [0, 255]");
+ }
+ }
+ case UINT -> {
+ if (value.bitLength() > schemaInput.bits()) {
+ throw new IllegalArgumentException(
+ "Input " + signalName + " exceeds " + schemaInput.bits()
+ + "-bit unsigned range");
+ }
+ }
+ case FIELD -> {
+ // Non-negative already enforced; curve-specific < p checked in validate()/WitnessCalculator.
+ }
+ }
+ }
+
public Map> toWitnessMap() {
var copy = new LinkedHashMap>();
values.forEach((name, value) -> copy.put(name, List.copyOf(value)));
diff --git a/zeroj-circuit-annotation-api/src/main/java/org/zeroj/circuit/annotation/ZkUInt.java b/zeroj-circuit-annotation-api/src/main/java/org/zeroj/circuit/annotation/ZkUInt.java
index 9d7ad6b1..1c405a58 100644
--- a/zeroj-circuit-annotation-api/src/main/java/org/zeroj/circuit/annotation/ZkUInt.java
+++ b/zeroj-circuit-annotation-api/src/main/java/org/zeroj/circuit/annotation/ZkUInt.java
@@ -77,7 +77,12 @@ public ZkUInt add(ZkUInt other) {
public ZkUInt sub(ZkUInt other) {
requireSameContext(other);
- return constrained(context, signal.sub(other.signal), Math.max(bits, other.bits));
+ int width = Math.max(bits, other.bits);
+ if (width >= MAX_BITS) {
+ throw new IllegalArgumentException(
+ "ZkUInt subtraction requires bit width < " + MAX_BITS + ", got " + width);
+ }
+ return constrained(context, signal.sub(other.signal), width);
}
public ZkUInt mul(ZkUInt other) {
diff --git a/zeroj-circuit-annotation-api/src/test/java/org/zeroj/circuit/annotation/ZkUIntSubAndInputMapHardeningTest.java b/zeroj-circuit-annotation-api/src/test/java/org/zeroj/circuit/annotation/ZkUIntSubAndInputMapHardeningTest.java
new file mode 100644
index 00000000..dd269d43
--- /dev/null
+++ b/zeroj-circuit-annotation-api/src/test/java/org/zeroj/circuit/annotation/ZkUIntSubAndInputMapHardeningTest.java
@@ -0,0 +1,168 @@
+package org.zeroj.circuit.annotation;
+
+import org.junit.jupiter.api.Test;
+import org.zeroj.api.CurveId;
+import org.zeroj.circuit.CircuitBuilder;
+import org.zeroj.circuit.FieldConfig;
+import org.zeroj.circuit.r1cs.R1CSConstraintSystem;
+
+import java.math.BigInteger;
+import java.util.List;
+import java.util.Map;
+
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/** ADR-0068: ZkUInt.sub 252-bit cap & ZkInputMap canonical/range validation. */
+class ZkUIntSubAndInputMapHardeningTest {
+
+ @Test
+ void zkUIntSubRejects253BitOperands() {
+ assertThrows(IllegalArgumentException.class, () -> CircuitBuilder.create("sub-253")
+ .secretVar("a").secretVar("b")
+ .defineSignals(c -> {
+ var a = ZkUInt.secret(c, "a", 253);
+ var b = ZkUInt.secret(c, "b", 253);
+ a.sub(b);
+ }));
+
+ assertThrows(IllegalArgumentException.class, () -> CircuitBuilder.create("sub-253-mixed-left")
+ .secretVar("a").secretVar("b")
+ .defineSignals(c -> {
+ var a = ZkUInt.secret(c, "a", 253);
+ var b = ZkUInt.secret(c, "b", 8);
+ a.sub(b);
+ }));
+
+ assertThrows(IllegalArgumentException.class, () -> CircuitBuilder.create("sub-253-mixed-right")
+ .secretVar("a").secretVar("b")
+ .defineSignals(c -> {
+ var a = ZkUInt.secret(c, "a", 8);
+ var b = ZkUInt.secret(c, "b", 253);
+ a.sub(b);
+ }));
+ }
+
+ @Test
+ void zkUIntSubAt252BitsAcceptsValidAndRejectsUnderflowOnBn254AndBls12381() {
+ CircuitBuilder circuit = CircuitBuilder.create("sub-252")
+ .publicVar("diff")
+ .secretVar("a")
+ .secretVar("b")
+ .defineSignals(c -> {
+ var a = ZkUInt.secret(c, "a", 252);
+ var b = ZkUInt.secret(c, "b", 252);
+ var diff = ZkUInt.publicInput(c, "diff", 252);
+ a.sub(b).assertEqual(diff);
+ });
+
+ BigInteger max252 = BigInteger.ONE.shiftLeft(252).subtract(BigInteger.ONE);
+
+ for (CurveId curve : List.of(CurveId.BN254, CurveId.BLS12_381)) {
+ R1CSConstraintSystem r1cs = circuit.compileR1CS(curve);
+
+ // Valid boundary cases: max252 - 0 = max252, max252 - max252 = 0
+ BigInteger[] w1 = circuit.calculateWitness(Map.of(
+ "a", List.of(max252),
+ "b", List.of(BigInteger.ZERO),
+ "diff", List.of(max252)), curve);
+ assertDoesNotThrow(() -> r1cs.verifyWitness(w1));
+
+ BigInteger[] w2 = circuit.calculateWitness(Map.of(
+ "a", List.of(max252),
+ "b", List.of(max252),
+ "diff", List.of(BigInteger.ZERO)), curve);
+ assertDoesNotThrow(() -> r1cs.verifyWitness(w2));
+
+ // Underflow cases: 0 - 1 and 0 - (2^252 - 1) must fail (p - (2^252 - 1) >= 2^252)
+ BigInteger p = FieldConfig.forCurve(curve).prime();
+ BigInteger wrapped = p.subtract(max252);
+ assertTrue(wrapped.bitLength() > 252,
+ "2^253 <= p must hold so underflow wraps above 2^252 on " + curve);
+
+ assertThrows(ArithmeticException.class, () -> circuit.calculateWitness(Map.of(
+ "a", List.of(BigInteger.ZERO),
+ "b", List.of(BigInteger.ONE),
+ "diff", List.of(BigInteger.ZERO)), curve));
+
+ assertThrows(ArithmeticException.class, () -> circuit.calculateWitness(Map.of(
+ "a", List.of(BigInteger.ZERO),
+ "b", List.of(max252),
+ "diff", List.of(BigInteger.ZERO)), curve));
+ }
+ }
+
+ @Test
+ void zkInputMapRejectsNegativeOutOfTypeUnknownAndNonCanonicalInputs() {
+ var schema = ZkCircuitSchema.of(
+ "typed-inputs",
+ List.of(),
+ List.of(
+ ZkCircuitSchema.Input.scalar("f", ZkCircuitSchema.Visibility.PUBLIC,
+ ZkCircuitSchema.Kind.FIELD, -1),
+ ZkCircuitSchema.Input.scalar("flag", ZkCircuitSchema.Visibility.PUBLIC,
+ ZkCircuitSchema.Kind.BOOL, 1)),
+ List.of(
+ ZkCircuitSchema.Input.scalar("amt", ZkCircuitSchema.Visibility.SECRET,
+ ZkCircuitSchema.Kind.UINT, 8),
+ ZkCircuitSchema.Input.array("data", ZkCircuitSchema.Visibility.SECRET,
+ ZkCircuitSchema.Kind.BYTES, 8, 2),
+ ZkCircuitSchema.Input.array("bits", ZkCircuitSchema.Visibility.SECRET,
+ ZkCircuitSchema.Kind.BITS, 1, 2)));
+
+ // Direct put rejects negative values
+ assertThrows(IllegalArgumentException.class, () -> new ZkInputMap().put("f", -1));
+
+ // Checked puts enforce type bounds
+ assertThrows(IllegalArgumentException.class, () -> new ZkInputMap()
+ .putChecked(schema.input("flag"), "flag", BigInteger.TWO));
+ assertThrows(IllegalArgumentException.class, () -> new ZkInputMap()
+ .putChecked(schema.input("amt"), "amt", BigInteger.valueOf(256)));
+ assertThrows(IllegalArgumentException.class, () -> new ZkInputMap()
+ .putArrayChecked(schema.input("data"), List.of(BigInteger.ZERO, BigInteger.valueOf(256))));
+ assertThrows(IllegalArgumentException.class, () -> new ZkInputMap()
+ .putArrayChecked(schema.input("bits"), List.of(BigInteger.ZERO, BigInteger.TWO)));
+
+ // Valid inputs pass validate on both curves
+ var valid = new ZkInputMap()
+ .putChecked(schema.input("f"), "f", BigInteger.valueOf(42))
+ .putChecked(schema.input("flag"), "flag", BigInteger.ONE)
+ .putChecked(schema.input("amt"), "amt", BigInteger.valueOf(255))
+ .putArrayChecked(schema.input("data"), List.of(BigInteger.ZERO, BigInteger.valueOf(255)))
+ .putArrayChecked(schema.input("bits"), List.of(BigInteger.ONE, BigInteger.ZERO));
+ assertDoesNotThrow(() -> valid.validate(schema, CurveId.BLS12_381));
+ assertDoesNotThrow(() -> valid.validate(schema, CurveId.BN254));
+ assertEquals(List.of(BigInteger.valueOf(42), BigInteger.ONE), valid.publicValues(schema));
+
+ // Unknown key rejected by validate
+ valid.put("extra", 1);
+ assertThrows(IllegalArgumentException.class, () -> valid.validate(schema, CurveId.BLS12_381));
+
+ // Non-canonical field value (>= p) rejected by validate without leaking the secret value
+ BigInteger secretSentinel = new BigInteger("98765432109876543210987654321");
+ BigInteger badField = FieldConfig.BLS12_381.prime().add(secretSentinel);
+ var nonCanonical = new ZkInputMap()
+ .put("f", badField)
+ .put("flag", 1)
+ .put("amt", 1)
+ .putArray("data", List.of(BigInteger.ZERO, BigInteger.ONE))
+ .putArray("bits", List.of(BigInteger.ZERO, BigInteger.ONE));
+ IllegalArgumentException fieldEx = assertThrows(IllegalArgumentException.class,
+ () -> nonCanonical.validate(schema, CurveId.BLS12_381));
+ assertTrue(fieldEx.getMessage() != null && !fieldEx.getMessage().contains(badField.toString())
+ && !fieldEx.getMessage().contains(secretSentinel.toString()),
+ "ZkInputMap.validate must redact witness values: " + fieldEx.getMessage());
+
+ IllegalArgumentException negEx = assertThrows(IllegalArgumentException.class,
+ () -> new ZkInputMap().put("amt", secretSentinel.negate()));
+ assertTrue(!negEx.getMessage().contains(secretSentinel.toString()),
+ "ZkInputMap.put must redact negative witness values: " + negEx.getMessage());
+
+ IllegalArgumentException rangeEx = assertThrows(IllegalArgumentException.class,
+ () -> new ZkInputMap().putChecked(schema.input("amt"), "amt", secretSentinel));
+ assertTrue(!rangeEx.getMessage().contains(secretSentinel.toString()),
+ "ZkInputMap.putChecked must redact out-of-range witness values: " + rangeEx.getMessage());
+ }
+}
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..44cc3708 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
@@ -585,7 +585,14 @@ private String render(TypeElement sourceType, String packageName, String sourceS
if (proveMethod.getReturnType().getKind() == TypeKind.VOID) {
out.append(" ").append(call).append(";\n");
} else {
- out.append(" ").append(call).append(".assertTrue();\n");
+ String resultLocal = uniqueLocalName("__zerojResult", usedLocalNames);
+ out.append(" ZkBool ").append(resultLocal).append(" = ").append(call).append(";\n")
+ .append(" if (").append(resultLocal).append(" == null) {\n")
+ .append(" throw new NullPointerException(\"@Prove method returned null ZkBool\");\n")
+ .append(" }\n")
+ .append(" ").append(zkLocal).append(".requireSignal(")
+ .append(resultLocal).append(".signal());\n")
+ .append(" ").append(resultLocal).append(".assertTrue();\n");
}
out.append(" });\n")
.append(" }\n");
@@ -813,6 +820,7 @@ private void renderInputsClass(StringBuilder out, List inputs) {
.append(" }\n\n")
.append(" public BigInteger[] calculateWitness(CircuitBuilder circuit, CurveId curve) {\n")
.append(" validateCircuit(circuit, __zerojSchema);\n")
+ .append(" __zerojInputs.validate(__zerojSchema, curve);\n")
.append(" return circuit.calculateWitness(toWitnessMap(), curve);\n")
.append(" }\n")
.append(" }\n");
@@ -820,7 +828,8 @@ private void renderInputsClass(StringBuilder out, List inputs) {
private void renderScalarInputMethods(StringBuilder out, InputModel input) {
out.append(" public Inputs ").append(input.javaName()).append("(BigInteger value) {\n")
- .append(" __zerojInputs.put(").append(input.constantName()).append(", value);\n")
+ .append(" __zerojInputs.putChecked(__zerojSchema.input(")
+ .append(input.constantName()).append("), ").append(input.constantName()).append(", value);\n")
.append(" return this;\n")
.append(" }\n\n");
if (!"wait".equals(input.javaName())) {
@@ -831,14 +840,15 @@ private void renderScalarInputMethods(StringBuilder out, InputModel input) {
}
private void renderArrayInputMethods(StringBuilder out, InputModel input) {
- String sizeExpression = "__zerojSchema.input(" + input.constantName() + ").size()";
+ String inputExpr = "__zerojSchema.input(" + input.constantName() + ")";
+ String sizeExpression = inputExpr + ".size()";
out.append(" public Inputs ").append(input.javaName()).append("(int index, BigInteger value) {\n")
.append(" if (index < 0 || index >= ").append(sizeExpression).append(") {\n")
.append(" throw new IllegalArgumentException(")
.append(stringLiteral("index out of bounds for " + input.baseName())).append(");\n")
.append(" }\n")
- .append(" __zerojInputs.put(").append(input.constantName())
- .append(" + \"_\" + index, value);\n")
+ .append(" __zerojInputs.putChecked(").append(inputExpr).append(", ")
+ .append(input.constantName()).append(" + \"_\" + index, value);\n")
.append(" return this;\n")
.append(" }\n\n")
.append(" public Inputs ").append(input.javaName()).append("(int index, long value) {\n")
@@ -846,12 +856,16 @@ private void renderArrayInputMethods(StringBuilder out, InputModel input) {
.append("(index, BigInteger.valueOf(value));\n")
.append(" }\n\n")
.append(" public Inputs ").append(input.javaName()).append("(List values) {\n")
+ .append(" if (values == null) {\n")
+ .append(" throw new NullPointerException(")
+ .append(stringLiteral(input.baseName() + " values must not be null")).append(");\n")
+ .append(" }\n")
.append(" if (values.size() != ").append(sizeExpression).append(") {\n")
.append(" throw new IllegalArgumentException(")
.append(stringLiteral(input.baseName() + " expects ")).append(" + ").append(sizeExpression)
.append(" + \" values\");\n")
.append(" }\n")
- .append(" __zerojInputs.putArray(").append(input.constantName()).append(", values);\n")
+ .append(" __zerojInputs.putArrayChecked(").append(inputExpr).append(", values);\n")
.append(" return this;\n")
.append(" }\n\n");
}
@@ -870,8 +884,8 @@ private void renderNestedArrayInputMethods(StringBuilder out, InputModel input)
.append(" throw new IllegalArgumentException(")
.append(stringLiteral("col out of bounds for " + input.baseName())).append(");\n")
.append(" }\n")
- .append(" __zerojInputs.put(").append(input.constantName())
- .append(" + \"_\" + row + \"_\" + col, value);\n")
+ .append(" __zerojInputs.putChecked(").append(inputExpression).append(", ")
+ .append(input.constantName()).append(" + \"_\" + row + \"_\" + col, value);\n")
.append(" return this;\n")
.append(" }\n\n")
.append(" public Inputs ").append(input.javaName()).append("(int row, int col, long value) {\n")
@@ -880,6 +894,10 @@ private void renderNestedArrayInputMethods(StringBuilder out, InputModel input)
.append(" }\n\n")
.append(" public Inputs ").append(input.javaName())
.append("(List extends List> values) {\n")
+ .append(" if (values == null) {\n")
+ .append(" throw new NullPointerException(")
+ .append(stringLiteral(input.baseName() + " values must not be null")).append(");\n")
+ .append(" }\n")
.append(" if (values.size() != ").append(outerSizeExpression).append(") {\n")
.append(" throw new IllegalArgumentException(")
.append(stringLiteral(input.baseName() + " expects ")).append(" + ").append(outerSizeExpression)
@@ -897,7 +915,7 @@ private void renderNestedArrayInputMethods(StringBuilder out, InputModel input)
.append(" + \" values per row\");\n")
.append(" }\n")
.append(" }\n")
- .append(" __zerojInputs.putNestedArray(").append(input.constantName()).append(", values);\n")
+ .append(" __zerojInputs.putNestedArrayChecked(").append(inputExpression).append(", values);\n")
.append(" return this;\n")
.append(" }\n\n");
}
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..e232d02f 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
@@ -7,6 +7,7 @@
import org.zeroj.api.VerificationKeyRef;
import org.zeroj.api.ZkProofEnvelope;
import org.zeroj.circuit.CircuitBuilder;
+import org.zeroj.circuit.FieldConfig;
import org.zeroj.circuit.annotation.ZkCircuitMetadata;
import org.zeroj.circuit.annotation.ZkCircuitSchema;
import org.zeroj.circuit.lib.poseidon.PoseidonHash;
@@ -22,6 +23,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;
@@ -35,6 +37,7 @@
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -967,7 +970,8 @@ boolean prove() {
var bigIntegerCompilation = compile("test.BigIntegerProof", """
package test;
- import java.math.BigInteger;
+ import java.lang.reflect.InvocationTargetException;
+import java.math.BigInteger;
import org.zeroj.circuit.annotation.*;
@ZKCircuit
@@ -1342,6 +1346,93 @@ ZkBool prove(@Secret ZkBool ok) {
assertTrue(unknown.diagnosticsText().contains("references unknown @CircuitParam: other"));
}
+ @Test
+ void generatedBuildRejectsForeignOrNullProveZkBoolAndValidatesTypedInputs() throws Exception {
+ var foreign = compile("test.ForeignZkBoolCircuit", """
+ package test;
+
+ import org.zeroj.circuit.CircuitBuilder;
+ import org.zeroj.circuit.annotation.*;
+
+ @ZKCircuit
+ public class ForeignZkBoolCircuit {
+ @Prove
+ ZkBool prove(@Secret ZkField x) {
+ var other = CircuitBuilder.create("other").secretVar("y");
+ final ZkBool[] escaped = new ZkBool[1];
+ other.defineSignals(c -> escaped[0] = ZkBool.secret(c, "y"));
+ return escaped[0];
+ }
+ }
+ """);
+ assertTrue(foreign.success(), foreign.diagnosticsText());
+ var foreignEx = assertThrows(InvocationTargetException.class,
+ () -> foreign.load("test.ForeignZkBoolCircuitCircuit").getMethod("build").invoke(null));
+ assertInstanceOf(IllegalArgumentException.class, foreignEx.getCause());
+
+ var returnsNull = compile("test.NullZkBoolCircuit", """
+ package test;
+
+ import org.zeroj.circuit.annotation.*;
+
+ @ZKCircuit
+ public class NullZkBoolCircuit {
+ @Prove
+ ZkBool prove(@Secret ZkField x) {
+ return null;
+ }
+ }
+ """);
+ assertTrue(returnsNull.success(), returnsNull.diagnosticsText());
+ var nullEx = assertThrows(InvocationTargetException.class,
+ () -> returnsNull.load("test.NullZkBoolCircuitCircuit").getMethod("build").invoke(null));
+ assertInstanceOf(NullPointerException.class, nullEx.getCause());
+
+ var typed = compile("test.TypedRangeInputs", """
+ package test;
+
+ import org.zeroj.circuit.annotation.*;
+
+ @ZKCircuit
+ public class TypedRangeInputs {
+ @Prove
+ ZkBool prove(
+ @Public ZkField field,
+ @Secret ZkBool flag,
+ @Secret @UInt(bits = 8) ZkUInt amount) {
+ return flag;
+ }
+ }
+ """);
+ assertTrue(typed.success(), typed.diagnosticsText());
+ Class> gen = typed.load("test.TypedRangeInputsCircuit");
+ CircuitBuilder circuit = (CircuitBuilder) gen.getMethod("build").invoke(null);
+ Object inputs = gen.getMethod("inputs").invoke(null);
+
+ // Out-of-type setters fail immediately
+ var badBool = assertThrows(InvocationTargetException.class,
+ () -> inputs.getClass().getMethod("flag", long.class).invoke(inputs, 2L));
+ assertInstanceOf(IllegalArgumentException.class, badBool.getCause());
+
+ var badUInt = assertThrows(InvocationTargetException.class,
+ () -> inputs.getClass().getMethod("amount", long.class).invoke(inputs, 256L));
+ assertInstanceOf(IllegalArgumentException.class, badUInt.getCause());
+
+ var negField = assertThrows(InvocationTargetException.class,
+ () -> inputs.getClass().getMethod("field", long.class).invoke(inputs, -1L));
+ assertInstanceOf(IllegalArgumentException.class, negField.getCause());
+
+ // Non-canonical >= p field rejected by Inputs.calculateWitness
+ inputs.getClass().getMethod("field", BigInteger.class)
+ .invoke(inputs, FieldConfig.BLS12_381.prime());
+ inputs.getClass().getMethod("flag", long.class).invoke(inputs, 1L);
+ inputs.getClass().getMethod("amount", long.class).invoke(inputs, 42L);
+ var gePrime = assertThrows(InvocationTargetException.class,
+ () -> inputs.getClass().getMethod("calculateWitness", CircuitBuilder.class, CurveId.class)
+ .invoke(inputs, circuit, CurveId.BLS12_381));
+ assertInstanceOf(IllegalArgumentException.class, gePrime.getCause());
+ }
+
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/CircuitAPI.java b/zeroj-circuit-dsl/src/main/java/org/zeroj/circuit/CircuitAPI.java
index 7cbd9627..b429258c 100644
--- a/zeroj-circuit-dsl/src/main/java/org/zeroj/circuit/CircuitAPI.java
+++ b/zeroj-circuit-dsl/src/main/java/org/zeroj/circuit/CircuitAPI.java
@@ -78,19 +78,25 @@ public interface CircuitAPI {
*/
BitDecomposition decompose(Variable a, int nBits);
- /** Recompose a field element from binary variables (LSB first). */
+ /**
+ * Recompose a field element from binary variables (LSB first).
+ *
+ * {@code bits.length} must be in {@code [1, 253]} so the recomposition stays below
+ * every supported scalar field prime when each bit is in {@code {0, 1}}. Callers are
+ * responsible for ensuring each bit wire is constrained to {@code {0, 1}}.
+ */
Variable fromBinary(Variable[] bits);
- /** Bitwise XOR: a ^ b. Both must be boolean. */
+ /** Bitwise XOR: a ^ b. Enforces {@link #assertBoolean} on both operands and returns a proven boolean. */
Variable xor(Variable a, Variable b);
- /** Bitwise AND: a & b. Both must be boolean. */
+ /** Bitwise AND: a & b. Enforces {@link #assertBoolean} on both operands and returns a proven boolean. */
Variable and(Variable a, Variable b);
- /** Bitwise OR: a | b. Both must be boolean. */
+ /** Bitwise OR: a | b. Enforces {@link #assertBoolean} on both operands and returns a proven boolean. */
Variable or(Variable a, Variable b);
- /** Bitwise NOT: !a. Must be boolean. Returns 1 - a. */
+ /** Bitwise NOT: !a. Enforces {@link #assertBoolean} on {@code a} and returns a proven boolean {@code 1 - a}. */
Variable not(Variable a);
// --- Assertions ---
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..6a97e909 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
@@ -8,9 +8,11 @@
*/
class CircuitAPIImpl implements CircuitAPI {
- // Max bit decomposition: 253 for BN254, safe upper bound for all supported curves.
- // BN254 ~253.6 bits, BLS12-381 ~254.8 bits, Pallas ~254.9 bits.
- // We use 253 because it's the tightest constraint (BN254 field order < 2^254).
+ // Max bit decomposition width: 253 bits.
+ // BN254 scalar order r ~ 2^253.57, BLS12-381 r ~ 2^254.85, Pallas r ~ 2^254.99.
+ // 2^bits < p suffices for unique bit decomposition (up to 253 bits on BN254), whereas
+ // difference-underflow checks (lessThan, ZkUInt.sub) require 2^(bits + 1) <= p, i.e. at
+ // most MAX_SAFE_BITS - 1 = 252 bits on BN254 (ADR-0068).
static final int MAX_SAFE_BITS = 253;
private final List gates = new ArrayList<>();
@@ -77,6 +79,7 @@ class CircuitAPIImpl implements CircuitAPI {
this.nextId = 1;
gates.add(new Gate.Const(oneWire, BigInteger.ONE));
constantWireValues.put(oneWire.id(), BigInteger.ONE);
+ booleanWires.add(oneWire.id());
// Public inputs
for (String name : publicVarNames) {
@@ -357,6 +360,9 @@ public Variable constant(BigInteger value) {
var out = newIntermediate();
gates.add(new Gate.Const(out, v));
constantWireValues.put(out.id(), v);
+ if (BigInteger.ZERO.equals(v) || BigInteger.ONE.equals(v)) {
+ booleanWires.add(out.id());
+ }
return out;
});
}
@@ -462,9 +468,16 @@ private void requireRange(Variable v, int nBits, String role) {
@Override
public Variable fromBinary(Variable[] bits) {
- var terms = new ArrayList();
+ requireNotFrozen();
+ Objects.requireNonNull(bits, "bits");
+ if (bits.length == 0 || bits.length > MAX_SAFE_BITS) {
+ throw new IllegalArgumentException(
+ "fromBinary bits length must be in [1, " + MAX_SAFE_BITS + "], got " + bits.length);
+ }
+ var terms = new ArrayList(bits.length);
BigInteger pow2 = BigInteger.ONE;
- for (Variable bit : bits) {
+ for (int i = 0; i < bits.length; i++) {
+ Variable bit = Objects.requireNonNull(bits[i], "bits[" + i + "]");
terms.add(new Gate.Term(pow2, bit));
pow2 = pow2.shiftLeft(1);
}
@@ -478,26 +491,41 @@ public Variable fromBinary(Variable[] bits) {
@Override
public Variable xor(Variable a, Variable b) {
- // a ^ b = a + b - 2*a*b (both must be boolean)
+ // a ^ b = a + b - 2*a*b (operands must be boolean; result is boolean)
+ assertBoolean(a);
+ assertBoolean(b);
var ab = mul(a, b);
var twoAb = add(ab, ab);
- return sub(add(a, b), twoAb);
+ var out = sub(add(a, b), twoAb);
+ booleanWires.add(out.id());
+ return out;
}
@Override
public Variable and(Variable a, Variable b) {
- return mul(a, b);
+ assertBoolean(a);
+ assertBoolean(b);
+ var out = mul(a, b);
+ booleanWires.add(out.id());
+ return out;
}
@Override
public Variable or(Variable a, Variable b) {
// a | b = a + b - a*b
- return sub(add(a, b), mul(a, b));
+ assertBoolean(a);
+ assertBoolean(b);
+ var out = sub(add(a, b), mul(a, b));
+ booleanWires.add(out.id());
+ return out;
}
@Override
public Variable not(Variable a) {
- return sub(oneWire, a);
+ assertBoolean(a);
+ var out = sub(oneWire, a);
+ booleanWires.add(out.id());
+ return out;
}
// --- Assertions ---
@@ -540,6 +568,8 @@ public Variable isZero(Variable a) {
assertEqual(aTimesInv, sub(oneWire, result));
var aTimesResult = mul(a, result);
assertEqual(aTimesResult, constant(0));
+ // Algebraically forces result in {0, 1} for every field element a.
+ booleanWires.add(result.id());
return result;
}
diff --git a/zeroj-circuit-dsl/src/main/java/org/zeroj/circuit/WitnessCalculator.java b/zeroj-circuit-dsl/src/main/java/org/zeroj/circuit/WitnessCalculator.java
index af79d8e6..592564a2 100644
--- a/zeroj-circuit-dsl/src/main/java/org/zeroj/circuit/WitnessCalculator.java
+++ b/zeroj-circuit-dsl/src/main/java/org/zeroj/circuit/WitnessCalculator.java
@@ -2,6 +2,7 @@
import java.math.BigInteger;
import java.util.BitSet;
+import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
@@ -141,26 +142,31 @@ public void set(int id, BigInteger v) {
private static void evaluate(ConstraintGraph graph, Map> inputs,
FieldConfig config, Store witness) {
+ Objects.requireNonNull(inputs, "inputs");
graph.requireCompatibleField(config);
BigInteger p = config.prime();
+ var declaredInputs = new HashSet(
+ graph.publicInputs().size() + graph.secretInputs().size());
+ for (var v : graph.publicInputs()) declaredInputs.add(v.name());
+ for (var v : graph.secretInputs()) declaredInputs.add(v.name());
+ for (String key : inputs.keySet()) {
+ if (!declaredInputs.contains(key)) {
+ throw new IllegalArgumentException("Unknown circuit input: " + key);
+ }
+ }
+
// Wire 0 = 1
witness.set(graph.oneWire().id(), BigInteger.ONE);
- // Set public inputs
+ // Set public inputs (strict canonical [0, p) without silent modular reduction)
for (var v : graph.publicInputs()) {
- var vals = inputs.get(v.name());
- if (vals == null || vals.isEmpty())
- throw new IllegalArgumentException("Missing public input: " + v.name());
- witness.set(v.id(), vals.getFirst().mod(p));
+ witness.set(v.id(), requireCanonicalInput(inputs, v.name(), "public", p));
}
- // Set secret inputs
+ // Set secret inputs (strict canonical [0, p) without silent modular reduction)
for (var v : graph.secretInputs()) {
- var vals = inputs.get(v.name());
- if (vals == null || vals.isEmpty())
- throw new IllegalArgumentException("Missing secret input: " + v.name());
- witness.set(v.id(), vals.getFirst().mod(p));
+ witness.set(v.id(), requireCanonicalInput(inputs, v.name(), "secret", p));
}
// Evaluate gates in topological order
@@ -191,8 +197,8 @@ private static void evaluate(ConstraintGraph graph, Map
case Gate.AssertEq(var left, var right) -> {
if (!witness.get(left.id()).equals(witness.get(right.id()))) {
- throw new ArithmeticException("Constraint violation: "
- + left + "=" + witness.get(left.id()) + " != " + right + "=" + witness.get(right.id()));
+ throw new ArithmeticException("Constraint violation: wire "
+ + left.id() + " != wire " + right.id());
}
}
@@ -262,4 +268,26 @@ private static void evaluate(ConstraintGraph graph, Map
}
}
}
+
+ private static BigInteger requireCanonicalInput(
+ Map> inputs, String name, String visibility, BigInteger prime) {
+ List vals = inputs.get(name);
+ if (vals == null || vals.isEmpty()) {
+ throw new IllegalArgumentException("Missing " + visibility + " input: " + name);
+ }
+ if (vals.size() != 1) {
+ throw new IllegalArgumentException(
+ "Input " + name + " must have exactly 1 value, got " + vals.size());
+ }
+ BigInteger value = vals.getFirst();
+ if (value == null) {
+ throw new IllegalArgumentException("Null value for " + visibility + " input: " + name);
+ }
+ if (value.signum() < 0 || value.compareTo(prime) >= 0) {
+ throw new IllegalArgumentException(
+ "Non-canonical " + visibility + " input " + name
+ + ": expected value in [0, p)");
+ }
+ return value;
+ }
}
diff --git a/zeroj-circuit-dsl/src/main/java/org/zeroj/circuit/r1cs/R1CSConstraintSystem.java b/zeroj-circuit-dsl/src/main/java/org/zeroj/circuit/r1cs/R1CSConstraintSystem.java
index 1daf657a..2352d3d2 100644
--- a/zeroj-circuit-dsl/src/main/java/org/zeroj/circuit/r1cs/R1CSConstraintSystem.java
+++ b/zeroj-circuit-dsl/src/main/java/org/zeroj/circuit/r1cs/R1CSConstraintSystem.java
@@ -6,6 +6,8 @@
import java.math.BigInteger;
import java.util.List;
+import java.util.Map;
+import java.util.Objects;
/**
* A compiled R1CS (Rank-1 Constraint System) for Groth16 proving.
@@ -33,4 +35,140 @@ public R1CSConstraintSystem(FieldConfig fieldConfig, int numWires, int numPublic
public BigInteger prime() { return fieldConfig.prime(); }
public int numConstraints() { return constraints.size(); }
+
+ /**
+ * Curve-generic R1CS witness verifier: checks wire count, wire 0 == 1, canonical field
+ * range {@code [0, prime)} on every witness entry, and every constraint
+ * {@code (A · w) * (B · w) ≡ (C · w) (mod prime)}.
+ *
+ * @throws IllegalArgumentException if the witness is malformed or violates any constraint
+ */
+ public void verifyWitness(BigInteger[] witness) {
+ Objects.requireNonNull(witness, "witness");
+ if (witness.length != numWires) {
+ throw new IllegalArgumentException(
+ "witness.length (" + witness.length + ") must match numWires (" + numWires + ")");
+ }
+ BigInteger mod = prime();
+ validateWitnessElements(witness, mod);
+ if (flat != null) {
+ int rows = flat.rows();
+ for (int i = 0; i < rows; i++) {
+ BigInteger aVal = evalFlatRow(flat, flat.a(), i, witness, mod);
+ BigInteger bVal = evalFlatRow(flat, flat.b(), i, witness, mod);
+ BigInteger cVal = evalFlatRow(flat, flat.c(), i, witness, mod);
+ BigInteger lhs = aVal.multiply(bVal).mod(mod);
+ if (!lhs.equals(cVal)) {
+ throw new IllegalArgumentException(
+ "Witness does not satisfy R1CS constraint " + i);
+ }
+ }
+ } else {
+ verifyWitnessConstraints(constraints, witness, constraints.size(), mod);
+ }
+ }
+
+ /**
+ * Curve-generic R1CS witness verification against an explicit constraint list and field.
+ */
+ public static void verifyWitness(List constraints, BigInteger[] witness, FieldConfig field) {
+ Objects.requireNonNull(field, "field");
+ verifyWitness(constraints, witness, field.prime(), constraints != null ? constraints.size() : 0);
+ }
+
+ /**
+ * Curve-generic R1CS witness verification against the first {@code numConstraints} entries of
+ * {@code constraints} modulo {@code prime}.
+ */
+ public static void verifyWitness(
+ List constraints,
+ BigInteger[] witness,
+ BigInteger prime,
+ int numConstraints) {
+ Objects.requireNonNull(constraints, "constraints");
+ Objects.requireNonNull(witness, "witness");
+ Objects.requireNonNull(prime, "prime");
+ if (prime.signum() <= 0) {
+ throw new IllegalArgumentException("prime must be positive");
+ }
+ if (numConstraints < 0 || numConstraints > constraints.size()) {
+ throw new IllegalArgumentException(
+ "numConstraints (" + numConstraints + ") out of bounds for size " + constraints.size());
+ }
+ validateWitnessElements(witness, prime);
+ verifyWitnessConstraints(constraints, witness, numConstraints, prime);
+ }
+
+ private static void validateWitnessElements(BigInteger[] witness, BigInteger mod) {
+ if (witness.length == 0) {
+ throw new IllegalArgumentException("Witness must not be empty");
+ }
+ for (int i = 0; i < witness.length; i++) {
+ BigInteger v = witness[i];
+ if (v == null || v.signum() < 0 || v.compareTo(mod) >= 0) {
+ throw new IllegalArgumentException(
+ "Witness entry at wire " + i + " is not a canonical field element in [0, p)");
+ }
+ }
+ if (!BigInteger.ONE.equals(witness[0])) {
+ throw new IllegalArgumentException(
+ "witness[0] must be 1 (the constant wire)");
+ }
+ }
+
+ private static void verifyWitnessConstraints(
+ List constraints,
+ BigInteger[] witness,
+ int numConstraints,
+ BigInteger mod) {
+ for (int i = 0; i < numConstraints; i++) {
+ R1CSConstraint c = Objects.requireNonNull(constraints.get(i), "constraints[" + i + "]");
+ if (c.a().isEmpty() && c.b().isEmpty() && c.c().isEmpty()) continue;
+ BigInteger aVal = evalLinearCombination(c.a(), witness, mod);
+ BigInteger bVal = evalLinearCombination(c.b(), witness, mod);
+ BigInteger cVal = evalLinearCombination(c.c(), witness, mod);
+ BigInteger lhs = aVal.multiply(bVal).mod(mod);
+ if (!lhs.equals(cVal)) {
+ throw new IllegalArgumentException(
+ "Witness does not satisfy R1CS constraint " + i);
+ }
+ }
+ }
+
+ private static BigInteger evalFlatRow(
+ R1CSFlat flat, R1CSFlat.Matrix m, int row, BigInteger[] witness, BigInteger mod) {
+ BigInteger sum = BigInteger.ZERO;
+ int end = m.end(row);
+ for (int k = m.start(row); k < end; k++) {
+ int wireIdx = m.wire(k);
+ if (wireIdx < 0 || wireIdx >= witness.length) {
+ throw new IllegalArgumentException(
+ "Constraint references wire " + wireIdx
+ + " outside witness length " + witness.length);
+ }
+ BigInteger coeff = flat.coeff(m, k);
+ if (coeff.signum() != 0) {
+ sum = sum.add(coeff.multiply(witness[wireIdx]));
+ }
+ }
+ return sum.mod(mod);
+ }
+
+ private static BigInteger evalLinearCombination(
+ Map lc, BigInteger[] witness, BigInteger mod) {
+ BigInteger sum = BigInteger.ZERO;
+ for (var entry : lc.entrySet()) {
+ int wireIdx = entry.getKey();
+ if (wireIdx < 0 || wireIdx >= witness.length) {
+ throw new IllegalArgumentException(
+ "Constraint references wire " + wireIdx
+ + " outside witness length " + witness.length);
+ }
+ BigInteger coeff = Objects.requireNonNull(entry.getValue(), "coefficient");
+ if (coeff.signum() != 0) {
+ sum = sum.add(coeff.multiply(witness[wireIdx]));
+ }
+ }
+ return sum.mod(mod);
+ }
}
diff --git a/zeroj-circuit-dsl/src/test/java/org/zeroj/circuit/CircuitDslHardeningTest.java b/zeroj-circuit-dsl/src/test/java/org/zeroj/circuit/CircuitDslHardeningTest.java
new file mode 100644
index 00000000..462334c0
--- /dev/null
+++ b/zeroj-circuit-dsl/src/test/java/org/zeroj/circuit/CircuitDslHardeningTest.java
@@ -0,0 +1,280 @@
+package org.zeroj.circuit;
+
+import org.junit.jupiter.api.Test;
+import org.zeroj.api.CurveId;
+import org.zeroj.api.R1CSConstraint;
+import org.zeroj.circuit.r1cs.R1CSConstraintSystem;
+
+import java.math.BigInteger;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+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;
+
+/**
+ * ADR-0068: raw CircuitAPI boolean enforcement, fromBinary width guard, strict canonical
+ * WitnessCalculator, and curve-generic R1CSConstraintSystem.verifyWitness.
+ */
+class CircuitDslHardeningTest {
+
+ @Test
+ void rawBooleanOpsRejectNonBooleanWitnessesEvenWhenBypassingWitnessCalculator() {
+ List circuits = List.of(
+ CircuitBuilder.create("raw-xor").secretVar("a").secretVar("b").publicVar("out")
+ .define(api -> api.assertEqual(api.xor(api.var("a"), api.var("b")), api.var("out"))),
+ CircuitBuilder.create("raw-and").secretVar("a").secretVar("b").publicVar("out")
+ .define(api -> api.assertEqual(api.and(api.var("a"), api.var("b")), api.var("out"))),
+ CircuitBuilder.create("raw-or").secretVar("a").secretVar("b").publicVar("out")
+ .define(api -> api.assertEqual(api.or(api.var("a"), api.var("b")), api.var("out"))),
+ CircuitBuilder.create("raw-not").secretVar("a").publicVar("out")
+ .define(api -> api.assertEqual(api.not(api.var("a")), api.var("out")))
+ );
+
+ for (CurveId curve : List.of(CurveId.BLS12_381, CurveId.BN254)) {
+ FieldConfig field = FieldConfig.forCurve(curve);
+ BigInteger p = field.prime();
+ for (CircuitBuilder circuit : circuits) {
+ R1CSConstraintSystem r1cs = circuit.compileR1CS(curve);
+ boolean binaryOp = circuit.constraintGraph().secretInputs().size() == 2;
+
+ // Honest boolean witness satisfies both WitnessCalculator and verifyWitness
+ Map> honestInputs = binaryOp
+ ? Map.of("a", List.of(BigInteger.ONE), "b", List.of(BigInteger.ZERO),
+ "out", List.of(circuit.constraintGraph().name().equals("raw-and")
+ ? BigInteger.ZERO : BigInteger.ONE))
+ : Map.of("a", List.of(BigInteger.ONE), "out", List.of(BigInteger.ZERO));
+ BigInteger[] honestWitness = circuit.calculateWitness(honestInputs, curve);
+ assertDoesNotThrow(() -> r1cs.verifyWitness(honestWitness));
+
+ // Non-boolean input a = 2 must be rejected by WitnessCalculator
+ Map> badInputs = binaryOp
+ ? Map.of("a", List.of(BigInteger.TWO), "b", List.of(BigInteger.ZERO),
+ "out", List.of(BigInteger.TWO))
+ : Map.of("a", List.of(BigInteger.TWO), "out", List.of(p.subtract(BigInteger.ONE)));
+ assertThrows(ArithmeticException.class, () -> circuit.calculateWitness(badInputs, curve));
+
+ // Adversarial raw witness bypassing WitnessCalculator with a = 2 (matching algebraic formula)
+ BigInteger[] forged = honestWitness.clone();
+ int aId = circuit.constraintGraph().secretInputs().getFirst().id();
+ int outId = circuit.constraintGraph().publicInputs().getFirst().id();
+ forged[aId] = BigInteger.TWO;
+ if (circuit.constraintGraph().name().equals("raw-not")) {
+ forged[outId] = p.subtract(BigInteger.ONE);
+ } else if (circuit.constraintGraph().name().equals("raw-and")) {
+ forged[outId] = BigInteger.ZERO;
+ } else {
+ forged[outId] = BigInteger.TWO;
+ }
+ assertThrows(IllegalArgumentException.class, () -> r1cs.verifyWitness(forged));
+ }
+ }
+ }
+
+ @Test
+ void derivedBooleansDoNotEmitRedundantAssertBooleanGates() {
+ var graph = CircuitBuilder.create("derived-bools")
+ .secretVar("x").secretVar("y")
+ .define(api -> {
+ var z = api.isZero(api.var("x"));
+ var eq = api.isEqual(api.var("x"), api.var("y"));
+ var c0 = api.constant(0);
+ var c1 = api.constant(1);
+ var combined = api.not(api.or(api.and(z, eq), api.xor(c0, c1)));
+ api.assertBoolean(combined);
+ api.select(combined, api.var("x"), api.var("y"));
+ }).constraintGraph();
+
+ long assertBoolCount = graph.gates().stream()
+ .filter(Gate.AssertBoolean.class::isInstance)
+ .count();
+ assertEquals(0, assertBoolCount,
+ "provably-boolean outputs (0, 1, isZero, isEqual, xor/and/or/not) must not re-emit AssertBoolean");
+ }
+
+ @Test
+ void fromBinaryEnforcesWidthBoundsAndNonNullBits() {
+ assertThrows(IllegalArgumentException.class, () -> CircuitBuilder.create("empty-bits")
+ .define(api -> api.fromBinary(new Variable[0])));
+
+ assertThrows(IllegalArgumentException.class, () -> CircuitBuilder.create("too-wide-bits")
+ .define(api -> {
+ Variable[] bits = new Variable[254];
+ Variable zero = api.constant(0);
+ for (int i = 0; i < bits.length; i++) bits[i] = zero;
+ api.fromBinary(bits);
+ }));
+
+ assertThrows(NullPointerException.class, () -> CircuitBuilder.create("null-bit-entry")
+ .define(api -> api.fromBinary(new Variable[]{api.constant(1), null})));
+
+ // Boundary 1 bit and 253 bits succeed
+ assertDoesNotThrow(() -> CircuitBuilder.create("max-253-bits")
+ .define(api -> {
+ Variable[] bits = new Variable[253];
+ Variable zero = api.constant(0);
+ for (int i = 0; i < bits.length; i++) bits[i] = zero;
+ api.fromBinary(bits);
+ }));
+ }
+
+ @Test
+ void witnessCalculatorRejectsUnknownKeysMultiValueListsNullAndNonCanonicalInputs() {
+ var circuit = CircuitBuilder.create("mul")
+ .publicVar("c").secretVar("a").secretVar("b")
+ .define(api -> api.assertEqual(api.mul(api.var("a"), api.var("b")), api.var("c")));
+ var graph = circuit.constraintGraph();
+ FieldConfig bls = FieldConfig.BLS12_381;
+ BigInteger p = bls.prime();
+
+ // Null map
+ assertThrows(NullPointerException.class, () -> WitnessCalculator.calculate(graph, null, bls));
+
+ // Unknown extra key
+ Map> unknownKey = Map.of(
+ "c", List.of(BigInteger.valueOf(6)),
+ "a", List.of(BigInteger.TWO),
+ "b", List.of(BigInteger.valueOf(3)),
+ "extra", List.of(BigInteger.ZERO));
+ assertThrows(IllegalArgumentException.class, () -> WitnessCalculator.calculate(graph, unknownKey, bls));
+ assertThrows(IllegalArgumentException.class, () -> WitnessCalculator.calculateFlat(graph, unknownKey, bls));
+
+ // Multi-value list
+ Map> multiVal = Map.of(
+ "c", List.of(BigInteger.valueOf(6)),
+ "a", List.of(BigInteger.TWO, BigInteger.ONE),
+ "b", List.of(BigInteger.valueOf(3)));
+ assertThrows(IllegalArgumentException.class, () -> WitnessCalculator.calculate(graph, multiVal, bls));
+
+ // Null element inside list
+ Map> nullElem = new HashMap<>();
+ nullElem.put("c", List.of(BigInteger.valueOf(6)));
+ nullElem.put("a", Collections.singletonList(null));
+ nullElem.put("b", List.of(BigInteger.valueOf(3)));
+ assertThrows(IllegalArgumentException.class, () -> WitnessCalculator.calculate(graph, nullElem, bls));
+
+ // Negative value (no silent mod p)
+ Map> negative = Map.of(
+ "c", List.of(BigInteger.ONE),
+ "a", List.of(BigInteger.ONE.negate()),
+ "b", List.of(BigInteger.ONE.negate()));
+ assertThrows(IllegalArgumentException.class, () -> WitnessCalculator.calculate(graph, negative, bls));
+
+ // Value >= p (no silent mod p) — exception must not leak private input value
+ BigInteger secretSentinel = new BigInteger("98765432109876543210987654321");
+ BigInteger gePrimeVal = p.add(secretSentinel);
+ Map> gePrime = Map.of(
+ "c", List.of(BigInteger.ZERO),
+ "a", List.of(gePrimeVal),
+ "b", List.of(BigInteger.ONE));
+ IllegalArgumentException calcEx = assertThrows(IllegalArgumentException.class,
+ () -> WitnessCalculator.calculate(graph, gePrime, bls));
+ assertEquals(false, calcEx.getMessage().contains(gePrimeVal.toString()),
+ "WitnessCalculator must redact private input value");
+ assertEquals(false, calcEx.getMessage().contains(secretSentinel.toString()),
+ "WitnessCalculator must redact private input value");
+ assertThrows(IllegalArgumentException.class, () -> WitnessCalculator.calculateFlat(graph, gePrime, bls));
+
+ // Gate.AssertEq failure must identify the wire IDs while redacting BOTH private witness values.
+ var eqCircuit = CircuitBuilder.create("secret-eq")
+ .secretVar("s1").secretVar("s2")
+ .define(api -> api.assertEqual(api.var("s1"), api.var("s2")));
+ var eqGraph = eqCircuit.constraintGraph();
+ BigInteger secretLeft = new BigInteger("111111111111");
+ BigInteger secretRight = new BigInteger("222222222222");
+ Map> unequalSecrets = Map.of(
+ "s1", List.of(secretLeft),
+ "s2", List.of(secretRight));
+ int leftId = eqGraph.secretInputs().get(0).id();
+ int rightId = eqGraph.secretInputs().get(1).id();
+
+ ArithmeticException boxedEqEx = assertThrows(ArithmeticException.class,
+ () -> WitnessCalculator.calculate(eqGraph, unequalSecrets, bls));
+ assertTrue(boxedEqEx.getMessage().contains("wire " + leftId)
+ && boxedEqEx.getMessage().contains("wire " + rightId),
+ "AssertEq failure must identify wire IDs, got: " + boxedEqEx.getMessage());
+ assertFalse(boxedEqEx.getMessage().contains(secretLeft.toString()),
+ "AssertEq failure must redact left private witness value");
+ assertFalse(boxedEqEx.getMessage().contains(secretRight.toString()),
+ "AssertEq failure must redact right private witness value");
+
+ ArithmeticException flatEqEx = assertThrows(ArithmeticException.class,
+ () -> WitnessCalculator.calculateFlat(eqGraph, unequalSecrets, bls));
+ assertFalse(flatEqEx.getMessage().contains(secretLeft.toString()),
+ "Flat AssertEq failure must redact left private witness value");
+ assertFalse(flatEqEx.getMessage().contains(secretRight.toString()),
+ "Flat AssertEq failure must redact right private witness value");
+ }
+
+ @Test
+ void curveGenericVerifyWitnessValidatesBothCurvesAndRejectsMalformedWitnesses() {
+ var circuit = CircuitBuilder.create("mul-generic")
+ .publicVar("c").secretVar("a").secretVar("b")
+ .define(api -> api.assertEqual(api.mul(api.var("a"), api.var("b")), api.var("c")));
+
+ for (CurveId curve : List.of(CurveId.BLS12_381, CurveId.BN254)) {
+ R1CSConstraintSystem r1cs = circuit.compileR1CS(curve);
+ BigInteger p = r1cs.prime();
+ BigInteger a = p.subtract(BigInteger.TWO);
+ BigInteger b = BigInteger.valueOf(3);
+ BigInteger c = a.multiply(b).mod(p);
+
+ BigInteger[] witness = circuit.calculateWitness(Map.of(
+ "c", List.of(c), "a", List.of(a), "b", List.of(b)), curve);
+ assertDoesNotThrow(() -> r1cs.verifyWitness(witness));
+ assertDoesNotThrow(() -> R1CSConstraintSystem.verifyWitness(
+ r1cs.constraints(), witness, r1cs.fieldConfig()));
+
+ // Wrong length
+ BigInteger[] shortW = Arrays.copyOf(witness, witness.length - 1);
+ assertThrows(IllegalArgumentException.class, () -> r1cs.verifyWitness(shortW));
+
+ // witness[0] != 1 — must redact private sentinel value
+ BigInteger sentinel = new BigInteger("777666555444333222111");
+ BigInteger[] badWire0 = witness.clone();
+ badWire0[0] = sentinel;
+ IllegalArgumentException wire0Ex = assertThrows(IllegalArgumentException.class,
+ () -> r1cs.verifyWitness(badWire0));
+ assertEquals(false, wire0Ex.getMessage().contains(sentinel.toString()),
+ "verifyWitness must redact wire-0 value");
+
+ // Non-canonical entry >= p
+ BigInteger[] geP = witness.clone();
+ geP[1] = p;
+ assertThrows(IllegalArgumentException.class, () -> r1cs.verifyWitness(geP));
+
+ // Negative entry
+ BigInteger[] negW = witness.clone();
+ negW[1] = BigInteger.ONE.negate();
+ assertThrows(IllegalArgumentException.class, () -> r1cs.verifyWitness(negW));
+
+ // Null entry
+ BigInteger[] nullW = witness.clone();
+ nullW[1] = null;
+ assertThrows(IllegalArgumentException.class, () -> r1cs.verifyWitness(nullW));
+
+ // Violated constraint — must redact witness-derived lhs/cVal in BOTH flat and list paths
+ BigInteger[] badC = witness.clone();
+ badC[1] = sentinel;
+ IllegalArgumentException flatEx = assertThrows(IllegalArgumentException.class,
+ () -> r1cs.verifyWitness(badC));
+ assertEquals(false, flatEx.getMessage().contains(sentinel.toString()),
+ "verifyWitness (flat) must redact witness-derived values");
+ IllegalArgumentException listEx = assertThrows(IllegalArgumentException.class,
+ () -> R1CSConstraintSystem.verifyWitness(r1cs.constraints(), badC, r1cs.fieldConfig()));
+ assertEquals(false, listEx.getMessage().contains(sentinel.toString()),
+ "verifyWitness (list) must redact witness-derived values");
+
+ // Out-of-bounds wire reference in explicit constraint list
+ R1CSConstraint oobConstraint = new R1CSConstraint(Map.of(99, BigInteger.ONE), Map.of(0, BigInteger.ONE), Map.of());
+ assertThrows(IllegalArgumentException.class, () -> R1CSConstraintSystem.verifyWitness(
+ List.of(oobConstraint), witness, r1cs.fieldConfig()));
+ }
+ }
+}
diff --git a/zeroj-circuit-lib/src/main/java/org/zeroj/circuit/lib/AliasCheck.java b/zeroj-circuit-lib/src/main/java/org/zeroj/circuit/lib/AliasCheck.java
index 10e5d85e..0dda4fa6 100644
--- a/zeroj-circuit-lib/src/main/java/org/zeroj/circuit/lib/AliasCheck.java
+++ b/zeroj-circuit-lib/src/main/java/org/zeroj/circuit/lib/AliasCheck.java
@@ -5,57 +5,40 @@
import org.zeroj.circuit.SignalBuilder;
import org.zeroj.circuit.Variable;
-import java.math.BigInteger;
-
/**
- * AliasCheck — asserts that a field element is in canonical range [0, p-1].
- *
- * In finite field arithmetic, {@code p} and {@code 0} are the same element.
- * An "alias" occurs when a value >= p is accepted. This circuit enforces the
- * canonical representation by decomposing to bits and checking the bit pattern
- * is strictly less than the prime.
- *
- * Implementation: decomposes the value to nBits and verifies bit reconstruction
- * matches the original value. Since {@code toBinary} already enforces each bit is
- * boolean and the reconstruction equals the value, any value >= 2^nBits would fail.
- * For values in [p, 2^nBits), we additionally check that the value != p (which the
- * field reduces to 0).
+ * Deprecated misnamed wrapper around {@link RangeCheck}.
*
- * Constraint cost: nBits + 1 constraints.
+ * Important: Despite its historical name, this gadget does not implement
+ * circomlib's {@code AliasCheck()} ({@code bits < p}). It delegates to
+ * {@link CircuitAPI#toBinary(Variable, int)}, which enforces {@code 0 <= value < 2^nBits} for
+ * {@code 1 <= nBits <= 253} — throwing at 254/255 bits and rejecting ~72.4% of valid BLS12-381
+ * scalar field elements at {@code nBits = 253}.
*
- * Circom equivalent: {@code AliasCheck()} from circomlib.
+ * @deprecated Misnamed: enforces {@code 0 <= value < 2^nBits}, not {@code < p}. Use
+ * {@link RangeCheck} for unsigned bit-width range checks.
*/
+@Deprecated(forRemoval = true)
public final class AliasCheck {
private AliasCheck() {}
/**
- * Assert that {@code value} is in canonical field range [0, p-1].
+ * Assert that {@code value} fits in {@code nBits} unsigned bits ({@code 0 <= value < 2^nBits}).
*
- * The binary decomposition via {@code toBinary} already constrains the value to
- * [0, 2^nBits). For primes where p < 2^nBits (which is always the case),
- * this is sufficient because the field automatically reduces values mod p,
- * so any value that would be >= p is already reduced by the witness calculator.
- *
- * The explicit check here is a defense-in-depth: it verifies the bits
- * reconstruct to the original value, preventing a malicious prover from
- * supplying an aliased representation.
- *
- * @param api circuit API
- * @param value the field element to check
- * @param nBits number of bits to decompose (must be >= bitLength of the prime)
+ * @deprecated Use {@link RangeCheck#check(CircuitAPI, Variable, int)}.
*/
+ @Deprecated(forRemoval = true)
public static void check(CircuitAPI api, Variable value, int nBits) {
- // toBinary decomposes to nBits, constrains each bit to {0,1},
- // and constrains reconstruction to equal the value.
- // This enforces value ∈ [0, 2^nBits) ∩ F_p = [0, p-1].
- api.toBinary(value, nBits);
+ RangeCheck.check(api, value, nBits);
}
/**
* Signal API wrapper.
+ *
+ * @deprecated Use {@link RangeCheck#check(SignalBuilder, Signal, int)}.
*/
+ @Deprecated(forRemoval = true)
public static void check(SignalBuilder c, Signal value, int nBits) {
- check(c.api(), value.variable(), nBits);
+ RangeCheck.check(c, value, nBits);
}
}
diff --git a/zeroj-circuit-lib/src/main/java/org/zeroj/circuit/lib/Binary.java b/zeroj-circuit-lib/src/main/java/org/zeroj/circuit/lib/Binary.java
index 1274117a..5f98cee3 100644
--- a/zeroj-circuit-lib/src/main/java/org/zeroj/circuit/lib/Binary.java
+++ b/zeroj-circuit-lib/src/main/java/org/zeroj/circuit/lib/Binary.java
@@ -3,6 +3,8 @@
import org.zeroj.circuit.CircuitAPI;
import org.zeroj.circuit.Variable;
+import java.util.Objects;
+
/**
* Bit manipulation circuit utilities.
*/
@@ -44,21 +46,41 @@ public static Variable[] bitXor(CircuitAPI api, Variable[] a, Variable[] b) {
return result;
}
- /** Circular left rotation of a bit array (free — just index shifting). */
+ /**
+ * Circular left rotation of an LSB-first bit array (free — index remapping only).
+ *
+ * Moves bit {@code j} to bit position {@code (j + n) mod len}, so {@code rotateLeft(0x01, 1)}
+ * produces {@code 0x02}. Negative {@code n} rotates right by {@code -n}.
+ */
public static Variable[] rotateLeft(Variable[] bits, int n) {
+ Objects.requireNonNull(bits, "bits");
int len = bits.length;
- n = n % len;
+ if (len == 0) {
+ throw new IllegalArgumentException("bits must not be empty");
+ }
+ int shift = Math.floorMod(n, len);
var result = new Variable[len];
- for (int i = 0; i < len; i++) result[i] = bits[(i + n) % len];
+ for (int i = 0; i < len; i++) {
+ result[i] = bits[(i - shift + len) % len];
+ }
return result;
}
- /** Logical right shift of a bit array with zero fill (free — index shifting). */
+ /**
+ * Logical right shift of an LSB-first bit array with zero fill (free — index remapping only).
+ *
+ * @throws IllegalArgumentException if {@code n < 0}
+ */
public static Variable[] shiftRight(CircuitAPI api, Variable[] bits, int n) {
+ Objects.requireNonNull(api, "api");
+ Objects.requireNonNull(bits, "bits");
+ if (n < 0) {
+ throw new IllegalArgumentException("Shift amount must be non-negative: " + n);
+ }
var result = new Variable[bits.length];
var zero = api.constant(0);
for (int i = 0; i < bits.length; i++) {
- result[i] = (i + n < bits.length) ? bits[i + n] : zero;
+ result[i] = (n < bits.length - i) ? bits[i + n] : zero;
}
return result;
}
diff --git a/zeroj-circuit-lib/src/main/java/org/zeroj/circuit/lib/PoseidonN.java b/zeroj-circuit-lib/src/main/java/org/zeroj/circuit/lib/PoseidonN.java
index ab9db85a..c7b7526f 100644
--- a/zeroj-circuit-lib/src/main/java/org/zeroj/circuit/lib/PoseidonN.java
+++ b/zeroj-circuit-lib/src/main/java/org/zeroj/circuit/lib/PoseidonN.java
@@ -7,37 +7,49 @@
import org.zeroj.circuit.lib.poseidon.PoseidonParams;
import org.zeroj.circuit.lib.poseidon.PoseidonParamsBN254T3;
+import java.util.Objects;
+
/**
- * Variable-arity Poseidon hash — left-folds pairs through the two-input
- * {@link Poseidon} gadget.
- *
- * {@code PoseidonN(a, b, c, d) = Poseidon(Poseidon(Poseidon(a, b), c), d)}
- *
- *
This is the practical approach used by most ZK applications: simple,
- * widely compatible, and produces ~330 constraints per pair rather than per
- * element. A true variable-width Poseidon would use separate MDS matrices
- * and round constants per arity; we do not support that today.
+ * Fixed-arity folded Poseidon hash — left-folds pairs through the two-input
+ * {@link Poseidon} gadget:
+ * {@code PoseidonN(a, b, c, d) = Poseidon(Poseidon(Poseidon(a, b), c), d)}.
*
- *
All overloads forward to {@link Poseidon}; see there for param/preset
- * selection and interop notes.
+ *
Security warning (fixed-arity only — not domain-separated across lengths):
+ * Because this construction folds without encoding input length or arity, distinct input
+ * tuples of different lengths collide trivially:
+ *
+ * - {@code PoseidonN(x) == Poseidon(x, 0) == PoseidonN(x, 0)}
+ * - {@code PoseidonN(a, b, c) == Poseidon(Poseidon(a, b), c) == PoseidonN(Poseidon(a, b), c)}
+ *
+ * Never accept variable-length inputs under the same commitment or hash domain without
+ * prepending an explicit domain separator and length tag.
*
- * Circom equivalent: {@code Poseidon(nInputs)} from circomlib (folded).
+ *
Interop note: This is not equivalent to circomlib's {@code Poseidon(nInputs)},
+ * which uses a width-{@code (nInputs + 1)} permutation with arity-specific MDS matrices and round
+ * constants. All overloads forward to two-input {@link Poseidon}; pass explicit
+ * {@link PoseidonParams} (e.g. {@link org.zeroj.circuit.lib.poseidon.PoseidonParamsBLS12_381T3#INSTANCE})
+ * for BLS12-381 circuits.
*/
public final class PoseidonN {
private PoseidonN() {}
/**
- * Hash N inputs under the given {@link PoseidonParams} using folded two-input
- * Poseidon.
+ * Hash a fixed-arity tuple of inputs under the given {@link PoseidonParams} using left-folded
+ * two-input Poseidon.
*
- * Single-input semantics: {@code PoseidonN(x) == Poseidon(x, 0)}. This
- * is a ZeroJ-specific convention (no published Poseidon spec defines a
- * 1-arity case). If spec interop with an external 1-input Poseidon is
- * required, hash {@code (x, 0)} explicitly.
+ *
Single-input semantics: {@code PoseidonN(x) == Poseidon(x, 0)} (collides with 2-input
+ * {@code PoseidonN(x, 0)}). Callers requiring cross-arity domain separation must prepend an
+ * explicit domain tag and arity element.
*/
public static Variable hash(CircuitAPI api, PoseidonParams params, Variable... inputs) {
+ Objects.requireNonNull(api, "api");
+ Objects.requireNonNull(params, "params");
+ Objects.requireNonNull(inputs, "inputs");
if (inputs.length == 0) throw new IllegalArgumentException("inputs must not be empty");
+ for (int i = 0; i < inputs.length; i++) {
+ Objects.requireNonNull(inputs[i], "inputs[" + i + "]");
+ }
if (inputs.length == 1) {
return Poseidon.hash(api, params, inputs[0], api.constant(0));
}
@@ -50,8 +62,18 @@ public static Variable hash(CircuitAPI api, PoseidonParams params, Variable... i
/** Signal-API variant. */
public static Signal hash(SignalBuilder c, PoseidonParams params, Signal... inputs) {
+ Objects.requireNonNull(c, "c");
+ Objects.requireNonNull(params, "params");
+ Objects.requireNonNull(inputs, "inputs");
Variable[] vars = new Variable[inputs.length];
- for (int i = 0; i < inputs.length; i++) vars[i] = inputs[i].variable();
+ for (int i = 0; i < inputs.length; i++) {
+ Signal input = Objects.requireNonNull(inputs[i], "inputs[" + i + "]");
+ if (!input.isFrom(c)) {
+ throw new IllegalArgumentException(
+ "inputs[" + i + "] does not belong to the given SignalBuilder");
+ }
+ vars[i] = input.variable();
+ }
return c.wrap(hash(c.api(), params, vars));
}
diff --git a/zeroj-circuit-lib/src/main/java/org/zeroj/circuit/lib/RangeCheck.java b/zeroj-circuit-lib/src/main/java/org/zeroj/circuit/lib/RangeCheck.java
new file mode 100644
index 00000000..9c5f6d13
--- /dev/null
+++ b/zeroj-circuit-lib/src/main/java/org/zeroj/circuit/lib/RangeCheck.java
@@ -0,0 +1,47 @@
+package org.zeroj.circuit.lib;
+
+import org.zeroj.circuit.CircuitAPI;
+import org.zeroj.circuit.Signal;
+import org.zeroj.circuit.SignalBuilder;
+import org.zeroj.circuit.Variable;
+
+import java.util.Objects;
+
+/**
+ * Unsigned bit-width range check — constrains {@code 0 <= value < 2^nBits}.
+ *
+ * Decomposes {@code value} into {@code nBits} boolean wires via
+ * {@link CircuitAPI#toBinary(Variable, int)} (enforcing {@code 1 <= nBits <= 253}).
+ *
+ * Scope note: This checks {@code value < 2^nBits}; it does not perform a
+ * strict {@code < p} prime-modulus alias check on an arbitrary 254/255-bit bit vector. For
+ * 256-bit big-endian BLS12-381 canonical-key checks, compare explicitly against the BLS12-381
+ * scalar modulus (as in {@code ZkJmtCanonicalKey} / {@code ZkMpf}).
+ */
+public final class RangeCheck {
+
+ private RangeCheck() {}
+
+ /**
+ * Assert that {@code value} fits in {@code nBits} unsigned bits ({@code 0 <= value < 2^nBits}).
+ *
+ * @param api circuit API
+ * @param value field element to range-constrain
+ * @param nBits unsigned bit width in {@code [1, 253]}
+ */
+ public static void check(CircuitAPI api, Variable value, int nBits) {
+ Objects.requireNonNull(api, "api");
+ Objects.requireNonNull(value, "value");
+ api.toBinary(value, nBits);
+ }
+
+ /** Signal API wrapper for {@link #check(CircuitAPI, Variable, int)}. */
+ public static void check(SignalBuilder c, Signal value, int nBits) {
+ Objects.requireNonNull(c, "c");
+ Objects.requireNonNull(value, "value");
+ if (!value.isFrom(c)) {
+ throw new IllegalArgumentException("Signal does not belong to the given SignalBuilder");
+ }
+ check(c.api(), value.variable(), nBits);
+ }
+}
diff --git a/zeroj-circuit-lib/src/main/java/org/zeroj/circuit/lib/SignalBinary.java b/zeroj-circuit-lib/src/main/java/org/zeroj/circuit/lib/SignalBinary.java
index 5b951cf1..ccf59633 100644
--- a/zeroj-circuit-lib/src/main/java/org/zeroj/circuit/lib/SignalBinary.java
+++ b/zeroj-circuit-lib/src/main/java/org/zeroj/circuit/lib/SignalBinary.java
@@ -3,6 +3,8 @@
import org.zeroj.circuit.Signal;
import org.zeroj.circuit.SignalBuilder;
+import java.util.Objects;
+
/**
* Bit manipulation using the Signal API.
*
@@ -49,12 +51,23 @@ public static Signal[] bitXor(Signal[] a, Signal[] b) {
return result;
}
- /** Circular left rotation (free — just index shift). */
+ /**
+ * Circular left rotation of an LSB-first bit array (free — index remapping only).
+ *
+ * Moves bit {@code j} to bit position {@code (j + n) mod len}, so {@code rotateLeft(0x01, 1)}
+ * produces {@code 0x02}. Negative {@code n} rotates right by {@code -n}.
+ */
public static Signal[] rotateLeft(Signal[] bits, int n) {
+ Objects.requireNonNull(bits, "bits");
int len = bits.length;
- n = n % len;
+ if (len == 0) {
+ throw new IllegalArgumentException("bits must not be empty");
+ }
+ int shift = Math.floorMod(n, len);
var result = new Signal[len];
- for (int i = 0; i < len; i++) result[i] = bits[(i + n) % len];
+ for (int i = 0; i < len; i++) {
+ result[i] = bits[(i - shift + len) % len];
+ }
return result;
}
}
diff --git a/zeroj-circuit-lib/src/test/java/org/zeroj/circuit/lib/GadgetHardeningTest.java b/zeroj-circuit-lib/src/test/java/org/zeroj/circuit/lib/GadgetHardeningTest.java
new file mode 100644
index 00000000..e11ab95a
--- /dev/null
+++ b/zeroj-circuit-lib/src/test/java/org/zeroj/circuit/lib/GadgetHardeningTest.java
@@ -0,0 +1,203 @@
+package org.zeroj.circuit.lib;
+
+import org.junit.jupiter.api.Test;
+import org.zeroj.api.CurveId;
+import org.zeroj.circuit.CircuitBuilder;
+import org.zeroj.circuit.Signal;
+import org.zeroj.circuit.Variable;
+import org.zeroj.circuit.lib.poseidon.PoseidonHash;
+import org.zeroj.circuit.lib.poseidon.PoseidonParamsBLS12_381T3;
+
+import java.math.BigInteger;
+import java.util.List;
+import java.util.Map;
+
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+/**
+ * ADR-0068: Binary/SignalBinary.rotateLeft & shiftRight, RangeCheck / deprecated AliasCheck,
+ * and PoseidonN validation.
+ */
+class GadgetHardeningTest {
+
+ @Test
+ void binaryAndSignalBinaryRotateLeftMatchIntegerLeftRotation() {
+ int[][] cases = {
+ {0x01, 1, 0x02},
+ {0x80, 1, 0x01},
+ {0xA5, 3, 0x2D},
+ {0x01, -1, 0x80},
+ {0x01, 0, 0x01},
+ {0x01, 8, 0x01},
+ {0xA5, -3, 0xB4},
+ {0x01, Integer.MIN_VALUE, 0x01} // -2^31 mod 8 == 0
+ };
+
+ for (int[] tc : cases) {
+ int input = tc[0];
+ int shift = tc[1];
+ int expected = tc[2];
+
+ var varCircuit = CircuitBuilder.create("bin-rotl-" + shift)
+ .secretVar("x").publicVar("out")
+ .define(api -> {
+ var bits = Binary.num2Bits(api, api.var("x"), 8);
+ var rotated = Binary.rotateLeft(bits, shift);
+ api.assertEqual(Binary.bits2Num(api, rotated), api.var("out"));
+ });
+ var varR1cs = varCircuit.compileR1CS(CurveId.BLS12_381);
+ var varWitness = varCircuit.calculateWitness(Map.of(
+ "x", List.of(BigInteger.valueOf(input)),
+ "out", List.of(BigInteger.valueOf(expected))), CurveId.BLS12_381);
+ assertDoesNotThrow(() -> varR1cs.verifyWitness(varWitness));
+
+ var sigCircuit = CircuitBuilder.create("sig-rotl-" + shift)
+ .secretVar("x").publicVar("out")
+ .defineSignals(c -> {
+ var bits = SignalBinary.num2Bits(c, c.privateInput("x"), 8);
+ var rotated = SignalBinary.rotateLeft(bits, shift);
+ c.assertEqual(SignalBinary.bits2Num(c, rotated), c.publicInput("out"));
+ });
+ var sigR1cs = sigCircuit.compileR1CS(CurveId.BLS12_381);
+ var sigWitness = sigCircuit.calculateWitness(Map.of(
+ "x", List.of(BigInteger.valueOf(input)),
+ "out", List.of(BigInteger.valueOf(expected))), CurveId.BLS12_381);
+ assertDoesNotThrow(() -> sigR1cs.verifyWitness(sigWitness));
+ }
+
+ assertThrows(NullPointerException.class, () -> Binary.rotateLeft(null, 1));
+ assertThrows(IllegalArgumentException.class, () -> Binary.rotateLeft(new Variable[0], 1));
+ assertThrows(NullPointerException.class, () -> SignalBinary.rotateLeft(null, 1));
+ assertThrows(IllegalArgumentException.class,
+ () -> SignalBinary.rotateLeft(new Signal[0], 1));
+ }
+
+ @Test
+ void binaryShiftRightGuardsNegativeAndLargeShifts() {
+ var circuit = CircuitBuilder.create("bin-shr")
+ .secretVar("x").publicVar("s1").publicVar("s8").publicVar("sMax")
+ .define(api -> {
+ var bits = Binary.num2Bits(api, api.var("x"), 8);
+ api.assertEqual(Binary.bits2Num(api, Binary.shiftRight(api, bits, 1)), api.var("s1"));
+ api.assertEqual(Binary.bits2Num(api, Binary.shiftRight(api, bits, 8)), api.var("s8"));
+ api.assertEqual(Binary.bits2Num(api, Binary.shiftRight(api, bits, Integer.MAX_VALUE)), api.var("sMax"));
+ });
+ var witness = circuit.calculateWitness(Map.of(
+ "x", List.of(BigInteger.valueOf(0xA5)),
+ "s1", List.of(BigInteger.valueOf(0x52)),
+ "s8", List.of(BigInteger.ZERO),
+ "sMax", List.of(BigInteger.ZERO)), CurveId.BLS12_381);
+ assertDoesNotThrow(() -> circuit.compileR1CS(CurveId.BLS12_381).verifyWitness(witness));
+
+ assertThrows(IllegalArgumentException.class, () -> CircuitBuilder.create("bin-shr-neg")
+ .secretVar("x")
+ .define(api -> Binary.shiftRight(api, Binary.num2Bits(api, api.var("x"), 8), -1)));
+ }
+
+ @Test
+ @SuppressWarnings("removal")
+ void rangeCheckAndDeprecatedAliasCheckEnforceBitWidthBounds() {
+ var circuit = CircuitBuilder.create("range-8")
+ .secretVar("x")
+ .define(api -> RangeCheck.check(api, api.var("x"), 8));
+ var r1cs = circuit.compileR1CS(CurveId.BLS12_381);
+ assertDoesNotThrow(() -> r1cs.verifyWitness(
+ circuit.calculateWitness(Map.of("x", List.of(BigInteger.valueOf(255))), CurveId.BLS12_381)));
+ assertThrows(ArithmeticException.class, () ->
+ circuit.calculateWitness(Map.of("x", List.of(BigInteger.valueOf(256))), CurveId.BLS12_381));
+
+ // 254 bits rejected at definition time (not a < p alias check)
+ assertThrows(IllegalArgumentException.class, () -> CircuitBuilder.create("range-254")
+ .secretVar("x")
+ .define(api -> RangeCheck.check(api, api.var("x"), 254)));
+ assertThrows(IllegalArgumentException.class, () -> CircuitBuilder.create("alias-254")
+ .secretVar("x")
+ .define(api -> AliasCheck.check(api, api.var("x"), 254)));
+ }
+
+ @Test
+ void poseidonNRejectsNullInputsAndMatchesFoldedHostHash() {
+ assertThrows(NullPointerException.class, () -> CircuitBuilder.create("p-null")
+ .define(api -> PoseidonN.hash(api, PoseidonParamsBLS12_381T3.INSTANCE, (Variable[]) null)));
+ assertThrows(NullPointerException.class, () -> CircuitBuilder.create("p-null-elem")
+ .secretVar("x")
+ .define(api -> PoseidonN.hash(api, PoseidonParamsBLS12_381T3.INSTANCE, api.var("x"), null)));
+
+ BigInteger a = BigInteger.valueOf(11);
+ BigInteger b = BigInteger.valueOf(22);
+ BigInteger c = BigInteger.valueOf(33);
+ BigInteger expected = PoseidonHash.hash(
+ PoseidonParamsBLS12_381T3.INSTANCE,
+ PoseidonHash.hash(PoseidonParamsBLS12_381T3.INSTANCE, a, b),
+ c);
+
+ var circuit = CircuitBuilder.create("poseidon-n-3")
+ .secretVar("a").secretVar("b").secretVar("c").publicVar("h")
+ .define(api -> api.assertEqual(
+ PoseidonN.hash(api, PoseidonParamsBLS12_381T3.INSTANCE,
+ api.var("a"), api.var("b"), api.var("c")),
+ api.var("h")));
+ var witness = circuit.calculateWitness(Map.of(
+ "a", List.of(a), "b", List.of(b), "c", List.of(c), "h", List.of(expected)),
+ CurveId.BLS12_381);
+ assertEquals(expected, witness[1]);
+ assertDoesNotThrow(() -> circuit.compileR1CS(CurveId.BLS12_381).verifyWitness(witness));
+
+ // Same-builder positive control for Signal-API RangeCheck and PoseidonN
+ var sigCircuit = CircuitBuilder.create("signal-range-poseidon")
+ .secretVar("a").secretVar("b").publicVar("h")
+ .defineSignals(s -> {
+ var sa = s.privateInput("a");
+ var sb = s.privateInput("b");
+ RangeCheck.check(s, sa, 8);
+ s.assertEqual(PoseidonN.hash(s, PoseidonParamsBLS12_381T3.INSTANCE, sa, sb),
+ s.publicInput("h"));
+ });
+ BigInteger h2 = PoseidonHash.hash(PoseidonParamsBLS12_381T3.INSTANCE, a, b);
+ var sigWitness = sigCircuit.calculateWitness(
+ Map.of("a", List.of(a), "b", List.of(b), "h", List.of(h2)), CurveId.BLS12_381);
+ assertDoesNotThrow(() -> sigCircuit.compileR1CS(CurveId.BLS12_381).verifyWitness(sigWitness));
+ }
+
+ @Test
+ @SuppressWarnings("removal")
+ void signalRangeCheckAliasCheckAndPoseidonNRejectForeignBuilderSignalsWithOverlappingWireIds() {
+ // Foreign builder allocates wire ID 1 for "x" — same wire ID as local builder's "x".
+ final Signal[] foreignSignal = new Signal[1];
+ CircuitBuilder.create("foreign-owner")
+ .secretVar("x")
+ .defineSignals(foreign -> foreignSignal[0] = foreign.privateInput("x"));
+
+ // RangeCheck rejects foreign signal before emitting gates
+ assertThrows(IllegalArgumentException.class, () -> CircuitBuilder.create("local-range")
+ .secretVar("x")
+ .defineSignals(local -> {
+ local.privateInput("x");
+ RangeCheck.check(local, foreignSignal[0], 8);
+ }));
+
+ // Deprecated AliasCheck inherits ownership check via RangeCheck
+ assertThrows(IllegalArgumentException.class, () -> CircuitBuilder.create("local-alias")
+ .secretVar("x")
+ .defineSignals(local -> {
+ local.privateInput("x");
+ AliasCheck.check(local, foreignSignal[0], 8);
+ }));
+
+ // PoseidonN rejects foreign signal in first OR second position atomically
+ assertThrows(IllegalArgumentException.class, () -> CircuitBuilder.create("local-poseidon-0")
+ .secretVar("x").secretVar("y")
+ .defineSignals(local -> {
+ var ly = local.privateInput("y");
+ PoseidonN.hash(local, PoseidonParamsBLS12_381T3.INSTANCE, foreignSignal[0], ly);
+ }));
+ assertThrows(IllegalArgumentException.class, () -> CircuitBuilder.create("local-poseidon-1")
+ .secretVar("x").secretVar("y")
+ .defineSignals(local -> {
+ var lx = local.privateInput("x");
+ PoseidonN.hash(local, PoseidonParamsBLS12_381T3.INSTANCE, lx, foreignSignal[0]);
+ }));
+ }
+}
diff --git a/zeroj-circuit-lib/src/test/java/org/zeroj/circuit/lib/NewStdlibTest.java b/zeroj-circuit-lib/src/test/java/org/zeroj/circuit/lib/NewStdlibTest.java
index 6f9920b1..0d638ed4 100644
--- a/zeroj-circuit-lib/src/test/java/org/zeroj/circuit/lib/NewStdlibTest.java
+++ b/zeroj-circuit-lib/src/test/java/org/zeroj/circuit/lib/NewStdlibTest.java
@@ -24,6 +24,7 @@ class NewStdlibTest {
// ===================================================================
@Test
+ @SuppressWarnings("removal")
void aliasCheck_validValue_passes() {
var circuit = CircuitBuilder.create("alias-test")
.secretVar("value")
@@ -34,6 +35,7 @@ void aliasCheck_validValue_passes() {
}
@Test
+ @SuppressWarnings("removal")
void aliasCheck_largeValid_passes() {
var circuit = CircuitBuilder.create("alias-test")
.secretVar("value")
diff --git a/zeroj-circuit-lib/src/test/java/org/zeroj/circuit/lib/hash/Sha512SecurityTest.java b/zeroj-circuit-lib/src/test/java/org/zeroj/circuit/lib/hash/Sha512SecurityTest.java
index 12208710..7beb8be2 100644
--- a/zeroj-circuit-lib/src/test/java/org/zeroj/circuit/lib/hash/Sha512SecurityTest.java
+++ b/zeroj-circuit-lib/src/test/java/org/zeroj/circuit/lib/hash/Sha512SecurityTest.java
@@ -56,12 +56,17 @@ void bitInterfaceUsesMsbFirstOrderAndEnforcesBooleanInputs() throws Exception {
var relation = circuit.compileR1CS(CURVE);
var witness = circuit.calculateWitness(inputs, CURVE);
assertTrue(satisfied(relation, witness));
- for (BigInteger invalid : List.of(BigInteger.TWO, BigInteger.ONE.negate())) {
+ // Non-canonical negative input rejected before circuit evaluation (ADR-0068)
+ var negativeBit = new HashMap<>(inputs);
+ negativeBit.put("m0", List.of(BigInteger.ONE.negate()));
+ assertThrows(IllegalArgumentException.class, () -> circuit.calculateWitness(negativeBit, CURVE));
+ // Canonical non-binary field elements (2 and p - 1) rejected by circuit boolean constraints
+ for (BigInteger invalid : List.of(BigInteger.TWO, relation.prime().subtract(BigInteger.ONE))) {
var bad = new HashMap<>(inputs);
bad.put("m0", List.of(invalid));
assertThrows(ArithmeticException.class, () -> circuit.calculateWitness(bad, CURVE));
assertMutationRejected(relation, witness, circuit.constraintGraph().secretInputs().getFirst().id(),
- invalid.mod(relation.prime()));
+ invalid);
}
// One changed legitimate input bit, with the old digest, must also reject.
var wrongMessage = new HashMap<>(inputs);
@@ -88,9 +93,13 @@ void byteInterfaceRejectsOutOfRangeAndWrongMessageInputs() throws Exception {
byte[] digest = MessageDigest.getInstance("SHA-512").digest(message);
var circuit = byteCircuit(message.length);
var inputs = byteInputs(message, digest);
- for (int invalid : new int[]{-1, 256, 257}) {
+ var negativeByte = new HashMap<>(inputs);
+ negativeByte.put("m0", List.of(BigInteger.ONE.negate()));
+ assertThrows(IllegalArgumentException.class, () -> circuit.calculateWitness(negativeByte, CURVE));
+ BigInteger pMinusOne = circuit.compileR1CS(CURVE).prime().subtract(BigInteger.ONE);
+ for (BigInteger invalid : List.of(pMinusOne, BigInteger.valueOf(256), BigInteger.valueOf(257))) {
var bad = new HashMap<>(inputs);
- bad.put("m0", List.of(BigInteger.valueOf(invalid)));
+ bad.put("m0", List.of(invalid));
assertThrows(ArithmeticException.class, () -> circuit.calculateWitness(bad, CURVE));
}
var wrongMessage = new HashMap<>(inputs);
diff --git a/zeroj-circuit-lib/src/test/java/org/zeroj/circuit/lib/zk/PedersenHomomorphicApiTest.java b/zeroj-circuit-lib/src/test/java/org/zeroj/circuit/lib/zk/PedersenHomomorphicApiTest.java
index 304bcff8..e04a1490 100644
--- a/zeroj-circuit-lib/src/test/java/org/zeroj/circuit/lib/zk/PedersenHomomorphicApiTest.java
+++ b/zeroj-circuit-lib/src/test/java/org/zeroj/circuit/lib/zk/PedersenHomomorphicApiTest.java
@@ -370,12 +370,13 @@ void costPins() {
R1CSConstraintSystem transfer = transferCircuit().compileR1CS(CurveId.BLS12_381);
// witnessAffine (5 rows) + [l]·P (EdDSA's verifyStrict − verifyWithRegisteredKey gap)
- // + the local Z ≠ 0 guard of isIdentity. The low-level, self-validating entry point on
+ // + the local Z ≠ 0 guard of isIdentity (minus 1 redundant AssertBoolean saved by
+ // ADR-0068 derived-boolean tracking). The low-level, self-validating entry point on
// raw coordinates is pinned at 5,304 in InCircuitJubjubSubgroupTest.
assertAll(
- () -> assertEquals(5_294, subgroupOnEstablished.constraints().size(), "subgroup assertion rows"),
- () -> assertEquals(340_431, nnz(subgroupOnEstablished), "subgroup assertion nonzeros"),
- () -> assertEquals(5_294, witnessed.constraints().size(), "witnessInSubgroup rows"),
+ () -> assertEquals(5_293, subgroupOnEstablished.constraints().size(), "subgroup assertion rows"),
+ () -> assertEquals(340_428, nnz(subgroupOnEstablished), "subgroup assertion nonzeros"),
+ () -> assertEquals(5_293, witnessed.constraints().size(), "witnessInSubgroup rows"),
() -> assertEquals(5_545, transfer.constraints().size(), "2-in/1-out + fee transfer rows"),
() -> assertEquals(30_027, nnz(transfer), "2-in/1-out + fee transfer nonzeros"));
}
diff --git a/zeroj-crypto/src/main/java/org/zeroj/crypto/groth16/Groth16Prover.java b/zeroj-crypto/src/main/java/org/zeroj/crypto/groth16/Groth16Prover.java
index 7e7c1f58..608b14b7 100644
--- a/zeroj-crypto/src/main/java/org/zeroj/crypto/groth16/Groth16Prover.java
+++ b/zeroj-crypto/src/main/java/org/zeroj/crypto/groth16/Groth16Prover.java
@@ -71,7 +71,7 @@ public static Groth16Proof prove(
if (witness == null || witness.length == 0)
throw new IllegalArgumentException("Witness must not be null or empty");
if (!BigInteger.ONE.equals(witness[0]))
- throw new IllegalArgumentException("witness[0] must be 1 (the constant wire), got " + witness[0]);
+ throw new IllegalArgumentException("witness[0] must be 1 (the constant wire)");
if (witness.length != numWires)
throw new IllegalArgumentException(
"witness.length (" + witness.length + ") must match numWires (" + numWires + ")");
@@ -404,16 +404,45 @@ private static BigInteger randomScalar(SecureRandom rng) {
}
/**
- * Validate that the witness satisfies all non-empty R1CS constraints.
- * Throws IllegalArgumentException if any constraint is violated.
+ * Validate that a BN254 witness satisfies all non-empty R1CS constraints.
*
- * Use this with standard R1CS constraints (from .r1cs files), NOT with .zkey
- * Section 4 constraints which use a different encoding where C is implicit.
+ * Deprecated: This method is hard-wired to the legacy BN254 scalar field modulus and
+ * requires explicit legacy opt-in via {@link LegacyCurvePolicy}. Use the curve-generic
+ * {@link org.zeroj.circuit.r1cs.R1CSConstraintSystem#verifyWitness} instead.
+ *
+ * @deprecated Hard-wired to BN254; use {@link org.zeroj.circuit.r1cs.R1CSConstraintSystem#verifyWitness}
+ * for curve-generic witness verification.
*/
+ @Deprecated(forRemoval = true)
public static void validateWitness(List constraints, BigInteger[] witness, int numConstraints) {
+ LegacyCurvePolicy.requireLegacyBn254Enabled();
+ if (constraints == null) {
+ throw new IllegalArgumentException("constraints must not be null");
+ }
+ if (witness == null || witness.length == 0) {
+ throw new IllegalArgumentException("Witness must not be null or empty");
+ }
+ if (numConstraints < 0 || numConstraints > constraints.size()) {
+ throw new IllegalArgumentException(
+ "numConstraints (" + numConstraints + ") out of bounds for size " + constraints.size());
+ }
BigInteger mod = MontFr254.modulus();
+ for (int i = 0; i < witness.length; i++) {
+ BigInteger v = witness[i];
+ if (v == null || v.signum() < 0 || v.compareTo(mod) >= 0) {
+ throw new IllegalArgumentException(
+ "Witness entry at wire " + i + " is not a canonical BN254 scalar");
+ }
+ }
+ if (!BigInteger.ONE.equals(witness[0])) {
+ throw new IllegalArgumentException(
+ "witness[0] must be 1 (the constant wire)");
+ }
for (int i = 0; i < numConstraints; i++) {
var c = constraints.get(i);
+ if (c == null) {
+ throw new IllegalArgumentException("constraints[" + i + "] must not be null");
+ }
// Empty constraints (0*0=0) are trivially satisfied — skip
if (c.a().isEmpty() && c.b().isEmpty() && c.c().isEmpty()) continue;
@@ -424,8 +453,7 @@ public static void validateWitness(List constraints, BigInteger[
if (!lhs.equals(cVal)) {
throw new IllegalArgumentException(
- "Witness does not satisfy R1CS constraint " + i
- + ": A·w * B·w = " + lhs + " but C·w = " + cVal);
+ "Witness does not satisfy R1CS constraint " + i);
}
}
}
@@ -434,11 +462,15 @@ private static BigInteger evalLCBigInt(Map lc, BigInteger[]
BigInteger sum = BigInteger.ZERO;
for (var entry : lc.entrySet()) {
int wireIdx = entry.getKey();
- if (wireIdx >= witness.length)
+ if (wireIdx < 0 || wireIdx >= witness.length)
throw new IllegalArgumentException(
- "Constraint references wire " + wireIdx + " but witness has only " + witness.length + " entries");
- if (entry.getValue().signum() != 0) {
- sum = sum.add(entry.getValue().multiply(witness[wireIdx]));
+ "Constraint references wire " + wireIdx + " outside witness length " + witness.length);
+ BigInteger coeff = entry.getValue();
+ if (coeff == null) {
+ throw new IllegalArgumentException("Null coefficient at wire " + wireIdx);
+ }
+ if (coeff.signum() != 0) {
+ sum = sum.add(coeff.multiply(witness[wireIdx]));
}
}
return sum.mod(mod);
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 5f2d11a6..22739145 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
@@ -410,7 +410,7 @@ private static PlonKProofBLS381 proveInternal(PlonKProvingKeyBLS381 pk, MontFr38
// L1(zeta) = omega^0 * zh / (n * (zeta - omega^0)) = zh / (n * (zeta - 1))
MontFr381 zetaN = zeta;
- for (int i = 1; i < n; i++) zetaN = zetaN.mul(zeta);
+ for (int i = 0; i < logN; i++) zetaN = zetaN.square();
MontFr381 zh = zetaN.sub(MontFr381.ONE);
MontFr381 l1Zeta = zh.mul(MontFr381.fromLong(n).mul(zeta.sub(MontFr381.ONE)).inverse());
@@ -481,11 +481,18 @@ private static PlonKProofBLS381 proveInternal(PlonKProvingKeyBLS381 pk, MontFr38
// --- Polynomial helpers ---
- /** Evaluate polynomial on coset {shift * omega^i}: IFFT → shift coeffs by shift^i → FFT */
+ /** Evaluate polynomial on coset {shift * omega^i}: shift coeffs by shift^i → FFT */
private static MontFr381[] cosetEval(MontFr381[] coeffs, MontFr381 shift, int n, int logN) {
MontFr381[] padded = new MontFr381[n];
- for (int i = 0; i < n; i++)
- padded[i] = i < coeffs.length ? coeffs[i].mul(powFr(shift, i)) : MontFr381.ZERO;
+ MontFr381 power = MontFr381.ONE;
+ int limit = Math.min(coeffs.length, n);
+ for (int i = 0; i < limit; i++) {
+ padded[i] = coeffs[i].mul(power);
+ power = power.mul(shift);
+ }
+ for (int i = limit; i < n; i++) {
+ padded[i] = MontFr381.ZERO;
+ }
return FieldFFTBLS381.fft(padded);
}
@@ -570,10 +577,22 @@ private static MontFr381[] addBlinding3(MontFr381[] coeffs, MontFr381 b1, MontFr
}
private static MontFr381 powFr(MontFr381 base, int exp) {
- if (exp == 0) return MontFr381.ONE;
- MontFr381 r = base;
- for (int i = 1; i < exp; i++) r = r.mul(base);
- return r;
+ if (exp < 0) {
+ throw new IllegalArgumentException("Exponent must be non-negative: " + exp);
+ }
+ MontFr381 result = MontFr381.ONE;
+ MontFr381 cur = base;
+ int e = exp;
+ while (e > 0) {
+ if ((e & 1) != 0) {
+ result = result.mul(cur);
+ }
+ e >>>= 1;
+ if (e > 0) {
+ cur = cur.square();
+ }
+ }
+ return result;
}
private static void addG1(FiatShamirTranscript t, AffineG1 p, TranscriptEncoding encoding) {
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 b439bdc6..ea3a6f3f 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
@@ -2,18 +2,14 @@
import org.zeroj.bls12381.ec.G1Point;
import org.zeroj.bls12381.ec.G2Point;
-import org.zeroj.bls12381.ec.JacobianG1BLS381;
import org.zeroj.bls12381.ec.JacobianG1BLS381.AffineG1;
-import org.zeroj.bls12381.ec.JacobianG2BLS381;
import org.zeroj.bls12381.ec.JacobianG2BLS381.AffineG2;
-import org.zeroj.bls12381.field.Fp;
-import org.zeroj.bls12381.field.Fp2;
import org.zeroj.bls12381.field.MontFr381;
-import org.zeroj.bls12381.pairing.BLS12381Pairing;
import org.zeroj.crypto.kzg.KZGCommitmentBLS381;
import org.zeroj.crypto.poly.FieldFFTBLS381;
import java.math.BigInteger;
+import java.util.Arrays;
import java.util.Objects;
/**
@@ -58,7 +54,8 @@ public static PlonKProvingKeyBLS381 setup(
// numerator has degree ~3n+6. The 4n coset needs 4n > 3n+6, i.e., n > 6.
int domainSize = domainSizeFor(numGates);
int logN = Integer.numberOfTrailingZeros(domainSize);
- validateSetupInputs(numGates, numPublic, gateSelectors, sigmaA, sigmaB, sigmaC, numWires, srs, domainSize);
+ ValidatedSrs validatedSrs = validateSetupInputs(
+ numGates, numPublic, gateSelectors, sigmaA, sigmaB, sigmaC, numWires, srs, domainSize);
MontFr381 omega = FieldFFTBLS381.rootOfUnity(logN);
BigInteger k1 = BigInteger.TWO;
@@ -94,18 +91,24 @@ public static PlonKProvingKeyBLS381 setup(
MontFr381 k1Fr = MontFr381.fromBigInteger(k1);
MontFr381 k2Fr = MontFr381.fromBigInteger(k2);
+ MontFr381[] omegaPows = new MontFr381[domainSize];
+ omegaPows[0] = MontFr381.ONE;
+ for (int i = 1; i < domainSize; i++) {
+ omegaPows[i] = omegaPows[i - 1].mul(omega);
+ }
+
for (int i = 0; i < domainSize; i++) {
// Default: identity permutation
// Position i in col A -> omega^i
// Position i in col B -> k1 * omega^i
// Position i in col C -> k2 * omega^i
- MontFr381 omegaI = evalOmegaPow(omega, i);
+ MontFr381 omegaI = omegaPows[i];
if (i < numGates) {
// sigma_a[i] gives the flattened target: target = row + col * numGates
- s1[i] = decodeSigmaTarget(sigmaA[i], numGates, omega, k1Fr, k2Fr);
- s2[i] = decodeSigmaTarget(sigmaB[i], numGates, omega, k1Fr, k2Fr);
- s3[i] = decodeSigmaTarget(sigmaC[i], numGates, omega, k1Fr, k2Fr);
+ s1[i] = decodeSigmaTarget(sigmaA[i], numGates, omegaPows, k1Fr, k2Fr);
+ s2[i] = decodeSigmaTarget(sigmaB[i], numGates, omegaPows, k1Fr, k2Fr);
+ s3[i] = decodeSigmaTarget(sigmaC[i], numGates, omegaPows, k1Fr, k2Fr);
} else {
// Padding rows: identity permutation
s1[i] = omegaI;
@@ -124,7 +127,7 @@ public static PlonKProvingKeyBLS381 setup(
var s2Coeffs = FieldFFTBLS381.ifft(s2);
var s3Coeffs = FieldFFTBLS381.ifft(s3);
- AffineG1[] srsG1 = srs.tauG1();
+ AffineG1[] srsG1 = validatedSrs.tauG1();
var qmCommit = KZGCommitmentBLS381.commit(srsG1, qmCoeffs).toAffine();
var qlCommit = KZGCommitmentBLS381.commit(srsG1, qlCoeffs).toAffine();
@@ -139,17 +142,17 @@ public static PlonKProvingKeyBLS381 setup(
domainSize, numPublic, numGates, k1, k2, omega,
ql, qr, qm, qo, qc, s1, s2, s3,
srsG1, srsG1, // lagrange SRS = standard SRS for now
- srs.x2(),
+ validatedSrs.tauG2()[1],
qmCommit, qlCommit, qrCommit, qoCommit, qcCommit,
s1Commit, s2Commit, s3Commit);
}
/** Decode a sigma permutation target from flattened index. */
private static MontFr381 decodeSigmaTarget(int flatIdx, int numGates,
- MontFr381 omega, MontFr381 k1, MontFr381 k2) {
+ MontFr381[] omegaPows, MontFr381 k1, MontFr381 k2) {
int row = flatIdx % numGates;
int col = flatIdx / numGates;
- MontFr381 omegaRow = evalOmegaPow(omega, row);
+ MontFr381 omegaRow = omegaPows[row];
return switch (col) {
case 0 -> omegaRow; // column A: omega^row
case 1 -> k1.mul(omegaRow); // column B: k1 * omega^row
@@ -171,7 +174,9 @@ private static int domainSizeFor(int numGates) {
return Math.max(domainSize, MIN_DOMAIN_SIZE);
}
- private static void validateSetupInputs(
+ private record ValidatedSrs(AffineG1[] tauG1, AffineG2[] tauG2) {}
+
+ private static ValidatedSrs validateSetupInputs(
int numGates,
int numPublic,
BigInteger[][] gateSelectors,
@@ -191,7 +196,7 @@ private static void validateSetupInputs(
validateSigma("sigmaA", sigmaA, numGates);
validateSigma("sigmaB", sigmaB, numGates);
validateSigma("sigmaC", sigmaC, numGates);
- validateSrs(srs, domainSize);
+ return validateSrs(srs, domainSize);
}
private static void validateGateSelectors(BigInteger[][] gateSelectors, int numGates) {
@@ -221,23 +226,32 @@ private static void validateSigma(String name, int[] sigma, int numGates) {
}
}
- private static void validateSrs(PtauImporterBLS381.SRS srs, int domainSize) {
+ private static ValidatedSrs validateSrs(PtauImporterBLS381.SRS srs, int domainSize) {
Objects.requireNonNull(srs, "srs");
- AffineG1[] tauG1 = srs.tauG1();
- AffineG2[] tauG2 = srs.tauG2();
+ AffineG1[] rawG1 = srs.tauG1();
+ AffineG2[] rawG2 = srs.tauG2();
int requiredG1 = domainSize + 6;
- if (tauG1 == null || tauG1.length < requiredG1) {
+ if (rawG1 == null || rawG1.length < requiredG1) {
throw new IllegalArgumentException("BLS12-381 SRS G1 length must be at least " + requiredG1);
}
- if (tauG2 == null || tauG2.length < 2) {
+ if (rawG2 == null || rawG2.length < 2) {
throw new IllegalArgumentException("BLS12-381 SRS G2 length must be at least 2");
}
+ // Pin private snapshots BEFORE validation/challenge drawing and reuse them through all
+ // commitments and the returned proving key so concurrent or post-setup caller edits to
+ // srs.tauG1()/tauG2() cannot bypass checks or alter the returned key (ADR-0068).
+ AffineG1[] snapshotG1 = Arrays.copyOf(rawG1, requiredG1);
+ AffineG2[] snapshotG2 = Arrays.copyOf(rawG2, 2);
+ if (SrsConsistencyBLS381.isUnmodifiedVerified(srs, snapshotG1, snapshotG2)) {
+ return new ValidatedSrs(snapshotG1, snapshotG2);
+ }
for (int i = 0; i < requiredG1; i++) {
- requireValidSrsG1(tauG1[i], "tauG1[" + i + "]");
+ requireValidSrsG1(snapshotG1[i], "tauG1[" + i + "]");
}
- requireValidSrsG2(tauG2[0], "tauG2[0]");
- requireValidSrsG2(tauG2[1], "tauG2[1]");
- validateSrsConsistency(tauG1, tauG2, requiredG1);
+ requireValidSrsG2(snapshotG2[0], "tauG2[0]");
+ requireValidSrsG2(snapshotG2[1], "tauG2[1]");
+ SrsConsistencyBLS381.verifyConsistency(snapshotG1, snapshotG2, requiredG1, "BLS12-381");
+ return new ValidatedSrs(snapshotG1, snapshotG2);
}
private static void requireScalar(BigInteger value, String label) {
@@ -250,7 +264,7 @@ private static void requireValidSrsG1(AffineG1 point, String label) {
if (point == null || point.isInfinity() || !point.isOnCurve()) {
throw new IllegalArgumentException(label + " must be a non-infinity BLS12-381 G1 point");
}
- G1Point p = new G1Point(Fp.of(point.xBigInt()), Fp.of(point.yBigInt()));
+ G1Point p = SrsConsistencyBLS381.toG1(point);
if (!p.isValid()) {
throw new IllegalArgumentException(label + " must be in the BLS12-381 G1 subgroup");
}
@@ -260,47 +274,9 @@ private static void requireValidSrsG2(AffineG2 point, String label) {
if (point == null || point.isInfinity() || !point.isOnCurve()) {
throw new IllegalArgumentException(label + " must be a non-infinity BLS12-381 G2 point");
}
- G2Point p = new G2Point(
- Fp2.of(Fp.of(point.x().reBigInt()), Fp.of(point.x().imBigInt())),
- Fp2.of(Fp.of(point.y().reBigInt()), Fp.of(point.y().imBigInt())));
+ G2Point p = SrsConsistencyBLS381.toG2(point);
if (!p.isValid()) {
throw new IllegalArgumentException(label + " must be in the BLS12-381 G2 subgroup");
}
}
-
- private static void validateSrsConsistency(AffineG1[] tauG1, AffineG2[] tauG2, int count) {
- if (!tauG1[0].equals(JacobianG1BLS381.GENERATOR.toAffine())) {
- throw new IllegalArgumentException("BLS12-381 SRS G1 generator anchor mismatch");
- }
- if (!tauG2[0].equals(JacobianG2BLS381.GENERATOR.toAffine())) {
- throw new IllegalArgumentException("BLS12-381 SRS G2 generator anchor mismatch");
- }
- G2Point g2 = toG2(tauG2[0]);
- G2Point tauG2Point = toG2(tauG2[1]);
- for (int i = 1; i < count; i++) {
- boolean consistent = BLS12381Pairing.pairingCheck(
- new G1Point[]{toG1(tauG1[i]), toG1(tauG1[i - 1]).negate()},
- new G2Point[]{g2, tauG2Point});
- if (!consistent) {
- throw new IllegalArgumentException("BLS12-381 SRS powers are inconsistent at G1 index " + i);
- }
- }
- }
-
- private static G1Point toG1(AffineG1 point) {
- return new G1Point(Fp.of(point.xBigInt()), Fp.of(point.yBigInt()));
- }
-
- private static G2Point toG2(AffineG2 point) {
- return new G2Point(
- Fp2.of(Fp.of(point.x().reBigInt()), Fp.of(point.x().imBigInt())),
- Fp2.of(Fp.of(point.y().reBigInt()), Fp.of(point.y().imBigInt())));
- }
-
- private static MontFr381 evalOmegaPow(MontFr381 omega, int exp) {
- if (exp == 0) return MontFr381.ONE;
- MontFr381 result = omega;
- for (int i = 1; i < exp; i++) result = result.mul(omega);
- return result;
- }
}
diff --git a/zeroj-crypto/src/main/java/org/zeroj/crypto/plonk/PtauImporterBLS381.java b/zeroj-crypto/src/main/java/org/zeroj/crypto/plonk/PtauImporterBLS381.java
index 34b63381..b6639f43 100644
--- a/zeroj-crypto/src/main/java/org/zeroj/crypto/plonk/PtauImporterBLS381.java
+++ b/zeroj-crypto/src/main/java/org/zeroj/crypto/plonk/PtauImporterBLS381.java
@@ -1,16 +1,9 @@
package org.zeroj.crypto.plonk;
-import org.zeroj.bls12381.ec.G1Point;
-import org.zeroj.bls12381.ec.G2Point;
-import org.zeroj.bls12381.ec.JacobianG1BLS381;
import org.zeroj.bls12381.ec.JacobianG1BLS381.AffineG1;
-import org.zeroj.bls12381.ec.JacobianG2BLS381;
import org.zeroj.bls12381.ec.JacobianG2BLS381.AffineG2;
-import org.zeroj.bls12381.field.Fp;
-import org.zeroj.bls12381.field.Fp2;
import org.zeroj.bls12381.field.MontFp2_381;
import org.zeroj.bls12381.field.MontFp381;
-import org.zeroj.bls12381.pairing.BLS12381Pairing;
import java.io.BufferedInputStream;
import java.io.IOException;
@@ -245,7 +238,9 @@ public static SRS importPtau(InputStream input, int maxPoints, byte[] expectedSh
}
validateSrsConsistency(tauG1, tauG2, tauG1.length);
- return new SRS(tauG1, tauG2, power);
+ SRS srs = new SRS(tauG1, tauG2, power);
+ SrsConsistencyBLS381.recordVerified(srs);
+ return srs;
}
/**
@@ -284,7 +279,7 @@ private static AffineG1 decodeSrsG1(byte[] ptBuf, int off, int index) throws IOE
if (!point.isOnCurve()) {
throw new IOException("BLS12-381 .ptau G1[" + index + "] is not on curve");
}
- if (!toG1(point).isValid()) {
+ if (!SrsConsistencyBLS381.toG1(point).isValid()) {
throw new IOException("BLS12-381 .ptau G1[" + index + "] is not in subgroup");
}
return point;
@@ -302,7 +297,7 @@ private static AffineG2 decodeSrsG2(byte[] ptBuf, int off, int index) throws IOE
if (!point.isOnCurve()) {
throw new IOException("BLS12-381 .ptau G2[" + index + "] is not on curve");
}
- if (!toG2(point).isValid()) {
+ if (!SrsConsistencyBLS381.toG2(point).isValid()) {
throw new IOException("BLS12-381 .ptau G2[" + index + "] is not in subgroup");
}
return point;
@@ -320,36 +315,13 @@ private static MontFp381 decodeMontFp(byte[] buf, int off, String label) throws
}
private static void validateSrsConsistency(AffineG1[] tauG1, AffineG2[] tauG2, int count) throws IOException {
- if (!tauG1[0].equals(JacobianG1BLS381.GENERATOR.toAffine())) {
- throw new IOException("BLS12-381 .ptau G1 generator anchor mismatch");
- }
- if (!tauG2[0].equals(JacobianG2BLS381.GENERATOR.toAffine())) {
- throw new IOException("BLS12-381 .ptau G2 generator anchor mismatch");
- }
- G2Point g2 = toG2(tauG2[0]);
- G2Point tauG2Point = toG2(tauG2[1]);
- for (int i = 1; i < count; i++) {
- boolean consistent = BLS12381Pairing.pairingCheck(
- new G1Point[]{toG1(tauG1[i]), toG1(tauG1[i - 1]).negate()},
- new G2Point[]{g2, tauG2Point});
- if (!consistent) {
- throw new IOException("BLS12-381 .ptau SRS powers are inconsistent at G1 index " + i);
- }
+ try {
+ SrsConsistencyBLS381.verifyConsistency(tauG1, tauG2, count, "BLS12-381 .ptau");
+ } catch (IllegalArgumentException e) {
+ throw new IOException(e.getMessage(), e);
}
}
- private static G1Point toG1(AffineG1 point) {
- if (point.isInfinity()) return G1Point.INFINITY;
- return new G1Point(Fp.of(point.xBigInt()), Fp.of(point.yBigInt()));
- }
-
- private static G2Point toG2(AffineG2 point) {
- if (point.isInfinity()) return G2Point.INFINITY;
- return new G2Point(
- Fp2.of(Fp.of(point.x().reBigInt()), Fp.of(point.x().imBigInt())),
- Fp2.of(Fp.of(point.y().reBigInt()), Fp.of(point.y().imBigInt())));
- }
-
private static BigInteger readUnsignedLE(byte[] buf, int off, int len) {
byte[] be = new byte[len];
for (int i = 0; i < len; i++) {
diff --git a/zeroj-crypto/src/main/java/org/zeroj/crypto/plonk/SrsConsistencyBLS381.java b/zeroj-crypto/src/main/java/org/zeroj/crypto/plonk/SrsConsistencyBLS381.java
new file mode 100644
index 00000000..ececbeda
--- /dev/null
+++ b/zeroj-crypto/src/main/java/org/zeroj/crypto/plonk/SrsConsistencyBLS381.java
@@ -0,0 +1,145 @@
+package org.zeroj.crypto.plonk;
+
+import org.zeroj.bls12381.ec.G1Point;
+import org.zeroj.bls12381.ec.G2Point;
+import org.zeroj.bls12381.ec.JacobianG1BLS381;
+import org.zeroj.bls12381.ec.JacobianG1BLS381.AffineG1;
+import org.zeroj.bls12381.ec.JacobianG2BLS381;
+import org.zeroj.bls12381.ec.JacobianG2BLS381.AffineG2;
+import org.zeroj.bls12381.field.Fp;
+import org.zeroj.bls12381.field.Fp2;
+import org.zeroj.bls12381.field.MontFr381;
+import org.zeroj.bls12381.pairing.BLS12381Pairing;
+import org.zeroj.crypto.msm.PippengerBLS381;
+
+import java.math.BigInteger;
+import java.security.SecureRandom;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Map;
+import java.util.Objects;
+import java.util.WeakHashMap;
+
+/**
+ * Batched random-linear-combination (RLC) SRS consistency verifier for BLS12-381 PlonK (ADR-0068).
+ *
+ * Given validated non-infinity prime-order subgroup points {@code tauG1[0..count-1]} and
+ * {@code tauG2[0..1]}, verifies {@code tauG1[0] == G1}, {@code tauG2[0] == G2}, and
+ * {@code e(tauG1[i], G2) == e(tauG1[i - 1], tauG2[1])} for all {@code 1 <= i < count} using a
+ * single two-pairing check over a {@link SecureRandom} challenge {@code r ∈ F_r \ {0}}.
+ */
+final class SrsConsistencyBLS381 {
+
+ private static final BigInteger FR = MontFr381.modulus();
+ private static final SecureRandom RNG = new SecureRandom();
+ private static final AffineG1 G1_GEN = JacobianG1BLS381.GENERATOR.toAffine();
+ private static final AffineG2 G2_GEN = JacobianG2BLS381.GENERATOR.toAffine();
+
+ private record VerifiedSnapshot(AffineG1[] tauG1, AffineG2[] tauG2) {}
+
+ /**
+ * Weak cache of SRS instances verified by {@link PtauImporterBLS381}, storing defensive
+ * snapshots of the verified arrays so {@link PlonKSetupBLS381} avoids duplicate subgroup and
+ * pairing verification only when no element has been mutated after import.
+ */
+ private static final Map VERIFIED =
+ Collections.synchronizedMap(new WeakHashMap<>());
+
+ private SrsConsistencyBLS381() {}
+
+ static void verifyConsistency(AffineG1[] tauG1, AffineG2[] tauG2, int count, String label) {
+ verifyConsistency(tauG1, tauG2, count, label, RNG);
+ }
+
+ static void verifyConsistency(
+ AffineG1[] tauG1,
+ AffineG2[] tauG2,
+ int count,
+ String label,
+ SecureRandom rng) {
+ if (count <= 0 || tauG1 == null || tauG1.length < count) {
+ throw new IllegalArgumentException(label + " G1 array is shorter than count " + count);
+ }
+ if (tauG2 == null || tauG2.length < 2) {
+ throw new IllegalArgumentException(label + " G2 array must contain at least 2 points");
+ }
+ if (!G1_GEN.equals(tauG1[0])) {
+ throw new IllegalArgumentException(label + " G1 generator anchor mismatch");
+ }
+ if (!G2_GEN.equals(tauG2[0])) {
+ throw new IllegalArgumentException(label + " G2 generator anchor mismatch");
+ }
+ if (count == 1) {
+ return;
+ }
+
+ int pairs = count - 1;
+ MontFr381 challenge = randomNonZeroFr(rng);
+ BigInteger[] weights = new BigInteger[pairs];
+ MontFr381 power = MontFr381.ONE;
+ for (int j = 0; j < pairs; j++) {
+ weights[j] = power.toBigInteger();
+ power = power.mul(challenge);
+ }
+
+ AffineG1[] shifted = Arrays.copyOfRange(tauG1, 1, count);
+ AffineG1[] base = Arrays.copyOfRange(tauG1, 0, count - 1);
+ AffineG1 lhsSum = PippengerBLS381.msm(shifted, weights).toAffine();
+ AffineG1 rhsSum = PippengerBLS381.msm(base, weights).toAffine();
+
+ boolean consistent = BLS12381Pairing.pairingCheck(
+ new G1Point[]{toG1(lhsSum), toG1(rhsSum).negate()},
+ new G2Point[]{toG2(tauG2[0]), toG2(tauG2[1])});
+ if (!consistent) {
+ throw new IllegalArgumentException(label + " SRS powers are inconsistent");
+ }
+ }
+
+ static void recordVerified(PtauImporterBLS381.SRS srs) {
+ Objects.requireNonNull(srs, "srs");
+ VERIFIED.put(srs, new VerifiedSnapshot(srs.tauG1().clone(), Arrays.copyOf(srs.tauG2(), 2)));
+ }
+
+ static boolean isUnmodifiedVerified(
+ PtauImporterBLS381.SRS srs,
+ AffineG1[] snapshotG1,
+ AffineG2[] snapshotG2) {
+ VerifiedSnapshot snap = VERIFIED.get(srs);
+ if (snap == null || snapshotG1 == null || snapshotG2 == null || snapshotG2.length < 2) {
+ return false;
+ }
+ int requiredG1 = snapshotG1.length;
+ if (snap.tauG1.length < requiredG1) {
+ return false;
+ }
+ return Arrays.equals(snapshotG1, 0, requiredG1, snap.tauG1, 0, requiredG1)
+ && Objects.equals(snapshotG2[0], snap.tauG2[0])
+ && Objects.equals(snapshotG2[1], snap.tauG2[1]);
+ }
+
+ static G1Point toG1(AffineG1 point) {
+ if (point == null || point.isInfinity()) {
+ return G1Point.INFINITY;
+ }
+ return new G1Point(Fp.of(point.xBigInt()), Fp.of(point.yBigInt()));
+ }
+
+ static G2Point toG2(AffineG2 point) {
+ if (point == null || point.isInfinity()) {
+ return G2Point.INFINITY;
+ }
+ return new G2Point(
+ Fp2.of(Fp.of(point.x().reBigInt()), Fp.of(point.x().imBigInt())),
+ Fp2.of(Fp.of(point.y().reBigInt()), Fp.of(point.y().imBigInt())));
+ }
+
+ private static MontFr381 randomNonZeroFr(SecureRandom rng) {
+ byte[] bytes = new byte[32];
+ BigInteger value;
+ do {
+ rng.nextBytes(bytes);
+ value = new BigInteger(1, bytes);
+ } while (value.signum() == 0 || value.compareTo(FR) >= 0);
+ return MontFr381.fromBigInteger(value);
+ }
+}
diff --git a/zeroj-crypto/src/test/java/org/zeroj/crypto/groth16/Groth16EndToEndTest.java b/zeroj-crypto/src/test/java/org/zeroj/crypto/groth16/Groth16EndToEndTest.java
index cc18cb84..f43ad1be 100644
--- a/zeroj-crypto/src/test/java/org/zeroj/crypto/groth16/Groth16EndToEndTest.java
+++ b/zeroj-crypto/src/test/java/org/zeroj/crypto/groth16/Groth16EndToEndTest.java
@@ -233,6 +233,7 @@ void cubicCircuit_proveAndVerify() throws IOException {
* Validates that validateWitness rejects an invalid witness with a clear error.
*/
@Test
+ @SuppressWarnings("removal")
void invalidWitness_validateWitnessThrows() throws IOException {
var r1csData = R1CSImporter.importR1CS(getClass().getResourceAsStream(R1CS_PATH));
var witness = ZkeyImporter.importWtns(getClass().getResourceAsStream(WTNS_PATH));
diff --git a/zeroj-crypto/src/test/java/org/zeroj/crypto/groth16/Groth16ProverValidateWitnessTest.java b/zeroj-crypto/src/test/java/org/zeroj/crypto/groth16/Groth16ProverValidateWitnessTest.java
new file mode 100644
index 00000000..47790082
--- /dev/null
+++ b/zeroj-crypto/src/test/java/org/zeroj/crypto/groth16/Groth16ProverValidateWitnessTest.java
@@ -0,0 +1,89 @@
+package org.zeroj.crypto.groth16;
+
+import org.junit.jupiter.api.Test;
+import org.zeroj.api.LegacyCurvePolicy;
+import org.zeroj.api.R1CSConstraint;
+import org.zeroj.crypto.field.MontFr254;
+
+import java.math.BigInteger;
+import java.util.List;
+import java.util.Map;
+
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+/**
+ * ADR-0068: Groth16Prover.validateWitness legacy BN254 gating, wire-0, canonical, and bounds checks.
+ */
+class Groth16ProverValidateWitnessTest {
+
+ @Test
+ @SuppressWarnings("removal")
+ void validateWitnessFailsClosedWhenLegacyBn254Disabled() {
+ String prev = System.getProperty(LegacyCurvePolicy.ALLOW_LEGACY_BN254_PROPERTY);
+ try {
+ System.clearProperty(LegacyCurvePolicy.ALLOW_LEGACY_BN254_PROPERTY);
+ List constraints = List.of(
+ new R1CSConstraint(Map.of(1, BigInteger.ONE), Map.of(2, BigInteger.ONE), Map.of(3, BigInteger.ONE)));
+ BigInteger[] witness = {BigInteger.ONE, BigInteger.TWO, BigInteger.valueOf(3), BigInteger.valueOf(6)};
+ assertThrows(IllegalStateException.class,
+ () -> Groth16Prover.validateWitness(constraints, witness, 1));
+ } finally {
+ if (prev == null) {
+ System.clearProperty(LegacyCurvePolicy.ALLOW_LEGACY_BN254_PROPERTY);
+ } else {
+ System.setProperty(LegacyCurvePolicy.ALLOW_LEGACY_BN254_PROPERTY, prev);
+ }
+ }
+ }
+
+ @Test
+ @SuppressWarnings("removal")
+ void validateWitnessEnforcesWireZeroCanonicalScalarsAndBoundsWhenEnabled() {
+ String prev = System.getProperty(LegacyCurvePolicy.ALLOW_LEGACY_BN254_PROPERTY);
+ try {
+ System.setProperty(LegacyCurvePolicy.ALLOW_LEGACY_BN254_PROPERTY, "true");
+ List constraints = List.of(
+ new R1CSConstraint(Map.of(1, BigInteger.ONE), Map.of(2, BigInteger.ONE), Map.of(3, BigInteger.ONE)));
+ BigInteger[] valid = {BigInteger.ONE, BigInteger.TWO, BigInteger.valueOf(3), BigInteger.valueOf(6)};
+ assertDoesNotThrow(() -> Groth16Prover.validateWitness(constraints, valid, 1));
+
+ // witness[0] != 1 rejected without leaking value
+ BigInteger sentinel = new BigInteger("777666555444333222111");
+ BigInteger[] badWire0 = {sentinel, BigInteger.TWO, BigInteger.valueOf(3), BigInteger.valueOf(6)};
+ IllegalArgumentException wire0Ex = assertThrows(IllegalArgumentException.class,
+ () -> Groth16Prover.validateWitness(constraints, badWire0, 1));
+ assertFalse(wire0Ex.getMessage().contains(sentinel.toString()));
+
+ // Violated constraint rejected without leaking witness-derived lhs/cVal
+ BigInteger[] badConstraint = {BigInteger.ONE, sentinel, BigInteger.ONE, BigInteger.ZERO};
+ IllegalArgumentException constrEx = assertThrows(IllegalArgumentException.class,
+ () -> Groth16Prover.validateWitness(constraints, badConstraint, 1));
+ assertFalse(constrEx.getMessage().contains(sentinel.toString()));
+
+ // Non-canonical scalar >= BN254 r rejected
+ BigInteger[] nonCanonical = {BigInteger.ONE, MontFr254.modulus(), BigInteger.ZERO, BigInteger.ZERO};
+ assertThrows(IllegalArgumentException.class,
+ () -> Groth16Prover.validateWitness(constraints, nonCanonical, 1));
+
+ // Negative numConstraints or > size rejected
+ assertThrows(IllegalArgumentException.class,
+ () -> Groth16Prover.validateWitness(constraints, valid, -1));
+ assertThrows(IllegalArgumentException.class,
+ () -> Groth16Prover.validateWitness(constraints, valid, 2));
+
+ // Negative wire index rejected
+ List negWire = List.of(
+ new R1CSConstraint(Map.of(-1, BigInteger.ONE), Map.of(0, BigInteger.ONE), Map.of()));
+ assertThrows(IllegalArgumentException.class,
+ () -> Groth16Prover.validateWitness(negWire, valid, 1));
+ } finally {
+ if (prev == null) {
+ System.clearProperty(LegacyCurvePolicy.ALLOW_LEGACY_BN254_PROPERTY);
+ } else {
+ System.setProperty(LegacyCurvePolicy.ALLOW_LEGACY_BN254_PROPERTY, prev);
+ }
+ }
+ }
+}
diff --git a/zeroj-crypto/src/test/java/org/zeroj/crypto/plonk/PlonKSrsAndScalingTest.java b/zeroj-crypto/src/test/java/org/zeroj/crypto/plonk/PlonKSrsAndScalingTest.java
new file mode 100644
index 00000000..e3f9495d
--- /dev/null
+++ b/zeroj-crypto/src/test/java/org/zeroj/crypto/plonk/PlonKSrsAndScalingTest.java
@@ -0,0 +1,199 @@
+package org.zeroj.crypto.plonk;
+
+import org.junit.jupiter.api.Test;
+import org.zeroj.api.CurveId;
+import org.zeroj.bls12381.ec.JacobianG1BLS381;
+import org.zeroj.bls12381.ec.JacobianG1BLS381.AffineG1;
+import org.zeroj.bls12381.ec.JacobianG2BLS381;
+import org.zeroj.bls12381.ec.JacobianG2BLS381.AffineG2;
+import org.zeroj.bls12381.field.MontFr381;
+import org.zeroj.circuit.CircuitBuilder;
+import org.zeroj.circuit.plonk.PlonKConstraintSystem;
+
+import java.math.BigInteger;
+import java.security.SecureRandom;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Map;
+
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+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;
+
+/**
+ * ADR-0068: Batched RLC SRS consistency checks, post-import mutation detection, and
+ * medium-domain PlonK setup/prover scaling correctness.
+ */
+class PlonKSrsAndScalingTest {
+
+ @Test
+ void batchedSrsConsistencyAcceptsValidAndRejectsEveryTamperedPower() {
+ BigInteger tau = BigInteger.valueOf(19);
+ int count = 16;
+ AffineG1[] tauG1 = new AffineG1[count];
+ BigInteger power = BigInteger.ONE;
+ BigInteger fr = MontFr381.modulus();
+ for (int i = 0; i < count; i++) {
+ tauG1[i] = JacobianG1BLS381.GENERATOR.scalarMul(power).toAffine();
+ power = power.multiply(tau).mod(fr);
+ }
+ AffineG2[] tauG2 = {
+ JacobianG2BLS381.GENERATOR.toAffine(),
+ JacobianG2BLS381.GENERATOR.scalarMul(tau).toAffine()
+ };
+
+ // Valid at count=1, count=2, and full count=16
+ assertDoesNotThrow(() -> SrsConsistencyBLS381.verifyConsistency(tauG1, tauG2, 1, "test"));
+ assertDoesNotThrow(() -> SrsConsistencyBLS381.verifyConsistency(tauG1, tauG2, 2, "test"));
+ assertDoesNotThrow(() -> SrsConsistencyBLS381.verifyConsistency(tauG1, tauG2, count, "test"));
+
+ // Tampering any G1 power i >= 1 must fail
+ for (int badIdx : new int[]{1, 2, 7, count - 1}) {
+ AffineG1[] tampered = tauG1.clone();
+ tampered[badIdx] = JacobianG1BLS381.GENERATOR.scalarMul(BigInteger.valueOf(badIdx + 100)).toAffine();
+ assertThrows(IllegalArgumentException.class,
+ () -> SrsConsistencyBLS381.verifyConsistency(tampered, tauG2, count, "test"),
+ "Expected tampered G1[" + badIdx + "] to be rejected");
+ }
+
+ // Swapping two powers must fail
+ AffineG1[] swapped = tauG1.clone();
+ AffineG1 tmp = swapped[3];
+ swapped[3] = swapped[4];
+ swapped[4] = tmp;
+ assertThrows(IllegalArgumentException.class,
+ () -> SrsConsistencyBLS381.verifyConsistency(swapped, tauG2, count, "test"));
+
+ // Wrong generator anchor must fail
+ AffineG1[] badGen = tauG1.clone();
+ badGen[0] = tauG1[1];
+ assertThrows(IllegalArgumentException.class,
+ () -> SrsConsistencyBLS381.verifyConsistency(badGen, tauG2, count, "test"));
+
+ // Wrong tauG2[1] must fail
+ AffineG2[] badTauG2 = {
+ tauG2[0],
+ JacobianG2BLS381.GENERATOR.scalarMul(tau.add(BigInteger.ONE)).toAffine()
+ };
+ assertThrows(IllegalArgumentException.class,
+ () -> SrsConsistencyBLS381.verifyConsistency(tauG1, badTauG2, count, "test"));
+ }
+
+ @Test
+ void verifiedSrsCacheDetectsPostImportMutationAndRejectsInSetup() {
+ BigInteger tau = BigInteger.valueOf(23);
+ int count = 14; // domainSize 8 + 6
+ AffineG1[] tauG1 = new AffineG1[count];
+ BigInteger power = BigInteger.ONE;
+ BigInteger fr = MontFr381.modulus();
+ for (int i = 0; i < count; i++) {
+ tauG1[i] = JacobianG1BLS381.GENERATOR.scalarMul(power).toAffine();
+ power = power.multiply(tau).mod(fr);
+ }
+ AffineG2[] tauG2 = {
+ JacobianG2BLS381.GENERATOR.toAffine(),
+ JacobianG2BLS381.GENERATOR.scalarMul(tau).toAffine()
+ };
+
+ var srs = new PtauImporterBLS381.SRS(tauG1, tauG2, 3);
+ SrsConsistencyBLS381.recordVerified(srs);
+ assertTrue(SrsConsistencyBLS381.isUnmodifiedVerified(srs, Arrays.copyOf(tauG1, count), Arrays.copyOf(tauG2, 2)));
+
+ // Setup must pin private copies so mutating caller-owned SRS arrays AFTER setup cannot alter the returned key.
+ var circuit = CircuitBuilder.create("mutated-srs")
+ .publicVar("c").secretVar("a").secretVar("b")
+ .define(api -> api.assertEqual(api.mul(api.var("a"), api.var("b")), api.var("c")));
+ PlonKConstraintSystem plonk = circuit.compilePlonK(CurveId.BLS12_381);
+ BigInteger[][] selectors = selectorsOf(plonk);
+ PlonKProvingKeyBLS381 pk = PlonKSetupBLS381.setup(
+ plonk.numGates(), plonk.numPublicInputs(), selectors,
+ plonk.sigmaA(), plonk.sigmaB(), plonk.sigmaC(), plonk.numWires(), srs);
+ AffineG1 originalG1At5 = pk.srsG1()[5];
+ AffineG2 originalX2 = pk.x2();
+
+ // Mutate caller's arrays after setup: returned key must stay immutable AND next setup must reject the mutated SRS
+ tauG1[5] = tauG1[0];
+ tauG2[1] = tauG2[0];
+ assertEquals(originalG1At5, pk.srsG1()[5], "post-setup caller mutation must not alter returned pk.srsG1()");
+ assertEquals(originalX2, pk.x2(), "post-setup caller mutation must not alter returned pk.x2()");
+ assertFalse(SrsConsistencyBLS381.isUnmodifiedVerified(srs, Arrays.copyOf(tauG1, count), Arrays.copyOf(tauG2, 2)));
+ assertThrows(IllegalArgumentException.class, () -> PlonKSetupBLS381.setup(
+ plonk.numGates(), plonk.numPublicInputs(), selectors,
+ plonk.sigmaA(), plonk.sigmaB(), plonk.sigmaC(), plonk.numWires(), srs));
+ }
+
+ @Test
+ void mediumDomainPlonkSetupAndProveWithEliminatedQuadraticLoops() {
+ // Build a 180-gate chain -> domainSize = 256 (n + 6 = 262 SRS points)
+ var circuit = CircuitBuilder.create("chain-180")
+ .publicVar("out").secretVar("x")
+ .define(api -> {
+ var cur = api.var("x");
+ for (int i = 0; i < 180; i++) {
+ cur = api.add(api.mul(cur, cur), api.constant(1));
+ }
+ api.assertEqual(cur, api.var("out"));
+ });
+
+ BigInteger x = BigInteger.valueOf(5);
+ BigInteger expected = x;
+ BigInteger fr = MontFr381.modulus();
+ for (int i = 0; i < 180; i++) {
+ expected = expected.multiply(expected).add(BigInteger.ONE).mod(fr);
+ }
+
+ BigInteger[] witness = circuit.calculateWitness(
+ Map.of("x", List.of(x), "out", List.of(expected)), CurveId.BLS12_381);
+ PlonKConstraintSystem plonk = circuit.compilePlonK(CurveId.BLS12_381);
+ int domainSize = Integer.highestOneBit(plonk.numGates() - 1) << 1;
+ int srsCount = domainSize + 6;
+
+ BigInteger tau = BigInteger.valueOf(31);
+ AffineG1[] tauG1 = new AffineG1[srsCount];
+ BigInteger pow = BigInteger.ONE;
+ for (int i = 0; i < srsCount; i++) {
+ tauG1[i] = JacobianG1BLS381.GENERATOR.scalarMul(pow).toAffine();
+ pow = pow.multiply(tau).mod(fr);
+ }
+ AffineG2[] tauG2 = {
+ JacobianG2BLS381.GENERATOR.toAffine(),
+ JacobianG2BLS381.GENERATOR.scalarMul(tau).toAffine()
+ };
+ var srs = new PtauImporterBLS381.SRS(tauG1, tauG2, Integer.numberOfTrailingZeros(domainSize));
+
+ PlonKProvingKeyBLS381 pk = PlonKSetupBLS381.setup(
+ plonk.numGates(), plonk.numPublicInputs(), selectorsOf(plonk),
+ plonk.sigmaA(), plonk.sigmaB(), plonk.sigmaC(), plonk.numWires(), srs);
+
+ BigInteger[] ext = plonk.extendWitness(witness);
+ int n = pk.domainSize();
+ MontFr381[] wireA = new MontFr381[n];
+ MontFr381[] wireB = new MontFr381[n];
+ MontFr381[] wireC = new MontFr381[n];
+ for (int i = 0; i < n; i++) {
+ if (i < plonk.numGates()) {
+ var row = plonk.gateRows().get(i);
+ wireA[i] = MontFr381.fromBigInteger(ext[row.wireA()]);
+ wireB[i] = MontFr381.fromBigInteger(ext[row.wireB()]);
+ wireC[i] = MontFr381.fromBigInteger(ext[row.wireC()]);
+ } else {
+ wireA[i] = wireB[i] = wireC[i] = MontFr381.ZERO;
+ }
+ }
+ BigInteger[] pubInputs = Arrays.copyOfRange(witness, 1, 1 + plonk.numPublicInputs());
+ PlonKProofBLS381 proof = PlonKProverBLS381.prove(pk, wireA, wireB, wireC, pubInputs, new SecureRandom());
+ assertFalse(proof.commitA().isInfinity());
+ assertFalse(proof.commitWxi().isInfinity());
+ }
+
+ private static BigInteger[][] selectorsOf(PlonKConstraintSystem plonk) {
+ BigInteger[][] selectors = new BigInteger[plonk.numGates()][];
+ for (int i = 0; i < plonk.numGates(); i++) {
+ var row = plonk.gateRows().get(i);
+ selectors[i] = new BigInteger[]{row.qL(), row.qR(), row.qO(), row.qM(), row.qC()};
+ }
+ return selectors;
+ }
+}
diff --git a/zeroj-integration-tests/src/test/java/org/zeroj/examples/annotation/AnnotatedCircuitExamplesTest.java b/zeroj-integration-tests/src/test/java/org/zeroj/examples/annotation/AnnotatedCircuitExamplesTest.java
index 21964fdc..e5fa5f3a 100644
--- a/zeroj-integration-tests/src/test/java/org/zeroj/examples/annotation/AnnotatedCircuitExamplesTest.java
+++ b/zeroj-integration-tests/src/test/java/org/zeroj/examples/annotation/AnnotatedCircuitExamplesTest.java
@@ -22,6 +22,7 @@
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
+import java.util.HashMap;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
@@ -295,12 +296,16 @@ void annotatedAnonymousVotingMirrorsReferenceDslCircuit() {
() -> circuit.calculateWitness(wrongCommitment.toWitnessMap(), CurveId.BLS12_381));
var invalidVote = BigInteger.valueOf(2);
- var invalidVoteInputs = AnnotatedAnonymousVotingCircuit.inputs()
+ assertThrows(IllegalArgumentException.class, () -> AnnotatedAnonymousVotingCircuit.inputs()
+ .vote(invalidVote));
+ var invalidVoteMap = new HashMap<>(AnnotatedAnonymousVotingCircuit.inputs()
.commitment(PoseidonHash.hash(PoseidonParamsBLS12_381T3.INSTANCE, invalidVote, nullifier))
- .vote(invalidVote)
- .nullifier(nullifier);
+ .vote(BigInteger.ZERO)
+ .nullifier(nullifier)
+ .toWitnessMap());
+ invalidVoteMap.put(AnnotatedAnonymousVotingCircuit.VOTE, List.of(invalidVote));
assertThrows(ArithmeticException.class,
- () -> circuit.calculateWitness(invalidVoteInputs.toWitnessMap(), CurveId.BLS12_381));
+ () -> circuit.calculateWitness(invalidVoteMap, CurveId.BLS12_381));
}
@Test
diff --git a/zeroj-integration-tests/src/test/java/org/zeroj/examples/annotation/AnnotatedPedersenProfilesTest.java b/zeroj-integration-tests/src/test/java/org/zeroj/examples/annotation/AnnotatedPedersenProfilesTest.java
index 57891ea0..1cb1708d 100644
--- a/zeroj-integration-tests/src/test/java/org/zeroj/examples/annotation/AnnotatedPedersenProfilesTest.java
+++ b/zeroj-integration-tests/src/test/java/org/zeroj/examples/annotation/AnnotatedPedersenProfilesTest.java
@@ -20,6 +20,7 @@
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.util.ArrayList;
+import java.util.HashMap;
import java.util.List;
import java.util.Map;
@@ -64,11 +65,15 @@ void confidentialTransferWitness() {
() -> circuit.calculateWitness(wrongCommitment.toWitnessMap(), CurveId.BLS12_381));
// Isolate the fee's range: in = out + 2^32 balances and both commitments are correct, so
- // only the public fee's 32-bit constraint can reject it.
- var oversizedFee = transfer(BigInteger.ONE.shiftLeft(32).add(BigInteger.valueOf(990)).longValueExact(),
- 990, 0).fee(BigInteger.ONE.shiftLeft(32));
+ // both the typed Inputs setter (ADR-0068) and the public fee's 32-bit R1CS constraint reject it.
+ var baseOversizedFee = transfer(BigInteger.ONE.shiftLeft(32).add(BigInteger.valueOf(990)).longValueExact(),
+ 990, 0);
+ assertThrows(IllegalArgumentException.class,
+ () -> baseOversizedFee.fee(BigInteger.ONE.shiftLeft(32)));
+ var oversizedFeeMap = new HashMap<>(baseOversizedFee.toWitnessMap());
+ oversizedFeeMap.put(AnnotatedConfidentialTransferCircuit.FEE, List.of(BigInteger.ONE.shiftLeft(32)));
assertThrows(ArithmeticException.class,
- () -> circuit.calculateWitness(oversizedFee.toWitnessMap(), CurveId.BLS12_381));
+ () -> circuit.calculateWitness(oversizedFeeMap, CurveId.BLS12_381));
assertThrows(IllegalStateException.class, () -> circuit.compileR1CS(CurveId.BN254));
}
@@ -110,12 +115,16 @@ void vectorCommitmentWitness() {
.add(PedersenVectorBases.valueBase(1).scalarMul(oversizedAsset))
.add(PedersenVectorBases.blindingBase().scalarMul(r))
.normalized();
- var tooWide = AnnotatedVectorCommitmentCircuit.inputs()
- .amount(1).asset(oversizedAsset).blinding(r)
+ assertThrows(IllegalArgumentException.class, () -> AnnotatedVectorCommitmentCircuit.inputs()
+ .amount(1).asset(oversizedAsset));
+ var tooWideMap = new HashMap<>(AnnotatedVectorCommitmentCircuit.inputs()
+ .amount(1).asset(0).blinding(r)
.schemaDigest(AnnotatedVectorCommitment.SCHEMA.digest())
- .u(matching.affineU()).v(matching.affineV());
+ .u(matching.affineU()).v(matching.affineV())
+ .toWitnessMap());
+ tooWideMap.put(AnnotatedVectorCommitmentCircuit.ASSET, List.of(oversizedAsset));
assertThrows(ArithmeticException.class,
- () -> circuit.calculateWitness(tooWide.toWitnessMap(), CurveId.BLS12_381));
+ () -> circuit.calculateWitness(tooWideMap, CurveId.BLS12_381));
assertThrows(IllegalStateException.class, () -> circuit.compileR1CS(CurveId.BN254));
}
diff --git a/zeroj-jmt-poseidon/src/test/java/org/zeroj/merkle/jmt/poseidon/circuit/ZkJmtOperationCircuitTest.java b/zeroj-jmt-poseidon/src/test/java/org/zeroj/merkle/jmt/poseidon/circuit/ZkJmtOperationCircuitTest.java
index 5b9755d3..4c9e0181 100644
--- a/zeroj-jmt-poseidon/src/test/java/org/zeroj/merkle/jmt/poseidon/circuit/ZkJmtOperationCircuitTest.java
+++ b/zeroj-jmt-poseidon/src/test/java/org/zeroj/merkle/jmt/poseidon/circuit/ZkJmtOperationCircuitTest.java
@@ -368,8 +368,9 @@ void templateIdsDigestsAndConstraintProfilesArePinned() {
assertProfile("insert-empty", 8, 2, 17_174, 95_176, 105,
"ca6dcee1a07d90b20676ec432db79807ec6d361faaa3604444e693c49ee71fe6",
PoseidonJmtCircuitTemplates::insertEmpty);
- assertProfile("insert-different-leaf", 8, 2, 85_146, 485_464, 170,
- "4f8e96a33cac777f9c782c99f742b7f32aa8f1d711acda700edc7e567a33effa",
+ // ADR-0068 derived-boolean tracking eliminates 160 redundant AssertBoolean rows here.
+ assertProfile("insert-different-leaf", 8, 2, 84_986, 485_464, 170,
+ "456d9aee32cd03489f04230d873a80dbdae407bc8c8f5985344687727a08a213",
PoseidonJmtCircuitTemplates::insertDifferentLeaf);
assertProfile("tombstone-update", 8, 3, 17_419, 96_597, 105,
"e2e242ea426a5db45ddad220a342664f8d85ac76df14c4f5d0cfa42b0d6b979b",
@@ -389,12 +390,13 @@ private static void assertProfile(
assertEquals("zeroj-jmt-v1-" + operation + "-s" + bound + "-p" + publicInputs,
circuit.constraintGraph().name());
var r1cs = circuit.compileR1CS(CurveId.BLS12_381);
- assertEquals(constraints, r1cs.numConstraints());
- assertEquals(wires, r1cs.numWires());
- assertEquals(publicInputs, r1cs.numPublicInputs());
- assertEquals(privateInputs, r1cs.numPrivateInputs());
- assertEquals(sha256, R1CSFlatIO.canonicalSha256(
- r1cs.flat(), r1cs.numWires(), r1cs.numPublicInputs()));
+ assertAll(operation + "-s" + bound,
+ () -> assertEquals(constraints, r1cs.numConstraints()),
+ () -> assertEquals(wires, r1cs.numWires()),
+ () -> assertEquals(publicInputs, r1cs.numPublicInputs()),
+ () -> assertEquals(privateInputs, r1cs.numPrivateInputs()),
+ () -> assertEquals(sha256, R1CSFlatIO.canonicalSha256(
+ r1cs.flat(), r1cs.numWires(), r1cs.numPublicInputs())));
}
private static void assertSyntheticS0Inclusion(BigInteger key, BigInteger value) {
diff --git a/zeroj-mpf-poseidon/src/main/java/org/zeroj/merkle/mpf/poseidon/ccl/PoseidonMpfCodec.java b/zeroj-mpf-poseidon/src/main/java/org/zeroj/merkle/mpf/poseidon/ccl/PoseidonMpfCodec.java
index 02d5bd42..d19bf5f0 100644
--- a/zeroj-mpf-poseidon/src/main/java/org/zeroj/merkle/mpf/poseidon/ccl/PoseidonMpfCodec.java
+++ b/zeroj-mpf-poseidon/src/main/java/org/zeroj/merkle/mpf/poseidon/ccl/PoseidonMpfCodec.java
@@ -306,10 +306,25 @@ static Step branch(int skip, List neighbors) {
}
static Step fork(int skip, int neighborNibble, byte[] prefix, byte[] root) {
+ Objects.requireNonNull(prefix, "prefix");
+ Objects.requireNonNull(root, "root");
+ if (skip < 0 || skip > PoseidonMpfHash.KEY_PATH_NIBBLES) {
+ throw new IllegalArgumentException("fork skip out of range: " + skip);
+ }
+ if (neighborNibble < 0 || neighborNibble > 15) {
+ throw new IllegalArgumentException("fork neighborNibble out of range: " + neighborNibble);
+ }
if (prefix.length > PoseidonMpfHash.KEY_PATH_NIBBLES) {
throw new IllegalArgumentException(
"fork prefix length exceeds " + PoseidonMpfHash.KEY_PATH_NIBBLES + ": " + prefix.length);
}
+ for (int i = 0; i < prefix.length; i++) {
+ int nibble = prefix[i] & 0xFF;
+ if (nibble > 15) {
+ throw new IllegalArgumentException(
+ "fork prefix byte at index " + i + " is not a valid nibble [0, 15]: " + nibble);
+ }
+ }
return new Step(KIND_FORK, skip, List.of(), neighborNibble, prefix.length,
prefixChunksForTrailingDigest(prefix),
PoseidonMpfHash.fieldFromDigestBytes(root),
diff --git a/zeroj-mpf-poseidon/src/main/java/org/zeroj/merkle/mpf/poseidon/circuit/ZkMpf.java b/zeroj-mpf-poseidon/src/main/java/org/zeroj/merkle/mpf/poseidon/circuit/ZkMpf.java
index cb231a0f..8b27be92 100644
--- a/zeroj-mpf-poseidon/src/main/java/org/zeroj/merkle/mpf/poseidon/circuit/ZkMpf.java
+++ b/zeroj-mpf-poseidon/src/main/java/org/zeroj/merkle/mpf/poseidon/circuit/ZkMpf.java
@@ -37,6 +37,7 @@ public final class ZkMpf {
private static final int MAX_PREFIX_NIBBLES = KEY_PATH_NIBBLES;
private static final int LEAF_CHUNK_BYTES = 31;
private static final int BYTE_DIGEST_CHUNK_BYTES = 32;
+ private static final int[] BLS12_381_MODULUS_NIBBLES = bls12381ModulusNibbles();
private ZkMpf() {}
@@ -400,6 +401,7 @@ private static ZkField computeRoot(
}
PathSignals leafPath = PathSignals.of(proof.leafKeyPath().get(i));
+ requireKeyPath(zk, proof.leafKeyPath().get(i));
ZkUInt leafNibble = leafPath.at(zk, queryIndex.signal());
ZkField neighborLeaf = commitLeafFromPath(
zk,
@@ -787,13 +789,34 @@ private static void requireKeyPath(ZkContext zk, ZkArray keyPath) {
throw new IllegalArgumentException(
"keyPath must contain " + KEY_PATH_NIBBLES + " nibbles, got " + keyPath.size());
}
+ Signal equalPrefix = zk.builder().constant(1);
+ Signal less = zk.builder().constant(0);
for (int i = 0; i < keyPath.size(); i++) {
- ZkUInt nibble = keyPath.get(i);
+ ZkUInt nibble = Objects.requireNonNull(keyPath.get(i), "keyPath[" + i + "]");
if (nibble.bits() != 4) {
throw new IllegalArgumentException("keyPath[" + i + "] must be a 4-bit ZkUInt");
}
zk.requireSignal(nibble.signal());
+ nibble.assertWellFormed();
+ // Enforce canonical BLS12-381 scalar encoding (< Fr) matching PoseidonMpfHash.digestToNibbles
+ // and poseidon-authenticated-state-v1.md invariant #8 (ADR-0068).
+ Signal modulusNibble = zk.builder().constant(BLS12_381_MODULUS_NIBBLES[i]);
+ Signal nibbleEqual = nibble.signal().isEqual(modulusNibble);
+ Signal nibbleLess = nibble.signal().lessThan(modulusNibble, 4);
+ less = less.or(equalPrefix.and(nibbleLess));
+ equalPrefix = equalPrefix.and(nibbleEqual);
}
+ zk.builder().assertEqual(less, zk.builder().constant(1));
+ }
+
+ private static int[] bls12381ModulusNibbles() {
+ String hex = FieldConfig.BLS12_381.prime().toString(16);
+ hex = "0".repeat(KEY_PATH_NIBBLES - hex.length()) + hex;
+ int[] out = new int[KEY_PATH_NIBBLES];
+ for (int i = 0; i < out.length; i++) {
+ out[i] = Character.digit(hex.charAt(i), 16);
+ }
+ return out;
}
private static void requireRoot(ZkContext zk, ZkField root) {
diff --git a/zeroj-mpf-poseidon/src/test/java/org/zeroj/merkle/mpf/poseidon/circuit/ZkMpfCanonicalKeyPathAndForkTest.java b/zeroj-mpf-poseidon/src/test/java/org/zeroj/merkle/mpf/poseidon/circuit/ZkMpfCanonicalKeyPathAndForkTest.java
new file mode 100644
index 00000000..345a75b3
--- /dev/null
+++ b/zeroj-mpf-poseidon/src/test/java/org/zeroj/merkle/mpf/poseidon/circuit/ZkMpfCanonicalKeyPathAndForkTest.java
@@ -0,0 +1,91 @@
+package org.zeroj.merkle.mpf.poseidon.circuit;
+
+import org.junit.jupiter.api.Test;
+import org.zeroj.api.CurveId;
+import org.zeroj.circuit.CircuitBuilder;
+import org.zeroj.circuit.FieldConfig;
+import org.zeroj.circuit.annotation.ZkArray;
+import org.zeroj.circuit.annotation.ZkContext;
+import org.zeroj.circuit.annotation.ZkField;
+import org.zeroj.circuit.annotation.ZkInputMap;
+import org.zeroj.circuit.annotation.ZkUInt;
+import org.zeroj.circuit.lib.poseidon.PoseidonParamsBLS12_381T3;
+import org.zeroj.merkle.mpf.poseidon.profile.PoseidonMpfHash;
+
+import java.math.BigInteger;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+/**
+ * ADR-0068: Enforces canonical BLS12-381 scalar (< Fr) key-path constraints in ZkMpf circuits.
+ */
+class ZkMpfCanonicalKeyPathAndForkTest {
+
+ @Test
+ void keyPathCommitmentRejectsNonCanonicalPathsAndAcceptsExactFrMinusOne() {
+ var builder = CircuitBuilder.create("mpf-keypath-canonical")
+ .publicVar("commitment");
+ for (int i = 0; i < ZkMpf.KEY_PATH_NIBBLES; i++) {
+ builder.secretVar("key_" + i);
+ }
+ CircuitBuilder circuit = builder.defineSignals(c -> {
+ var zk = new ZkContext(c);
+ var keyPath = ZkArray.secretUInts(c, "key", ZkMpf.KEY_PATH_NIBBLES, 4);
+ var expected = ZkField.publicInput(c, "commitment");
+ ZkMpf.keyPathCommitment(zk, PoseidonParamsBLS12_381T3.INSTANCE, keyPath).assertEqual(expected);
+ });
+ var r1cs = circuit.compileR1CS(CurveId.BLS12_381);
+
+ BigInteger fr = FieldConfig.BLS12_381.prime();
+
+ // Exact canonical boundary: Fr - 1 must pass
+ int[] maxCanonical = toNibbles(fr.subtract(BigInteger.ONE));
+ BigInteger maxCommitment = PoseidonMpfHash.keyPathCommitment(PoseidonParamsBLS12_381T3.INSTANCE, maxCanonical);
+ var validInputs = new ZkInputMap()
+ .put("commitment", maxCommitment)
+ .putArray("key", toBigInts(maxCanonical));
+ BigInteger[] validWitness = assertDoesNotThrow(
+ () -> circuit.calculateWitness(validInputs.toWitnessMap(), CurveId.BLS12_381));
+ assertDoesNotThrow(() -> r1cs.verifyWitness(validWitness));
+
+ // Exact modulus Fr must be rejected in-circuit
+ int[] exactFr = toNibbles(fr);
+ BigInteger frCommitment = PoseidonMpfHash.keyPathCommitment(PoseidonParamsBLS12_381T3.INSTANCE, exactFr);
+ var exactFrInputs = new ZkInputMap()
+ .put("commitment", frCommitment)
+ .putArray("key", toBigInts(exactFr));
+ assertThrows(ArithmeticException.class,
+ () -> circuit.calculateWitness(exactFrInputs.toWitnessMap(), CurveId.BLS12_381));
+
+ // 64 x 0xF (all 15s, > Fr) must be rejected in-circuit
+ int[] allFs = new int[ZkMpf.KEY_PATH_NIBBLES];
+ Arrays.fill(allFs, 15);
+ BigInteger allFsCommitment = PoseidonMpfHash.keyPathCommitment(PoseidonParamsBLS12_381T3.INSTANCE, allFs);
+ var allFsInputs = new ZkInputMap()
+ .put("commitment", allFsCommitment)
+ .putArray("key", Collections.nCopies(ZkMpf.KEY_PATH_NIBBLES, BigInteger.valueOf(15)));
+ assertThrows(ArithmeticException.class,
+ () -> circuit.calculateWitness(allFsInputs.toWitnessMap(), CurveId.BLS12_381));
+ }
+
+ private static int[] toNibbles(BigInteger value) {
+ String hex = value.toString(16);
+ hex = "0".repeat(ZkMpf.KEY_PATH_NIBBLES - hex.length()) + hex;
+ int[] out = new int[ZkMpf.KEY_PATH_NIBBLES];
+ for (int i = 0; i < out.length; i++) {
+ out[i] = Character.digit(hex.charAt(i), 16);
+ }
+ return out;
+ }
+
+ private static List toBigInts(int[] values) {
+ var out = new ArrayList(values.length);
+ for (int v : values) out.add(BigInteger.valueOf(v));
+ return out;
+ }
+}
diff --git a/zeroj-mpf-poseidon/src/test/java/org/zeroj/merkle/mpf/poseidon/circuit/ZkMpfOperationCircuitTest.java b/zeroj-mpf-poseidon/src/test/java/org/zeroj/merkle/mpf/poseidon/circuit/ZkMpfOperationCircuitTest.java
index abff2a2c..91b9db05 100644
--- a/zeroj-mpf-poseidon/src/test/java/org/zeroj/merkle/mpf/poseidon/circuit/ZkMpfOperationCircuitTest.java
+++ b/zeroj-mpf-poseidon/src/test/java/org/zeroj/merkle/mpf/poseidon/circuit/ZkMpfOperationCircuitTest.java
@@ -151,27 +151,28 @@ void randomizedCclInclusionsDifferentiallyMatchTheSpecializedCircuit() {
}
}
- // Template names identify semantic/schema versions. ADR-0063 direct Boolean lowering
- // changes the exact R1CS pins and requires fresh circuit-specific keys.
+ // Template names identify semantic/schema versions. ADR-0068 canonical < Fr key-path
+ // constraints and derived-boolean deduplication update the exact R1CS pins and require
+ // fresh circuit-specific keys.
@Test
void branchProfileConstraintCountsArePinned() {
int[][] expected = {
- {0, 3_051, 13_259, 65},
- {1, 8_921, 46_095, 71},
- {3, 20_163, 111_749, 83},
- {8, 48_268, 275_884, 113},
- {9, 53_889, 308_711, 119},
- {12, 70_752, 407_192, 137},
- {64, 363_045, 2_114_196, 449}
+ {0, 3_879, 14_731, 65},
+ {1, 9_747, 47_567, 71},
+ {3, 20_985, 113_221, 83},
+ {8, 49_080, 277_356, 113},
+ {9, 54_699, 310_183, 119},
+ {12, 71_556, 408_664, 137},
+ {64, 363_745, 2_115_668, 449}
};
String[] digests = {
- "29b7aa4d9c198c94017a26432008ac9ad6feb8eb2010a3047033661a9d884847",
- "c163d744f308044b5aaea66b301be2e42bec907d14d3bef0e560f3dacd98cadb",
- "14b8718f15e8181e9d24eb02a781e523181cb3fa941b8d0ad54adb967f042647",
- "ff0c5c68e02fd7418d014fc1ec74d89626611d9aedad1907f8dc8fba25e0e2a5",
- "dd69a34951612ab67283ecf6ffbd6c5cdf47003db3bdb2ecc6b0da2f72eb3b7d",
- "baa1ce903d9bf95a669477dd7032187a663e0f8c0e5b5c05d872f9e80b41d9b9",
- "3517e47361e51c47c5ca190c494b15fd6278da49f1818da55a4e6ebb7d9a07a4"
+ "3893593eb165646cf488ed2a7a6a9cdbb69eed3e5cc68be6da3c9c483f7c028d",
+ "e1e8f031df19a35eecbb50eeb31f6757f6c8c13ccf956db06df692a4ee20cecc",
+ "3c7a3726a67247f70037b448c99161d295c6f215c91ed4f73ede09a44f4c9ecb",
+ "434051064e5c75e9b0a475fa35d5dbfefff218202ab392934824551071813afb",
+ "3e646c58603d06834be66bde5df18cef24d3313b730dd36f4f8590a60ef38a1f",
+ "53a2d3db06463f1acf53a84828b13dfdf35b3a4a8882a7c21f657e23744f3857",
+ "113cac537c007cfb6d5a506dc0cc87e67ce60ab12872da71e25f029f5342ffb7"
};
for (int index = 0; index < expected.length; index++) {
int[] profile = expected[index];
@@ -206,16 +207,17 @@ void canonicalTemplateIdentityBindsOperationAndExactR1cs() {
() -> PoseidonMpfCircuitTemplates.inclusion(-1));
assertThrows(IllegalArgumentException.class,
() -> PoseidonMpfCircuitTemplates.inclusion(65));
- assertExactProfile(
- PoseidonMpfCircuitTemplates.nonInclusionEmpty(8),
- "zeroj-mpf-v1-non-inclusion-empty-s8-p1",
- 45_165, 263_282, 112,
- "aea0fbe7a19badb27df3db6dd8851681464b55d8e897344de2226eee20ad2a0a");
- assertExactProfile(
- PoseidonMpfCircuitTemplates.nonInclusionDifferentLeaf(8),
- "zeroj-mpf-v1-non-inclusion-different-leaf-s8-p1",
- 50_881, 279_787, 178,
- "22c45307ee886d545013d6ce0f38b6d0ed32ff0c43233cf7cb1b759b2c3f196c");
+ assertAll(
+ () -> assertExactProfile(
+ PoseidonMpfCircuitTemplates.nonInclusionEmpty(8),
+ "zeroj-mpf-v1-non-inclusion-empty-s8-p1",
+ 45_979, 264_754, 112,
+ "cf3ae294b80deb308e3dc978603bf3484d1f84b13cf8aa54f3d989ffb78828a5"),
+ () -> assertExactProfile(
+ PoseidonMpfCircuitTemplates.nonInclusionDifferentLeaf(8),
+ "zeroj-mpf-v1-non-inclusion-different-leaf-s8-p1",
+ 52_523, 282_731, 178,
+ "d03b5b62654d8d4d27b40c0669682eaba95e5482b94cba8022f06fa9368cc5a5"));
}
private static void assertExactProfile(
@@ -227,12 +229,13 @@ private static void assertExactProfile(
String sha256) {
assertEquals(templateId, circuit.constraintGraph().name());
var r1cs = circuit.compileR1CS(CurveId.BLS12_381);
- assertEquals(constraints, r1cs.numConstraints());
- assertEquals(wires, r1cs.numWires());
- assertEquals(1, r1cs.numPublicInputs());
- assertEquals(privateInputs, r1cs.numPrivateInputs());
- assertEquals(sha256, R1CSFlatIO.canonicalSha256(
- r1cs.flat(), r1cs.numWires(), r1cs.numPublicInputs()));
+ assertAll(templateId,
+ () -> assertEquals(constraints, r1cs.numConstraints()),
+ () -> assertEquals(wires, r1cs.numWires()),
+ () -> assertEquals(1, r1cs.numPublicInputs()),
+ () -> assertEquals(privateInputs, r1cs.numPrivateInputs()),
+ () -> assertEquals(sha256, R1CSFlatIO.canonicalSha256(
+ r1cs.flat(), r1cs.numWires(), r1cs.numPublicInputs())));
}
@Test
diff --git a/zeroj-mpf-poseidon/src/test/java/org/zeroj/merkle/mpf/poseidon/circuit/ZkMpfTransitionCircuitTest.java b/zeroj-mpf-poseidon/src/test/java/org/zeroj/merkle/mpf/poseidon/circuit/ZkMpfTransitionCircuitTest.java
index e364ae3a..5afa44f9 100644
--- a/zeroj-mpf-poseidon/src/test/java/org/zeroj/merkle/mpf/poseidon/circuit/ZkMpfTransitionCircuitTest.java
+++ b/zeroj-mpf-poseidon/src/test/java/org/zeroj/merkle/mpf/poseidon/circuit/ZkMpfTransitionCircuitTest.java
@@ -20,43 +20,46 @@
import java.util.List;
import java.util.Map;
+import static org.junit.jupiter.api.Assertions.assertAll;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
class ZkMpfTransitionCircuitTest {
- // Template names identify semantic/schema versions. ADR-0063 direct Boolean lowering
- // changes the exact R1CS pins and requires fresh circuit-specific keys.
+ // Template names identify semantic/schema versions. ADR-0068 canonical < Fr key-path
+ // constraints and derived-boolean deduplication update the exact R1CS pins and require
+ // fresh circuit-specific keys.
@Test
void transitionTemplateIdentitiesAndReleaseProfilesArePinned() {
- assertProfile("value-update", 8, 80_119, 509_503, 114,
- "2bdcd87c53a3ad649cb27c28a3c4caf1d66c5efc37044cd69e737ed991ebb4e0",
- PoseidonMpfCircuitTemplates::valueUpdate);
- assertProfile("insert-empty", 8, 78_917, 502_429, 113,
- "48a0267e615a670218de76bb08304699efd4b263bdfc67896acd7ddffc12002c",
- PoseidonMpfCircuitTemplates::insertEmpty);
- assertProfile("insert-different-leaf", 8, 100_973, 626_087, 179,
- "d096de1decc20bb4df12da79a54aa8facc61462e1031bd03ead0b5bbd1c4576d",
- PoseidonMpfCircuitTemplates::insertDifferentLeaf);
- assertProfile("value-update", 9, 89_571, 570_648, 120,
- "dd4ef446732a67c57a8cf97d3f320eca6d76f227ad42625b5f80770c2bd1eb04",
- PoseidonMpfCircuitTemplates::valueUpdate);
- assertProfile("insert-empty", 9, 88_369, 563_574, 119,
- "d8d132110e41bfc6b646f2775d4ad7d1abb18fd631760a8f76b4ba82eb870ca2",
- PoseidonMpfCircuitTemplates::insertEmpty);
- assertProfile("insert-different-leaf", 9, 110_425, 687_232, 185,
- "1627ee290b5f9f09056152fd1a9eb222d1d2e1f0fef421a8b101a772cd09b899",
- PoseidonMpfCircuitTemplates::insertDifferentLeaf);
- assertProfile("value-update", 12, 117_927, 754_083, 138,
- "65f6458656d08bf960e76dcd211457341a099cc0ec687b3afb6362a5e45becaa",
- PoseidonMpfCircuitTemplates::valueUpdate);
- assertProfile("insert-empty", 12, 116_725, 747_009, 137,
- "53ee3e54949d973a1e0ae1e7af7c7d7c1cd80020ecb5afdc9221500f0e9585c1",
- PoseidonMpfCircuitTemplates::insertEmpty);
- assertProfile("insert-different-leaf", 12, 138_781, 870_667, 203,
- "4e923b71ad150c2f7cd3a50b51e3df22a6b3276a09b486cd2158d32be13ae3c1",
- PoseidonMpfCircuitTemplates::insertDifferentLeaf);
+ assertAll(
+ () -> assertProfile("value-update", 8, 80_931, 510_975, 114,
+ "984d4da5dc29ce4d9ee0de8a572e0e5e3ba350aa75f79e54c76efb2f41d8c300",
+ PoseidonMpfCircuitTemplates::valueUpdate),
+ () -> assertProfile("insert-empty", 8, 79_729, 503_901, 113,
+ "112a2b7848dc8a4de818a9476867a239478151ea02e6abc84fd37c83ef94a251",
+ PoseidonMpfCircuitTemplates::insertEmpty),
+ () -> assertProfile("insert-different-leaf", 8, 102_577, 629_031, 179,
+ "45adb2a0194e5518341fa3fff4fe8f695a0bf60c2b358c3b70a9c4f2ab308e8e",
+ PoseidonMpfCircuitTemplates::insertDifferentLeaf),
+ () -> assertProfile("value-update", 9, 90_381, 572_120, 120,
+ "9bace08aa18e45fa7861265c0a9820b7a179f1da99c7a00b944b2881afdd3df9",
+ PoseidonMpfCircuitTemplates::valueUpdate),
+ () -> assertProfile("insert-empty", 9, 89_179, 565_046, 119,
+ "943dadf5b5b83874748d04790c61d72f5295891b43cb0921198bc06ba722f9ea",
+ PoseidonMpfCircuitTemplates::insertEmpty),
+ () -> assertProfile("insert-different-leaf", 9, 112_027, 690_176, 185,
+ "9ebc6b9f69d282780c1da9473bb86b855eb1defef278a282a65ccd31cc45c49f",
+ PoseidonMpfCircuitTemplates::insertDifferentLeaf),
+ () -> assertProfile("value-update", 12, 118_731, 755_555, 138,
+ "5c5e088da4e39c7ef68f685e09b953eead144fd682b4b7120a646d4aeda80d9e",
+ PoseidonMpfCircuitTemplates::valueUpdate),
+ () -> assertProfile("insert-empty", 12, 117_529, 748_481, 137,
+ "5d22c04bf535f54d87c9d765b4a0b0edcc78b0dd275900fdc7410c0b0bc05eca",
+ PoseidonMpfCircuitTemplates::insertEmpty),
+ () -> assertProfile("insert-different-leaf", 12, 140_377, 873_611, 203,
+ "b37e1af49bf0f543095fcbbf781fde341f0a1c5e901a474139c0839eac2dda03",
+ PoseidonMpfCircuitTemplates::insertDifferentLeaf));
}
private static void assertProfile(
@@ -71,12 +74,13 @@ private static void assertProfile(
assertEquals("zeroj-mpf-v1-" + operation + "-s" + bound + "-p2",
circuit.constraintGraph().name());
var r1cs = circuit.compileR1CS(CurveId.BLS12_381);
- assertEquals(constraints, r1cs.numConstraints());
- assertEquals(wires, r1cs.numWires());
- assertEquals(2, r1cs.numPublicInputs());
- assertEquals(privateInputs, r1cs.numPrivateInputs());
- assertEquals(sha256, R1CSFlatIO.canonicalSha256(
- r1cs.flat(), r1cs.numWires(), r1cs.numPublicInputs()));
+ assertAll(operation + "-s" + bound,
+ () -> assertEquals(constraints, r1cs.numConstraints()),
+ () -> assertEquals(wires, r1cs.numWires()),
+ () -> assertEquals(2, r1cs.numPublicInputs()),
+ () -> assertEquals(privateInputs, r1cs.numPrivateInputs()),
+ () -> assertEquals(sha256, R1CSFlatIO.canonicalSha256(
+ r1cs.flat(), r1cs.numWires(), r1cs.numPublicInputs())));
}
@Test
diff --git a/zeroj-mpf-poseidon/src/test/java/org/zeroj/merkle/mpf/poseidon/witness/PoseidonMpfOperationWitnessTest.java b/zeroj-mpf-poseidon/src/test/java/org/zeroj/merkle/mpf/poseidon/witness/PoseidonMpfOperationWitnessTest.java
index ab492841..0a51c81c 100644
--- a/zeroj-mpf-poseidon/src/test/java/org/zeroj/merkle/mpf/poseidon/witness/PoseidonMpfOperationWitnessTest.java
+++ b/zeroj-mpf-poseidon/src/test/java/org/zeroj/merkle/mpf/poseidon/witness/PoseidonMpfOperationWitnessTest.java
@@ -325,6 +325,14 @@ void rejectsEveryInvalidForkLeafAndPrefixEncodingPath() {
// CBOR wire with fork prefix > 64 bytes rejected at decode.
assertThrows(IllegalArgumentException.class, () -> PoseidonMpfCodec.decode(
encodeProof(forkStepCbor(0, 1, new byte[65], new byte[32]))));
+
+ // CBOR wire with non-nibble fork prefix byte (> 15) or invalid neighborNibble rejected at decode (ADR-0068).
+ assertThrows(IllegalArgumentException.class, () -> PoseidonMpfCodec.decode(
+ encodeProof(forkStepCbor(0, 1, new byte[]{0x01, 0x10}, new byte[32]))));
+ assertThrows(IllegalArgumentException.class, () -> PoseidonMpfCodec.decode(
+ encodeProof(forkStepCbor(0, 1, new byte[]{(byte) 0xFF}, new byte[32]))));
+ assertThrows(IllegalArgumentException.class, () -> PoseidonMpfCodec.decode(
+ encodeProof(forkStepCbor(0, 16, new byte[]{0x01}, new byte[32]))));
}
private static byte[][] independentSiblings(byte[][] children, int meNibble) {