From 3b99311ddbbbf96803d7a60be0b57b646e891d5f Mon Sep 17 00:00:00 2001 From: Satya Date: Fri, 20 Nov 2026 17:33:15 +0800 Subject: [PATCH 1/2] security(circuit-dsl): enforce index bounds in arrayAccess and add arrayAccessOrZero (ADR-0065) Implements ADR-0065 to close silent out-of-bounds-to-zero arrayAccess soundness bug: - CircuitAPIImpl.arrayAccess: validate lifecycle/nulls atomically, reject empty arrays, and emit Gate.LinComb(selectorSum) + assertEqual(selectorSum, oneWire) (1 R1CS constraint, 1 wire) so 0 <= index < arr.length is strictly enforced across CircuitAPI, SignalBuilder, and Mux. - CircuitAPI.arrayAccessOrZero / SignalBuilder.arrayAccessOrZero: add explicit total-function opt-in returning 0 on out-of-bounds indices without an index constraint, with soundness warning Javadoc. - ZkMpf.PathSignals.at: opt into arrayAccessOrZero for independently bounded active reads and valid-masked padding rows, preserving 100% of pinned MPF R1CS SHA-256 digests. - Add ADR-0065 (Proposed), ADR-0010 back-reference, user-guide updates, ArrayAccessSoundnessTest (BN254 & BLS12-381, R1CS & PlonK), and Mux.arrayAccess bounds tests. --- docs/adr/0010-java-circuit-dsl.md | 4 +- .../adr/0065-array-access-bounds-soundness.md | 97 +++++ docs/circuit-dsl-user-guide.md | 3 +- .../docs/guides/circuits/circuit-dsl.md | 2 +- .../java/org/zeroj/circuit/CircuitAPI.java | 35 +- .../org/zeroj/circuit/CircuitAPIImpl.java | 34 +- .../java/org/zeroj/circuit/SignalBuilder.java | 31 +- .../circuit/ArrayAccessSoundnessTest.java | 332 ++++++++++++++++++ .../main/java/org/zeroj/circuit/lib/Mux.java | 7 +- .../org/zeroj/circuit/lib/CircuitLibTest.java | 26 ++ .../merkle/mpf/poseidon/circuit/ZkMpf.java | 6 +- 11 files changed, 568 insertions(+), 9 deletions(-) create mode 100644 docs/adr/0065-array-access-bounds-soundness.md create mode 100644 zeroj-circuit-dsl/src/test/java/org/zeroj/circuit/ArrayAccessSoundnessTest.java diff --git a/docs/adr/0010-java-circuit-dsl.md b/docs/adr/0010-java-circuit-dsl.md index 990ffa05..c27d55b0 100644 --- a/docs/adr/0010-java-circuit-dsl.md +++ b/docs/adr/0010-java-circuit-dsl.md @@ -1,7 +1,9 @@ # ADR-0010: Java DSL for ZK Circuit Definition ## Status -Updated by ADR-0020 +Updated by ADR-0020. **Amended by [ADR-0065](0065-array-access-bounds-soundness.md)** (2026-11-20): +`CircuitAPI.arrayAccess` now rejects empty arrays and constrains `0 <= index < arr.length` +(`sum_i isEqual(index, i) == 1`), with `arrayAccessOrZero` added as the explicit total-function opt-in. ## Date 2026-03-28 diff --git a/docs/adr/0065-array-access-bounds-soundness.md b/docs/adr/0065-array-access-bounds-soundness.md new file mode 100644 index 00000000..ec448565 --- /dev/null +++ b/docs/adr/0065-array-access-bounds-soundness.md @@ -0,0 +1,97 @@ +# ADR-0065: Bounds-Constrained `CircuitAPI.arrayAccess` and Explicit Total Lookup (`arrayAccessOrZero`) + +## Status +Proposed — 2026-11-20 (pending review sign-off). Hardens `CircuitAPI.arrayAccess` (and its delegates `SignalBuilder.arrayAccess` and `Mux.arrayAccess`) to enforce `0 <= index < arr.length` in-circuit, and introduces an explicitly named total-function variant `arrayAccessOrZero` for callers with independently constrained indices and masked padding rows. Amends [ADR-0010](0010-java-circuit-dsl.md). + +**Risk class: R2.** Changes circuit soundness semantics and emitted R1CS/PlonK constraints for every caller of `CircuitAPI.arrayAccess` / `SignalBuilder.arrayAccess` / `Mux.arrayAccess`. + +## Date +2026-11-20 + +## Context +`CircuitAPIImpl.arrayAccess(Variable[] arr, Variable index)` implements dynamic indexing over a fixed-length circuit array by computing: + +$$\text{result} = \sum_{i=0}^{n-1} \text{arr}[i] \cdot \text{isEqual}(\text{index}, i)$$ + +Previously, the method neither rejected empty arrays nor constrained `index` to lie in `[0, n - 1]`. Consequently, whenever a prover supplied any out-of-bounds field element (`index = n`, `index = p - 1`, etc.), every selector `isEqual(index, i)` evaluated to `0`, the sum silently produced `0`, and the constraint system remained satisfied. + +In an application circuit that assumes `arr[index]` reads a real entry of `arr` (for example, looking up an allowlisted value, permission flag, fee tier, or commitment at a secret index, or asserting `arr[index] == 0`), a malicious prover could supply an out-of-bounds index (such as `arr.length` or `p - 1`) to fabricate a `0` lookup result without possessing a valid array entry. + +A full in-repository caller census showed only three production call paths: +1. `SignalBuilder.arrayAccess(Signal[], Signal)` (`zeroj-circuit-dsl`) — delegates to `CircuitAPI.arrayAccess`. +2. `Mux.arrayAccess(CircuitAPI, Variable[], Variable)` (`zeroj-circuit-lib`) — delegates to `CircuitAPI.arrayAccess`. +3. `ZkMpf.PathSignals.at(ZkContext, Signal)` (`zeroj-mpf-poseidon/.../circuit/ZkMpf.java:829`) — looks up a nibble in a 64-element key path. Every active lookup in `ZkMpf` already carries an explicit `lteConst` bounds constraint (`<= 63`), whereas inactive padding rows (`valid == 0`) intentionally evaluate `queryIndex = 64` and discard the lookup via `valid.select(...)`. + +## Threat Model and Trust Assumptions +- **Untrusted:** Any prover-controlled witness wire passed as `index` or as an element of `arr` (including `index = arr.length`, `index = p - 1`, or arbitrary field elements in `F_p`). +- **Trusted:** Circuit-construction-time array length `arr.length` (`1 <= arr.length <= Integer.MAX_VALUE < p` for all supported curves: BLS12-381 `Fr`, BN254 `Fr`, Pallas `Fp`). +- **Constraint-system assumption:** `isEqual(index, constant(i))` is sound (returns `1` iff `index == i (mod p)` and `0` otherwise, enforced via `isZero`). + +## Pinned Normative References +- [ADR-0010](0010-java-circuit-dsl.md) — Java Circuit DSL (`CircuitAPI.arrayAccess`). +- [ADR-0037](0037-jubjub-soundness-and-hardening.md) — Circuit-DSL soundness precedent (explicit in-circuit bounds on `lessThan` rather than undocumented caller preconditions). +- [ADR-0042](0042-operation-specific-poseidon-mpf-and-jmt-circuits.md) — Operation-specific Poseidon MPF circuits and their pinned canonical R1CS SHA-256 digests (`ZkMpfOperationCircuitTest`, `ZkMpfTransitionCircuitTest`). + +## Decision +1. **D1 (Strict bounds-constrained `arrayAccess`):** + - `CircuitAPIImpl.arrayAccess(Variable[] arr, Variable index)` validates `requireNotFrozen()`, rejects `null` arguments (array, elements, or `index`) atomically before emitting any gate, and rejects `arr.length == 0` with `IllegalArgumentException`. + - For `arr.length >= 1`, `arrayAccess` computes `selector_i = isEqual(index, constant(i))`, accumulates `result = sum(arr[i] * selector_i)`, forms the single linear combination `selectorSum = sum(selector_i)` via `Gate.LinComb`, and emits **`assertEqual(selectorSum, oneWire)`**. + - **Soundness proof:** Because `1 <= n <= Integer.MAX_VALUE < p`, the constants `0, 1, ..., n - 1` are pairwise distinct modulo `p`. For any field element `index ∈ F_p`, at most one `selector_i` equals `1` (the rest are `0`). Hence `sum_{i=0}^{n-1} selector_i == 1` holds **if and only if** `index ∈ {0, 1, ..., n - 1}`, in which case `result == arr[index]`. Any out-of-bounds `index` yields `selectorSum == 0 != 1`, making the constraint system unsatisfiable. + - **Cost:** Adding `Gate.LinComb` + `AssertEq` costs **1 R1CS constraint and 1 wire** regardless of `arr.length` (no extra multiplications or bit decompositions). + - `SignalBuilder.arrayAccess` and `Mux.arrayAccess` delegate directly to `CircuitAPI.arrayAccess` and inherit this invariant automatically. +2. **D2 (Explicit total-function lookup `arrayAccessOrZero`):** + - Add `default Variable arrayAccessOrZero(Variable[] arr, Variable index)` to `CircuitAPI` (overridden in `CircuitAPIImpl` with lifecycle/null validation) and `SignalBuilder.arrayAccessOrZero(Signal[] arr, Signal index)` with explicit Javadoc warning that out-of-bounds indices silently return `0` without constraining `index`. + - `arrayAccessOrZero` is strictly opt-in for circuits that independently constrain `index` on active rows and mask inactive padding rows. +3. **D3 (`ZkMpf` padding-row preservation):** + - Update `ZkMpf.PathSignals.at` (`ZkMpf.java:829`) to call `zk.builder().arrayAccessOrZero(signals, index)` with an inline citation to `ZkMpf`'s existing explicit bounds constraints (`prepareBranchProof:249`, `computeRoot:321`, `nonInclusionDifferentLeaf:131`, `verifyDifferentLeafInsertion:168`) and padding-row masking (`valid.select`). + - This preserves all existing pinned `ZkMpf` R1CS constraint counts and canonical SHA-256 digests unchanged while making the opt-in total-lookup semantics explicit in source. + +## Alternatives Considered +- **Clamp `queryIndex` on padding rows in `ZkMpf` and keep only strict `arrayAccess`:** Rejected for this PR because clamping adds `select` + `arrayAccess` constraints on every `ZkMpf` branch step and breaks every pinned R1CS SHA-256 digest and proving key across `zeroj-mpf-poseidon` even though `ZkMpf` already constrains active bounds independently. Providing `arrayAccessOrZero` keeps the general `arrayAccess` API sound by default with zero key churn on `ZkMpf`. +- **Add a `lessThan(index, n)` bit-decomposition check instead of `sum(selector_i) == 1`:** Rejected — `arrayAccess` already computes all `n` equality selectors `isEqual(index, i)`, so constraining `sum(selector_i) == 1` costs 1 linear constraint instead of `ceil(log2(n)) + 2` range-check constraints and requires no bit-width parameter. +- **Document OOB → 0 as a precondition on `arrayAccess`:** Rejected — matches the unsafe pattern ADR-0037 retired for `lessThan`; dynamic array indexing must fail closed by default. + +## Security Invariants +- **I1 (In-bounds enforcement):** For any non-empty array `arr` of length `n >= 1`, `arrayAccess(arr, index)` is satisfiable iff `index ∈ {0, 1, ..., n - 1}` (as a field element in `F_p`), and its output wire equals `arr[index]`. +- **I2 (OOB rejection):** Any witness with `index = n`, `index = n + 1`, or `index = p - 1` fails R1CS and PlonK constraint satisfaction on both BLS12-381 and BN254, even when `arr` contains `0` entries. +- **I3 (Empty-array & null rejection):** `arrayAccess` throws `IllegalArgumentException` on `arr.length == 0` and `NullPointerException` on null `arr`, null elements, or null `index`, atomically before emitting any gate. +- **I4 (Explicit total opt-in):** Out-of-bounds → `0` semantics are reachable only through the explicitly named `arrayAccessOrZero` method. +- **I5 (MPF template stability):** All pinned `ZkMpf` R1CS constraint counts and canonical SHA-256 digests in `zeroj-mpf-poseidon` remain identical. + +## Consequences +- **Positive:** Eliminates a silent under-constrained OOB→0 forgery class across `CircuitAPI.arrayAccess`, `SignalBuilder.arrayAccess`, and `Mux.arrayAccess` at a cost of 1 R1CS constraint per lookup. +- **Trade-offs:** + - Circuits calling `arrayAccess` outside `ZkMpf` gain 1 R1CS constraint and 1 wire per `arrayAccess` call and therefore produce new R1CS digests / proving & verification keys. + - Custom `CircuitAPI` implementations remain source-compatible because `arrayAccessOrZero` has a `default` implementation on `CircuitAPI`. + +## Risks +- **Misuse of `arrayAccessOrZero`:** A caller choosing `arrayAccessOrZero` without independently constraining active indices reintroduces OOB→0 behavior. Mitigated by naming (`OrZero`), explicit Javadoc warning, and keeping `Mux.arrayAccess` / `SignalBuilder.arrayAccess` / `CircuitAPI.arrayAccess` strictly constrained. +- **Downstream key migration:** External circuits (e.g., in downstream applications using `Mux.arrayAccess` or `SignalBuilder.arrayAccess`) must regenerate proving/verifying keys after upgrading. + +## Compatibility +- **Breaking R1CS / key change for `arrayAccess` callers:** Every circuit calling `CircuitAPI.arrayAccess`, `SignalBuilder.arrayAccess`, or `Mux.arrayAccess` gains 1 R1CS constraint and 1 wire per call and requires fresh circuit-specific keys. Release notes must record this explicitly. +- **Non-breaking for `zeroj-mpf-poseidon`:** `ZkMpf` switches to `arrayAccessOrZero` (matching its independently constrained active indices and masked padding rows), so all pinned MPF R1CS digests and keys remain unchanged. +- **Source/binary API compatibility:** `CircuitAPI.arrayAccessOrZero` is added as a `default` method so existing `CircuitAPI` implementations compile unchanged. + +## Implementation Milestones +- **M1 — DSL & MPF implementation (Complete):** Enforce `sum(selector_i) == 1` and reject empty arrays in `CircuitAPIImpl.arrayAccess`, add `arrayAccessOrZero` to `CircuitAPI`/`CircuitAPIImpl`/`SignalBuilder`, update `Mux.arrayAccess` Javadoc, and switch `ZkMpf.PathSignals.at` to `arrayAccessOrZero`. +- **M2 — Adversarial & cross-backend verification (Complete):** Add `ArrayAccessSoundnessTest` in `zeroj-circuit-dsl` covering in-bounds reads, OOB rejections (`arr.length`, `arr.length + 1`, `p - 1`, `arr.length == 1`, zero-valued entries), empty/null/frozen rejections, `SignalBuilder` and `Mux` delegation, both BLS12-381 and BN254, and both R1CS and PlonK constraint checks; verify `zeroj-mpf-poseidon` pinned R1CS digests remain unchanged. +- **M3 — Documentation & review (In progress):** `ADR-0010` back-reference and user guides (`docs/circuit-dsl-user-guide.md`, `www/src/content/docs/guides/circuits/circuit-dsl.md`) updated; awaiting external review sign-off before marking ADR-0065 `Accepted`. + +## Verification Strategy +1. **Unit & adversarial soundness (`zeroj-circuit-dsl` — `ArrayAccessSoundnessTest`):** + - Positive tests: every valid index `0 .. n - 1` (for `n = 1` and `n = 4`) returns exact `arr[index]` and satisfies R1CS and PlonK on both BLS12-381 and BN254. + - Negative OOB tests (all must fail witness / constraint verification): `index = n`, `index = n + 1`, `index = p - 1`, including when `arr` contains `0` and when the caller asserts `result == 0` (reproducing the pre-fix forgery). + - Guard tests: empty `arr` throws `IllegalArgumentException`, null `arr` / null element / null `index` throws `NullPointerException` atomically before emitting gates, and post-freeze invocation throws `IllegalStateException`. + - `arrayAccessOrZero` tests: returns `arr[i]` for `0 <= i < n` and `0` for `index = n` / `index = p - 1` / empty `arr`. +2. **Stdlib & MPF regression (`zeroj-circuit-lib`, `zeroj-mpf-poseidon`, `zeroj-integration-tests`):** + - Verify `Mux.arrayAccess` rejects OOB indices. + - Verify all pinned `ZkMpfOperationCircuitTest` and `ZkMpfTransitionCircuitTest` R1CS SHA-256 digests and padding-row tests pass unchanged. + +## Remaining Production / Audit Gates +- External cryptographic/circuit audit remains required before mainnet or value-bearing deployment of circuits built with `zeroj-circuit-dsl`. + +## Revision History +| Date | Status | Summary | +|---|---|---| +| 2026-11-20 | Proposed (rev 1) | Initial ADR and implementation for bounds-constrained `arrayAccess` and opt-in `arrayAccessOrZero`. | diff --git a/docs/circuit-dsl-user-guide.md b/docs/circuit-dsl-user-guide.md index ee8cf030..1304a0dd 100644 --- a/docs/circuit-dsl-user-guide.md +++ b/docs/circuit-dsl-user-guide.md @@ -368,7 +368,8 @@ BigInteger[] witness = circuit.calculateWitness(inputs, CurveId.BLS12_381); | Method | Returns | Constraints | |--------|---------|------------| -| `arrayAccess(arr, idx)` | arr[idx] via MUX tree | O(arr.length) | +| `arrayAccess(arr, idx)` | `arr[idx]` via MUX scan; constrains `0 <= idx < arr.length` (ADR-0065) | O(arr.length) | +| `arrayAccessOrZero(arr, idx)` | `arr[idx]` if in bounds, else `0` (no bounds check; opt-in for masked padding rows) | O(arr.length) | ## Standard Library (zeroj-circuit-lib) diff --git a/www/src/content/docs/guides/circuits/circuit-dsl.md b/www/src/content/docs/guides/circuits/circuit-dsl.md index fee3d9d1..7e45530e 100644 --- a/www/src/content/docs/guides/circuits/circuit-dsl.md +++ b/www/src/content/docs/guides/circuits/circuit-dsl.md @@ -114,7 +114,7 @@ var circuit = CircuitBuilder.create("range") | `cond.select(x, y)` | `cond ? x : y`, with `cond` boolean | Small constant | | `a.assertBoolean()`, `a.assertInRange(n)` | Constrain to {0,1} or to `[0, 2ⁿ)` | 1, about `n + 1` | | `c.assertEqual(a, b)`, `c.assertNotEqual(a, b)` | Equality constraints | Small constant | -| `c.constant(v)`, `c.fromBinary(bits)`, `c.arrayAccess(arr, idx)` | Constants, recomposition, MUX lookup | Free, free, O(length) | +| `c.constant(v)`, `c.fromBinary(bits)`, `c.arrayAccess(arr, idx)` | Constants, recomposition, bounds-checked MUX lookup (`0 <= idx < arr.length`) | Free, free, O(length) | The golden rule of R1CS cost: additions are free, multiplications are not. Reuse intermediate results instead of recomputing them, and prefer `select` over any "branching". 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 220daec2..6f7657eb 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 @@ -1,6 +1,7 @@ package org.zeroj.circuit; import java.math.BigInteger; +import java.util.Objects; /** * The circuit construction API — the DSL surface that circuit authors program against. @@ -160,9 +161,41 @@ public interface CircuitAPI { // --- Array --- - /** Access arr[index] via MUX tree. */ + /** + * Access {@code arr[index]} via a MUX scan, constraining {@code 0 <= index < arr.length}. + * + *

