Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion docs/adr/0010-java-circuit-dsl.md
Original file line number Diff line number Diff line change
@@ -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
Expand Down
105 changes: 105 additions & 0 deletions docs/adr/0065-array-access-bounds-soundness.md

Large diffs are not rendered by default.

3 changes: 2 additions & 1 deletion docs/circuit-dsl-user-guide.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
2 changes: 1 addition & 1 deletion www/src/content/docs/guides/circuits/circuit-dsl.md
Original file line number Diff line number Diff line change
Expand Up @@ -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".
Expand Down
2 changes: 1 addition & 1 deletion www/src/content/docs/guides/circuits/gadgets.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
@@ -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.
Expand Down Expand Up @@ -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}.
*
* <p>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, <em>without</em> emitting a bounds constraint on {@code index}.
*
* <p><b>Soundness warning (ADR-0065):</b> 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 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");
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. */
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<Gate.Term> 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));
Expand Down
8 changes: 7 additions & 1 deletion zeroj-circuit-dsl/src/main/java/org/zeroj/circuit/Gate.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import java.math.BigInteger;
import java.util.List;
import java.util.Objects;

/**
* An operation (gate) in the arithmetic circuit.
Expand Down Expand Up @@ -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<Term> terms) implements Gate {}
record LinComb(Variable output, List<Term> 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) {}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package org.zeroj.circuit;

import java.math.BigInteger;
import java.util.Objects;

/**
* Builder for the {@link Signal}-based circuit API.
Expand Down Expand Up @@ -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).
*
* <p>Only use this when the caller independently constrains {@code index} on active rows and
* masks inactive padding rows; otherwise use {@link #arrayAccess(Signal[], Signal)}.</p>
*/
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);
Expand Down
Loading
Loading