Skip to content

security(circuit-dsl): enforce index bounds in arrayAccess and add arrayAccessOrZero (ADR-0065) - #119

Merged
satran004 merged 2 commits into
mainfrom
fix/adr-0065-array-access-soundness
Nov 20, 2026
Merged

satran004 merged 2 commits into
mainfrom
fix/adr-0065-array-access-soundness

Conversation

@satran004

@satran004 satran004 commented Nov 20, 2026 •

Copy link
Copy Markdown
Member

Summary

Implements ADR-0065 (docs/adr/0065-array-access-bounds-soundness.md, status Proposed) to close a circuit-soundness defect where CircuitAPI.arrayAccess (and its delegates SignalBuilder.arrayAccess and Mux.arrayAccess) silently returned 0 and satisfied R1CS/PlonK/Halo2 for out-of-bounds indices (index = arr.length, index = p - 1, or empty arrays).

Changes

  • Governing R2 ADR: Added docs/adr/0065-array-access-bounds-soundness.md (Proposed) and an "Amended by ADR-0065" back-reference in docs/adr/0010-java-circuit-dsl.md, plus updated docs/circuit-dsl-user-guide.md, www/src/content/docs/guides/circuits/circuit-dsl.md, www/src/content/docs/guides/circuits/gadgets.md, and zeroj-circuit-lib/README.md.
  • Bounds-constrained arrayAccess (zeroj-circuit-dsl, zeroj-circuit-lib):
    • CircuitAPIImpl.arrayAccess validates builder lifecycle (requireNotFrozen()), rejects null array/elements/index atomically before emitting gates, rejects empty arrays (IllegalArgumentException), and emits Gate.LinComb(selectorSum) + assertEqual(selectorSum, oneWire).
    • Gate.LinComb defensively copies terms via List.copyOf in its compact constructor so published constraint graphs cannot be mutated post-build (protects both arrayAccess and fromBinary).
    • SignalBuilder.arrayAccess and Mux.arrayAccess delegate directly and inherit the invariant automatically.
  • Explicit total-function opt-in (arrayAccessOrZero):
    • Added default Variable arrayAccessOrZero(Variable[] arr, Variable index) to CircuitAPI (overridden in CircuitAPIImpl with lifecycle/null guards) and SignalBuilder.arrayAccessOrZero with explicit soundness warning Javadoc.
    • Updated ZkMpf.PathSignals.at (zeroj-mpf-poseidon/.../circuit/ZkMpf.java) to opt into arrayAccessOrZero, since ZkMpf already independently constrains all active indices to [0, 63] (prepareBranchProof:249, computeRoot:323, differentLeafRoot:131, verifyDifferentLeafInsertion:168) and masks inactive padding rows (which evaluate the final cursor, possibly 64) with valid.select. All pinned ZkMpf R1CS constraint counts and canonical SHA-256 digests remain 100% unchanged.

Breaking Note

  • Per-backend constraint & key change (arrayAccess callers outside ZkMpf):
    • DSL graph: +1 intermediate wire (selectorSum), +1 Gate.LinComb, +1 Gate.AssertEq.
    • R1CS: +1 constraint row when selectorSum is inlined; +2 rows under compiler pressure mode.
    • PlonK and Halo2: +n rows/gates (n - 1 binary addition gates for the n-term LinComb chain plus 1 equality gate).
    • Every backend (R1CS, PlonK, Halo2): callers of CircuitAPI.arrayAccess, SignalBuilder.arrayAccess, or Mux.arrayAccess must regenerate circuit-specific proving/verifying keys.
  • Empty arrays: arrayAccess with an empty array previously compiled and returned constant(0); it now throws IllegalArgumentException at circuit definition time (opt into arrayAccessOrZero if total empty-array lookup is intended).
  • Custom CircuitAPI implementations: CircuitBuilder always instantiates CircuitAPIImpl, so standard DSL circuits inherit the fix automatically. Downstream custom CircuitAPI providers passed directly into Mux.arrayAccess or other zeroj-circuit-lib gadgets still compile against the unchanged signature and must update their arrayAccess implementation and verify OOB rejection before regenerating keys.
  • zeroj-mpf-poseidon: Templates and pinned R1CS SHA-256 digests are unchanged.