Emits {@code sum_i isEqual(index, i) == 1}, so any out-of-bounds index (such as + * {@code arr.length} or {@code p - 1}) makes the constraint system unsatisfiable rather than + * silently returning {@code 0} (ADR-0065). + * + * @throws IllegalArgumentException if {@code arr} is empty + */ Variable arrayAccess(Variable[] arr, Variable index); + /** + * Total-function array lookup: returns {@code arr[index]} when {@code 0 <= index < arr.length}, + * and {@code 0} otherwise, without emitting a bounds constraint on {@code index}. + * + *

Soundness warning (ADR-0065): only use this when the caller independently + * constrains {@code index} on every active row and masks out-of-bounds results on inactive + * padding rows (for example, {@code ZkMpf} padding rows that pass {@code queryIndex = 64} + * and discard the result via {@code valid.select(...)}). For general dynamic indexing, use + * {@link #arrayAccess(Variable[], Variable)}. + */ + default Variable arrayAccessOrZero(Variable[] arr, Variable index) { + Objects.requireNonNull(arr, "arr"); + Objects.requireNonNull(index, "index"); + for (int i = 0; i < arr.length; i++) { + Objects.requireNonNull(arr[i], "arr[" + i + "]"); + } + Variable result = constant(0); + for (int i = 0; i < arr.length; i++) { + var selector = isEqual(index, constant(i)); + result = add(result, mul(arr[i], selector)); + } + return result; + } + // --- Variable access --- /** Look up a declared variable by name. */ 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 5caed8c8..3cd468a7 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 @@ -602,7 +602,39 @@ private Variable lessThanUnchecked(Variable a, Variable b, int nBits) { @Override public Variable arrayAccess(Variable[] arr, Variable index) { - // MUX: sum(arr[i] * isEqual(index, i)) + requireNotFrozen(); + Objects.requireNonNull(arr, "arr"); + Objects.requireNonNull(index, "index"); + if (arr.length == 0) { + throw new IllegalArgumentException("arrayAccess requires a non-empty array"); + } + for (int i = 0; i < arr.length; i++) { + Objects.requireNonNull(arr[i], "arr[" + i + "]"); + } + // MUX: sum(arr[i] * isEqual(index, i)) with explicit bounds constraint sum(selector_i) == 1 + // so out-of-bounds indices (e.g., arr.length or p - 1) cannot silently satisfy with 0 (ADR-0065). + Variable result = constant(0); + List selectorTerms = new ArrayList<>(arr.length); + for (int i = 0; i < arr.length; i++) { + var selector = isEqual(index, constant(i)); + selectorTerms.add(new Gate.Term(BigInteger.ONE, selector)); + result = add(result, mul(arr[i], selector)); + } + var selectorSum = newIntermediate(); + gates.add(new Gate.LinComb(selectorSum, selectorTerms)); + assertEqual(selectorSum, oneWire); + return result; + } + + @Override + public Variable arrayAccessOrZero(Variable[] arr, Variable index) { + requireNotFrozen(); + Objects.requireNonNull(arr, "arr"); + Objects.requireNonNull(index, "index"); + for (int i = 0; i < arr.length; i++) { + Objects.requireNonNull(arr[i], "arr[" + i + "]"); + } + // Total MUX without index bounds check (ADR-0065 opt-in): returns 0 when index >= arr.length. Variable result = constant(0); for (int i = 0; i < arr.length; i++) { var selector = isEqual(index, constant(i)); diff --git a/zeroj-circuit-dsl/src/main/java/org/zeroj/circuit/SignalBuilder.java b/zeroj-circuit-dsl/src/main/java/org/zeroj/circuit/SignalBuilder.java index 893d65e7..257b4823 100644 --- a/zeroj-circuit-dsl/src/main/java/org/zeroj/circuit/SignalBuilder.java +++ b/zeroj-circuit-dsl/src/main/java/org/zeroj/circuit/SignalBuilder.java @@ -1,6 +1,7 @@ package org.zeroj.circuit; import java.math.BigInteger; +import java.util.Objects; /** * Builder for the {@link Signal}-based circuit API. @@ -82,13 +83,39 @@ public Signal fromBinary(Signal[] bits) { // --- Array access --- - /** Access arr[index] via MUX tree. */ + /** + * Access {@code arr[index]} via MUX scan, constraining {@code 0 <= index < arr.length} + * (ADR-0065). + * + * @throws IllegalArgumentException if {@code arr} is empty + */ public Signal arrayAccess(Signal[] arr, Signal index) { + Objects.requireNonNull(arr, "arr"); + Objects.requireNonNull(index, "index"); var vars = new Variable[arr.length]; - for (int i = 0; i < arr.length; i++) vars[i] = arr[i].variable(); + for (int i = 0; i < arr.length; i++) { + vars[i] = Objects.requireNonNull(arr[i], "arr[" + i + "]").variable(); + } return new Signal(api.arrayAccess(vars, index.variable()), api); } + /** + * Total-function lookup returning {@code arr[index]} when {@code 0 <= index < arr.length} and + * {@code 0} otherwise, without emitting an index bounds constraint (ADR-0065). + * + *

