Skip to content

feat(confidential): register circuit - #715

Merged
brozorec merged 18 commits into
mainfrom
ct-noir-circuits
May 21, 2026
Merged

brozorec merged 18 commits into
mainfrom
ct-noir-circuits

Conversation

@brozorec

@brozorec brozorec commented May 20, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Implements the Register circuit (circuit_register) — the first of six per-operation circuits tracked by #703 — and seeds two cross-cutting deliverables that the remaining five sub-issues will reuse.

Closes #704. Stacked on top of #703's primitives lib (base: ct-noir-lib).

Register circuit (design doc §7.2)

# Constraint
R1 Y = sk · H
R2 vk = Poseidon2(δ_vk, sk, wrap)
R3 PVK = vk · H

Plus assert_on_curve_non_identity(Y) and assert_on_curve_non_identity(PVK) per design doc §7.1 point 4 — the verifier doesn't check curve membership, so skipping it accepts a key for which ECDH collapses.

Public inputs (frozen in circuits/PUBLIC_INPUTS.md): Y.x, Y.y, PVK.x, PVK.y, wrap. Private witness: sk.

Body is three lib calls and five assertions; all crypto delegates to stellar_confidential_lib.

Anti-poisoning tests (per #703)

Inline in register/src/main.nr:

  • matches_fixture — happy path against the canonical testdata/*.json vectors.
  • rejects_tampered_pvk — PVK.x perturbed by +1.
  • rejects_wrong_wrap — Y/PVK derived against wrap=0xbeef but proof supplies 0xcafe.
  • rejects_off_curve_y — Y = (1, 2).
  • rejects_identity_y — Y = (0, 0).
  • vk_intermediate_matches_lib — sanity check the fixture against the lib.

Cross-cutting (per #703)

  1. circuits/PUBLIC_INPUTS.md — frozen public-input ordering doc, seeded with Register's entry; sub-issues append theirs as they land. This is the integration contract with the verifier (Multi-VK UltraHonk verifier contract for confidential token wrapper #701), wrapper, and SDK.
  2. VK extraction pipeline — scripts/extract_vks.sh compiles each per-operation circuit and writes its UltraHonk VK to vks/<name>.vk using pinned bb 0.87.0. The committed vks/register.vk (1764 bytes) is byte-reproducible. noir.yml re-runs the extraction and diffs against the committed copies; drift fails CI, mirroring the existing constraints.baseline check.

Caveat to flag

The verifier (#701) hasn't pinned the VK ingestion format yet. bb write_vk emits raw bytes here; if #701 ends up wanting a different serialization (hex/JSON-wrapped), only extract_vks.sh and the committed artifact need updating — the script is the source of truth, not the artifact format.

Benchmarks (reference hardware: M-series laptop)

Metric Value
Constraints 33 ACIR opcodes
nargo execute ~0.06s
bb prove ~0.5s

Well under the "single-digit seconds" target the overview UX section calls out.

Test plan

  • nargo check clean on the workspace
  • nargo test — all 6 Register tests pass + existing lib/gadget suites stay green
  • nargo info shows circuit_register | main | 33 ACIR | 63 Brillig; matches constraints.baseline
  • ./scripts/extract_vks.sh reproduces vks/register.vk byte-identically
  • bb prove + bb verify round-trip succeeds against the committed VK
  • CI passes (nargo check/test, constraint-baseline diff, VK reproducibility diff)

Summary by CodeRabbit

  • New Features

    • Added register circuit for confidential token operations with on-curve point validation and scalar operations.
    • Enhanced CI pipeline with automated verification key artifact consistency checks and detailed drift reporting.
  • Documentation

    • Added public inputs specification documenting circuit encoding, Grumpkin point format, and non-identity constraints.
    • Added verification key artifact guide with regeneration instructions and pinned toolchain requirements.

Review Change Stack

brozorec added 13 commits May 20, 2026 09:39
`sort` is locale-sensitive: macOS (en_US) sorts case-insensitively, so
`gadget_*` sorts before `Package`; Ubuntu CI (C locale) sorts by byte,
so `P` (0x50) sorts before `g` (0x67). Same content, different order
between local regen and CI -> spurious diff failure.

Fix by pinning `LC_ALL=C` in both the CI step and the documented regen
command, and regenerate `constraints.baseline` under the same setting
so the file matches what CI computes.
The `typos` linter (default ruleset) flags `ba` as a likely misspelling
of `by` / `be`. The identifier `s_ba` in the ECDH symmetry test triggers
this, even though it's notation for "shared secret computed from b's
side". Rename `s_ab` / `s_ba` to `s_a_b` / `s_b_a` -- underscore-split
tokens dodge the substring match without losing the math symmetry.
- noir.yml: drop persisted GITHUB_TOKEN on the checkout step. The Noir
  job only reads source -- no push, no API calls -- so a compromised
  dependency in any later step can't exfiltrate the token.

- Architecture.md: add `text` language to the directory-tree fence so
  markdownlint and renderers treat it as plain text.

- gadgets/ecdh: document why the on-curve check is intentionally absent.
  Per design doc Section 7.1, point validation is the wrapper contract's
  responsibility, not the circuit's; adding the check in-gadget would
  inflate the constraint count and misrepresent production circuits'
  real cost.
Adds `assert_on_curve` (lenient, allows identity -- for commitments)
and `assert_on_curve_non_identity` (strict -- for keys, per design doc
Section 7.1 point 4) to the lib. The verifier itself doesn't check
curve membership, so a missed validation at the contract layer would
let the prover slip an off-curve point past every commitment / ECDH
constraint -- proof still verifies, resulting state is malformed.

In-circuit validation makes that soundness-bound. Cost is ~2 ACIR
opcodes per point check (less than 1% overhead on the heaviest
circuit), so there's no real tradeoff vs. the safety gain.

- `lib/src/lib.nr`: two new helpers + 5 unit tests (positive G/H,
  identity-lenient, off-curve rejection, identity rejection in the
  strict variant).
- `gadgets/ecdh`: now calls `assert_on_curve_non_identity` before
  `ecdh`, so the measured constraint count reflects what production
  circuits will pay (+2 ACIR opcodes vs. previous gadget).
- `gadgets/assert_on_curve`: new gadget measuring the check in
  isolation.
- `constraints.baseline`: regenerated.

Contract-side validation (per Section 7.1) stays as a defense-in-depth
layer and early-rejection ergonomic; this PR doesn't change that.
The lenient `assert_on_curve` accepted any (x, y, is_infinite=true)
because the curve-equation constraint gated off (x, y) when is_infinite
was set. A caller doing field-wise coordinate comparisons later could
be tricked into accepting attacker-chosen values that present as
"identity" but carry arbitrary x and y.

Close the gap by also constraining x == 0 and y == 0 when is_infinite,
matching the design doc's canonical identity encoding (Section 7.1
point 2). Cost: 2 mul gates; no gadget calls the lenient variant so
the baseline is unaffected.

Adds `on_curve_rejects_non_canonical_identity` test that exercises
the attack vector directly.

`assert_on_curve_non_identity` doesn't need this fix -- it already
rejects is_infinite=true upfront.
`nargo` writes empty `Prover.toml` templates per-package on first run
and a `target/` for compiled ACIR. Neither needs to be in the repo;
add a `.gitignore` at the circuits workspace root and remove the
seven templates that slipped in via the previous commit.
Implements design doc §7.2 constraints R1-R3 (spending key well-formedness,
wrapper-bound viewing key derivation, public viewing key consistency) plus
on-curve / non-identity validation on Y and PVK per §7.1 point 4. All crypto
delegates to the primitives lib; the circuit body is three lib calls and
five assertions. Six tests cover the happy path and the anti-poisoning
negatives (tampered PVK, wrong wrap, off-curve Y, identity Y) per #703's
soundness-critical regression coverage. 33 ACIR opcodes.

Closes #704.
Seeds circuits/PUBLIC_INPUTS.md with Register's frozen layout. This doc is
the integration contract between the circuits, the verifier (#701), the
wrapper, and the SDK — sub-issues append their tables as each per-circuit
PR lands. Cross-cutting deliverable per #703.
Adds scripts/extract_vks.sh (compiles each per-operation circuit and writes
its UltraHonk VK to vks/<name>.vk via pinned bb 0.87.0), commits the
register VK as the first artifact, and extends noir.yml to re-extract under
the pinned toolchain and diff against the committed copies. Mirrors the
constraints-baseline drift check: byte-identical or CI fails. Cross-cutting
deliverable per #703; remaining circuits append to the CIRCUITS array as
they land.
@coderabbitai

coderabbitai Bot commented May 20, 2026 •

Copy link
Copy Markdown
Contributor

Walkthrough

This PR implements the Register Noir circuit and its supporting infrastructure. It adds the circuit package with configuration and constraint logic enforcing key derivation rules, documents the v0.8 public-input specification, defines comprehensive tests covering happy and rejection paths, extracts verification key artifacts, and integrates VK drift detection into CI to prevent artifact divergence.

Changes

Register Circuit and VK Infrastructure

Layer / File(s) Summary
Workspace and package configuration
packages/tokens/src/confidential/circuits/Nargo.toml, packages/tokens/src/confidential/circuits/register/Nargo.toml
Register circuit is added to the workspace member list; the circuit package declares compiler version requirement and dependency on stellar_confidential_lib.
Public-input specification (v0.8 contract)
packages/tokens/src/confidential/circuits/PUBLIC_INPUTS.md
Frozen v0.8 integration contract defining how circuits encode public inputs as flat Field sequences, Grumpkin point encoding as ordered (x, y) pairs, non-identity constraints on keys, and per-circuit schema including register's public-input layout and named constraints (R1, R2, R3).
Circuit implementation and constraints
packages/tokens/src/confidential/circuits/register/src/main.nr, packages/tokens/src/confidential/circuits/constraints.baseline, packages/tokens/src/confidential/circuits/vks/register.vk.json
Circuit main function accepts sk privately and Y, PVK, wrap as public inputs; constructs embedded-curve points, asserts on-curve non-identity, derives Y via scalar_mul(sk, H), derives vk via vk_from_sk(sk, wrap), derives PVK via pvk_from_vk(vk), and asserts all derived coordinates match public inputs. Constraint baseline adds opcode counts for circuit functions; extracted VK artifact provided.
Circuit test suite
packages/tokens/src/confidential/circuits/register/src/tests.nr
Fixture constants pin canonical test vector values; happy-path test calls main with fixture values; negative tests reject tampered PVK coordinate, wrong wrap value, off-curve Y encoding, and identity point encoding; consistency test recomputes vk and pvk from fixtures and verifies they match pinned constants.
VK extraction and CI integration
.github/workflows/noir.yml, packages/tokens/src/confidential/circuits/scripts/extract_vks.sh, packages/tokens/src/confidential/circuits/vks/README.md
Workflow pins BB_VERSION, installs bbup, and adds bbup/tool version printout; extraction script compiles circuits, stages bb write_vk output in temp directory, and writes VK artifacts as deterministic JSON; VK README documents format, reproducibility rationale, and regeneration workflow; CI drift check re-extracts VKs, diffs against committed artifacts (excluding markdown), and fails job if mismatch found with detailed diff output.

Sequence Diagram

sequenceDiagram
  participant main as main()
  participant scalar_mul as scalar_mul
  participant vk_from_sk as vk_from_sk
  participant pvk_from_vk as pvk_from_vk
  main->>main: receive sk (private), Y.x/y, PVK.x/y, wrap (public)
  main->>main: construct EmbeddedCurvePoint for Y and PVK
  main->>main: assert_on_curve_non_identity(Y, PVK)
  main->>scalar_mul: compute Y_derived = scalar_mul(sk, H)
  scalar_mul-->>main: Y_derived
  main->>main: assert Y.x == Y_derived.x AND Y.y == Y_derived.y
  main->>vk_from_sk: compute vk = vk_from_sk(sk, wrap)
  vk_from_sk-->>main: vk
  main->>pvk_from_vk: compute pvk = pvk_from_vk(vk)
  pvk_from_vk-->>main: pvk
  main->>main: assert PVK.x == pvk.x AND PVK.y == pvk.y
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related issues

  • #699: Noir primitives library — The main changes directly use and depend on primitives introduced there (scalar_mul, vk_from_sk, pvk_from_vk, assert_on_curve_non_identity, and EmbeddedCurvePoint).
  • #703: Confidential circuit epic — The main changes implement core parts of that epic, adding the Register circuit, test coverage, public-input specification, VK artifacts, extraction automation, and CI drift detection.

Poem

🐰 A circuit springs to life, three constraints tight,
Deriving keys with scalar magic bright,
Tests reject each tainted bit with grace,
While VK artifacts hold their place.
The register stands guard, verified true! ✨

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title 'feat(confidential): register circuit' directly and accurately summarizes the main change—implementing the Register Noir circuit.
Linked Issues check ✅ Passed The PR comprehensively addresses all coding requirements from issue #704: implements constraints R1–R3, enforces on-curve/non-identity checks, includes happy-path and negative tests (tampered PVK, wrong wrap, off-curve/identity Y), documents frozen public-input ordering in PUBLIC_INPUTS.md, and extracts/commits reproducible VK artifacts.
Out of Scope Changes check ✅ Passed All changes are in scope: Register circuit implementation (circuits/register/), circuit workspace configuration (Nargo.toml additions), documentation (PUBLIC_INPUTS.md), VK extraction tooling (scripts/extract_vks.sh), CI workflow updates (noir.yml), and constraint baseline records. No unrelated changes detected.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Description check ✅ Passed PR description is comprehensive and well-structured, covering objectives, implementation details, tests, cross-cutting deliverables, and benchmarks.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch ct-noir-circuits

Comment @coderabbitai help to get the list of available commands and usage tips.

@codecov

codecov Bot commented May 20, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 96.31%. Comparing base (6e211ce) to head (893e4b1).

Additional details and impacted files
@@           Coverage Diff           @@
##             main     #715   +/-   ##
=======================================
  Coverage   96.31%   96.31%           
=======================================
  Files          60       60           
  Lines        6376     6376           
=======================================
  Hits         6141     6141           
  Misses        235      235           

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

bb's `bytes` output prefixes the field elements with header information
that differs between macOS and Linux, so committing the binary VK and
diffing in CI failed reproducibility. Switch to `--output_format fields`
(JSON array of hex-encoded Fr elements) -- byte-identical across platforms
and parseable by the verifier without round-tripping through bb's
deserializer. Renames the artifact to `register.vk.json`.
@brozorec brozorec changed the title feat(noir): register circuit (#704) feat(confidential): register circuit May 20, 2026
Base automatically changed from ct-noir-lib to main May 21, 2026 11:43
Resolves conflicts with #712 (the lib PR that landed first). Takes main's
reviewed version of the lib, gadgets, Architecture.md, testdata README,
noir.yml, and Nargo.toml; re-applies register/, vks/, scripts/, BB pin +
VK diff CI step on top.

Moves register's tests to register/src/tests.nr to mirror the lib's new
`mod tests;` convention. constraints.baseline regenerated; register's VK
is byte-identical (lib changes were docs + constant renames, no
computational behavior change).

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In @.github/workflows/noir.yml:
- Around line 54-59: Replace the live "install | bash" fetches with immutable
references: update the "Install bbup" step that currently curls
https://raw.githubusercontent.com/AztecProtocol/aztec-packages/master/.../install
to pin that URL to a specific commit SHA (or an immutable release asset) instead
of "master", and likewise update the noirup fetch (the curl to
https://raw.githubusercontent.com/noir-lang/noirup/main/.../install) to a
specific commit SHA or signed release; ensure both steps still pipe to bash (or
preferably download-verify-then-execute) but use the exact commit SHAs/releases
so the "Install bbup" and "noirup" installs are reproducible and supply-chain
safe.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 8a92addd-3151-4b12-8ff3-0ce1ef8fdfaf

📥 Commits

Reviewing files that changed from the base of the PR and between 6e211ce and ed3ca29.

📒 Files selected for processing (10)
  • .github/workflows/noir.yml
  • packages/tokens/src/confidential/circuits/Nargo.toml
  • packages/tokens/src/confidential/circuits/PUBLIC_INPUTS.md
  • packages/tokens/src/confidential/circuits/constraints.baseline
  • packages/tokens/src/confidential/circuits/register/Nargo.toml
  • packages/tokens/src/confidential/circuits/register/src/main.nr
  • packages/tokens/src/confidential/circuits/register/src/tests.nr
  • packages/tokens/src/confidential/circuits/scripts/extract_vks.sh
  • packages/tokens/src/confidential/circuits/vks/README.md
  • packages/tokens/src/confidential/circuits/vks/register.vk.json

Comment thread .github/workflows/noir.yml Resolved
brozorec added 3 commits May 21, 2026 14:18
The design doc adds two explicit non-zero scalar constraints to Register
and retires in-circuit `assert_on_curve_non_identity` on Y and PVK: both
points are bound to in-circuit `scalar_mul` outputs and are therefore
on-curve by construction. The only remaining gap is the identity, which
R4 and R5 close exactly.

Drops the separate PUBLIC_INPUTS.md doc in favor of an inline doc block
at the top of `main.nr` -- inline docs stay in lockstep with the code by
construction; a separate doc just creates drift risk.

VK regenerated; constraints baseline picks up a `directive_invert`
Brillig opcode from the inverse-based `!= 0` checks.
Both install scripts were fetched from moving branches (noirup/main,
aztec-packages/master) and piped to bash, so a silent upstream rewrite
would have been executed by every CI run. Pin each URL to a specific
commit and verify the script's SHA256 before exec; mismatch aborts.

Bump the URL and the hash together when intentionally tracking new
upstream.
@brozorec brozorec self-assigned this May 21, 2026
@brozorec
brozorec requested a review from ozgunozerk May 21, 2026 12:40
Comment thread .github/workflows/noir.yml Resolved
@brozorec
brozorec merged commit bfa222d into main May 21, 2026
9 checks passed
@brozorec
brozorec deleted the ct-noir-circuits branch May 21, 2026 16:51
@coderabbitai coderabbitai Bot mentioned this pull request May 27, 2026
4 tasks done
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.

Noir circuit: Register

2 participants