Verification

  • New adversarial & regression tests:
    • ArrayAccessSoundnessTest (zeroj-circuit-dsl): verified on both BLS12-381 and BN254 across WitnessCalculator, R1CS, PlonK, and Halo2:
      • In-bounds reads 0 .. n - 1 (n = 1 and n = 4) succeed and satisfy R1CS, PlonK, and Halo2.
      • Direct forged-witness matrix verification over index ∈ {n, n + 1, p - 1} fails R1CS, PlonK, and Halo2 for strict arrayAccess while the identical forged witnesses pass the matching arrayAccessOrZero control circuit on all three backends.
      • WitnessCalculator OOB tests (n, n + 1, 64, p - 1, p - 12345) rejected even with zero-valued array entries and expected == 0.
      • Empty-array, atomic null-argument, post-freeze, and Gate.LinComb.terms() immutability guards verified.
      • Exact per-backend row deltas verified (+1 R1CS inlined, +n PlonK, +n Halo2) along with total arrayAccessOrZero semantics.
    • CircuitLibTest.mux_arrayAccess_enforcesBoundsAndRejectsEmpty (zeroj-circuit-lib).
  • Affected suites (all green):
    • ./gradlew :zeroj-circuit-dsl:test :zeroj-circuit-lib:test :zeroj-circuit-annotation-api:test :zeroj-circuit-annotation-processor:test :zeroj-mpf-poseidon:test :zeroj-jmt-poseidon:test verifyDefaultModuleSurface verifyNoBuiltinProfileDefine — BUILD SUCCESSFUL (0 failures; all pinned ZkMpf & ZkJmt R1CS digests verified unchanged).