Only use this when the caller independently constrains {@code index} on active rows and + * masks inactive padding rows; otherwise use {@link #arrayAccess(Signal[], Signal)}.

+ */ + public Signal arrayAccessOrZero(Signal[] arr, Signal index) { + Objects.requireNonNull(arr, "arr"); + Objects.requireNonNull(index, "index"); + var vars = new Variable[arr.length]; + for (int i = 0; i < arr.length; i++) { + vars[i] = Objects.requireNonNull(arr[i], "arr[" + i + "]").variable(); + } + return new Signal(api.arrayAccessOrZero(vars, index.variable()), api); + } + /** Wrap a Variable as a Signal (for stdlib interop). */ public Signal wrap(Variable variable) { return new Signal(variable, api); diff --git a/zeroj-circuit-dsl/src/test/java/org/zeroj/circuit/ArrayAccessSoundnessTest.java b/zeroj-circuit-dsl/src/test/java/org/zeroj/circuit/ArrayAccessSoundnessTest.java new file mode 100644 index 00000000..87f9a4db --- /dev/null +++ b/zeroj-circuit-dsl/src/test/java/org/zeroj/circuit/ArrayAccessSoundnessTest.java @@ -0,0 +1,332 @@ +package org.zeroj.circuit; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EnumSource; +import org.zeroj.api.CurveId; +import org.zeroj.circuit.plonk.PlonKCompiler; +import org.zeroj.circuit.plonk.PlonKConstraintSystem; +import org.zeroj.circuit.r1cs.R1CSCompiler; +import org.zeroj.circuit.r1cs.R1CSConstraintSystem; + +import java.math.BigInteger; +import java.util.List; +import java.util.Map; +import java.util.concurrent.atomic.AtomicReference; + +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; + +/** + * Soundness and regression tests for {@link CircuitAPI#arrayAccess} and + * {@link CircuitAPI#arrayAccessOrZero} (ADR-0065). + */ +class ArrayAccessSoundnessTest { + + @ParameterizedTest + @EnumSource(value = CurveId.class, names = {"BLS12_381", "BN254"}) + @DisplayName("in-bounds arrayAccess succeeds and satisfies both R1CS and PlonK") + void inBoundsArrayAccessSucceeds(CurveId curve) { + var circuit = CircuitBuilder.create("array-access-in-bounds") + .publicVar("expected") + .secretVar("index") + .define(api -> { + Variable[] arr = { + api.constant(10), api.constant(20), api.constant(30), api.constant(40) + }; + Variable out = api.arrayAccess(arr, api.var("index")); + api.assertEqual(out, api.var("expected")); + }); + + var field = FieldConfig.forCurve(curve); + var r1cs = R1CSCompiler.compile(circuit.constraintGraph(), field); + var plonk = PlonKCompiler.compile(circuit.constraintGraph(), field); + + long[] expected = {10, 20, 30, 40}; + for (int idx = 0; idx < expected.length; idx++) { + var inputs = Map.of( + "index", List.of(BigInteger.valueOf(idx)), + "expected", List.of(BigInteger.valueOf(expected[idx]))); + BigInteger[] witness = circuit.calculateWitness(inputs, curve); + assertTrue(r1csSatisfied(r1cs, witness), "R1CS must accept valid index=" + idx); + assertTrue(plonkSatisfied(plonk, witness), "PlonK must accept valid index=" + idx); + } + } + + @ParameterizedTest + @EnumSource(value = CurveId.class, names = {"BLS12_381", "BN254"}) + @DisplayName("out-of-bounds arrayAccess cannot forge 0 (index = length, length+1, p-1)") + void outOfBoundsArrayAccessIsRejected(CurveId curve) { + BigInteger p = FieldConfig.forCurve(curve).prime(); + var circuit = CircuitBuilder.create("array-access-oob-forgery") + .publicVar("expected") + .secretVar("index") + .define(api -> { + // Include both non-zero and zero entries to ensure zero elements do not mask OOB. + Variable[] arr = { + api.constant(0), api.constant(11), api.constant(22), api.constant(33) + }; + Variable out = api.arrayAccess(arr, api.var("index")); + api.assertEqual(out, api.var("expected")); + }); + + // Pre-fix: all of these satisfied the circuit with expected = 0. + BigInteger[] oobIndices = { + BigInteger.valueOf(4), + BigInteger.valueOf(5), + BigInteger.valueOf(64), + p.subtract(BigInteger.ONE), + p.subtract(BigInteger.valueOf(12345)) + }; + for (BigInteger badIndex : oobIndices) { + var inputs = Map.of( + "index", List.of(badIndex), + "expected", List.of(BigInteger.ZERO)); + assertThrows(ArithmeticException.class, + () -> circuit.calculateWitness(inputs, curve), + "arrayAccess must reject OOB index=" + badIndex + " on " + curve); + } + } + + @ParameterizedTest + @EnumSource(value = CurveId.class, names = {"BLS12_381", "BN254"}) + @DisplayName("raw forged OOB witness is rejected directly by R1CS and PlonK constraint matrices") + void forgedOobWitnessFailsConstraintMatricesDirectly(CurveId curve) { + var circuit = CircuitBuilder.create("array-access-matrix-check") + .secretVar("index") + .define(api -> { + Variable[] arr = {api.constant(7), api.constant(9)}; + Variable out = api.arrayAccess(arr, api.var("index")); + api.assertEqual(out, api.constant(0)); + }); + + // Construct the exact witness an adversary would produce for index = 2 (OOB) with all + // selectors = 0 and output = 0; every gate except the ADR-0065 selectorSum == 1 check + // would hold. Verify R1CS and PlonK both reject it. + var graph = circuit.constraintGraph(); + var field = FieldConfig.forCurve(curve); + var r1cs = R1CSCompiler.compile(graph, field); + var plonk = PlonKCompiler.compile(graph, field); + BigInteger p = FieldConfig.forCurve(curve).prime(); + BigInteger[] forged = computeForgedWitnessIgnoringFinalAssert(graph, BigInteger.TWO, p); + + assertFalse(r1csSatisfied(r1cs, forged), + "R1CS matrix must reject forged OOB witness on " + curve); + assertFalse(plonkSatisfied(plonk, forged), + "PlonK constraint system must reject forged OOB witness on " + curve); + } + + @ParameterizedTest + @EnumSource(value = CurveId.class, names = {"BLS12_381", "BN254"}) + @DisplayName("single-element arrayAccess accepts index 0 and rejects index 1 and p-1") + void singleElementArrayAccess(CurveId curve) { + BigInteger p = FieldConfig.forCurve(curve).prime(); + var circuit = CircuitBuilder.create("array-access-single") + .publicVar("expected") + .secretVar("index") + .defineSignals(c -> { + Signal out = c.arrayAccess(new Signal[]{c.constant(42)}, c.privateInput("index")); + c.assertEqual(out, c.publicInput("expected")); + }); + + assertDoesNotThrow(() -> circuit.calculateWitness( + Map.of("index", List.of(BigInteger.ZERO), "expected", List.of(BigInteger.valueOf(42))), + curve)); + assertThrows(ArithmeticException.class, () -> circuit.calculateWitness( + Map.of("index", List.of(BigInteger.ONE), "expected", List.of(BigInteger.ZERO)), + curve)); + assertThrows(ArithmeticException.class, () -> circuit.calculateWitness( + Map.of("index", List.of(p.subtract(BigInteger.ONE)), "expected", List.of(BigInteger.ZERO)), + curve)); + } + + @Test + @DisplayName("arrayAccess rejects empty array, null arguments atomically, and frozen builders") + void guardRailsRejectEmptyNullAndFrozen() { + assertThrows(IllegalArgumentException.class, () -> + CircuitBuilder.create("empty-api") + .secretVar("index") + .define(api -> api.arrayAccess(new Variable[0], api.var("index")))); + + assertThrows(IllegalArgumentException.class, () -> + CircuitBuilder.create("empty-signal") + .secretVar("index") + .defineSignals(c -> c.arrayAccess(new Signal[0], c.privateInput("index")))); + + // Null array, null element, or null index must fail before emitting any gates. + var escapedApi = new AtomicReference(); + var escapedIndex = new AtomicReference(); + var graph = CircuitBuilder.create("null-atomic-check") + .secretVar("index") + .define(api -> { + Variable idx = api.var("index"); + assertThrows(NullPointerException.class, () -> api.arrayAccess(null, idx)); + assertThrows(NullPointerException.class, + () -> api.arrayAccess(new Variable[]{api.constant(1), null}, idx)); + assertThrows(NullPointerException.class, + () -> api.arrayAccess(new Variable[]{api.constant(1)}, null)); + escapedApi.set(api); + escapedIndex.set(idx); + }) + .constraintGraph(); + // Only the constant(1) created while constructing the test array argument may exist; no + // isEqual/mul/AssertEq gates were emitted by the rejected arrayAccess calls. + assertTrue(graph.gates().stream().noneMatch(g -> g instanceof Gate.AssertEq || g instanceof Gate.Mul), + "rejected arrayAccess calls must not emit partial constraints"); + + // Post-freeze calls must fail loudly on both arrayAccess and arrayAccessOrZero. + assertThrows(IllegalStateException.class, () -> + escapedApi.get().arrayAccess(new Variable[]{escapedIndex.get()}, escapedIndex.get())); + assertThrows(IllegalStateException.class, () -> + escapedApi.get().arrayAccessOrZero(new Variable[]{escapedIndex.get()}, escapedIndex.get())); + } + + @ParameterizedTest + @EnumSource(value = CurveId.class, names = {"BLS12_381", "BN254"}) + @DisplayName("arrayAccessOrZero preserves opt-in total semantics and costs 1 fewer R1CS row") + void arrayAccessOrZeroTotalSemanticsAndCost(CurveId curve) { + BigInteger p = FieldConfig.forCurve(curve).prime(); + var strictCircuit = CircuitBuilder.create("cost-strict") + .secretVar("index") + .defineSignals(c -> c.arrayAccess( + new Signal[]{c.constant(5), c.constant(6), c.constant(7)}, + c.privateInput("index"))); + var totalCircuit = CircuitBuilder.create("cost-total") + .publicVar("expected") + .secretVar("index") + .defineSignals(c -> { + Signal out = c.arrayAccessOrZero( + new Signal[]{c.constant(5), c.constant(6), c.constant(7)}, + c.privateInput("index")); + c.assertEqual(out, c.publicInput("expected")); + }); + var totalNoAssert = CircuitBuilder.create("cost-total-raw") + .secretVar("index") + .defineSignals(c -> c.arrayAccessOrZero( + new Signal[]{c.constant(5), c.constant(6), c.constant(7)}, + c.privateInput("index"))); + + int strictRows = strictCircuit.compileR1CS(curve).numConstraints(); + int totalRows = totalNoAssert.compileR1CS(curve).numConstraints(); + assertEquals(totalRows + 1, strictRows, + "strict arrayAccess must cost exactly 1 additional R1CS constraint"); + + var field = FieldConfig.forCurve(curve); + var r1cs = R1CSCompiler.compile(totalCircuit.constraintGraph(), field); + var plonk = PlonKCompiler.compile(totalCircuit.constraintGraph(), field); + + // In-bounds reads return arr[index]. + BigInteger[] inBoundsWitness = totalCircuit.calculateWitness( + Map.of("index", List.of(BigInteger.ONE), "expected", List.of(BigInteger.valueOf(6))), curve); + assertTrue(r1csSatisfied(r1cs, inBoundsWitness)); + assertTrue(plonkSatisfied(plonk, inBoundsWitness)); + + // Out-of-bounds reads return 0 explicitly. + for (BigInteger oob : new BigInteger[]{BigInteger.valueOf(3), p.subtract(BigInteger.ONE)}) { + BigInteger[] oobWitness = totalCircuit.calculateWitness( + Map.of("index", List.of(oob), "expected", List.of(BigInteger.ZERO)), curve); + assertTrue(r1csSatisfied(r1cs, oobWitness)); + assertTrue(plonkSatisfied(plonk, oobWitness)); + } + + // Empty array returns 0 under arrayAccessOrZero. + var emptyTotal = CircuitBuilder.create("empty-total") + .publicVar("expected") + .secretVar("index") + .defineSignals(c -> c.assertEqual( + c.arrayAccessOrZero(new Signal[0], c.privateInput("index")), + c.publicInput("expected"))); + assertDoesNotThrow(() -> emptyTotal.calculateWitness( + Map.of("index", List.of(BigInteger.ZERO), "expected", List.of(BigInteger.ZERO)), curve)); + } + + /** + * Evaluates all assignment gates in {@code graph} for an OOB {@code index} without throwing on + * {@link Gate.AssertEq}, producing the exact witness an adversary would submit to a prover. + */ + private static BigInteger[] computeForgedWitnessIgnoringFinalAssert( + ConstraintGraph graph, BigInteger indexValue, BigInteger p) { + BigInteger[] w = new BigInteger[graph.numWires()]; + w[0] = BigInteger.ONE; + for (Variable secret : graph.secretInputs()) { + if ("index".equals(secret.name())) { + w[secret.id()] = indexValue.mod(p); + } + } + for (Gate gate : graph.gates()) { + switch (gate) { + case Gate.Const(var out, var value) -> w[out.id()] = value.mod(p); + case Gate.Add(var out, var a, var b) -> w[out.id()] = w[a.id()].add(w[b.id()]).mod(p); + case Gate.Mul(var out, var a, var b) -> w[out.id()] = w[a.id()].multiply(w[b.id()]).mod(p); + case Gate.LinComb(var out, var terms) -> { + BigInteger sum = BigInteger.ZERO; + for (Gate.Term t : terms) { + sum = sum.add(t.coefficient().multiply(w[t.variable().id()])); + } + w[out.id()] = sum.mod(p); + } + case Gate.Hint(var out, var type, var in) -> { + if (type == Gate.HintType.IS_ZERO_INVERSE) { + BigInteger val = w[in.id()].mod(p); + w[out.id()] = val.signum() == 0 ? BigInteger.ZERO : val.modInverse(p); + } else if (type == Gate.HintType.IS_ZERO_RESULT) { + w[out.id()] = w[in.id()].mod(p).signum() == 0 ? BigInteger.ONE : BigInteger.ZERO; + } else { + throw new IllegalStateException("Unexpected hint: " + type); + } + } + case Gate.AssertEq ignored -> { + // Intentionally ignored so we can test the compiled R1CS/PlonK matrices directly. + } + default -> throw new IllegalStateException("Unexpected gate: " + gate); + } + } + return w; + } + + private static boolean r1csSatisfied(R1CSConstraintSystem system, BigInteger[] witness) { + BigInteger p = system.prime(); + for (var row : system.constraints()) { + BigInteger a = dot(row.a(), witness, p); + BigInteger b = dot(row.b(), witness, p); + BigInteger c = dot(row.c(), witness, p); + if (!a.multiply(b).subtract(c).mod(p).equals(BigInteger.ZERO)) { + return false; + } + } + return true; + } + + private static BigInteger dot(Map terms, BigInteger[] witness, BigInteger p) { + BigInteger value = BigInteger.ZERO; + for (var term : terms.entrySet()) { + value = value.add(term.getValue().multiply(witness[term.getKey()])); + } + return value.mod(p); + } + + private static boolean plonkSatisfied(PlonKConstraintSystem system, BigInteger[] witness) { + BigInteger[] extended = system.extendWitness(witness); + BigInteger p = system.fieldConfig().prime(); + for (int i = system.numPublicInputs(); i < system.numGates(); i++) { + var row = system.gateRows().get(i); + BigInteger a = extended[row.wireA()]; + BigInteger b = extended[row.wireB()]; + BigInteger c = extended[row.wireC()]; + BigInteger eval = row.qL().multiply(a) + .add(row.qR().multiply(b)) + .add(row.qO().multiply(c)) + .add(row.qM().multiply(a).multiply(b)) + .add(row.qC()) + .mod(p); + if (!eval.equals(BigInteger.ZERO)) { + return false; + } + } + return true; + } +} diff --git a/zeroj-circuit-lib/src/main/java/org/zeroj/circuit/lib/Mux.java b/zeroj-circuit-lib/src/main/java/org/zeroj/circuit/lib/Mux.java index e1e728c6..181be513 100644 --- a/zeroj-circuit-lib/src/main/java/org/zeroj/circuit/lib/Mux.java +++ b/zeroj-circuit-lib/src/main/java/org/zeroj/circuit/lib/Mux.java @@ -24,7 +24,12 @@ public static Variable mux2(CircuitAPI api, Variable sel0, Variable sel1, return api.select(sel1, cd, ab); } - /** Array access: returns arr[index] via MUX tree. */ + /** + * Bounds-constrained array access: returns {@code arr[index]} via MUX scan and constrains + * {@code 0 <= index < arr.length} (ADR-0065). + * + * @throws IllegalArgumentException if {@code arr} is empty + */ public static Variable arrayAccess(CircuitAPI api, Variable[] arr, Variable index) { return api.arrayAccess(arr, index); } diff --git a/zeroj-circuit-lib/src/test/java/org/zeroj/circuit/lib/CircuitLibTest.java b/zeroj-circuit-lib/src/test/java/org/zeroj/circuit/lib/CircuitLibTest.java index 624af6f2..13a37806 100644 --- a/zeroj-circuit-lib/src/test/java/org/zeroj/circuit/lib/CircuitLibTest.java +++ b/zeroj-circuit-lib/src/test/java/org/zeroj/circuit/lib/CircuitLibTest.java @@ -2,6 +2,7 @@ import org.zeroj.api.CurveId; import org.zeroj.circuit.CircuitBuilder; +import org.zeroj.circuit.Variable; import org.junit.jupiter.api.Test; import java.math.BigInteger; @@ -113,6 +114,31 @@ void mux2_allCombinations() { assertEquals(BigInteger.valueOf(400), w2[1]); } + @Test + void mux_arrayAccess_enforcesBoundsAndRejectsEmpty() { + var circuit = CircuitBuilder.create("mux-array-access") + .publicVar("out") + .secretVar("index") + .define(api -> { + var result = Mux.arrayAccess(api, + new Variable[]{api.constant(10), api.constant(20), api.constant(30)}, + api.var("index")); + api.assertEqual(result, api.var("out")); + }); + + var w = circuit.calculateWitness(Map.of( + "index", List.of(BigInteger.TWO), + "out", List.of(BigInteger.valueOf(30))), CurveId.BLS12_381); + assertEquals(BigInteger.valueOf(30), w[1]); + + assertThrows(ArithmeticException.class, () -> circuit.calculateWitness(Map.of( + "index", List.of(BigInteger.valueOf(3)), + "out", List.of(BigInteger.ZERO)), CurveId.BLS12_381)); + assertThrows(IllegalArgumentException.class, () -> CircuitBuilder.create("mux-array-empty") + .secretVar("index") + .define(api -> Mux.arrayAccess(api, new Variable[0], api.var("index")))); + } + // --- MiMC --- @Test 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 1ffc934d..07964a0b 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 @@ -826,7 +826,11 @@ static PathSignals of(ZkArray path) { } ZkUInt at(ZkContext zk, Signal index) { - return ZkUInt.wrap(zk, zk.builder().arrayAccess(signals, index), 4); + // ADR-0065: every active lookup in ZkMpf already constrains index <= 63 + // (prepareBranchProof/computeRoot lteConst on active rows; nonInclusionDifferentLeaf / + // verifyDifferentLeafInsertion lteConst on divergenceIndex), while inactive padding + // rows intentionally evaluate queryIndex = 64 and discard the result via valid.select. + return ZkUInt.wrap(zk, zk.builder().arrayAccessOrZero(signals, index), 4); } } } From a36e99c20a1d357735bc94982dcc3d1b21fff93a Mon Sep 17 00:00:00 2001 From: Satya Date: Fri, 20 Nov 2026 19:49:13 +0800 Subject: [PATCH 2/2] security(circuit-dsl): address PR #119 review findings (immutable LinComb, Halo2/control tests, ADR-0065 per-backend costs) Addresses all review findings from reviewer1 and reviewer2 on PR #119: - Gate.LinComb: defend terms with List.copyOf in the compact constructor (covers both arrayAccess and fromBinary) and add immutability regression test in ArrayAccessSoundnessTest. - ArrayAccessSoundnessTest: extend direct forged-witness matrix verification to {n, n + 1, p - 1} across R1CS, PlonK, and Halo2 on both BN254 and BLS12-381, add matching arrayAccessOrZero positive control, and assert exact per-backend row deltas (+1 R1CS inlined, +n PlonK, +n Halo2). - ADR-0065: record per-backend costs (R1CS +1 inlined / +2 under pressure mode, PlonK & Halo2 +n, new keys on all backends), add Halo2 to I2/M2/Verification Strategy, add empty-array Compatibility bullet and custom CircuitAPI migration note, and fix ZkMpf citations (differentLeafRoot:131, computeRoot:323, final-cursor padding wording). - Update CircuitAPI.java, ZkMpf.java comment, gadgets.md, and zeroj-circuit-lib/README.md to match. --- .../adr/0065-array-access-bounds-soundness.md | 54 ++++--- .../content/docs/guides/circuits/gadgets.md | 2 +- .../java/org/zeroj/circuit/CircuitAPI.java | 6 +- .../src/main/java/org/zeroj/circuit/Gate.java | 8 +- .../circuit/ArrayAccessSoundnessTest.java | 136 +++++++++++++++--- zeroj-circuit-lib/README.md | 2 +- .../merkle/mpf/poseidon/circuit/ZkMpf.java | 7 +- 7 files changed, 161 insertions(+), 54 deletions(-) diff --git a/docs/adr/0065-array-access-bounds-soundness.md b/docs/adr/0065-array-access-bounds-soundness.md index ec448565..e624665e 100644 --- a/docs/adr/0065-array-access-bounds-soundness.md +++ b/docs/adr/0065-array-access-bounds-soundness.md @@ -3,7 +3,7 @@ ## Status Proposed — 2026-11-20 (pending review sign-off). Hardens `CircuitAPI.arrayAccess` (and its delegates `SignalBuilder.arrayAccess` and `Mux.arrayAccess`) to enforce `0 <= index < arr.length` in-circuit, and introduces an explicitly named total-function variant `arrayAccessOrZero` for callers with independently constrained indices and masked padding rows. Amends [ADR-0010](0010-java-circuit-dsl.md). -**Risk class: R2.** Changes circuit soundness semantics and emitted R1CS/PlonK constraints for every caller of `CircuitAPI.arrayAccess` / `SignalBuilder.arrayAccess` / `Mux.arrayAccess`. +**Risk class: R2.** Changes circuit soundness semantics and emitted R1CS/PlonK/Halo2 constraints for every caller of `CircuitAPI.arrayAccess` / `SignalBuilder.arrayAccess` / `Mux.arrayAccess`. ## Date 2026-11-20 @@ -20,7 +20,7 @@ In an application circuit that assumes `arr[index]` reads a real entry of `arr` A full in-repository caller census showed only three production call paths: 1. `SignalBuilder.arrayAccess(Signal[], Signal)` (`zeroj-circuit-dsl`) — delegates to `CircuitAPI.arrayAccess`. 2. `Mux.arrayAccess(CircuitAPI, Variable[], Variable)` (`zeroj-circuit-lib`) — delegates to `CircuitAPI.arrayAccess`. -3. `ZkMpf.PathSignals.at(ZkContext, Signal)` (`zeroj-mpf-poseidon/.../circuit/ZkMpf.java:829`) — looks up a nibble in a 64-element key path. Every active lookup in `ZkMpf` already carries an explicit `lteConst` bounds constraint (`<= 63`), whereas inactive padding rows (`valid == 0`) intentionally evaluate `queryIndex = 64` and discard the lookup via `valid.select(...)`. +3. `ZkMpf.PathSignals.at(ZkContext, Signal)` (`zeroj-mpf-poseidon/.../circuit/ZkMpf.java:829`) — looks up a nibble in a 64-element key path. Every active lookup in `ZkMpf` already carries an explicit `lteConst` bounds constraint (`<= 63`), whereas inactive padding rows (`valid == 0`) evaluate the final cursor (`cursor + 0 + 1 - 1`), which can be `64` when the full 64-nibble key path has been consumed, and discard the lookup via `valid.select(...)`. ## Threat Model and Trust Assumptions - **Untrusted:** Any prover-controlled witness wire passed as `index` or as an element of `arr` (including `index = arr.length`, `index = p - 1`, or arbitrary field elements in `F_p`). @@ -35,57 +35,64 @@ A full in-repository caller census showed only three production call paths: ## Decision 1. **D1 (Strict bounds-constrained `arrayAccess`):** - `CircuitAPIImpl.arrayAccess(Variable[] arr, Variable index)` validates `requireNotFrozen()`, rejects `null` arguments (array, elements, or `index`) atomically before emitting any gate, and rejects `arr.length == 0` with `IllegalArgumentException`. - - For `arr.length >= 1`, `arrayAccess` computes `selector_i = isEqual(index, constant(i))`, accumulates `result = sum(arr[i] * selector_i)`, forms the single linear combination `selectorSum = sum(selector_i)` via `Gate.LinComb`, and emits **`assertEqual(selectorSum, oneWire)`**. - - **Soundness proof:** Because `1 <= n <= Integer.MAX_VALUE < p`, the constants `0, 1, ..., n - 1` are pairwise distinct modulo `p`. For any field element `index ∈ F_p`, at most one `selector_i` equals `1` (the rest are `0`). Hence `sum_{i=0}^{n-1} selector_i == 1` holds **if and only if** `index ∈ {0, 1, ..., n - 1}`, in which case `result == arr[index]`. Any out-of-bounds `index` yields `selectorSum == 0 != 1`, making the constraint system unsatisfiable. - - **Cost:** Adding `Gate.LinComb` + `AssertEq` costs **1 R1CS constraint and 1 wire** regardless of `arr.length` (no extra multiplications or bit decompositions). + - For `arr.length >= 1`, `arrayAccess` computes `selector_i = isEqual(index, constant(i))`, accumulates `result = sum(arr[i] * selector_i)`, forms the single linear combination `selectorSum = sum(selector_i)` via `Gate.LinComb` (whose compact constructor defends `terms` with `List.copyOf` so published graphs are immutable), and emits **`assertEqual(selectorSum, oneWire)`**. + - **Soundness proof:** Because `1 <= n <= Integer.MAX_VALUE < p`, the constants `0, 1, ..., n - 1` are pairwise distinct modulo `p`. For any field element `index ∈ F_p`, at most one `selector_i` equals `1` (the rest are `0`). Hence `sum_{i=0}^{n-1} selector_i == 1` holds **if and only if** `index ∈ {0, 1, ..., n - 1}`, in which case `result == arr[index]`. Any out-of-bounds `index` yields `selectorSum == 0 != 1`, making the constraint system unsatisfiable across R1CS, PlonK, and Halo2. + - **Per-backend cost (vs `arrayAccessOrZero` for an `n`-element array):** + - **DSL graph:** `+1` intermediate wire (`selectorSum`), `+1` `Gate.LinComb`, `+1` `Gate.AssertEq`. + - **R1CS (`R1CSCompiler`):** `+1` constraint row when `selectorSum` is inlined; `+2` constraint rows under compiler pressure mode (when the compiler materializes `selectorSum` in its own row before the equality row). + - **PlonK (`PlonKCompiler`) and Halo2 (`Halo2Compiler`):** `+n` rows/gates (`n - 1` binary addition gates for the `n`-term `LinComb` chain plus `1` equality gate; e.g., `50 -> 54` at `n = 4`, `185 -> 201` at `n = 16`, `713 -> 777` at `n = 64`). - `SignalBuilder.arrayAccess` and `Mux.arrayAccess` delegate directly to `CircuitAPI.arrayAccess` and inherit this invariant automatically. 2. **D2 (Explicit total-function lookup `arrayAccessOrZero`):** - Add `default Variable arrayAccessOrZero(Variable[] arr, Variable index)` to `CircuitAPI` (overridden in `CircuitAPIImpl` with lifecycle/null validation) and `SignalBuilder.arrayAccessOrZero(Signal[] arr, Signal index)` with explicit Javadoc warning that out-of-bounds indices silently return `0` without constraining `index`. - `arrayAccessOrZero` is strictly opt-in for circuits that independently constrain `index` on active rows and mask inactive padding rows. 3. **D3 (`ZkMpf` padding-row preservation):** - - Update `ZkMpf.PathSignals.at` (`ZkMpf.java:829`) to call `zk.builder().arrayAccessOrZero(signals, index)` with an inline citation to `ZkMpf`'s existing explicit bounds constraints (`prepareBranchProof:249`, `computeRoot:321`, `nonInclusionDifferentLeaf:131`, `verifyDifferentLeafInsertion:168`) and padding-row masking (`valid.select`). + - Update `ZkMpf.PathSignals.at` (`ZkMpf.java:829`) to call `zk.builder().arrayAccessOrZero(signals, index)` with an inline citation to `ZkMpf`'s existing explicit bounds constraints (`prepareBranchProof:249`, `computeRoot:323`, `differentLeafRoot:131`, `verifyDifferentLeafInsertion:168`) and padding-row masking (`valid.select`, where padding rows evaluate the final cursor, which can be `64`). - This preserves all existing pinned `ZkMpf` R1CS constraint counts and canonical SHA-256 digests unchanged while making the opt-in total-lookup semantics explicit in source. ## Alternatives Considered - **Clamp `queryIndex` on padding rows in `ZkMpf` and keep only strict `arrayAccess`:** Rejected for this PR because clamping adds `select` + `arrayAccess` constraints on every `ZkMpf` branch step and breaks every pinned R1CS SHA-256 digest and proving key across `zeroj-mpf-poseidon` even though `ZkMpf` already constrains active bounds independently. Providing `arrayAccessOrZero` keeps the general `arrayAccess` API sound by default with zero key churn on `ZkMpf`. -- **Add a `lessThan(index, n)` bit-decomposition check instead of `sum(selector_i) == 1`:** Rejected — `arrayAccess` already computes all `n` equality selectors `isEqual(index, i)`, so constraining `sum(selector_i) == 1` costs 1 linear constraint instead of `ceil(log2(n)) + 2` range-check constraints and requires no bit-width parameter. +- **Add a `lessThan(index, n)` bit-decomposition check instead of `sum(selector_i) == 1`:** Rejected — `arrayAccess` already computes all `n` equality selectors `isEqual(index, i)`, so constraining `sum(selector_i) == 1` reuses existing selectors, costs 1–2 rows on R1CS (and `n` linear/eq rows on PlonK/Halo2), and requires no bit-width parameter. - **Document OOB → 0 as a precondition on `arrayAccess`:** Rejected — matches the unsafe pattern ADR-0037 retired for `lessThan`; dynamic array indexing must fail closed by default. ## Security Invariants - **I1 (In-bounds enforcement):** For any non-empty array `arr` of length `n >= 1`, `arrayAccess(arr, index)` is satisfiable iff `index ∈ {0, 1, ..., n - 1}` (as a field element in `F_p`), and its output wire equals `arr[index]`. -- **I2 (OOB rejection):** Any witness with `index = n`, `index = n + 1`, or `index = p - 1` fails R1CS and PlonK constraint satisfaction on both BLS12-381 and BN254, even when `arr` contains `0` entries. -- **I3 (Empty-array & null rejection):** `arrayAccess` throws `IllegalArgumentException` on `arr.length == 0` and `NullPointerException` on null `arr`, null elements, or null `index`, atomically before emitting any gate. +- **I2 (OOB rejection across all backends):** Any witness with `index ∈ {n, n + 1, p - 1}` fails R1CS, PlonK, and Halo2 constraint satisfaction on both BLS12-381 and BN254, even when `arr` contains `0` entries, while the identical witness satisfies the `arrayAccessOrZero` control circuit on all three backends. +- **I3 (Empty-array, null, frozen, and immutability guards):** `arrayAccess` throws `IllegalArgumentException` on `arr.length == 0`, `NullPointerException` on null `arr`/elements/`index` atomically before emitting any gate, and `IllegalStateException` after graph freeze; published `Gate.LinComb.terms()` lists are immutable (`List.copyOf`). - **I4 (Explicit total opt-in):** Out-of-bounds → `0` semantics are reachable only through the explicitly named `arrayAccessOrZero` method. - **I5 (MPF template stability):** All pinned `ZkMpf` R1CS constraint counts and canonical SHA-256 digests in `zeroj-mpf-poseidon` remain identical. ## Consequences -- **Positive:** Eliminates a silent under-constrained OOB→0 forgery class across `CircuitAPI.arrayAccess`, `SignalBuilder.arrayAccess`, and `Mux.arrayAccess` at a cost of 1 R1CS constraint per lookup. +- **Positive:** Eliminates a silent under-constrained OOB→0 forgery class across `CircuitAPI.arrayAccess`, `SignalBuilder.arrayAccess`, and `Mux.arrayAccess` on R1CS, PlonK, and Halo2, and makes `Gate.LinComb.terms()` immutable for all callers (including `fromBinary`). - **Trade-offs:** - - Circuits calling `arrayAccess` outside `ZkMpf` gain 1 R1CS constraint and 1 wire per `arrayAccess` call and therefore produce new R1CS digests / proving & verification keys. - - Custom `CircuitAPI` implementations remain source-compatible because `arrayAccessOrZero` has a `default` implementation on `CircuitAPI`. + - Circuits calling `arrayAccess` outside `ZkMpf` pay `+1` R1CS row when inlined (`+2` under pressure mode) or `+n` PlonK/Halo2 rows per `arrayAccess` call and produce new proving/verifying keys across every backend. + - Empty-array `arrayAccess` calls now fail fast at circuit definition time instead of silently returning `constant(0)`. ## Risks - **Misuse of `arrayAccessOrZero`:** A caller choosing `arrayAccessOrZero` without independently constraining active indices reintroduces OOB→0 behavior. Mitigated by naming (`OrZero`), explicit Javadoc warning, and keeping `Mux.arrayAccess` / `SignalBuilder.arrayAccess` / `CircuitAPI.arrayAccess` strictly constrained. -- **Downstream key migration:** External circuits (e.g., in downstream applications using `Mux.arrayAccess` or `SignalBuilder.arrayAccess`) must regenerate proving/verifying keys after upgrading. +- **Custom `CircuitAPI` implementations:** Downstream code supplying its own `CircuitAPI` implementation to `Mux` or other `zeroj-circuit-lib` gadgets compiles without error against the unchanged `arrayAccess` signature and would silently retain old zero-on-miss behavior if not updated. Mitigated by the explicit provider migration note in Compatibility below (`CircuitBuilder` always instantiates `CircuitAPIImpl`). +- **Downstream key migration:** External circuits using `Mux.arrayAccess`, `SignalBuilder.arrayAccess`, or `CircuitAPI.arrayAccess` must regenerate proving/verifying keys across R1CS, PlonK, and Halo2 after upgrading. ## Compatibility -- **Breaking R1CS / key change for `arrayAccess` callers:** Every circuit calling `CircuitAPI.arrayAccess`, `SignalBuilder.arrayAccess`, or `Mux.arrayAccess` gains 1 R1CS constraint and 1 wire per call and requires fresh circuit-specific keys. Release notes must record this explicitly. +- **Breaking constraint & key change across all backends (R1CS, PlonK, Halo2):** Every circuit calling `CircuitAPI.arrayAccess`, `SignalBuilder.arrayAccess`, or `Mux.arrayAccess` (outside `ZkMpf`) changes its compiled constraint system (`+1` R1CS row when inlined, `+2` under pressure mode; `+n` PlonK/Halo2 rows; `+1` DSL wire) and requires fresh circuit-specific proving/verifying keys. Release notes must record this explicitly. +- **Breaking build-time behavior for empty arrays:** Previously `arrayAccess(new Variable[0], index)` compiled and returned `constant(0)`. It now throws `IllegalArgumentException` at circuit definition time; callers genuinely requiring a total empty-array lookup must opt into `arrayAccessOrZero`. +- **Migration note for custom `CircuitAPI` implementations:** `CircuitBuilder` always constructs `CircuitAPIImpl`, so standard DSL circuits inherit the fix automatically. However, because `CircuitAPI.arrayAccess` retains its method signature, any downstream custom `CircuitAPI` implementation passed directly into `Mux.arrayAccess` or other `zeroj-circuit-lib` gadgets will still compile and load. Custom `CircuitAPI` authors **must** update their `arrayAccess` implementation to reject empty arrays and constrain `sum_i isEqual(index, i) == 1` (and confirm compiled constraints reject out-of-range indices) before regenerating keys. - **Non-breaking for `zeroj-mpf-poseidon`:** `ZkMpf` switches to `arrayAccessOrZero` (matching its independently constrained active indices and masked padding rows), so all pinned MPF R1CS digests and keys remain unchanged. - **Source/binary API compatibility:** `CircuitAPI.arrayAccessOrZero` is added as a `default` method so existing `CircuitAPI` implementations compile unchanged. ## Implementation Milestones -- **M1 — DSL & MPF implementation (Complete):** Enforce `sum(selector_i) == 1` and reject empty arrays in `CircuitAPIImpl.arrayAccess`, add `arrayAccessOrZero` to `CircuitAPI`/`CircuitAPIImpl`/`SignalBuilder`, update `Mux.arrayAccess` Javadoc, and switch `ZkMpf.PathSignals.at` to `arrayAccessOrZero`. -- **M2 — Adversarial & cross-backend verification (Complete):** Add `ArrayAccessSoundnessTest` in `zeroj-circuit-dsl` covering in-bounds reads, OOB rejections (`arr.length`, `arr.length + 1`, `p - 1`, `arr.length == 1`, zero-valued entries), empty/null/frozen rejections, `SignalBuilder` and `Mux` delegation, both BLS12-381 and BN254, and both R1CS and PlonK constraint checks; verify `zeroj-mpf-poseidon` pinned R1CS digests remain unchanged. -- **M3 — Documentation & review (In progress):** `ADR-0010` back-reference and user guides (`docs/circuit-dsl-user-guide.md`, `www/src/content/docs/guides/circuits/circuit-dsl.md`) updated; awaiting external review sign-off before marking ADR-0065 `Accepted`. +- **M1 — DSL & MPF implementation (Complete):** Enforce `sum(selector_i) == 1` and reject empty arrays in `CircuitAPIImpl.arrayAccess`, defend `Gate.LinComb.terms()` with `List.copyOf`, add `arrayAccessOrZero` to `CircuitAPI`/`CircuitAPIImpl`/`SignalBuilder`, update `Mux.arrayAccess` Javadoc, and switch `ZkMpf.PathSignals.at` to `arrayAccessOrZero`. +- **M2 — Adversarial & cross-backend verification (Complete):** Add `ArrayAccessSoundnessTest` in `zeroj-circuit-dsl` covering in-bounds reads, OOB rejections (`{n, n + 1, p - 1}` directly against R1CS, PlonK, and Halo2 constraint matrices with `arrayAccessOrZero` positive control, plus `WitnessCalculator` checks with zero-valued entries), per-backend row deltas, empty/null/frozen/immutability guards, and `Mux.arrayAccess` delegation on both BLS12-381 and BN254; verify `zeroj-mpf-poseidon` pinned R1CS digests remain unchanged. +- **M3 — Documentation & review (In progress):** `ADR-0010` back-reference and user guides (`docs/circuit-dsl-user-guide.md`, `www/src/content/docs/guides/circuits/circuit-dsl.md`, `www/src/content/docs/guides/circuits/gadgets.md`, `zeroj-circuit-lib/README.md`) updated; awaiting external review sign-off before marking ADR-0065 `Accepted`. ## Verification Strategy 1. **Unit & adversarial soundness (`zeroj-circuit-dsl` — `ArrayAccessSoundnessTest`):** - - Positive tests: every valid index `0 .. n - 1` (for `n = 1` and `n = 4`) returns exact `arr[index]` and satisfies R1CS and PlonK on both BLS12-381 and BN254. - - Negative OOB tests (all must fail witness / constraint verification): `index = n`, `index = n + 1`, `index = p - 1`, including when `arr` contains `0` and when the caller asserts `result == 0` (reproducing the pre-fix forgery). - - Guard tests: empty `arr` throws `IllegalArgumentException`, null `arr` / null element / null `index` throws `NullPointerException` atomically before emitting gates, and post-freeze invocation throws `IllegalStateException`. - - `arrayAccessOrZero` tests: returns `arr[i]` for `0 <= i < n` and `0` for `index = n` / `index = p - 1` / empty `arr`. -2. **Stdlib & MPF regression (`zeroj-circuit-lib`, `zeroj-mpf-poseidon`, `zeroj-integration-tests`):** - - Verify `Mux.arrayAccess` rejects OOB indices. + - Positive tests: every valid index `0 .. n - 1` (for `n = 1` and `n = 4`) returns exact `arr[index]` and satisfies R1CS, PlonK, and Halo2 on both BLS12-381 and BN254. + - Direct constraint-matrix OOB tests with control: forged OOB witnesses for `index ∈ {n, n + 1, p - 1}` fail R1CS, PlonK, and Halo2 on both BLS12-381 and BN254 for strict `arrayAccess`, while the identical forged witnesses satisfy the `arrayAccessOrZero` control circuit on all three backends. + - `WitnessCalculator` OOB tests: `index ∈ {n, n + 1, 64, p - 1, p - 12345}` rejected even when `arr` contains `0` entries and the caller asserts `result == 0`. + - Guard & immutability tests: empty `arr` throws `IllegalArgumentException`, null `arr` / null element / null `index` throws `NullPointerException` atomically before emitting gates, post-freeze invocation throws `IllegalStateException`, and published `Gate.LinComb.terms()` lists throw `UnsupportedOperationException` on mutation. + - Cost & `arrayAccessOrZero` tests: verifies `+1` R1CS (inlined), `+n` PlonK, and `+n` Halo2 row deltas, plus total-function behavior for `0 <= i < n`, `index = n`, `index = p - 1`, and empty `arr`. +2. **Stdlib & MPF regression (`zeroj-circuit-lib`, `zeroj-mpf-poseidon`):** + - Verify `Mux.arrayAccess` accepts in-bounds reads and rejects OOB indices and empty arrays. - Verify all pinned `ZkMpfOperationCircuitTest` and `ZkMpfTransitionCircuitTest` R1CS SHA-256 digests and padding-row tests pass unchanged. ## Remaining Production / Audit Gates @@ -95,3 +102,4 @@ A full in-repository caller census showed only three production call paths: | Date | Status | Summary | |---|---|---| | 2026-11-20 | Proposed (rev 1) | Initial ADR and implementation for bounds-constrained `arrayAccess` and opt-in `arrayAccessOrZero`. | +| 2026-11-20 | Proposed (rev 2) | Addressed PR #119 review findings: made `Gate.LinComb.terms()` immutable via `List.copyOf` + test; documented exact per-backend costs (R1CS inlined `+1` / pressure `+2`, PlonK/Halo2 `+n`); extended constraint-matrix forged-witness tests to `{n, n + 1, p - 1}` across R1CS, PlonK, and Halo2 with `arrayAccessOrZero` positive control; added custom `CircuitAPI` migration note and empty-array Compatibility bullet; fixed `ZkMpf` citations (`differentLeafRoot:131`, `computeRoot:323`, final-cursor padding wording) and updated `gadgets.md` + `zeroj-circuit-lib/README.md`. | diff --git a/www/src/content/docs/guides/circuits/gadgets.md b/www/src/content/docs/guides/circuits/gadgets.md index 5b1b897d..ec2c42a5 100644 --- a/www/src/content/docs/guides/circuits/gadgets.md +++ b/www/src/content/docs/guides/circuits/gadgets.md @@ -124,7 +124,7 @@ makes honest witnesses fail. | Decompose or recompose bits | `SignalBinary.num2Bits` / `bits2Num`, `Binary.*`; `ZkBits` for fixed bit-vector inputs | | Bitwise logic | `SignalBinary.bitAnd/bitOr/bitXor`, `rotateLeft` (a free re-indexing) | | Choose between values | `ZkBool.select(a, b)`; `Mux.mux1`, `Mux.mux2` | -| Dynamic array lookup | `Mux.arrayAccess(api, array, index)` or `SignalBuilder.arrayAccess` (cost grows with length) | +| Dynamic array lookup | `Mux.arrayAccess(api, array, index)` or `SignalBuilder.arrayAccess` (constrains `0 <= index < array.length`, rejects empty arrays; use `arrayAccessOrZero` only for masked padding rows) | | Canonical field representation | `AliasCheck.check(c, value, nBits)`, a decomposition that proves `value < 2^nBits` | ## Jubjub, Pedersen and EdDSA 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 6f7657eb..7cbd9627 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 @@ -178,9 +178,9 @@ public interface CircuitAPI { * *

Soundness warning (ADR-0065): only use this when the caller independently * constrains {@code index} on every active row and masks out-of-bounds results on inactive - * padding rows (for example, {@code ZkMpf} padding rows that pass {@code queryIndex = 64} - * and discard the result via {@code valid.select(...)}). For general dynamic indexing, use - * {@link #arrayAccess(Variable[], Variable)}. + * padding rows (for example, {@code ZkMpf} padding rows that evaluate the final cursor, which + * can be {@code 64}, and discard the result via {@code valid.select(...)}). For general + * dynamic indexing, use {@link #arrayAccess(Variable[], Variable)}. */ default Variable arrayAccessOrZero(Variable[] arr, Variable index) { Objects.requireNonNull(arr, "arr"); diff --git a/zeroj-circuit-dsl/src/main/java/org/zeroj/circuit/Gate.java b/zeroj-circuit-dsl/src/main/java/org/zeroj/circuit/Gate.java index 4b4d2cd4..0bfd3660 100644 --- a/zeroj-circuit-dsl/src/main/java/org/zeroj/circuit/Gate.java +++ b/zeroj-circuit-dsl/src/main/java/org/zeroj/circuit/Gate.java @@ -2,6 +2,7 @@ import java.math.BigInteger; import java.util.List; +import java.util.Objects; /** * An operation (gate) in the arithmetic circuit. @@ -30,7 +31,12 @@ record AssertBoolean(Variable value) implements Gate {} record Select(Variable output, Variable cond, Variable ifTrue, Variable ifFalse) implements Gate {} /** Linear combination: output = sum(coefficient_i * variable_i). Free in R1CS. */ - record LinComb(Variable output, List terms) implements Gate {} + record LinComb(Variable output, List terms) implements Gate { + public LinComb { + Objects.requireNonNull(output, "output"); + terms = List.copyOf(Objects.requireNonNull(terms, "terms")); + } + } /** A term in a linear combination. */ record Term(BigInteger coefficient, Variable variable) {} diff --git a/zeroj-circuit-dsl/src/test/java/org/zeroj/circuit/ArrayAccessSoundnessTest.java b/zeroj-circuit-dsl/src/test/java/org/zeroj/circuit/ArrayAccessSoundnessTest.java index 87f9a4db..f848d550 100644 --- a/zeroj-circuit-dsl/src/test/java/org/zeroj/circuit/ArrayAccessSoundnessTest.java +++ b/zeroj-circuit-dsl/src/test/java/org/zeroj/circuit/ArrayAccessSoundnessTest.java @@ -5,6 +5,8 @@ import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.EnumSource; import org.zeroj.api.CurveId; +import org.zeroj.circuit.halo2.Halo2CircuitSystem; +import org.zeroj.circuit.halo2.Halo2Compiler; import org.zeroj.circuit.plonk.PlonKCompiler; import org.zeroj.circuit.plonk.PlonKConstraintSystem; import org.zeroj.circuit.r1cs.R1CSCompiler; @@ -29,7 +31,7 @@ class ArrayAccessSoundnessTest { @ParameterizedTest @EnumSource(value = CurveId.class, names = {"BLS12_381", "BN254"}) - @DisplayName("in-bounds arrayAccess succeeds and satisfies both R1CS and PlonK") + @DisplayName("in-bounds arrayAccess succeeds and satisfies R1CS, PlonK, and Halo2") void inBoundsArrayAccessSucceeds(CurveId curve) { var circuit = CircuitBuilder.create("array-access-in-bounds") .publicVar("expected") @@ -45,6 +47,7 @@ void inBoundsArrayAccessSucceeds(CurveId curve) { var field = FieldConfig.forCurve(curve); var r1cs = R1CSCompiler.compile(circuit.constraintGraph(), field); var plonk = PlonKCompiler.compile(circuit.constraintGraph(), field); + var halo2 = Halo2Compiler.compile(circuit.constraintGraph(), field); long[] expected = {10, 20, 30, 40}; for (int idx = 0; idx < expected.length; idx++) { @@ -54,6 +57,7 @@ void inBoundsArrayAccessSucceeds(CurveId curve) { BigInteger[] witness = circuit.calculateWitness(inputs, curve); assertTrue(r1csSatisfied(r1cs, witness), "R1CS must accept valid index=" + idx); assertTrue(plonkSatisfied(plonk, witness), "PlonK must accept valid index=" + idx); + assertTrue(halo2Satisfied(halo2, witness), "Halo2 must accept valid index=" + idx); } } @@ -94,30 +98,58 @@ void outOfBoundsArrayAccessIsRejected(CurveId curve) { @ParameterizedTest @EnumSource(value = CurveId.class, names = {"BLS12_381", "BN254"}) - @DisplayName("raw forged OOB witness is rejected directly by R1CS and PlonK constraint matrices") + @DisplayName("forged OOB witnesses for {n, n+1, p-1} fail R1CS, PlonK, and Halo2 while passing arrayAccessOrZero control") void forgedOobWitnessFailsConstraintMatricesDirectly(CurveId curve) { - var circuit = CircuitBuilder.create("array-access-matrix-check") + var strictCircuit = CircuitBuilder.create("array-access-matrix-check") .secretVar("index") .define(api -> { Variable[] arr = {api.constant(7), api.constant(9)}; Variable out = api.arrayAccess(arr, api.var("index")); api.assertEqual(out, api.constant(0)); }); + var controlCircuit = CircuitBuilder.create("array-access-or-zero-control") + .secretVar("index") + .define(api -> { + Variable[] arr = {api.constant(7), api.constant(9)}; + Variable out = api.arrayAccessOrZero(arr, api.var("index")); + api.assertEqual(out, api.constant(0)); + }); - // Construct the exact witness an adversary would produce for index = 2 (OOB) with all - // selectors = 0 and output = 0; every gate except the ADR-0065 selectorSum == 1 check - // would hold. Verify R1CS and PlonK both reject it. - var graph = circuit.constraintGraph(); + var strictGraph = strictCircuit.constraintGraph(); + var controlGraph = controlCircuit.constraintGraph(); var field = FieldConfig.forCurve(curve); - var r1cs = R1CSCompiler.compile(graph, field); - var plonk = PlonKCompiler.compile(graph, field); - BigInteger p = FieldConfig.forCurve(curve).prime(); - BigInteger[] forged = computeForgedWitnessIgnoringFinalAssert(graph, BigInteger.TWO, p); + var strictR1cs = R1CSCompiler.compile(strictGraph, field); + var strictPlonk = PlonKCompiler.compile(strictGraph, field); + var strictHalo2 = Halo2Compiler.compile(strictGraph, field); + var controlR1cs = R1CSCompiler.compile(controlGraph, field); + var controlPlonk = PlonKCompiler.compile(controlGraph, field); + var controlHalo2 = Halo2Compiler.compile(controlGraph, field); + + BigInteger p = field.prime(); + BigInteger[] oobIndices = { + BigInteger.valueOf(2), + BigInteger.valueOf(3), + p.subtract(BigInteger.ONE) + }; + for (BigInteger oob : oobIndices) { + BigInteger[] forgedStrict = computeForgedWitnessIgnoringFinalAssert(strictGraph, oob, p); + assertFalse(r1csSatisfied(strictR1cs, forgedStrict), + "R1CS matrix must reject forged OOB index=" + oob + " on " + curve); + assertFalse(plonkSatisfied(strictPlonk, forgedStrict), + "PlonK constraint system must reject forged OOB index=" + oob + " on " + curve); + assertFalse(halo2Satisfied(strictHalo2, forgedStrict), + "Halo2 constraint system must reject forged OOB index=" + oob + " on " + curve); - assertFalse(r1csSatisfied(r1cs, forged), - "R1CS matrix must reject forged OOB witness on " + curve); - assertFalse(plonkSatisfied(plonk, forged), - "PlonK constraint system must reject forged OOB witness on " + curve); + // Positive control: the exact same forged OOB assignment satisfies arrayAccessOrZero + // on all three backends, proving rejection comes specifically from the ADR-0065 check. + BigInteger[] forgedControl = computeForgedWitnessIgnoringFinalAssert(controlGraph, oob, p); + assertTrue(r1csSatisfied(controlR1cs, forgedControl), + "R1CS control (arrayAccessOrZero) must accept OOB index=" + oob + " on " + curve); + assertTrue(plonkSatisfied(controlPlonk, forgedControl), + "PlonK control (arrayAccessOrZero) must accept OOB index=" + oob + " on " + curve); + assertTrue(halo2Satisfied(controlHalo2, forgedControl), + "Halo2 control (arrayAccessOrZero) must accept OOB index=" + oob + " on " + curve); + } } @ParameterizedTest @@ -185,11 +217,36 @@ void guardRailsRejectEmptyNullAndFrozen() { escapedApi.get().arrayAccessOrZero(new Variable[]{escapedIndex.get()}, escapedIndex.get())); } + @Test + @DisplayName("published Gate.LinComb term lists reject post-build mutation") + void linCombTermsAreImmutableAfterGraphConstruction() { + var graph = CircuitBuilder.create("lincomb-immutable") + .secretVar("index") + .secretVar("bit0") + .secretVar("bit1") + .define(api -> { + api.arrayAccess(new Variable[]{api.constant(10), api.constant(20)}, api.var("index")); + api.fromBinary(new Variable[]{api.var("bit0"), api.var("bit1")}); + }) + .constraintGraph(); + + List linCombs = graph.gates().stream() + .filter(Gate.LinComb.class::isInstance) + .map(Gate.LinComb.class::cast) + .toList(); + assertFalse(linCombs.isEmpty(), "expected LinComb gates from arrayAccess and fromBinary"); + for (Gate.LinComb linComb : linCombs) { + assertThrows(UnsupportedOperationException.class, () -> linComb.terms().clear(), + "Gate.LinComb.terms() must be immutable after graph construction"); + } + } + @ParameterizedTest @EnumSource(value = CurveId.class, names = {"BLS12_381", "BN254"}) - @DisplayName("arrayAccessOrZero preserves opt-in total semantics and costs 1 fewer R1CS row") + @DisplayName("arrayAccessOrZero preserves opt-in total semantics and per-backend cost deltas") void arrayAccessOrZeroTotalSemanticsAndCost(CurveId curve) { BigInteger p = FieldConfig.forCurve(curve).prime(); + int n = 3; var strictCircuit = CircuitBuilder.create("cost-strict") .secretVar("index") .defineSignals(c -> c.arrayAccess( @@ -210,20 +267,27 @@ void arrayAccessOrZeroTotalSemanticsAndCost(CurveId curve) { new Signal[]{c.constant(5), c.constant(6), c.constant(7)}, c.privateInput("index"))); - int strictRows = strictCircuit.compileR1CS(curve).numConstraints(); - int totalRows = totalNoAssert.compileR1CS(curve).numConstraints(); - assertEquals(totalRows + 1, strictRows, - "strict arrayAccess must cost exactly 1 additional R1CS constraint"); - var field = FieldConfig.forCurve(curve); + assertEquals(totalNoAssert.compileR1CS(curve).numConstraints() + 1, + strictCircuit.compileR1CS(curve).numConstraints(), + "strict arrayAccess must cost +1 R1CS constraint when selector sum is inlined"); + assertEquals(PlonKCompiler.compile(totalNoAssert.constraintGraph(), field).numGates() + n, + PlonKCompiler.compile(strictCircuit.constraintGraph(), field).numGates(), + "strict arrayAccess must cost +n PlonK gates"); + assertEquals(Halo2Compiler.compile(totalNoAssert.constraintGraph(), field).numRows() + n, + Halo2Compiler.compile(strictCircuit.constraintGraph(), field).numRows(), + "strict arrayAccess must cost +n Halo2 rows"); + var r1cs = R1CSCompiler.compile(totalCircuit.constraintGraph(), field); var plonk = PlonKCompiler.compile(totalCircuit.constraintGraph(), field); + var halo2 = Halo2Compiler.compile(totalCircuit.constraintGraph(), field); // In-bounds reads return arr[index]. BigInteger[] inBoundsWitness = totalCircuit.calculateWitness( Map.of("index", List.of(BigInteger.ONE), "expected", List.of(BigInteger.valueOf(6))), curve); assertTrue(r1csSatisfied(r1cs, inBoundsWitness)); assertTrue(plonkSatisfied(plonk, inBoundsWitness)); + assertTrue(halo2Satisfied(halo2, inBoundsWitness)); // Out-of-bounds reads return 0 explicitly. for (BigInteger oob : new BigInteger[]{BigInteger.valueOf(3), p.subtract(BigInteger.ONE)}) { @@ -231,6 +295,7 @@ void arrayAccessOrZeroTotalSemanticsAndCost(CurveId curve) { Map.of("index", List.of(oob), "expected", List.of(BigInteger.ZERO)), curve); assertTrue(r1csSatisfied(r1cs, oobWitness)); assertTrue(plonkSatisfied(plonk, oobWitness)); + assertTrue(halo2Satisfied(halo2, oobWitness)); } // Empty array returns 0 under arrayAccessOrZero. @@ -280,7 +345,7 @@ private static BigInteger[] computeForgedWitnessIgnoringFinalAssert( } } case Gate.AssertEq ignored -> { - // Intentionally ignored so we can test the compiled R1CS/PlonK matrices directly. + // Intentionally ignored so we can test the compiled R1CS/PlonK/Halo2 matrices directly. } default -> throw new IllegalStateException("Unexpected gate: " + gate); } @@ -329,4 +394,31 @@ private static boolean plonkSatisfied(PlonKConstraintSystem system, BigInteger[] } return true; } + + private static boolean halo2Satisfied(Halo2CircuitSystem system, BigInteger[] witness) { + BigInteger[] extended = system.extendWitness(witness); + BigInteger p = system.fieldConfig().prime(); + var selectors = system.selectorColumns(); + var advice = system.adviceColumns(); + for (int i = 0; i < system.numRows(); i++) { + BigInteger ql = selectors.get(0).values()[i]; + BigInteger qr = selectors.get(1).values()[i]; + BigInteger qo = selectors.get(2).values()[i]; + BigInteger qm = selectors.get(3).values()[i]; + BigInteger qc = selectors.get(4).values()[i]; + BigInteger a = extended[advice.get(0).wireIndices()[i]]; + BigInteger b = extended[advice.get(1).wireIndices()[i]]; + BigInteger c = extended[advice.get(2).wireIndices()[i]]; + BigInteger eval = ql.multiply(a) + .add(qr.multiply(b)) + .add(qo.multiply(c)) + .add(qm.multiply(a).multiply(b)) + .add(qc) + .mod(p); + if (!eval.equals(BigInteger.ZERO)) { + return false; + } + } + return true; + } } diff --git a/zeroj-circuit-lib/README.md b/zeroj-circuit-lib/README.md index d91657b2..09d139f1 100644 --- a/zeroj-circuit-lib/README.md +++ b/zeroj-circuit-lib/README.md @@ -39,7 +39,7 @@ final proof, verification key data, and public inputs. | Bit and byte vectors | `Binary`, `SignalBinary` | `ZkBits`, `ZkBytes` | Generic | Ready for binding/equality on BLS12-381 Groth16 | Symbolic bitwise operations are still limited; use `SignalBinary` or add wrappers when needed. | | Binary decomposition | `Binary`, `SignalBinary`, `AliasCheck` | Partly via `ZkUInt`, `ZkBits`, `ZkBool` | Generic | Ready on BLS12-381 Groth16 | `AliasCheck` remains a lower-level helper for canonical field representation checks. | | Comparators and ranges | `Comparators`, `SignalComparators` | Mostly through `ZkUInt` | Generic | Ready on BLS12-381 Groth16 | Optional symbolic `min`/`max` helpers can be added later if needed. | -| Selection / mux | `Mux` | `ZkBool.select(...)` | Generic for scalar values | Ready on BLS12-381 Groth16 | Dynamic array access remains a lower-level `Mux.arrayAccess(...)` pattern. `ZkJubjubPoint.select(...)` inherits the Jubjub-row status below, not this one. | +| Selection / mux | `Mux` | `ZkBool.select(...)` | Generic for scalar values | Ready on BLS12-381 Groth16 | Dynamic array access remains a lower-level `Mux.arrayAccess(...)` pattern (bounds-constrained `0 <= index < arr.length`, rejects empty arrays; use `CircuitAPI.arrayAccessOrZero` only for independently bounded / masked padding rows per ADR-0065). `ZkJubjubPoint.select(...)` inherits the Jubjub-row status below, not this one. | | MiMC | `MiMC`, `SignalMiMC` | `ZkMiMC` | BN254 only | Not Cardano-ready | `MiMC` and `SignalMiMC` call `requireField(FieldConfig.BN254)`. Use Poseidon for Cardano circuits. | | MiMC sponge | `MiMCSponge` | No direct `ZkMiMCSponge` | BN254 only, because it uses MiMC | Not Cardano-ready | Useful for BN254/off-chain legacy circuits only. | | Poseidon T3 | `Poseidon`, `SignalPoseidon` | `ZkPoseidon` | BN254 default; BLS12-381 with explicit params | Ready when using `PoseidonParamsBLS12_381T3.INSTANCE` | No-params overloads are BN254 for backward compatibility. | 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 07964a0b..cb231a0f 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 @@ -827,9 +827,10 @@ static PathSignals of(ZkArray path) { ZkUInt at(ZkContext zk, Signal index) { // ADR-0065: every active lookup in ZkMpf already constrains index <= 63 - // (prepareBranchProof/computeRoot lteConst on active rows; nonInclusionDifferentLeaf / - // verifyDifferentLeafInsertion lteConst on divergenceIndex), while inactive padding - // rows intentionally evaluate queryIndex = 64 and discard the result via valid.select. + // (prepareBranchProof:249 and computeRoot:323 lteConst on active rows; + // differentLeafRoot:131 and verifyDifferentLeafInsertion:168 lteConst on + // divergenceIndex), while inactive padding rows evaluate the final cursor (which can + // be 64) and discard the result via valid.select. return ZkUInt.wrap(zk, zk.builder().arrayAccessOrZero(signals, index), 4); } }