…rayAccessOrZero (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.

Copy link
Copy Markdown

Initial automated review · Aster

Hi @satran004, thanks for the PR! 🙏 This is an automatic first check by an AI reviewer. It does not replace maintainer review and may be wrong.

Reviewed commit: 3b99311ddbbbf96803d7a60be0b57b646e891d5f

No issues found in this first check.

Not tested: Code and tests were read only; I did not run the build or tests.

@satran004

Copy link
Copy Markdown
Member Author

reviewer1 · Changes requested on 3b99311d

The built-in lookup constrains the index correctly. Each equality selector is bound by isZero, and requiring their sum to equal one forces the index to select exactly one array entry. I also traced the MPF callers. Active branch reads are bounded by the cursor constraints, divergence reads have their own bound, and padding rows can still use the zero fallback.

  1. Document the migration for custom CircuitAPI implementations. The existing arrayAccess method keeps its signature. A downstream implementation with the old zero-on-miss behavior will still compile and load, and Mux.arrayAccess delegates directly to it. Updating ZeroJ and regenerating keys with that provider would therefore preserve the old relation. Please add a migration note telling provider authors to update their strict lookup and confirm that their compiled constraints reject an out-of-range index before regenerating keys. ADR-0065 compatibility

  2. Make the selector terms immutable when the graph is built. The new Gate.LinComb retains an ArrayList. Code inspecting the public constraintGraph().gates() can modify its terms() after define returns, changing the bounds relation used by subsequent compilations of the same circuit. A defensive List.copyOf in the LinComb constructor would protect all callers. A regression test can assert that the published term list rejects mutation. Selector-sum gate construction

  3. Qualify the one-row cost in ADR-0065. I appended a three-element lookup to the existing BooleanAssertionTest pressure-mode fixture and compiled both variants on BLS12-381. The total lookup produced 25 R1CS rows and the strict lookup 27. Under pressure the compiler materializes the selector sum in its own row, then emits the equality row. The one-extra-wire claim holds for the DSL graph. The one-extra-row claim should be scoped to compilation that inlines the sum. ADR-0065 cost

I reran the Gradle test tasks for zeroj-circuit-dsl, zeroj-circuit-lib, and zeroj-mpf-poseidon on Java 25. 1,471 passed, 24 skipped, 0 failed. The MPF operation and transition suites passed their pinned R1CS digest checks.

@satran004

Copy link
Copy Markdown
Member Author

Verdict: CHANGES REQUESTED

Reviewer: reviewer2 · Review of ADR-0065 and its implementation (PR #119) at 3b99311ddbbbf96803d7a60be0b57b646e891d5f.

The fix is sound, and I could not break it. Each isEqual(index, i) selector is pinned by isZero. The constants 0..n-1 are distinct mod p, so sum(selector_i) == 1 holds exactly when index is in range. I confirmed this with a forged-witness probe on all three compilers (R1CS, PlonK and Halo2) and on both curves, and with a mutation check. The ZkMpf opt-in (D3) is justified: making ZkMpf strict breaks an honest padding-row test.

The one change I need is to the ADR's cost and backend statements, which are only true for R1CS (F1). The other findings are P3. No code change to the relation is requested.

F1 [P2] Cost and backend scope are stated only for R1CS; the Halo2 backend is not covered

Location:

  • ADR-0065 D1 "Cost", Consequences, Compatibility.
  • The PR description's "Breaking Note".
  • I2, M2 and the Verification Strategy.

Problem:

  • The ADR says the change costs "1 R1CS constraint and 1 wire regardless of arr.length". That is true for R1CS when the sum is inlined. reviewer1's feat: extract shared BLS12-381 primitives and add CFRG BBS draft-10 #3 shows it becomes 2 rows in pressure mode.
  • For PlonK and Halo2 the cost grows with the array: the n-term LinComb is compiled as a chain of n - 1 addition gates, plus the equality row.
  • zeroj-circuit-dsl ships a third compiler, halo2/Halo2Compiler, which ADR-0065 never mentions. AGENTS.md asks for every provider path to be covered.

Evidence: I wrote a temporary probe in the worktree and deleted it afterwards. It compares the strict lookup with arrayAccessOrZero on the same circuit. Results are identical on BLS12-381 and BN254.

n R1CS rows PlonK gates Halo2 rows
4 17 → 18 50 → 54 50 → 54
16 65 → 66 185 → 201 185 → 201
64 257 → 258 (+0.4%) 713 → 777 (+9.0%) 713 → 777 (+9.0%)

Soundness holds on Halo2. A forged out-of-range witness is rejected there just as on R1CS and PlonK; see F2.

Requested revision:

  • State the cost per backend:
    • R1CS: +1 row when inlined, +2 under pressure (per reviewer1).
    • PlonK and Halo2: +n rows.
    • Every backend: new keys.
  • Add Halo2 to I2, M2 and the Verification Strategy, and to the test (see F2).
  • Fix the PR's Breaking Note to match.

F2 [P3] The constraint-level evidence for I2 covers only index = n, n = 2, with no control case

Location: ArrayAccessSoundnessTest.forgedOobWitnessFailsConstraintMatricesDirectly, and I2.

Problem:

  • I2 claims that index = n, n + 1 and p - 1 all fail R1CS and PlonK. Only index = 2 with n = 2 is checked against the compiled constraints.
  • The other indices are checked through calculateWitness, which throws because the witness calculator evaluates AssertEq. That shows the prover tooling fails closed, not that the constraints reject the witness.
  • There is no control case showing that the same forged witness satisfies the arrayAccessOrZero circuit. Without one, a rejection could come from something other than the new constraint.

Evidence: My probe ran forged witnesses for index ∈ {2, 3, p-1} with n = 2:

  • strict lookup: rejected by R1CS, PlonK and Halo2 on both curves.
  • arrayAccessOrZero: the identical witnesses are accepted by all three.

So the test would pass if extended. It just isn't proving the whole invariant today.

Requested revision: Run the forged-witness test over {n, n + 1, p - 1}. Add the Halo2 system. Add the arrayAccessOrZero acceptance check as a control.

F3 [P3] Wrong method name and an imprecise padding-row description

Location:

  • ADR-0065 D3.
  • ZkMpf.java:830 (the new comment).
  • ADR-0065 Context item 3.

Problem:

  • Both D3 and the code comment cite nonInclusionDifferentLeaf, but no such method exists. The bound at ZkMpf.java:131 is in differentLeafRoot (ZkMpf.java:112).
  • D3 gives the bound as computeRoot:321, but it is at :323.
  • The text says padding rows "evaluate queryIndex = 64". In fact a padding row evaluates the final cursor (cursor + 0 + 1 - 1). That is 64 only when the whole key path has been consumed; otherwise it is an in-range index whose result valid.select discards.

The conclusion still holds. Making ZkMpf strict fails ZkMpfOperationCircuitTest.streamingPathPackingMatchesHostAtEverySkipAndWithPadding on honest witnesses, plus the three pinned digest/count tests.

Requested revision: Correct the method name and line reference in the ADR and the comment. Say "the final cursor, which can be 64".

F4 [P3] Compatibility omits the empty-array change, and two docs still describe the old lookup

Location:

  • ADR-0065 Compatibility.
  • www/src/content/docs/guides/circuits/gadgets.md:127.
  • zeroj-circuit-lib/README.md:42.

Problem:

  • An empty-array arrayAccess used to compile and return constant(0). It now throws IllegalArgumentException when the circuit is built. That is a source-level behaviour change, separate from the key change.
  • The two docs listed above describe Mux.arrayAccess and SignalBuilder.arrayAccess with no mention of the bounds check or arrayAccessOrZero.

Requested revision: Add one Compatibility bullet for the empty-array change, and update the two docs.

On reviewer1's findings

Things to retain

  • The sum(selector_i) == 1 check: it reuses selectors that are already computed and needs no bit-width parameter.
  • The fail-closed default, with the unsafe variant opted into by name (arrayAccessOrZero) and carrying a Javadoc warning.
  • D3, keeping ZkMpf on the total lookup. This is backed by the mutation evidence above and leaves the MPF/JMT digests unchanged.
  • Null and frozen-builder checks that run before any gate is emitted, and OOB tests that include zero-valued entries.

Validation

Run at 3b99311ddbbbf96803d7a60be0b57b646e891d5f in an isolated worktree with Java 25.0.2-graal:

./gradlew :zeroj-circuit-dsl:test :zeroj-circuit-lib:test :zeroj-circuit-annotation-api:test \
  :zeroj-circuit-annotation-processor:test :zeroj-mpf-poseidon:test :zeroj-jmt-poseidon:test \
  verifyDefaultModuleSurface verifyNoBuiltinProfileDefine --continue      # BUILD SUCCESSFUL
Suite Tests Failures Errors Skipped
zeroj-circuit-dsl 134 0 0 1
zeroj-circuit-lib 1313 0 0 26
zeroj-circuit-annotation-api 22 0 0 0
zeroj-circuit-annotation-processor 31 0 0 0
zeroj-mpf-poseidon 48 0 0 0
zeroj-jmt-poseidon 15 0 0 0

Mutation checks (both reverted afterwards):

  • With assertEqual(selectorSum, oneWire) removed, 8 of 11 ArrayAccessSoundnessTest cases fail, and so does CircuitLibTest.mux_arrayAccess_enforcesBoundsAndRejectsEmpty. The new tests catch the bug.
  • With ZkMpf.PathSignals.at switched to strict arrayAccess, 4 of 48 zeroj-mpf-poseidon tests fail: the honest padding-row test and three pinned digest/count tests.

Probe: a forged-witness and cost comparison across R1CS, PlonK and Halo2 on BLS12-381 and BN254, with results as in F1 and F2. It was never committed and has been deleted.

Caller census: I confirmed that the only production callers are SignalBuilder, Mux and ZkMpf. The local zeroj-usecases checkout has no arrayAccess callers.

Not run:

No files in the PR were changed by this review.

This is design acceptance only. It does not certify the implementation, its tests or its security. ADR-0065 itself records that an external circuit audit is still needed before value-bearing use.

…Comb, 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.
@satran004

Copy link
Copy Markdown
Member Author

Addressed all review findings from reviewer1 and reviewer2 in commit a36e99c2 (and updated the PR Breaking Note to match):

  • Immutable Gate.LinComb terms (reviewer1 feat: Usage Improvements #2): Added List.copyOf (and non-null checks) in Gate.LinComb's compact constructor (Gate.java), protecting both arrayAccess and fromBinary, with a post-build immutability regression test in ArrayAccessSoundnessTest.linCombTermsAreImmutableAfterGraphConstruction.
  • Per-backend cost & Halo2 coverage (reviewer1 feat: extract shared BLS12-381 primitives and add CFRG BBS draft-10 #3, reviewer2 F1): Updated ADR-0065 (D1 Cost, I2, Consequences, Compatibility, M2, Verification Strategy) and the PR Breaking Note with exact per-backend costs — R1CS +1 row when inlined / +2 rows under compiler pressure mode (+1 DSL wire), PlonK & Halo2 +n rows/gates, and new keys required on every backend — and asserted +1 R1CS / +n PlonK / +n Halo2 deltas in ArrayAccessSoundnessTest.
  • Expanded constraint-matrix forged-witness test + control (reviewer2 F2): Extended ArrayAccessSoundnessTest.forgedOobWitnessFailsConstraintMatricesDirectly over {n, n + 1, p - 1} across R1CS, PlonK, and Halo2 on both BN254 and BLS12-381, with the matching arrayAccessOrZero circuit verified as a positive control accepting the exact same forged OOB witnesses on all three backends (and verified Halo2 satisfaction on honest in-bounds reads).
  • Custom CircuitAPI migration note (reviewer1 Add BLS12-381 Poseidon, Jubjub-in-circuit support #1) & empty-array Compatibility bullet (reviewer2 F4): Documented both explicitly in ADR-0065 §Compatibility (and in the PR Breaking Note), clarifying that CircuitBuilder always instantiates CircuitAPIImpl while custom CircuitAPI providers passed into Mux / zeroj-circuit-lib must update their strict lookup and verify OOB rejection before regenerating keys.
  • ZkMpf citations & padding wording (reviewer2 F3): Corrected differentLeafRoot:131, computeRoot:323, and "evaluate the final cursor, which can be 64" in ADR-0065, ZkMpf.java:830, and CircuitAPI.java:180.
  • Remaining docs (reviewer2 F4): Updated www/src/content/docs/guides/circuits/gadgets.md and zeroj-circuit-lib/README.md to document the arrayAccess bounds check, empty-array rejection, and arrayAccessOrZero.

Re-ran ./gradlew :zeroj-circuit-dsl:test :zeroj-circuit-lib:test :zeroj-circuit-annotation-api:test :zeroj-circuit-annotation-processor:test :zeroj-mpf-poseidon:test :zeroj-jmt-poseidon:test verifyDefaultModuleSurface verifyNoBuiltinProfileDefine — BUILD SUCCESSFUL (0 failures; all pinned MPF & JMT R1CS digests unchanged).

@satran004

Copy link
Copy Markdown
Member Author

Verdict: APPROVED

Reviewer: reviewer2 · Round 2 review of a36e99c20a1d357735bc94982dcc3d1b21fff93a, diffed from 3b99311ddbbbf96803d7a60be0b57b646e891d5f. The branch fast-forwarded; no history was rewritten.

I checked the files at the new head, not the author's reply. All four of my findings are resolved in the ADR text, the code and the tests. I re-ran the affected suites and the mutation check at this head. I have no new findings.

Finding Status Notes
F1 [P2] Cost and backend scope covered R1CS only; Halo2 missing Resolved See below.
F2 [P3] Forged-witness constraint evidence and control case Resolved See below.
F3 [P3] ZkMpf method name, line reference, padding wording Resolved See below.
F4 [P3] Empty-array compatibility and stale docs Resolved See below.

F1.

  • D1 now gives the cost for each backend:
    • DSL graph: +1 wire.
    • R1CS: +1 row when inlined, +2 under pressure mode.
    • PlonK and Halo2: +n rows. The figures 50→54, 185→201 and 713→777 match my round-1 probe.
  • Consequences, Compatibility, Risks, the Alternatives cost line, and the risk-class line all name R1CS, PlonK and Halo2.
  • I2, M2 and the Verification Strategy include Halo2.
  • arrayAccessOrZeroTotalSemanticsAndCost asserts the +1 R1CS, +n PlonK and +n Halo2 differences.
  • The PR's Breaking Note is updated to match.

F2. forgedOobWitnessFailsConstraintMatricesDirectly now:

  • runs index ∈ {n, n+1, p-1} against the R1CS, PlonK and Halo2 systems on both curves;
  • checks that the identical forged witnesses satisfy the arrayAccessOrZero control circuit on all three backends.

Halo2 is also checked on honest in-range reads. The new halo2Satisfied helper checks the same gate equation as the existing Halo2CompilerTest helper.

F3.

  • The ADR and the ZkMpf.java comment both now cite differentLeafRoot:131 and computeRoot:323.
  • Padding rows are described as evaluating "the final cursor, which can be 64", in ADR Context item 3, D3, the CircuitAPI.arrayAccessOrZero Javadoc and the ZkMpf comment.
  • I checked the cited lines at this head: 131, 168, 249 and 323 are the lteConst bounds.

F4.

  • Compatibility has a new bullet: an empty array used to return constant(0) and now throws IllegalArgumentException when the circuit is defined.
  • gadgets.md and zeroj-circuit-lib/README.md now describe the bounds check, the empty-array rejection and when to use arrayAccessOrZero.

reviewer1's points, which I also endorsed:

  • Migration note (Add BLS12-381 Poseidon, Jubjub-in-circuit support #1). It is in Compatibility and Risks, and records that CircuitBuilder always constructs CircuitAPIImpl.
  • Immutable term list (feat: Usage Improvements #2). Gate.LinComb now has a compact constructor with List.copyOf and null checks, which covers arrayAccess and fromBinary. The three in-repo constructors of LinComb (CircuitAPIImpl.java:328, :472, :624) only build the term list and never modify it afterwards, so the copy breaks nothing. linCombTermsAreImmutableAfterGraphConstruction tests both producers.
  • Pressure-mode cost (feat: extract shared BLS12-381 primitives and add CFRG BBS draft-10 #3). It is documented in D1, but it isn't asserted in a test. That's acceptable to me because reviewer1 measured it.

Validation

Run at a36e99c20a1d357735bc94982dcc3d1b21fff93a in an isolated worktree with Java 25.0.2-graal:

./gradlew :zeroj-circuit-dsl:test :zeroj-circuit-lib:test :zeroj-circuit-annotation-api:test \
  :zeroj-circuit-annotation-processor:test :zeroj-mpf-poseidon:test :zeroj-jmt-poseidon:test \
  verifyDefaultModuleSurface verifyNoBuiltinProfileDefine --continue      # BUILD SUCCESSFUL
Suite Tests Failures Errors Skipped
zeroj-circuit-dsl 135 0 0 1
zeroj-circuit-lib 1313 0 0 26
zeroj-circuit-annotation-api 22 0 0 0
zeroj-circuit-annotation-processor 31 0 0 0
zeroj-mpf-poseidon 48 0 0 0
zeroj-jmt-poseidon 15 0 0 0
  • Pinned digests: the MPF and JMT R1CS digest tests pass unchanged, so I5 holds.
  • Mutation check, repeated at this head: I removed assertEqual(selectorSum, oneWire) and then reverted it. 8 of 12 ArrayAccessSoundnessTest cases fail, including the new three-backend forged-witness test on both curves. The tests still catch the bug.
  • Not run: the full ./gradlew build.
  • PR CI when I checked: build, gnark and snarkjs had passed. Build & Test, Linux and the WASM job were still pending. Test (macos-arm64) fails immediately, the same runner-configuration problem as on security(bbs): harden on-chain/off-chain BBS verification (ADR-0064) and upgrade JuLC 0.1.0-pre22 / CCL 0.8.0-pre8 #118.

No files in the PR were changed by this review.

No P0–P3 findings remain open. The one recorded gate is ADR-0065's external circuit audit before any value-bearing deployment.

This is design acceptance only. It does not certify the implementation, its tests or its security. Commits pushed after a36e99c2 are not covered by this approval.

@satran004

Copy link
Copy Markdown
Member Author

Verdict: APPROVED (one non-blocking P3, two nits)

Reviewer: reviewer3 · Independent review of ADR-0065 and its implementation at a36e99c20a1d357735bc94982dcc3d1b21fff93a.

I read reviewer1's and reviewer2's comments, but I re-derived the soundness argument and re-checked the compiler paths myself rather than relying on theirs.

Soundness of the relation

  • isZero emits a·inv = 1 − r and a·r = 0 (CircuitAPIImpl.java:533-544).
    • If a = 0, then r = 1.
    • If a ≠ 0, then r = 0, and the first row forces inv = a⁻¹.
    • So every selector is pinned to [index == i], and the hints cannot override it.
  • The constants 0..n−1 are distinct mod p because n ≤ Integer.MAX_VALUE < p. So Σ selector_i ∈ {0, 1}, and it equals 1 exactly when index ∈ [0, n). With the sum equal to 1, result = arr[index].
  • R1CS lowering: AssertEq drops a row only when left − right is symbolically empty (R1CSCompiler.java:311-326). The selectors are hint wires, so selectorSum − 1 is never empty and the bounds row cannot be folded away.
  • Selector reads: each selector wire is read twice, by the Mul and by the new LinComb. The read-count analysis counts both reads (R1CSCompiler.java:151-156). Consuming the selector in one place therefore cannot leave the other read unconstrained.
  • D3 (ZkMpf): I traced each PathSignals.at call.
    • differentLeafRoot and verifyDifferentLeafInsertion bound divergenceIndex ≤ 63 unconditionally (lines 131 and 168).
    • foldBranchCurrents (line 278) and computeRoot (lines 356 and 403) look up nextCursor − 1, with valid ⇒ advanced ≤ 64 at lines 249 and 323.
    • The inactive rows' results reach the output only through valid.select.
    • So I agree that ZkMpf is correct to use the total lookup.

F1 [P3, non-blocking] Every soundness test uses an array of constants; add a witness-valued array and the R1CS inlining policies

Location: ArrayAccessSoundnessTest and CircuitLibTest.mux_arrayAccess_enforcesBoundsAndRejectsEmpty.

Problem:

  • In every test, arr is built from api.constant(...). The R1CS compiler folds mul(constant, selector) into a scaled term, so it emits no row for it (R1CSCompiler.java:295-307).
  • The ADR's threat model says the elements of arr are prover-controlled witness wires. Compiling those takes the other branch, which emits a Mul row per element. None of the I2 forged-witness evidence covers that branch.
  • The +2-rows-under-pressure claim in D1 is still not covered by a test (reviewer2 accepted that).

Evidence: I ran a temporary probe in an isolated worktree, then deleted it; nothing was committed.

  • Probe 1: arr = {a0, a1, a2} as secret inputs set to 5, 6, 7, with assert out == 0, on BLS12-381 and BN254. I used the existing computeForgedWitnessIgnoringFinalAssert approach.
    • index ∈ {3, 4, p−1}:
      • strict: rejected by R1CS, PlonK and Halo2;
      • arrayAccessOrZero control: accepted by all three.
    • Honest in-range reads are accepted.
    • Rows: R1CS 16→17, PlonK 35→38, Halo2 35→38. That is +1, +n and +n, matching D1.
  • Probe 2: the same circuit compiled with each of LinearInliningPolicy.inlineAll, materialiseAll and select, using R1CSCompiler.compile(graph, field, policy).
    • strict: rejects {3, p−1} under every policy;
    • control: accepts them under every policy.
    • Under materialiseAll, the row count goes from 23 to 25. This independently confirms the +2 figure that reviewer1 measured.

So the implementation is correct. The test suite just doesn't pin these paths.

Suggested revision (can be a follow-up):

  • Add a witness-valued variant of forgedOobWitnessFailsConstraintMatricesDirectly.
  • Add a small org.zeroj.circuit.r1cs test that loops over the three LinearInliningPolicy factories, as BooleanAssertionTest already does. It should assert that the strict lookup rejects the forged witness, that the control accepts it, and that the materialiseAll cost difference is +2.

N1 [nit] arrayAccess and arrayAccessOrZero duplicate the MUX loop

CircuitAPIImpl.java:604-644

  • The two methods contain the same validation and selector loop.
  • A shared private helper could return result and the selector list, with arrayAccess appending the LinComb and AssertEq. That would keep the two lookups from drifting apart.
  • ZkMpf digests stay byte-identical only if the gate order is unchanged. The helper has to keep the current order, and the pinned digests would catch any slip.

N2 [nit] The ZkMpf comment slightly overstates the bound

  • ZkMpf.java:829-833 and ADR D3 say that lines 249 and 323 "constrain index <= 63".
  • What those lines actually constrain is advanced ≤ 64. The looked-up index is advanced − 1, and its lower bound (advanced ≥ 1) comes from the range-bounded cursor and skip.
  • The conclusion is correct. A wording such as "bound advanced ≤ 64, so the active query index advanced − 1 lies in [0, 63]" would make the comment accurate.

Things to retain

  • The fail-closed default, with an opt-in variant whose name says what it does.
  • Null and frozen-builder checks that run before any gate is emitted. arrayAccessOrZero is also overridden with requireNotFrozen(). That matters for an empty array after the builder is frozen: constant(0) comes from the cache, so it would never reach newIntermediate's guard.
  • List.copyOf in Gate.LinComb. The only constructors of LinComb in the repo are the three in CircuitAPIImpl, and nothing modifies terms() after construction.
  • The arrayAccessOrZero control in the forged-witness test.

Validation

Run at a36e99c20a1d357735bc94982dcc3d1b21fff93a in an isolated worktree with Java 25.0.2-graal, with the probes removed first:

./gradlew :zeroj-circuit-dsl:test :zeroj-circuit-lib:test :zeroj-circuit-annotation-api:test \
  :zeroj-circuit-annotation-processor:test :zeroj-mpf-poseidon:test :zeroj-jmt-poseidon:test \
  verifyDefaultModuleSurface verifyNoBuiltinProfileDefine --continue      # BUILD SUCCESSFUL
Suite Tests Failures Errors Skipped
zeroj-circuit-dsl 135 0 0 1
zeroj-circuit-lib 1313 0 0 26
zeroj-circuit-annotation-api 22 0 0 0
zeroj-circuit-annotation-processor 31 0 0 0
zeroj-mpf-poseidon 48 0 0 0
zeroj-jmt-poseidon 15 0 0 0
  • Caller census: the production callers of arrayAccess are SignalBuilder, Mux and ZkMpf (now on OrZero). The only other CircuitAPI implementations in the repo are the two test-only NonOwningCircuitAPI fixtures. No other main-code MUX scans use isEqual(index, constant(i)).
  • Not run: the full ./gradlew build.
  • PR CI when I checked: build, gnark, snarkjs and the BLS/BBS WASM differential job had passed. Build & Test and Test (linux-x86_64) were pending. Test (macos-arm64) fails after 1s, the same runner-configuration problem seen on security(bbs): harden on-chain/off-chain BBS verification (ADR-0064) and upgrade JuLC 0.1.0-pre22 / CCL 0.8.0-pre8 #118.

No files in the PR were changed by this review.

This is design acceptance only. It does not certify the implementation, its tests or its security. ADR-0065's external circuit audit is still required before any value-bearing deployment. Commits pushed after a36e99c2 are not covered by this approval.

@satran004
satran004 merged commit 6c5da74 into main Nov 20, 2026
7 of 8 checks passed
@satran004
satran004 deleted the fix/adr-0065-array-access-soundness branch November 20, 2026 15:24
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants