From 80e59d40b5d980bbf6af4b7ce242d0a2c42d02bd Mon Sep 17 00:00:00 2001 From: Shramee Srivastav <11048263+shramee@users.noreply.github.com> Date: Thu, 26 Nov 2026 04:56:09 +0530 Subject: [PATCH 01/17] docs(contracts): show how the four contracts call each other Adds a closing-row modifier to the architecture diagram grammar so the registrar can sit under the Reserves. Co-Authored-By: Claude Opus 5.5 --- src/content/docs/contracts/how-they-fit.mdx | 119 ++++++++++++++++++++ src/styles/diagram.css | 4 + 2 files changed, 123 insertions(+) create mode 100644 src/content/docs/contracts/how-they-fit.mdx diff --git a/src/content/docs/contracts/how-they-fit.mdx b/src/content/docs/contracts/how-they-fit.mdx new file mode 100644 index 0000000..d221594 --- /dev/null +++ b/src/content/docs/contracts/how-they-fit.mdx @@ -0,0 +1,119 @@ +--- +title: How the contracts fit +description: "How Chamber, Reserve, ManagerSigRegistrar and ChamberVerifier call each other, step by step for a deposit, a spend, a withdrawal, a registration and a removal." +sidebar: + order: 1 +--- + +import Figure from "../../../components/diagrams/Figure.astro"; +import Reserve from "../../../components/diagrams/Reserve.astro"; +import { Steps } from "@astrojs/starlight/components"; + +Four contracts carry the protocol. The Chamber keeps the record and verifies spends, each Reserve holds its own assets, the registrar admits members, and the generated verifier checks proofs. Every call between them follows a fixed direction, set out below. + +
+
+
+ ChamberVerifier + +

verifyProof, on every spend

+
+ +
+

Chamber ยท holds no assets

+
    +
  • Transactions trees
  • +
  • Nullifiers
  • +
  • zkState tree
  • +
  • Pending deposits
  • +
  • Reserve registry
  • +
+
+ +
+ + + +
+ +
+ ManagerSigRegistrar + +

addUser, on each Reserve that grants it USERS

+
+
+
+ +## Calls between contracts + +| Caller | Callee | Function | Guard on the callee | +| --- | --- | --- | --- | +| Chamber | ChamberVerifier | `verifyProof(proof, input)` | None. A view that reverts on a bad proof | +| Chamber | Reserve | `deposit(from, amount, asset)` | `onlyChamber` | +| Chamber | Reserve | `withdraw(to, amount, asset)` | `onlyChamber` | +| Chamber | Reserve | `new Reserve(...)` from `registerReserve` | Chamber owner only, on the Chamber | +| Reserve | Chamber | `setReserveConfig(reserveConfig)` | Registered Reserve, its own record | +| Reserve | Chamber | `setReserveStateRoot(stateRoot)` | Registered Reserve, its own record | +| Reserve | Chamber | `setReserveScreener(screener)` | Registered Reserve, its own record | +| Reserve | Chamber | `setReserveAssetMinDeposit(asset, minDeposit)` | Registered Reserve, its own record | +| ManagerSigRegistrar | Reserve | `addUser(leaf)` | `USERS` permission | +| ManagerSigRegistrar | Reserve | `registrations(leaf)`, `hasPermission(role, account)` | Views | +| ManagerSigRegistrar | A `USERS` holder with code | `isValidSignature(digest, signature)` | ERC-1271 view | +| Reserve | ERC-20 asset | `safeTransferFrom`, `safeTransfer`, `balanceOf` | The asset's own rules | + +The four Chamber setters act on `msg.sender`'s record, and the Chamber accepts them only from a Reserve it registered. A Reserve's role holders act on the Reserve, and the Reserve pushes the result. + +## Deposit + + + +1. The depositor approves the Reserve, not the Chamber, to transfer the asset. + +2. The depositor calls `Chamber.deposit(reserve, ownerCommitment, amount, asset)`, or the overload with a trailing `refundTo`. + +3. The Chamber checks that inflows are open, the Reserve is registered, the asset is listed there and the owner commitment is below the field order. + +4. The Chamber calls `Reserve.deposit(msg.sender, amount, asset)`. The Reserve pulls the asset and returns the balance it actually gained. + +5. The Chamber checks the received amount against 2^120 and the Reserve's minimum, and hashes the note over the received amount. + +6. Without a screener, the note is appended at once and `deposit` returns `(noteHash, 0)`. With one, the note is queued under a new deposit id and `deposit` returns `(noteHash, depositId)`. The screener later calls `approveDeposits` or `rejectDeposits`, and the depositor or `refundTo` can call `reclaimDeposit` while it is pending or rejected. + + + +## Spend and withdrawal + + + +1. The prover builds a proof off-chain against a transactions root and a zkState root. + +2. The note owner, or anyone when `auth_done = 1`, calls `Chamber.handleZkp(proof, input, auditorCommitments)`. + +3. The Chamber calls `ChamberVerifier.verifyProof`, then checks the published commitments, both roots, the authorisation and both nullifiers. + +4. The Chamber marks both nullifiers spent, files any commitments, and appends both new notes. A private payment ends here. No assets move. + +5. If `withdraw_amount` is not 0, the Chamber calls `Reserve(withdraw_reserve).withdraw(withdraw_to, withdraw_amount, withdraw_asset)` as its last step, and the Reserve pays the recipient. + + + +## Registration and removal + + + +1. A member and the key holder agree a `userKeyExchange` off-chain. The member's leaf is `H2(owner, userKeyExchange)`. + +2. A `USERS` holder signs an EIP-712 `RegisterUser` message for the leaf, with a deadline. + +3. Anyone calls `ManagerSigRegistrar.registerUser(reserve, leaf, deadline, signer, signature)`. The registrar checks the signature and the signer's permission and calls `Reserve.addUser(leaf)`. + +4. The Reserve appends the leaf and pushes its new users root with `Chamber.setReserveStateRoot`. The Chamber updates the Reserve's zkState leaf, and the zkState root changes. + +5. To remove the member, a `USERS` holder calls `Reserve.removeUser(index)` with the index from `UserRegistered`. The Reserve zeroes the leaf and pushes the new root the same way. + + + +A metadata change follows the same push: a `METADATA` holder calls `Reserve.updateAuditorKey`, and the Reserve calls `Chamber.setReserveConfig`. A `SCREENING` or `ASSETS` holder calls `Reserve.setScreener` or `Reserve.setAssetMinDeposit`, and the Reserve calls the matching Chamber setter. diff --git a/src/styles/diagram.css b/src/styles/diagram.css index dc2c930..5c2a1b1 100644 --- a/src/styles/diagram.css +++ b/src/styles/diagram.css @@ -227,6 +227,10 @@ flex: none; min-width: 2rem; } +/* A closing row under the Reserves (a contract that calls into them) */ +.mist-arch__proof--end { + margin: 1.25rem 0 0; +} .mist-arch__reserves { display: grid; gap: 1rem; From fef42f124a1803434ba4b1ba5c383057cf3f6b70 Mon Sep 17 00:00:00 2001 From: Shramee Srivastav <11048263+shramee@users.noreply.github.com> Date: Thu, 26 Nov 2026 04:56:09 +0530 Subject: [PATCH 02/17] docs(contracts): document Chamber deposits, screening and spends Co-Authored-By: Claude Opus 5.5 --- src/content/docs/contracts/chamber.mdx | 157 +++++++++++++++++++++++++ 1 file changed, 157 insertions(+) create mode 100644 src/content/docs/contracts/chamber.mdx diff --git a/src/content/docs/contracts/chamber.mdx b/src/content/docs/contracts/chamber.mdx new file mode 100644 index 0000000..7827247 --- /dev/null +++ b/src/content/docs/contracts/chamber.mdx @@ -0,0 +1,157 @@ +--- +title: Chamber +description: "Chamber.sol in detail: deposits with refundTo and returned ids, the asset list and minimum deposit, deposit screening and reclaim, handleZkp spends, and the Reserve registry." +sidebar: + order: 2 +--- + +The Chamber is the state engine: it takes deposits, verifies each spend and applies it, and keeps the record of notes. It holds no assets. Every asset sits in a Reserve, and the Chamber moves it only by calling that Reserve. + +## Constants + +| Constant | Value | Meaning | +| --- | --- | --- | +| `MAX_AMOUNT_SUPPORTED` | 2^120 | Every deposited amount and minimum deposit is below it | +| `ZK_STATE_ROOT_GRACE` | 10 minutes | How long a superseded zkState root stays accepted | +| `VERIFIER_DELAY` | 7 days | Delay between proposing and executing a verifier change | +| `OWNERSHIP_DELAY` | 7 days | Delay before a new owner can accept ownership | +| `SPEND_PAUSE_MAX` | 3 days | Length of one spend pause | +| `SPEND_PAUSE_COOLDOWN` | 7 days | Minimum gap between the end of one spend pause and the next | + +The immutable `chamberId` is `H2(block.chainid, address(this))`, computed in the constructor. The constructor takes `(owner_, verifier_)` and reverts with `invalid verifier` if the verifier address has no code. + +## Deposits + +```solidity +function deposit( + address reserve_, + uint256 ownerCommitment_, + uint256 amount, + address asset_ +) external returns (uint256 noteHash, uint256 depositId); + +function deposit( + address reserve_, + uint256 ownerCommitment_, + uint256 amount, + address asset_, + address refundTo +) external returns (uint256 noteHash, uint256 depositId); +``` + +A deposit takes no proof. The depositor approves the Reserve, not the Chamber, for `amount` of the asset. The Chamber then checks, in order: + +1. Inflows are not paused (`Chamber: inflows paused`). +2. The Reserve is registered (`reserve is not registered`). +3. The asset is listed at the Reserve: its minimum deposit is not 0 (`Chamber: asset not allowed`). +4. `ownerCommitment_` is below the field order (`Chamber: owner commitment not in field`). +5. `Reserve.deposit(msg.sender, amount, asset_)` pulls the asset and returns the balance the Reserve actually gained, which must be above 0 (`Reserve: zero deposit`). +6. The received amount is below 2^120 (`amount exceeds 2^120`) and at least the minimum (`Chamber: deposit below minimum`). +7. The note hash, `hashNote(chamberId, reserve_, ownerCommitment_, asset_, received)`, is not already in a transactions tree (`transaction already exists`). + +The note binds the received amount, so an asset that takes a fee on the incoming transfer yields a smaller note, not a shortfall. What happens next depends on the Reserve's screener: + +| Reserve | Result | Return value | +| --- | --- | --- | +| No screener | The note is appended to the transactions tree at once and recorded in `assets` | `(noteHash, 0)` | +| A screener | The deposit is queued under `depositId = ++depositCount`, and `DepositQueued` is emitted. The note stays out of the tree until the screener decides | `(noteHash, depositId)` | + +`refundTo` names who receives a reclaim. It cannot be zero (`Chamber: zero refundTo`). The four-argument form uses the depositor. A router that deposits for a user names the user, so a rejected deposit is never stranded behind a contract that cannot reclaim. `refundTo` matters only for a queued deposit. + +An owner commitment is single-use per Reserve, asset and amount: a second deposit with the same values gives a note hash that is already recorded, and reverts. Use a fresh blinding for every deposit. + +## Screening + +A Reserve's screener is an off-chain service, such as a KYT bot or an API relayer, that decides which deposits enter the transactions tree. Its decision is recorded with a `bytes32 evidence`, a commitment to the off-chain screening record, emitted per deposit. Screening is experimental and runs on entry only. + +```solidity +function approveDeposits(uint256[] calldata depositIds, bytes32 evidence) external; +function rejectDeposits(uint256[] calldata depositIds, bytes32 evidence) external; +function reclaimDeposit(uint256 depositId) external; +function depositRefundTo(uint256 depositId) public view returns (address); +``` + +| Function | Who | Effect | +| --- | --- | --- | +| `approveDeposits` | The screener of each deposit's Reserve | Appends each pending note and emits `DepositApproved`. A note already in a tree is rejected instead, with `DepositDuplicateRejected`. Ids that are not pending are skipped. Paused with inflows | +| `rejectDeposits` | The same | Marks each pending deposit rejected and emits `DepositRejected`. Rejection is final. Never paused | +| `reclaimDeposit` | The depositor or `refundTo` | Pays a pending or rejected deposit back to `depositRefundTo(id)`, which is `refundTo` if one was named and the depositor otherwise. Emits `DepositReclaimed`. Never paused | + +- **The screener is read at decision time.** A batch reverts with `Chamber: only reserve screener` if the caller is not the current screener of a pending deposit in it. A new screener therefore decides every deposit still waiting. With no screener set, waiting deposits can only be reclaimed. +- **The queue is keyed by deposit id,** not by note hash. A note hash is public in the deposit calldata, so a hash-keyed queue would let anyone block a deposit by queueing the same note first. Duplicate notes may queue side by side, and approval admits only the first. +- **A screener cannot take funds.** It can keep a note out of the tree, but the depositor can always reclaim. +- `pendingDeposits(id)` returns `(depositor, status, reserve, asset, amount, noteHash)`, with status `None`, `Pending` or `Rejected`. Approval and reclaim clear the record, so `None` also covers settled and unknown ids. + +## Spends + +```solidity +function handleZkp( + uint256[8] calldata proof, + uint256[14] calldata input, + uint256[] calldata auditorCommitments_ +) external returns (PublicParams memory params); +``` + +One function settles every spend: a private payment, a withdrawal or both. It runs these steps in order and reverts at the first that fails: + +| Step | Check or effect | Revert | +| --- | --- | --- | +| 1 | Spends are not paused | `Chamber: spends paused` | +| 2 | Inputs 7, 8 and 9 (`withdraw_asset`, `withdraw_reserve`, `withdraw_to`) are below 2^160 | `address input out of range` | +| 3 | `verifier.verifyProof(proof, input)` | `ProofInvalid` or `PublicInputNotInField` | +| 4 | `auditorCommitments_` has six elements below the field order that fold to input 13, or is empty and input 13 is 0 | `bad commitments preimage` | +| 5 | `transactions_root` is a root some transactions tree has had | `invalid merkle proof` | +| 6 | `state_root` is the current zkState root or a superseded one still in its grace window | `invalid state root` | +| 7 | With `auth_done = 0`, `owner == uint160(msg.sender)`. Any value other than 0 or 1 reverts | `only owner caller`, `invalid authDone` | +| 8 | Neither nullifier is spent. Both are marked spent | `transaction is spent` | +| 9 | If commitments were published: file them under element 0 and emit `PrivateTransfer` | `private tx key used` | +| 10 | Append `new_note_1`, then `new_note_2` | None in practice: a full tree rolls over | +| 11 | If `withdraw_amount` is not 0: `Reserve(withdraw_reserve).withdraw(withdraw_to, withdraw_amount, withdraw_asset)` | The asset's transfer revert | + +- **No assets move on a private payment.** The withdrawal call is last, after every state write. +- **Every spend appends two notes,** zero-amount outputs included, so spends look alike. +- **The Reserve is not looked up.** The circuit binds `withdraw_reserve` to the custody of the spent notes, and a note enters a tree only through a registered Reserve's deposit. +- **A filed spend** is stored as `privateTxCommitments(privateTxKey)`, which returns `(newNote1, newNote2, blockNumber, txIndex)`. `txIndex` is `newNote1`'s global index, and `newNote2` follows it. An identifier can be filed once, across every Reserve. +- **Calling `handleZkp`** with `auth_done = 1` is open to anyone, so a relayer can submit it. Nothing in core pays the relayer. A relayer fee is **Planned**. + +`deposit`, `handleZkp`, `approveDeposits`, `rejectDeposits` and `reclaimDeposit` share one reentrancy guard. + +## Reserve registry + +```solidity +function registerReserve( + address admin_, + uint256 keyHash_, + uint256 keyInputPoint_ +) external onlyOwner returns (address); +``` + +Only the Chamber owner registers a Reserve. `registerReserve` deploys a new `Reserve(admin_, address(this), keyHash_, keyInputPoint_)`, records it, and appends its zkState leaf `H3(reserve, H2(keyHash_, keyInputPoint_), 0)`, so the Reserve is spendable from its first block. It reverts with `invalid reserve admin` for a zero admin. After registration the Chamber owner holds no role on the Reserve: only its admin moves the admin role and grants permissions. + +A new Reserve has no listed asset and no screener, so nothing is depositable until its `ASSETS` holder lists an asset. If an asset is listed before a screener is set, deposits made in between enter unscreened. + +A registered Reserve updates its own record through four setters. Each acts on `msg.sender`'s record and reverts with `Chamber: not a registered reserve` for any other caller: + +| Setter | Called from | Effect | +| --- | --- | --- | +| `setReserveConfig(reserveConfig)` | `Reserve.updateAuditorKey` | Rewrites the Reserve's zkState leaf and makes the new zkState root current | +| `setReserveStateRoot(stateRoot)` | `Reserve.addUser`, `Reserve.removeUser` | The same, with the new users root. When the users root first becomes non-zero, every superseded zkState root stops being accepted | +| `setReserveScreener(screener)` | `Reserve.setScreener` | Sets or clears, with zero, the Reserve's screener | +| `setReserveAssetMinDeposit(asset, minDeposit)` | `Reserve.setAssetMinDeposit` | Lists the asset with a minimum below 2^120, or delists it with zero | + +`reserveConfigs(reserve)` returns `(leafIndex, reserveConfig, stateRoot)`, `reserveScreeners(reserve)` the screener and `reserveAssetMinDeposit(reserve, asset)` the minimum. [Trees and roots](/contracts/trees-and-roots/) covers the zkState root and its grace window. + +## Views + +| View | Returns | +| --- | --- | +| `hashNote(chamber_, reserve_, ownerCommitment_, asset_, amount_)` | A note hash, in the circuit's preimage order | +| `nullified(nullifier)`, `nullifiersSpent(nullifiers)` | Whether each nullifier is spent | +| `transactionsExist(notes)`, `noteIndexPlusOne(note)` | Whether each note was appended, and 1 plus a note's first global index (0 if never) | +| `assetsFromNote(noteHash)` | `(amount, addr)` of a deposited note. Spend outputs have no entry | +| `privateTxCommitments(privateTxKey)` | The record of a spend filed under that identifier | +| `pendingDeposits(id)`, `depositCount()`, `depositRefundTo(id)` | Queued deposits and their reclaim recipient | +| `isRegisteredReserve(reserve)` | Whether this Chamber registered the address | +| `spendsPaused()`, `spendPausedUntil()`, `inflowsPaused()`, `guardian()` | Pause state. See [Roles and security](/contracts/roles-and-security/) | + +The transactions-tree and zkState views are on [Trees and roots](/contracts/trees-and-roots/). From f78122c846d0b461a6a667193d99749d29771fdd Mon Sep 17 00:00:00 2001 From: Shramee Srivastav <11048263+shramee@users.noreply.github.com> Date: Thu, 26 Nov 2026 04:56:09 +0530 Subject: [PATCH 03/17] docs(contracts): document tx tree rollover and the zkState grace window Co-Authored-By: Claude Opus 5.5 --- .../docs/contracts/trees-and-roots.mdx | 85 +++++++++++++++++++ 1 file changed, 85 insertions(+) create mode 100644 src/content/docs/contracts/trees-and-roots.mdx diff --git a/src/content/docs/contracts/trees-and-roots.mdx b/src/content/docs/contracts/trees-and-roots.mdx new file mode 100644 index 0000000..6c02d77 --- /dev/null +++ b/src/content/docs/contracts/trees-and-roots.mdx @@ -0,0 +1,85 @@ +--- +title: Trees and roots +description: "The Chamber's transactions trees with rollover, how to fetch a note's index, tree leaves and proof, and the zkState tree with its 10-minute root grace window." +sidebar: + order: 3 +--- + +The Chamber keeps two kinds of Merkle tree: transactions trees of notes, and one zkState tree with a leaf per Reserve. Both are depth-10, 4-ary `Merkle4` trees whose nodes match the circuit's `HM4`, so a root the Chamber computes is a root a proof can use. + +## Transactions trees + +Every note, deposited or created by a spend, is appended to `txArray` and to the current transactions tree. A tree holds `txTreeCapacity()` leaves, which is 4^10 = 1,048,576. When it fills, the next tree opens. + +| Global index `i` | Tree | Position in the tree | +| --- | --- | --- | +| Any | `i / capacity` | `i % capacity` | + +- **Rollover.** The leaf at a global index divisible by the capacity opens a new tree. For every tree after the first, the Chamber emits `TxTreeOpened(treeId, firstIndex)`. +- **Roots stay valid.** Every root any transactions tree has had is recorded in `merkleRoots` and never retired. A proof built against an older root still verifies after the tree has grown, and a note in a full tree stays spendable. +- **One tree per spend.** A spend proves both inputs against one `transactions_root`, so two real notes in different trees cannot be spent together. +- **A spend can straddle trees.** If `new_note_1` fills the last slot of a tree, `new_note_2` opens the next one. +- **`NoteAppended(index, note, root)`** is emitted for every leaf, with `root` the new root of that leaf's tree. + +## Fetching a note's leaves and proof + +A prover needs a note's tree and a 30-element proof against a root of that tree. + +| View | Returns | +| --- | --- | +| `noteIndexPlusOne(note)` | 1 plus the note's first global index, 0 if it was never appended | +| `txTreeOf(index)` | `(treeId, localIndex)` for a global index | +| `merkleProof(index)` | The 30-element proof for the leaf at a global index, against the current root of its tree | +| `txTreeRoot(treeId)` | The current root of one tree | +| `merkleRoot()` | The current root of the latest tree | +| `currentTxTreeId()` | The id of the latest tree | +| `txCount()` | The number of leaves across every tree | +| `getTxArray(offset, limit)` | Up to `limit` leaves from global index `offset` | +| `txArray(i)` | One leaf | +| `merkleRoots(root)` | Whether a root is accepted | + +Two ways to build a proof: + +1. **Ask the Chamber.** Read the index with `noteIndexPlusOne(note) - 1`, then call `merkleProof(index)`. The proof matches `txTreeRoot(treeId)` at the block it was read. +2. **Rebuild the tree.** Tree `t` holds global indices `t * capacity` up to `(t + 1) * capacity - 1`. Read them with `getTxArray(t * capacity, limit)` in pages, or from `NoteAppended` events, and build the tree off-chain with the same `HM4` rule. A wallet that rebuilds keeps working as the tree grows, and reveals nothing about which note it wants. + +Asking the Chamber for one note's proof tells the node operator which note the caller is interested in. Rebuilding the tree from all its leaves does not. + +## The zkState tree + +The zkState tree has one leaf per Reserve: + +```text +leaf = H3(reserve, reserveConfig, usersRoot) +``` + +`reserveConfig` is `H2(keyHash, keyInputPoint)`, the Reserve's opaque metadata, and `usersRoot` is the root of its registered-users tree. `registerReserve` appends the leaf with `usersRoot = 0`, and the Reserve's pushes update it in place. Every update makes a new root current and emits `ZkStateRootUpdated(newRoot, previousRootExpiresAt)`. + +| View | Returns | +| --- | --- | +| `zkStateRoot()`, `currentZkStateRoot()` | The current root | +| `isValidZkStateRoot(root)` | Whether a spend may use the root now | +| `zkStateRootExpiresAt(root)` | When a superseded root stops being accepted | +| `zkStateHistoryCutoff()` | Superseded roots expiring at or before this are not accepted | +| `zkStateLeaf(index)` | One leaf | +| `reserveConfigs(reserve)` | `(leafIndex, reserveConfig, stateRoot)` for one Reserve | + +The Chamber has no zkState proof view. A prover reads the leaves with `zkStateLeaf`, at the `leafIndex` each `ReserveRegistered` event gives, or recomputes them from `ReserveRegistered` and `ReserveConfigUpdated`, and builds the proof off-chain. + +## The grace window + +The zkState root is shared by every Reserve, so a change at any Reserve replaces it. A proof built against the previous root would fail if only the current root counted. The Chamber therefore accepts a superseded root for `ZK_STATE_ROOT_GRACE`, 10 minutes: + +- **Accepted:** the current root, and any root superseded less than 10 minutes ago, unless a Reserve's messaging switched on at or after the moment it was superseded. +- **Rejected:** any other root. + +Each superseded root gets its own expiry, `block.timestamp + 10 minutes` at the moment it is replaced. When several changes land in a short time, every root replaced in the last 10 minutes stays valid. + +Two events cut the window short or depend on it: + +| Event | Effect | +| --- | --- | +| A Reserve's users root first becomes non-zero | The Chamber sets `zkStateHistoryCutoff` to now plus 10 minutes and emits `ZkStateHistoryRetired(reserve, cutoff)`. Every root superseded up to that moment stops being accepted at once, at every Reserve. Those roots hold a zero users root for that Reserve and would let a spend skip messaging | +| A user is removed | The new root lacks the user's leaf, but the previous root still holds it. The removal takes full effect when that root leaves the window, at most 10 minutes later | + +A prover that sees `ZkStateRootUpdated` after building a proof has 10 minutes to land it, or rebuilds against the new root. From 849c9bdcb53305d5f644179f101c84e923a3b428 Mon Sep 17 00:00:00 2001 From: Shramee Srivastav <11048263+shramee@users.noreply.github.com> Date: Thu, 26 Nov 2026 04:56:09 +0530 Subject: [PATCH 04/17] docs(contracts): document the Reserve admin, permissions and users tree Co-Authored-By: Claude Opus 5.5 --- src/content/docs/contracts/reserve.mdx | 119 +++++++++++++++++++++++++ 1 file changed, 119 insertions(+) create mode 100644 src/content/docs/contracts/reserve.mdx diff --git a/src/content/docs/contracts/reserve.mdx b/src/content/docs/contracts/reserve.mdx new file mode 100644 index 0000000..0cfc566 --- /dev/null +++ b/src/content/docs/contracts/reserve.mdx @@ -0,0 +1,119 @@ +--- +title: Reserve +description: "Reserve.sol in detail: the admin and its two-step handover, the four permission roles, the users tree with addUser and removeUser, the auditor key, the screener, the asset list and the Chamber-only deposit and withdraw." +sidebar: + order: 4 +--- + +A Reserve holds the assets of the notes in its custody, under one rule set. It moves assets only when its Chamber asks, and it keeps the registered-users tree that decides who can spend there. + +:::caution[Assets sent to a Reserve directly are lost] +A Reserve takes assets only through `Chamber.deposit`. Assets sent to a Reserve address by a plain transfer are unrecoverable: no function moves them out. +::: + +## Deposit and withdraw + +```solidity +function deposit(address from, uint256 amount, address asset) + external onlyChamber returns (uint256 received); + +function withdraw(address to, uint256 amount, address asset) + external onlyChamber; +``` + +Both revert with `Reserve: only chamber` for any caller other than the immutable `chamber`. `deposit` pulls `amount` from `from` with `safeTransferFrom` and returns the balance the Reserve actually gained, which must be above 0. `withdraw` sends `amount` with `safeTransfer`. The Chamber calls `withdraw` for a spend's withdrawal and for `reclaimDeposit`. + +A Reserve keeps no note accounting. Its own balance of each asset caps what it can pay out, and the circuit's conservation rule is what keeps payouts within the notes it custodies. + +## Admin + +```solidity +function transferAdmin(address newAdmin) external onlyAdmin; +function acceptAdmin() external; +``` + +The admin is named by the Chamber owner in `registerReserve` and cannot be zero. It holds every permission, grants and revokes them, and is the only account that moves the admin role. A live Reserve's admin should be a Safe. + +- **Two steps.** `transferAdmin(newAdmin)` nominates, and emits `AdminTransferStarted`. The nominee calls `acceptAdmin()`, and the Reserve emits `AdminTransferred`. Nominating zero cancels. There is no delay. +- **Grants survive a handover.** Explicit grants are not cleared. The new admin reviews the Reserve's `PermissionGranted` and `PermissionRevoked` events and revokes stale grants, including any held by the previous admin's address. Registrars and bots keep working through a handover. + +## Permissions + +```solidity +function grantPermission(bytes32 role, address account) external onlyAdmin; +function revokePermission(bytes32 role, address account) external onlyAdmin; +function hasPermission(bytes32 role, address account) public view returns (bool); +``` + +Each role is held by any number of accounts. `hasPermission` is true for the admin on every role, and for any account with an explicit grant. The admin's implicit permissions cannot be revoked. An unknown role reverts with `Reserve: unknown permission`. + +| Role | `bytes32` value | Functions | +| --- | --- | --- | +| `ASSETS` | `keccak256("ASSETS")` | `setAssetMinDeposit` | +| `USERS` | `keccak256("USERS")` | `addUser`, `removeUser`. The registrar checks it on every signer | +| `METADATA` | `keccak256("METADATA")` | `updateAuditorKey` | +| `SCREENING` | `keccak256("SCREENING")` | `setScreener` | + +The role hashes, computed with `cast keccak`: + +```text +ASSETS 0xbedf7b8facec7798b9b01bb658494261f59b3146617a1cf263926c9626250046 +USERS 0x80e5f4d2db32e62ee85b4d06c4355ea22b847c9659454b4b59d5724ae281b12c +METADATA 0x6afae84a1cc73825b77b2d8f14dc55a052ec6456df5cb0940e5de49ee56c0bd3 +SCREENING 0x87738fabb7e519ff1ec6a8c1dd5301bff177effd9d2630cd988fe8a333139530 +``` + +Every permissioned action is taken on the Reserve, which pushes the result to the Chamber. The Reserve makes no call whose target or data a role holder chooses: it holds custody and depositors' allowances, and such a call could move both. + +## Users tree + +```solidity +function addUser(uint256 leaf) external onlyPermission(USERS) returns (uint256 index); +function removeUser(uint256 index) external onlyPermission(USERS); +``` + +A member's leaf is `H2(owner, userKeyExchange)`, computed off-chain. Only the hash goes on-chain. + +- **`addUser`** requires a non-zero leaf below the field order that is not currently registered. It appends the leaf, increments `registrations(leaf)`, emits `UserRegistered(leaf, index, root)` and pushes the new root with `Chamber.setReserveStateRoot`. +- **`removeUser`** takes the index from `UserRegistered`. It zeroes the leaf, clears `isRegisteredUser(leaf)`, emits `UserRemoved(index, leaf, root)` and pushes the new root. It reverts with `Reserve: no user at index` for an index past the last leaf or an already-zero leaf, and with `Reserve: last user` if the users root would become zero. A zero users root would switch messaging off. +- **Re-registration.** A removed leaf can be added again, at a new index. `registrations(leaf)` counts every registration, and the registrar binds its signatures to that count, so no signature collected before the latest registration can be used again. +- **Lag.** A removal takes full effect within 10 minutes, when the last zkState root that holds the leaf leaves the Chamber's grace window. + +A user removed from a Reserve with members cannot spend or withdraw there while removed. An exit spend that lets any owner withdraw in public is **Planned**. + +| View | Returns | +| --- | --- | +| `registeredUsersRoot()` | The users root, zero while empty | +| `registeredUsersCount()` | Leaf slots used, removed users included | +| `registeredUserProof(index)` | The 30-element membership proof for the leaf at `index` | +| `isRegisteredUser(leaf)` | Whether the leaf is currently in the tree | +| `registrations(leaf)` | How many times the leaf has been registered | + +## Auditor key + +```solidity +function updateAuditorKey(uint256 keyHash_, uint256 keyInputPoint_) + external onlyPermission(METADATA); +function auditorKey() external view returns (uint256, uint256); +``` + +`keyHash` and `keyInputPoint` are two opaque field elements of Reserve metadata, for example a hash of the Reserve's policy or of its key-exchange public key. They have no cryptographic role and no on-chain curve check. Both must be below the field order (`Reserve: auditor key not in field`). `updateAuditorKey` stores them, emits `AuditorKeyUpdated(keyHash, keyInputPoint, reserveConfig)` and pushes `reserveConfig = H2(keyHash, keyInputPoint)` with `Chamber.setReserveConfig`, which replaces the zkState root. + +## Screener and asset list + +```solidity +function setScreener(address screener) external onlyPermission(SCREENING); +function setAssetMinDeposit(address asset, uint256 minDeposit) + external onlyPermission(ASSETS); +``` + +- **`setScreener`** sets the Reserve's deposit screener in the Chamber, or clears it with zero. The screener is read when each deposit is decided, so a new screener decides every deposit still waiting. +- **`setAssetMinDeposit`** lists an asset with a minimum deposit below 2^120, or delists it with zero. Nothing is depositable until an asset is listed. Delisting stops new deposits and leaves existing notes spendable. + +The minimum applies to the amount the Reserve received. A maximum transaction amount per asset is **Planned**. + +:::caution[Assets that must not be listed] +Withdrawals and reclaims send a fixed amount. An asset that charges a fee on outgoing transfers, rebases downward, blocklists the Reserve or can be upgraded into either, leaves notes that claim more than the Reserve can pay. Never list such an asset. +::: + +Set the screener before listing the first asset. Deposits made while an asset is listed and no screener is set enter unscreened. From cd5d84a96f01491440d7c10d3772cf17296bd406 Mon Sep 17 00:00:00 2001 From: Shramee Srivastav <11048263+shramee@users.noreply.github.com> Date: Thu, 26 Nov 2026 04:56:09 +0530 Subject: [PATCH 05/17] docs(contracts): document the ManagerSigRegistrar signature scheme Co-Authored-By: Claude Opus 5.5 --- src/content/docs/contracts/registrar.mdx | 130 +++++++++++++++++++++++ 1 file changed, 130 insertions(+) create mode 100644 src/content/docs/contracts/registrar.mdx diff --git a/src/content/docs/contracts/registrar.mdx b/src/content/docs/contracts/registrar.mdx new file mode 100644 index 0000000..0cc93da --- /dev/null +++ b/src/content/docs/contracts/registrar.mdx @@ -0,0 +1,130 @@ +--- +title: ManagerSigRegistrar +description: "The registrar that adds a member to a Reserve on an EIP-712 signature from a USERS holder: domain and struct, deadline, revocation, ERC-1271, and the registration-count binding." +sidebar: + order: 5 +--- + +`ManagerSigRegistrar` adds a member to a Reserve when an account holding that Reserve's `USERS` permission has signed the member's leaf. Anyone can submit the signed registration. One instance serves every Reserve that grants it `USERS`. + +## Setup + +A Reserve uses the registrar after two grants by its admin: + +1. `grantPermission(USERS, registrar)`, so the registrar can call `Reserve.addUser`. +2. `grantPermission(USERS, signer)` for each account whose signatures it should accept. The admin holds `USERS` implicitly and can sign without a grant. + +The signer names itself in each call, so several signers can serve one Reserve. + +## The signed message + +The registrar uses EIP-712: + +| Part | Value | +| --- | --- | +| Domain type | `EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)` | +| `name` | `MistReserveRegistrar` | +| `version` | `2` | +| `chainId` | `block.chainid`, read on every call, so a chain fork gets its own domain | +| `verifyingContract` | The registrar's address | +| Struct type | `RegisterUser(address reserve,uint256 leaf,uint256 registrations,uint256 deadline)` | +| `REGISTER_USER_TYPEHASH` | `0x6588b0d0279abb2e1a411801d4c8d83f482215f054953374f5b15da0702fce40` | + +- **`leaf`** is `H2(owner, userKeyExchange)`, computed off-chain. `userKeyExchange` stays off-chain and must be a full-entropy key-exchange output, or the leaf can be brute-forced. +- **`registrations`** is `Reserve(reserve).registrations(leaf)` when the call lands. Every registration of the leaf increments it. +- **`deadline`** is the last valid timestamp, inclusive. + +`registerUserDigest(reserve, leaf, deadline)` returns the digest to sign, with the current count filled in: `keccak256("\x19\x01" || domainSeparator() || structHash)`. + +A signer can produce the same digest with viem's `signTypedData`. This assumes `publicClient`, `walletClient`, `account`, `reserve`, `registrar`, `leaf` and `deadline` are already defined: + +```ts +import { parseAbi } from "viem"; + +const reserveAbi = parseAbi([ + "function registrations(uint256 leaf) view returns (uint256)", +]); + +// The count moves on every registration, so read it just before signing. +const registrations = await publicClient.readContract({ + address: reserve, + abi: reserveAbi, + functionName: "registrations", + args: [leaf], +}); + +const signature = await walletClient.signTypedData({ + account, + domain: { + name: "MistReserveRegistrar", + version: "2", + chainId: await publicClient.getChainId(), + verifyingContract: registrar, + }, + types: { + RegisterUser: [ + { name: "reserve", type: "address" }, + { name: "leaf", type: "uint256" }, + { name: "registrations", type: "uint256" }, + { name: "deadline", type: "uint256" }, + ], + }, + primaryType: "RegisterUser", + message: { reserve, leaf, registrations, deadline }, +}); +``` + +## Registering + +```solidity +function registerUser( + address reserve, + uint256 leaf, + uint256 deadline, + address signer, + bytes calldata signature +) external returns (uint256); +``` + +Anyone can call it. It checks, in order: + +| Check | Revert | +| --- | --- | +| `block.timestamp <= deadline` | `Registrar: signature expired` | +| The digest is not revoked | `Registrar: signature revoked` | +| `signer` holds `USERS` on `reserve` | `Registrar: missing users permission` | +| The signature is valid for `signer` | `Registrar: invalid signature` | + +It then calls `Reserve(reserve).addUser(leaf)` and returns the leaf. The Reserve emits `UserRegistered(leaf, index, root)` with the index that `removeUser` needs, and pushes its new users root to the Chamber, which changes the shared zkState root. + +Whoever holds a signature chooses when, before the deadline, the registration lands. + +## Signatures + +| Signer | Accepted | +| --- | --- | +| An account with no code | ECDSA only. A malformed signature reverts with its reason: `Registrar: bad signature length` (not 65 bytes), `Registrar: malleable signature` (`s` above half the curve order) or `Registrar: bad signature v` (not 27 or 28) | +| A contract | ECDSA first. If that does not recover the signer, ERC-1271: `isValidSignature(digest, signature)` must return `0x1626ba7e`. Only the first return word is read | + +ECDSA is implemented in the contract because the Paris EVM target lacks `mcopy`. The signature is ECDSA over secp256k1 and is not post-quantum. + +:::caution[ERC-1271 signers are trusted] +The registrar accepts whatever a `USERS` holder with code approves. Grant `USERS` only to contracts whose `isValidSignature` cannot approve arbitrary digests. +::: + +## Revoking + +```solidity +function revoke(address reserve, uint256 leaf, uint256 deadline) external; +``` + +A `USERS` holder on `reserve` can revoke one authorisation before it is used. `revoke` computes the digest for `(reserve, leaf, deadline)` at the leaf's current registration count, marks it in `revoked`, and emits `SignatureRevoked(reserve, leaf, deadline, digest)`. Revocation is permanent. Any `USERS` holder can revoke a digest, whoever signed it. + +## Registration-count binding + +The signed message carries `registrations`, and `addUser` increments it on every registration. Two things follow: + +- A signature registers the leaf at most once. After it lands, the count has moved and the digest no longer matches. +- A member who was removed cannot return with any signature collected before their latest registration. Re-registering needs a new signature. + +Removing a member is not done here: a `USERS` holder calls `Reserve.removeUser(index)` directly. See [Reserve](/contracts/reserve/#users-tree). From 8b77973863015729f2860b4f3c63006cd3f74c67 Mon Sep 17 00:00:00 2001 From: Shramee Srivastav <11048263+shramee@users.noreply.github.com> Date: Thu, 26 Nov 2026 04:56:09 +0530 Subject: [PATCH 06/17] docs(contracts): list privileged roles, timelocks and security notes Co-Authored-By: Claude Opus 5.5 --- .../docs/contracts/roles-and-security.mdx | 78 +++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 src/content/docs/contracts/roles-and-security.mdx diff --git a/src/content/docs/contracts/roles-and-security.mdx b/src/content/docs/contracts/roles-and-security.mdx new file mode 100644 index 0000000..c58f73c --- /dev/null +++ b/src/content/docs/contracts/roles-and-security.mdx @@ -0,0 +1,78 @@ +--- +title: Roles and security +description: "Every privileged role in the MIST contracts and what it can and cannot do: the Chamber owner and its timelocks, the guardian's pauses, the Reserve admin and permissions, the screener, and the trust each one carries." +sidebar: + order: 6 +--- + +Each power over the contracts belongs to a named role, and most are bounded by a delay, a cooldown or the depositor's right to reclaim. This page lists every role, the timelocks and pauses, and plainly what a role holder acting against users could do. + +## Roles and permissions + +| Role | Held by | Can | Cannot | +| --- | --- | --- | --- | +| Chamber owner | One address, set at deployment. A Safe for a live Chamber | `registerReserve`, `setGuardian`, `proposeVerifier`, `executeVerifierUpdate`, `cancelVerifierUpdate`, `transferOwnership`, `unpauseInflows`, `unpauseSpends` | Renounce ownership. Pause anything without being the guardian. Act on a Reserve after registering it | +| Guardian | One address, set by the owner. May be zero | `pauseInflows`, `unpauseInflows`, `pauseSpends`, `unpauseSpends` | Pause spends for more than 3 days, or again within 7 days of the last pause ending. Pause `reclaimDeposit` or `rejectDeposits` | +| Reserve admin | One address per Reserve, named in `registerReserve` | Every permission below. `grantPermission`, `revokePermission`, `transferAdmin` | Move a Reserve's assets | +| `ASSETS` | Any accounts the admin grants | `setAssetMinDeposit` | Move assets | +| `USERS` | Any accounts the admin grants, typically the registrar and its signers | `addUser`, `removeUser`, sign registrations, `revoke` a registration | Remove the last member | +| `METADATA` | Any accounts the admin grants | `updateAuditorKey` | Read members' spends: the auditor key has no cryptographic role | +| `SCREENING` | Any accounts the admin grants | `setScreener` | Decide deposits itself, unless it names itself screener | +| Deposit screener | One address per Reserve, set by `SCREENING` | `approveDeposits`, `rejectDeposits` for that Reserve's pending deposits | Move funds. Stop a reclaim | +| Depositor, `refundTo` | Whoever deposited, and the address they named | `reclaimDeposit` on a pending or rejected deposit | Reclaim an approved deposit | +| Note owner | A wallet or contract, for `auth_done = 0` notes | Submit the spend of its notes | Hand submission to anyone else: the Chamber requires the owner as caller | +| Relayer | Anyone | Submit an `auth_done = 1` spend | Change any public input of it | + +A key holder, whoever holds a Reserve's members' key exchanges, is not an on-chain role. It reads member spends off-chain: see [Circuits](/circuits/). + +## Verifier timelock + +The verifier decides which spends are valid, so replacing it is the most powerful action in the protocol. It is timelocked: + +1. The owner calls `proposeVerifier(verifier_)`. The address must have code. The Chamber stores it with its code hash and an eta 7 days out, and emits `VerifierUpdateProposed(verifier, codehash, eta)`. A new proposal replaces a pending one and restarts the delay. +2. Users and monitors compare the published code hash with a build of the expected verifier. +3. After the eta, the owner calls `executeVerifierUpdate()`. It reverts with `verifier timelock` before the eta and with `verifier code changed` if the code at the address no longer matches the hash. It emits `VerifierUpdated(verifier, codehash)`. + +`cancelVerifierUpdate()` drops a pending proposal and emits `VerifierUpdateCancelled`. The 7-day delay is longer than the 3-day maximum spend pause, so a guardian pause cannot cover the whole window of a queued change: users can always exit first. + +## Ownership timelock + +The Chamber uses OpenZeppelin's `Ownable2Step` with a delay: + +- `transferOwnership(newOwner)` sets the pending owner and an eta 7 days out, and emits `OwnershipTransferQueued(newOwner, eta)`. Passing zero cancels, with eta 0. +- The pending owner calls `acceptOwnership()` after the eta, or it reverts with `ownership timelock`. +- `renounceOwnership()` always reverts with `renounce disabled`. + +## Guardian pauses + +| Pause | Stops | Length | Ended by | +| --- | --- | --- | --- | +| `pauseInflows` | `deposit`, `approveDeposits` | Until unpaused | `unpauseInflows`, by the guardian or the owner | +| `pauseSpends` | `handleZkp`: private payments and withdrawals | 3 days | Expiry, or `unpauseSpends` by the guardian or the owner | + +- **Cooldown.** A new spend pause can start only 7 days after the previous one ended. Ending a pause early starts the cooldown from that moment. Rotating the guardian does not reset it. +- **Never paused.** `reclaimDeposit` and `rejectDeposits`, so a pause never traps a queued deposit. + +## Security notes + +These are the trust assumptions, stated plainly. + +| Holder | Worst case if acting against users | +| --- | --- | +| Chamber owner | Proposes a verifier that accepts any proof. After 7 days it could authorise the withdrawal of every asset in every Reserve, because no on-chain ledger checks withdrawals against notes. The defence is the published code hash and the 7-day window to exit. The owner can also make itself guardian with `setGuardian` at once | +| Guardian | Pauses deposits with no time limit, until the owner unpauses or replaces it. Halts all spends, withdrawals included, for up to 3 days, then must wait 7 days after that pause ends before the next | +| Whoever ran the trusted setup | Could forge a proof for any public inputs, including a withdrawal, if they kept the setup's secret randomness. The keys come from a single-party setup. See [Circuits](/circuits/) | +| Reserve admin or `USERS` | Decides who can spend at a Reserve with members. Removing a member, or never registering a holder, leaves that holder's notes unspendable there. An exit spend for that case is **Planned** | +| `METADATA` | Each update replaces the shared zkState root. Proofs against the old root stay valid for 10 minutes | +| `ASSETS` | Listing an asset that charges outgoing fees, rebases downward, blocklists the Reserve or is upgradeable can leave notes that claim more than the Reserve holds | +| Screener | Keeps deposits out of the tree. Cannot take them: the depositor reclaims | + +Further limits that hold for every user: + +- **No solvency ledger.** The Chamber cannot check a withdrawal against private notes. Each Reserve's own balance caps what it pays, and the circuit's conservation rule keeps payouts within the notes. +- **One zkState root for every Reserve.** A busy Reserve changes it often. Each superseded root stays valid for 10 minutes. When any Reserve gets its first member, every superseded root is retired at once, across all Reserves. +- **Assets sent to a Reserve directly are lost.** +- **Identifiers are first come, first served** across every Reserve. +- **Compliance is experimental.** Screening is off-chain and on entry only. + +Review findings and their status are tracked in the specification's implementation status file. These pages claim no external audit. From 2170f146c614cedc0433898269dcf4306be5db82 Mon Sep 17 00:00:00 2001 From: Shramee Srivastav <11048263+shramee@users.noreply.github.com> Date: Thu, 26 Nov 2026 04:56:09 +0530 Subject: [PATCH 07/17] docs(contracts): add the events and revert reasons reference Co-Authored-By: Claude Opus 5.5 --- .../docs/contracts/events-and-errors.mdx | 157 ++++++++++++++++++ 1 file changed, 157 insertions(+) create mode 100644 src/content/docs/contracts/events-and-errors.mdx diff --git a/src/content/docs/contracts/events-and-errors.mdx b/src/content/docs/contracts/events-and-errors.mdx new file mode 100644 index 0000000..4407b84 --- /dev/null +++ b/src/content/docs/contracts/events-and-errors.mdx @@ -0,0 +1,157 @@ +--- +title: Events and errors +description: "Every event the Chamber, Reserve and ManagerSigRegistrar emit, with parameters and when each fires, and the revert reasons an integrator meets." +sidebar: + order: 7 +--- + +The contracts emit an event for every note appended, every deposit decision, every registry change and every governance action, so an indexer can rebuild the record from logs. The reverts are plain strings except in the generated verifier and inherited OpenZeppelin code, which use custom errors. + +## Chamber events + +### Notes and spends + +| Event | Emitted when | +| --- | --- | +| `NoteAppended(uint256 indexed index, uint256 indexed note, uint256 root)` | Any note joins a transactions tree. `index` is global, `root` is the new root of that note's tree | +| `TxTreeOpened(uint256 indexed treeId, uint256 firstIndex)` | A full tree rolls over and tree `treeId` takes its first leaf. Not emitted for tree 0 | +| `PrivateTransfer(uint256 indexed privateTxKey, uint256 newNote1, uint256 newNote2, uint256[] commitments)` | A spend publishes commitments. `commitments` is the full six-element preimage | + +A spend with no commitments emits only its two `NoteAppended` events. Nullifiers are not emitted. They are in `handleZkp`'s calldata and readable with `nullified`. + +### Deposits + +| Event | Emitted when | +| --- | --- | +| `DepositQueued(uint256 indexed depositId, uint256 noteHash, address indexed reserve, address indexed depositor, address asset, uint256 amount)` | A deposit at a screened Reserve is queued. `amount` is what the Reserve received | +| `DepositApproved(uint256 indexed depositId, uint256 indexed noteHash, bytes32 evidence)` | The screener admits a queued deposit. A `NoteAppended` follows | +| `DepositRejected(uint256 indexed depositId, bytes32 evidence)` | The screener refuses a queued deposit | +| `DepositDuplicateRejected(uint256 indexed depositId, uint256 indexed noteHash)` | Approval finds the note already in a tree and rejects the deposit instead | +| `DepositReclaimed(uint256 indexed depositId, address indexed depositor, address to)` | A pending or rejected deposit is paid back to `to` | + +An unscreened deposit emits only `NoteAppended`. + +### Reserves and zkState + +| Event | Emitted when | +| --- | --- | +| `ReserveRegistered(address indexed reserve, address indexed admin, uint256 leafIndex, uint256 reserveConfig, uint256 stateRoot)` | The owner registers a Reserve. `stateRoot` is 0 | +| `ReserveConfigUpdated(address indexed reserve, uint256 reserveConfig, uint256 stateRoot)` | A Reserve's zkState leaf changes, from a config update or a users-root update | +| `ZkStateRootUpdated(uint256 indexed newRoot, uint256 previousRootExpiresAt)` | The zkState root changes. `previousRootExpiresAt` is when the old root stops being accepted, 0 if there was none | +| `ZkStateHistoryRetired(address indexed reserve, uint256 cutoff)` | A Reserve's users root first becomes non-zero, and every superseded root is retired | +| `ReserveScreenerSet(address indexed reserve, address indexed screener)` | A Reserve sets or clears its screener | +| `ReserveAssetMinDepositSet(address indexed reserve, address indexed asset, uint256 minDeposit)` | A Reserve lists an asset, changes its minimum, or delists it with 0 | + +### Governance + +| Event | Emitted when | +| --- | --- | +| `VerifierUpdateProposed(address indexed verifier, bytes32 codehash, uint256 eta)` | The owner proposes a verifier | +| `VerifierUpdateCancelled(address indexed verifier)` | The owner drops a pending proposal | +| `VerifierUpdated(address indexed verifier, bytes32 codehash)` | A proposed verifier goes live | +| `OwnershipTransferQueued(address indexed newOwner, uint256 eta)` | The owner queues a transfer. Zero `newOwner` and `eta` mean it was cancelled | +| `OwnershipTransferStarted(address indexed previousOwner, address indexed newOwner)` | The same moment, from `Ownable2Step` | +| `OwnershipTransferred(address indexed previousOwner, address indexed newOwner)` | A transfer completes, from `Ownable` | +| `GuardianSet(address indexed guardian)` | The owner sets the guardian | +| `InflowsPaused(address indexed by)`, `InflowsUnpaused(address indexed by)` | Inflows are paused or resumed | +| `SpendsPaused(uint256 until)`, `SpendsUnpaused(address indexed by)` | Spends are paused until `until`, or resumed early | + +## Reserve events + +| Event | Emitted when | +| --- | --- | +| `UserRegistered(uint256 indexed leaf, uint256 index, uint256 root)` | `addUser` appends a member. `index` is what `removeUser` takes | +| `UserRemoved(uint256 indexed index, uint256 indexed leaf, uint256 root)` | `removeUser` zeroes a member's leaf | +| `AuditorKeyUpdated(uint256 keyHash, uint256 keyInputPoint, uint256 reserveConfig)` | `updateAuditorKey` rotates the metadata | +| `PermissionGranted(bytes32 indexed role, address indexed account)` | The admin grants a role | +| `PermissionRevoked(bytes32 indexed role, address indexed account)` | The admin revokes a role | +| `AdminTransferStarted(address indexed admin, address indexed pendingAdmin)` | The admin nominates a successor, or cancels with zero | +| `AdminTransferred(address indexed previousAdmin, address indexed newAdmin)` | The nominee accepts | + +## ManagerSigRegistrar events + +| Event | Emitted when | +| --- | --- | +| `SignatureRevoked(address indexed reserve, uint256 indexed leaf, uint256 deadline, bytes32 digest)` | A `USERS` holder revokes an authorisation | + +A successful `registerUser` emits nothing of its own. The Reserve's `UserRegistered` records it. + +## What to monitor + +Watch `VerifierUpdateProposed` and compare its code hash with the expected build. Watch `SpendsPaused`, `InflowsPaused`, `OwnershipTransferQueued` and `TxTreeOpened`, `ZkStateRootUpdated` for root churn, and each Reserve's `AdminTransferStarted` and `PermissionGranted`. Compare each Reserve's balances with the notes it custodies. + +## Revert reasons + +### Chamber + +| Revert | Cause | +| --- | --- | +| `Chamber: inflows paused` | `deposit` or `approveDeposits` while inflows are paused | +| `reserve is not registered` | Deposit to an address this Chamber did not register | +| `Chamber: asset not allowed` | The asset is not listed at the Reserve | +| `Chamber: owner commitment not in field` | The owner commitment is at or above the field order | +| `amount exceeds 2^120` | The received amount, or a minimum deposit, is too large | +| `Chamber: deposit below minimum` | The received amount is below the Reserve's minimum | +| `transaction already exists` | The deposit's note hash is already in a tree | +| `Chamber: zero refundTo` | The `refundTo` overload with a zero address | +| `Chamber: only reserve screener` | A screening batch holds a pending deposit the caller does not screen | +| `Chamber: no queued deposit` | Reclaim of an approved, reclaimed or unknown deposit | +| `Chamber: only depositor or refundTo` | Reclaim by anyone else | +| `Chamber: spends paused` | `handleZkp` during a spend pause | +| `address input out of range` | A withdrawal address input is at or above 2^160 | +| `bad commitments preimage` | The published commitments are not six in-field elements folding to the public input, or are present when it is 0 | +| `invalid merkle proof` | `transactions_root` is not a root any transactions tree has had | +| `invalid state root` | `state_root` is neither current nor in its grace window | +| `only owner caller` | `auth_done = 0` and the caller is not `owner` | +| `invalid authDone` | `auth_done` is neither 0 nor 1 | +| `transaction is spent` | A nullifier is already spent | +| `private tx key used` | The identifier was filed by an earlier spend | +| `Chamber: not a registered reserve` | A Reserve setter called by any other address | +| `invalid reserve admin` | `registerReserve` with a zero admin | +| `invalid verifier` | A verifier address with no code, in the constructor or `proposeVerifier` | +| `no pending verifier` | Execute or cancel with nothing proposed | +| `verifier timelock` | Execute before the eta | +| `verifier code changed` | The code at the proposed address no longer matches its hash | +| `ownership timelock` | Accept before the eta | +| `renounce disabled` | Any call to `renounceOwnership` | +| `Chamber: only guardian`, `Chamber: only guardian or owner` | A pause function from another caller | +| `Chamber: spend pause cooldown` | A spend pause within 7 days of the last one ending | +| `Chamber: spends not paused` | `unpauseSpends` when no pause is running | +| `merkle leaf index out of range` | `txTreeOf` or `merkleProof` past the last leaf | + +### Reserve + +| Revert | Cause | +| --- | --- | +| `Reserve: only chamber` | `deposit` or `withdraw` from any address but the Chamber | +| `Reserve: zero deposit` | The Reserve's balance did not grow | +| `Reserve: only admin` | An admin function from another caller | +| `Reserve: only pending admin` | `acceptAdmin` from anyone but the nominee | +| `Reserve: missing permission` | A permissioned function without the role | +| `Reserve: unknown permission` | Grant or revoke of a role that is not one of the four | +| `Reserve: zero user leaf`, `Reserve: user leaf not in field` | `addUser` with a zero or out-of-field leaf | +| `Reserve: user already registered` | `addUser` with a leaf that is in the tree | +| `Reserve: no user at index` | `removeUser` past the last leaf or on a zeroed leaf | +| `Reserve: last user` | `removeUser` that would empty the users tree | +| `Reserve: auditor key not in field` | A key element at or above the field order | +| `Reserve: zero admin`, `Reserve: zero chamber` | Constructor with a zero address | + +### ManagerSigRegistrar + +| Revert | Cause | +| --- | --- | +| `Registrar: signature expired` | Called after the deadline | +| `Registrar: signature revoked` | The digest was revoked | +| `Registrar: missing users permission` | The signer, or the caller of `revoke`, lacks `USERS` on the Reserve | +| `Registrar: invalid signature` | The signature does not verify for the signer | +| `Registrar: bad signature length`, `Registrar: malleable signature`, `Registrar: bad signature v` | A malformed ECDSA signature from a signer with no code | + +### Custom errors + +| Error | From | +| --- | --- | +| `ProofInvalid()` | `ChamberVerifier`: the pairing check failed or a point is not on its curve | +| `PublicInputNotInField()` | `ChamberVerifier`: a public input is at or above the field order | +| `OwnableUnauthorizedAccount(address)` | `Ownable`: an owner function from another caller, or `acceptOwnership` from anyone but the pending owner | +| `ReentrancyGuardReentrantCall()` | `ReentrancyGuard`: a reentrant call into a guarded Chamber function | +| `SafeERC20FailedOperation(address)` | `SafeERC20`: an asset transfer returned false | From 35f471c1b531c02408f27df0258882ca1ffce018 Mon Sep 17 00:00:00 2001 From: Shramee Srivastav <11048263+shramee@users.noreply.github.com> Date: Thu, 26 Nov 2026 04:56:09 +0530 Subject: [PATCH 08/17] docs(contracts): document the verifier and Deploy.s.sol Co-Authored-By: Claude Opus 5.5 --- .../contracts/verifier-and-deployment.mdx | 87 +++++++++++++++++++ 1 file changed, 87 insertions(+) create mode 100644 src/content/docs/contracts/verifier-and-deployment.mdx diff --git a/src/content/docs/contracts/verifier-and-deployment.mdx b/src/content/docs/contracts/verifier-and-deployment.mdx new file mode 100644 index 0000000..551d6d6 --- /dev/null +++ b/src/content/docs/contracts/verifier-and-deployment.mdx @@ -0,0 +1,87 @@ +--- +title: Verifier and deployment +description: "ChamberVerifier, the generated Groth16 verifier and how it is replaced, and what Deploy.s.sol deploys, checks and configures, with the steps that follow a deployment." +sidebar: + order: 8 +--- + +`ChamberVerifier` is generated from the circuit's proving key and never edited by hand. `script/Deploy.s.sol` deploys it with the Chamber and the registrar, and the rest of a deployment is configuration by the owner and each Reserve's admin. + +## ChamberVerifier + +The file header reads: generated, do not edit by hand, exported from the gnark proving key for `PrimaryTransactionCircuit`. It is gnark's Groth16 verifier template for BN254, with the verifying key as constants: the alpha, beta, gamma and delta points, a constant point and one point per public input, `PUB_0` to `PUB_13`. + +```solidity +function verifyProof(bytes calldata proof, uint256[14] calldata input) public view; +function verifyCompressedProof(uint256[4] calldata compressedProof, uint256[14] calldata input) public view; +function compressProof(bytes calldata proof) public view returns (uint256[4] memory compressed); +``` + +| Function | Takes | Reverts | +| --- | --- | --- | +| `verifyProof` | An uncompressed 256-byte proof | `invalid proof length`, `PublicInputNotInField()`, `ProofInvalid()` | +| `verifyCompressedProof` | A compressed proof of four words | `PublicInputNotInField()`, `ProofInvalid()` | +| `compressProof` | An uncompressed 256-byte proof | `invalid proof length`, or `ProofInvalid()` for a point off its curve | + +`Chamber.handleZkp` uses `verifyProof` only, with its eight proof words packed into 256 bytes. The verifier uses the EVM's precompiles for modular exponentiation, point addition, scalar multiplication and the pairing check. It rejects any public input at or above the field order: the scalar-multiplication precompile reduces its scalar, so without the check `x` and `x + r` would verify alike. + +The keys behind the verifier come from a single-party setup. [Circuits](/circuits/) states what that means. + +### Keeping it in sync + +- Core's `TestVerifierPublicInputCountMatchesCircuit` requires the circuit, the verifier and `Chamber.PublicParams` to agree on 14 public inputs. +- The Foundry suite replays `testdata/e2e_fixture.json`, a real proof made offline from the keys, against the real verifier. Count checks alone cannot show that the verifier's constants match the proving key. A real proof does. + +### Replacing it + +1. From `core/contracts`, run `../../core-deploy/scripts/build.sh`. It writes `src/ChamberVerifier.sol`, and a new fixture when the keys changed. Review the diff and commit it with the new keys. +2. Deploy the new verifier. +3. The Chamber owner calls `proposeVerifier(newVerifier)` and publishes the code hash from `VerifierUpdateProposed`. +4. After 7 days the owner calls `executeVerifierUpdate()`, which checks the code hash again. + +Regenerating the file changes nothing on-chain. Only the timelocked call does. See [Roles and security](/contracts/roles-and-security/#verifier-timelock). + +## Deploy.s.sol + +The script reads its settings from the environment: + +| Variable | Default | Meaning | +| --- | --- | --- | +| `PRIVATE_KEY` | Required | The deployer's key. The deployer is the Chamber's first owner | +| `CHAMBER_OWNER` | Zero | The final owner, a Safe. Required on chain ID 1 | +| `GUARDIAN` | Zero | The guardian, set if not zero | +| `DEV_FIXTURES` | `false` | Deploy a development Reserve, a mock asset and one registered user | +| `USER_KEY_EXCHANGE` | 0 | The development user's key exchange. Required with `DEV_FIXTURES` | + +On chain ID 1, `validate` refuses development fixtures and the fixture key exchange `0x6b6579`, and requires `CHAMBER_OWNER` to be set, to differ from the deployer and to have code. + +The script then broadcasts, in order: + +1. `new ChamberVerifier()`. +2. `new Chamber(deployer, verifier)`. +3. `new ManagerSigRegistrar()`. +4. `chamber.setGuardian(GUARDIAN)`, if set. +5. With `DEV_FIXTURES`: a mock ERC-20, `registerReserve(deployer, 789, 987)`, `setAssetMinDeposit(asset, 1)`, a `USERS` grant to the registrar, and a registration of `H2(deployer, USER_KEY_EXCHANGE)` signed by the deployer with a deadline one hour out. +6. `chamber.transferOwnership(CHAMBER_OWNER)`, if set and not the deployer. The Safe calls `acceptOwnership()` after the 7-day delay. + +It writes the address book to `deployments/.json`, with the Chamber, verifier, registrar, development Reserve and mock asset addresses. These pages list no deployed addresses. + +`Poseidon2` in `lib/Poseidon.sol` exposes `public` functions, so it is deployed as its own library contract and linked into the contracts that hash. + +:::caution[Development fixtures are not for real funds] +The development Reserve has a fixed auditor key (789, 987), a mock asset, no screener, and the deployer as admin. Its registered user's key exchange is whatever `USER_KEY_EXCHANGE` holds. The fixture value `0x6b6579` is public, so anyone can decrypt that user's messaging. +::: + +## After deployment + +1. **Ownership.** After 7 days the Safe named in `CHAMBER_OWNER` calls `acceptOwnership()`. +2. **Guardian.** If none was set, the owner calls `setGuardian`. +3. **Reserves.** The owner calls `registerReserve(admin, keyHash, keyInputPoint)` for each Reserve, naming a Safe as admin. +4. **Screener first.** The Reserve admin, or a `SCREENING` holder, calls `setScreener` before any asset is listed. +5. **Registration.** The admin grants `USERS` to the registrar and to each signer. +6. **Assets.** An `ASSETS` holder lists each asset with `setAssetMinDeposit`. Never list an asset that charges outgoing fees, rebases, blocklists or can be upgraded. +7. **Monitoring.** Watch the events listed on [Events and errors](/contracts/events-and-errors/#what-to-monitor). + +## Toolchain + +`foundry.toml` pins solc 0.8.35, the Paris EVM target and 200 optimizer runs. The deployed sources pin `pragma solidity 0.8.35`. The Paris target has no `PUSH0`. From 0d0cb80e0ca96990ad5e35a030bf2adea322161a Mon Sep 17 00:00:00 2001 From: Shramee Srivastav <11048263+shramee@users.noreply.github.com> Date: Thu, 26 Nov 2026 04:56:09 +0530 Subject: [PATCH 09/17] docs(contracts): link the detailed pages from the overview Co-Authored-By: Claude Opus 5.5 --- src/content/docs/contracts/index.mdx | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/src/content/docs/contracts/index.mdx b/src/content/docs/contracts/index.mdx index e52171e..236dbf4 100644 --- a/src/content/docs/contracts/index.mdx +++ b/src/content/docs/contracts/index.mdx @@ -6,6 +6,8 @@ sidebar: order: 0 --- +import RuledIndex from "../../../components/RuledIndex.astro"; + MIST's contracts are written in Solidity and built with Foundry. Three kinds of contract carry the protocol: the Chamber, Reserves and middlewares. Two more support them: the verifier and the registrar. | Contract | Role | Entry points | @@ -44,6 +46,21 @@ The Chamber emits `NoteAppended` for every note it adds, `TxTreeOpened` when a t The contracts are pinned to solc 0.8.35, the Paris EVM and 200 optimizer runs. `ChamberVerifier.sol` is generated by gnark from the circuit and is never edited by hand. +## Detailed pages + + + ## Source The contracts are in `core/contracts/src`. The [specification](https://github.com/mistcash/mist/blob/main/spec/02_smart_contract.md) defines their state, actions and trusted roles. From 359d2a3f9738e42281aaadeeb96cf3f9241cad08 Mon Sep 17 00:00:00 2001 From: Shramee Srivastav <11048263+shramee@users.noreply.github.com> Date: Thu, 26 Nov 2026 04:57:28 +0530 Subject: [PATCH 10/17] style(docs): stack wide-chip diagram rows at phone width Co-Authored-By: Claude Opus 5.5 --- src/content/docs/contracts/how-they-fit.mdx | 4 ++-- src/styles/diagram.css | 11 +++++++++++ 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/src/content/docs/contracts/how-they-fit.mdx b/src/content/docs/contracts/how-they-fit.mdx index d221594..63299e7 100644 --- a/src/content/docs/contracts/how-they-fit.mdx +++ b/src/content/docs/contracts/how-they-fit.mdx @@ -16,7 +16,7 @@ Four contracts carry the protocol. The Chamber keeps the record and verifies spe caption="Who calls whom. The Chamber holds no assets. A Reserve's only outbound calls are asset transfers the Chamber asks for and fixed pushes to its own Chamber record." >
-
+
ChamberVerifier

verifyProof, on every spend

@@ -39,7 +39,7 @@ Four contracts carry the protocol. The Chamber keeps the record and verifies spe
-
+
ManagerSigRegistrar

addUser, on each Reserve that grants it USERS

diff --git a/src/styles/diagram.css b/src/styles/diagram.css index 5c2a1b1..a15ebf2 100644 --- a/src/styles/diagram.css +++ b/src/styles/diagram.css @@ -231,6 +231,17 @@ .mist-arch__proof--end { margin: 1.25rem 0 0; } +/* A row whose first item is a wide chip: chip over label at phone width */ +@media (max-width: 39.99rem) { + .mist-arch__proof--stack { + flex-direction: column; + align-items: flex-start; + gap: 0.5rem; + } + .mist-arch__proof--stack .mist-lane { + display: none; + } +} .mist-arch__reserves { display: grid; gap: 1rem; From 5c7f59ed5a6d047e4cb28ac742caa044f1ee2585 Mon Sep 17 00:00:00 2001 From: Shramee Srivastav <11048263+shramee@users.noreply.github.com> Date: Thu, 26 Nov 2026 05:05:01 +0530 Subject: [PATCH 11/17] docs(contracts): correct accuracy points from an independent review Replacing the guardian does not end an inflow pause; the exit-window claim is scoped to users who can spend; duplicate deposits queue at a screened Reserve; tree capacity and slot reuse are stated; and the event, error, registrar and deploy notes are made exact. Co-Authored-By: Claude Opus 5.5 --- src/content/docs/contracts/chamber.mdx | 6 +++--- src/content/docs/contracts/events-and-errors.mdx | 9 ++++++--- src/content/docs/contracts/registrar.mdx | 4 ++++ src/content/docs/contracts/reserve.mdx | 4 ++-- src/content/docs/contracts/roles-and-security.mdx | 12 +++++++----- src/content/docs/contracts/trees-and-roots.mdx | 2 +- .../docs/contracts/verifier-and-deployment.mdx | 4 ++-- 7 files changed, 25 insertions(+), 16 deletions(-) diff --git a/src/content/docs/contracts/chamber.mdx b/src/content/docs/contracts/chamber.mdx index 7827247..0d97cfb 100644 --- a/src/content/docs/contracts/chamber.mdx +++ b/src/content/docs/contracts/chamber.mdx @@ -39,7 +39,7 @@ function deposit( ) external returns (uint256 noteHash, uint256 depositId); ``` -A deposit takes no proof. The depositor approves the Reserve, not the Chamber, for `amount` of the asset. The Chamber then checks, in order: +A deposit takes no proof. The depositor approves the Reserve, not the Chamber, for `amount` of the asset. The `refundTo` overload first rejects a zero `refundTo`. The Chamber then checks, in order: 1. Inflows are not paused (`Chamber: inflows paused`). 2. The Reserve is registered (`reserve is not registered`). @@ -58,7 +58,7 @@ The note binds the received amount, so an asset that takes a fee on the incoming `refundTo` names who receives a reclaim. It cannot be zero (`Chamber: zero refundTo`). The four-argument form uses the depositor. A router that deposits for a user names the user, so a rejected deposit is never stranded behind a contract that cannot reclaim. `refundTo` matters only for a queued deposit. -An owner commitment is single-use per Reserve, asset and amount: a second deposit with the same values gives a note hash that is already recorded, and reverts. Use a fresh blinding for every deposit. +An owner commitment is single-use per Reserve, asset and amount. Once a note is in a tree, a second deposit with the same values gives the same note hash and reverts. At a screened Reserve, an identical deposit made while the first is still queued queues beside it, and approval admits only the first. Use a fresh blinding for every deposit. ## Screening @@ -110,7 +110,7 @@ One function settles every spend: a private payment, a withdrawal or both. It ru - **No assets move on a private payment.** The withdrawal call is last, after every state write. - **Every spend appends two notes,** zero-amount outputs included, so spends look alike. -- **The Reserve is not looked up.** The circuit binds `withdraw_reserve` to the custody of the spent notes, and a note enters a tree only through a registered Reserve's deposit. +- **The Reserve is not looked up.** The circuit binds `withdraw_reserve` to the custody of the spent notes. Every note under a Reserve's custody descends from deposits at that Reserve, which the Chamber registered: a spend's outputs inherit its inputs' custody. - **A filed spend** is stored as `privateTxCommitments(privateTxKey)`, which returns `(newNote1, newNote2, blockNumber, txIndex)`. `txIndex` is `newNote1`'s global index, and `newNote2` follows it. An identifier can be filed once, across every Reserve. - **Calling `handleZkp`** with `auth_done = 1` is open to anyone, so a relayer can submit it. Nothing in core pays the relayer. A relayer fee is **Planned**. diff --git a/src/content/docs/contracts/events-and-errors.mdx b/src/content/docs/contracts/events-and-errors.mdx index 4407b84..9062577 100644 --- a/src/content/docs/contracts/events-and-errors.mdx +++ b/src/content/docs/contracts/events-and-errors.mdx @@ -37,7 +37,7 @@ An unscreened deposit emits only `NoteAppended`. | --- | --- | | `ReserveRegistered(address indexed reserve, address indexed admin, uint256 leafIndex, uint256 reserveConfig, uint256 stateRoot)` | The owner registers a Reserve. `stateRoot` is 0 | | `ReserveConfigUpdated(address indexed reserve, uint256 reserveConfig, uint256 stateRoot)` | A Reserve's zkState leaf changes, from a config update or a users-root update | -| `ZkStateRootUpdated(uint256 indexed newRoot, uint256 previousRootExpiresAt)` | The zkState root changes. `previousRootExpiresAt` is when the old root stops being accepted, 0 if there was none | +| `ZkStateRootUpdated(uint256 indexed newRoot, uint256 previousRootExpiresAt)` | A Reserve is registered or pushes an update. `previousRootExpiresAt` is when the old root stops being accepted, or 0 if there was no old root or the root did not change | | `ZkStateHistoryRetired(address indexed reserve, uint256 cutoff)` | A Reserve's users root first becomes non-zero, and every superseded root is retired | | `ReserveScreenerSet(address indexed reserve, address indexed screener)` | A Reserve sets or clears its screener | | `ReserveAssetMinDepositSet(address indexed reserve, address indexed asset, uint256 minDeposit)` | A Reserve lists an asset, changes its minimum, or delists it with 0 | @@ -113,11 +113,12 @@ Watch `VerifierUpdateProposed` and compare its code hash with the expected build | `verifier timelock` | Execute before the eta | | `verifier code changed` | The code at the proposed address no longer matches its hash | | `ownership timelock` | Accept before the eta | -| `renounce disabled` | Any call to `renounceOwnership` | +| `renounce disabled` | `renounceOwnership` called by the owner | | `Chamber: only guardian`, `Chamber: only guardian or owner` | A pause function from another caller | | `Chamber: spend pause cooldown` | A spend pause within 7 days of the last one ending | | `Chamber: spends not paused` | `unpauseSpends` when no pause is running | | `merkle leaf index out of range` | `txTreeOf` or `merkleProof` past the last leaf | +| `merkle tree capacity exceeded` | `registerReserve` when the zkState tree holds 4^10 Reserves. Transactions trees roll over instead | ### Reserve @@ -134,6 +135,7 @@ Watch `VerifierUpdateProposed` and compare its code hash with the expected build | `Reserve: no user at index` | `removeUser` past the last leaf or on a zeroed leaf | | `Reserve: last user` | `removeUser` that would empty the users tree | | `Reserve: auditor key not in field` | A key element at or above the field order | +| `merkle tree capacity exceeded` | `addUser` when all 4^10 leaf slots of the users tree are used | | `Reserve: zero admin`, `Reserve: zero chamber` | Constructor with a zero address | ### ManagerSigRegistrar @@ -153,5 +155,6 @@ Watch `VerifierUpdateProposed` and compare its code hash with the expected build | `ProofInvalid()` | `ChamberVerifier`: the pairing check failed or a point is not on its curve | | `PublicInputNotInField()` | `ChamberVerifier`: a public input is at or above the field order | | `OwnableUnauthorizedAccount(address)` | `Ownable`: an owner function from another caller, or `acceptOwnership` from anyone but the pending owner | +| `OwnableInvalidOwner(address)` | `Ownable`: the Chamber constructor with a zero owner | | `ReentrancyGuardReentrantCall()` | `ReentrancyGuard`: a reentrant call into a guarded Chamber function | -| `SafeERC20FailedOperation(address)` | `SafeERC20`: an asset transfer returned false | +| `SafeERC20FailedOperation(address)` | `SafeERC20`: an asset transfer returned false or a malformed value, or the asset has no code. An asset that reverts bubbles up its own revert data | diff --git a/src/content/docs/contracts/registrar.mdx b/src/content/docs/contracts/registrar.mdx index 0cc93da..90c9ede 100644 --- a/src/content/docs/contracts/registrar.mdx +++ b/src/content/docs/contracts/registrar.mdx @@ -106,6 +106,8 @@ Whoever holds a signature chooses when, before the deadline, the registration la | An account with no code | ECDSA only. A malformed signature reverts with its reason: `Registrar: bad signature length` (not 65 bytes), `Registrar: malleable signature` (`s` above half the curve order) or `Registrar: bad signature v` (not 27 or 28) | | A contract | ECDSA first. If that does not recover the signer, ERC-1271: `isValidSignature(digest, signature)` must return `0x1626ba7e`. Only the first return word is read | +The branch is chosen by whether `signer` has code when the call lands. An account with an EIP-7702 delegation has code, so a malformed ECDSA signature from it falls through to ERC-1271 instead of reverting with its reason. + ECDSA is implemented in the contract because the Paris EVM target lacks `mcopy`. The signature is ECDSA over secp256k1 and is not post-quantum. :::caution[ERC-1271 signers are trusted] @@ -127,4 +129,6 @@ The signed message carries `registrations`, and `addUser` increments it on every - A signature registers the leaf at most once. After it lands, the count has moved and the digest no longer matches. - A member who was removed cannot return with any signature collected before their latest registration. Re-registering needs a new signature. +A signature made while the member is registered carries the current count, so it stays valid after a removal and can re-register the member until its deadline. Do not sign ahead for a registered leaf. `revoke` is the only way to cancel a signature before its deadline. + Removing a member is not done here: a `USERS` holder calls `Reserve.removeUser(index)` directly. See [Reserve](/contracts/reserve/#users-tree). diff --git a/src/content/docs/contracts/reserve.mdx b/src/content/docs/contracts/reserve.mdx index 0cfc566..6389368 100644 --- a/src/content/docs/contracts/reserve.mdx +++ b/src/content/docs/contracts/reserve.mdx @@ -72,7 +72,7 @@ function addUser(uint256 leaf) external onlyPermission(USERS) returns (uint256 i function removeUser(uint256 index) external onlyPermission(USERS); ``` -A member's leaf is `H2(owner, userKeyExchange)`, computed off-chain. Only the hash goes on-chain. +A member's leaf is `H2(owner, userKeyExchange)`, computed off-chain. Only the hash goes on-chain. The tree holds 4^10 = 1,048,576 leaf slots. Removals do not free slots, so every registration, including a re-registration, uses one, and `addUser` reverts with `merkle tree capacity exceeded` once all are used. - **`addUser`** requires a non-zero leaf below the field order that is not currently registered. It appends the leaf, increments `registrations(leaf)`, emits `UserRegistered(leaf, index, root)` and pushes the new root with `Chamber.setReserveStateRoot`. - **`removeUser`** takes the index from `UserRegistered`. It zeroes the leaf, clears `isRegisteredUser(leaf)`, emits `UserRemoved(index, leaf, root)` and pushes the new root. It reverts with `Reserve: no user at index` for an index past the last leaf or an already-zero leaf, and with `Reserve: last user` if the users root would become zero. A zero users root would switch messaging off. @@ -84,7 +84,7 @@ A user removed from a Reserve with members cannot spend or withdraw there while | View | Returns | | --- | --- | | `registeredUsersRoot()` | The users root, zero while empty | -| `registeredUsersCount()` | Leaf slots used, removed users included | +| `registeredUsersCount()` | Leaf slots used, removed users included. A removed slot is never reused | | `registeredUserProof(index)` | The 30-element membership proof for the leaf at `index` | | `isRegisteredUser(leaf)` | Whether the leaf is currently in the tree | | `registrations(leaf)` | How many times the leaf has been registered | diff --git a/src/content/docs/contracts/roles-and-security.mdx b/src/content/docs/contracts/roles-and-security.mdx index c58f73c..2ee21c8 100644 --- a/src/content/docs/contracts/roles-and-security.mdx +++ b/src/content/docs/contracts/roles-and-security.mdx @@ -33,7 +33,9 @@ The verifier decides which spends are valid, so replacing it is the most powerfu 2. Users and monitors compare the published code hash with a build of the expected verifier. 3. After the eta, the owner calls `executeVerifierUpdate()`. It reverts with `verifier timelock` before the eta and with `verifier code changed` if the code at the address no longer matches the hash. It emits `VerifierUpdated(verifier, codehash)`. -`cancelVerifierUpdate()` drops a pending proposal and emits `VerifierUpdateCancelled`. The 7-day delay is longer than the 3-day maximum spend pause, so a guardian pause cannot cover the whole window of a queued change: users can always exit first. +`cancelVerifierUpdate()` drops a pending proposal and emits `VerifierUpdateCancelled`. The 7-day delay is longer than the 3-day maximum spend pause, so a guardian pause alone cannot cover the whole window of a queued change. A user who can spend has time to exit first. A member removed from a Reserve with members cannot spend there, so that user has no exit until exit spends, which are **Planned**. + +The code-hash check pins the verifier's code, not its behaviour. A verifier whose `verifyProof` read mutable external state would pass it, so reviewers read the proposed code, not only its hash. ## Ownership timelock @@ -41,7 +43,7 @@ The Chamber uses OpenZeppelin's `Ownable2Step` with a delay: - `transferOwnership(newOwner)` sets the pending owner and an eta 7 days out, and emits `OwnershipTransferQueued(newOwner, eta)`. Passing zero cancels, with eta 0. - The pending owner calls `acceptOwnership()` after the eta, or it reverts with `ownership timelock`. -- `renounceOwnership()` always reverts with `renounce disabled`. +- `renounceOwnership()` always reverts: with `renounce disabled` for the owner, and with `OwnableUnauthorizedAccount` for anyone else. ## Guardian pauses @@ -51,7 +53,7 @@ The Chamber uses OpenZeppelin's `Ownable2Step` with a delay: | `pauseSpends` | `handleZkp`: private payments and withdrawals | 3 days | Expiry, or `unpauseSpends` by the guardian or the owner | - **Cooldown.** A new spend pause can start only 7 days after the previous one ended. Ending a pause early starts the cooldown from that moment. Rotating the guardian does not reset it. -- **Never paused.** `reclaimDeposit` and `rejectDeposits`, so a pause never traps a queued deposit. +- **Never paused.** `reclaimDeposit` and `rejectDeposits`, so a pause never traps a queued deposit. Neither pause touches governance or registration either: `registerReserve`, every Reserve function and the registrar keep working. ## Security notes @@ -60,7 +62,7 @@ These are the trust assumptions, stated plainly. | Holder | Worst case if acting against users | | --- | --- | | Chamber owner | Proposes a verifier that accepts any proof. After 7 days it could authorise the withdrawal of every asset in every Reserve, because no on-chain ledger checks withdrawals against notes. The defence is the published code hash and the 7-day window to exit. The owner can also make itself guardian with `setGuardian` at once | -| Guardian | Pauses deposits with no time limit, until the owner unpauses or replaces it. Halts all spends, withdrawals included, for up to 3 days, then must wait 7 days after that pause ends before the next | +| Guardian | Pauses deposits with no time limit. Replacing the guardian does not end the pause: the owner first rotates the guardian with `setGuardian`, then calls `unpauseInflows`. Halts all spends, withdrawals included, for up to 3 days, then must wait 7 days after that pause ends before the next | | Whoever ran the trusted setup | Could forge a proof for any public inputs, including a withdrawal, if they kept the setup's secret randomness. The keys come from a single-party setup. See [Circuits](/circuits/) | | Reserve admin or `USERS` | Decides who can spend at a Reserve with members. Removing a member, or never registering a holder, leaves that holder's notes unspendable there. An exit spend for that case is **Planned** | | `METADATA` | Each update replaces the shared zkState root. Proofs against the old root stay valid for 10 minutes | @@ -75,4 +77,4 @@ Further limits that hold for every user: - **Identifiers are first come, first served** across every Reserve. - **Compliance is experimental.** Screening is off-chain and on entry only. -Review findings and their status are tracked in the specification's implementation status file. These pages claim no external audit. +These pages claim no external audit. diff --git a/src/content/docs/contracts/trees-and-roots.mdx b/src/content/docs/contracts/trees-and-roots.mdx index 6c02d77..0f7fa37 100644 --- a/src/content/docs/contracts/trees-and-roots.mdx +++ b/src/content/docs/contracts/trees-and-roots.mdx @@ -53,7 +53,7 @@ The zkState tree has one leaf per Reserve: leaf = H3(reserve, reserveConfig, usersRoot) ``` -`reserveConfig` is `H2(keyHash, keyInputPoint)`, the Reserve's opaque metadata, and `usersRoot` is the root of its registered-users tree. `registerReserve` appends the leaf with `usersRoot = 0`, and the Reserve's pushes update it in place. Every update makes a new root current and emits `ZkStateRootUpdated(newRoot, previousRootExpiresAt)`. +`reserveConfig` is `H2(keyHash, keyInputPoint)`, the Reserve's opaque metadata, and `usersRoot` is the root of its registered-users tree. `registerReserve` appends the leaf with `usersRoot = 0`, and the Reserve's pushes update it in place. Every push emits `ZkStateRootUpdated(newRoot, previousRootExpiresAt)`. When a push leaves the root unchanged, nothing expires and `previousRootExpiresAt` is 0. | View | Returns | | --- | --- | diff --git a/src/content/docs/contracts/verifier-and-deployment.mdx b/src/content/docs/contracts/verifier-and-deployment.mdx index 551d6d6..f746d9e 100644 --- a/src/content/docs/contracts/verifier-and-deployment.mdx +++ b/src/content/docs/contracts/verifier-and-deployment.mdx @@ -53,7 +53,7 @@ The script reads its settings from the environment: | `DEV_FIXTURES` | `false` | Deploy a development Reserve, a mock asset and one registered user | | `USER_KEY_EXCHANGE` | 0 | The development user's key exchange. Required with `DEV_FIXTURES` | -On chain ID 1, `validate` refuses development fixtures and the fixture key exchange `0x6b6579`, and requires `CHAMBER_OWNER` to be set, to differ from the deployer and to have code. +On chain ID 1, `validate` refuses development fixtures and the fixture key exchange `0x6b6579`, and requires `CHAMBER_OWNER` to be set, to differ from the deployer and to have code. On any other chain these rules do not apply: an unset `CHAMBER_OWNER` leaves the deployer's key as the owner, and `GUARDIAN` is not checked. The script then broadcasts, in order: @@ -69,7 +69,7 @@ It writes the address book to `deployments/.json`, with the Chamber, ve `Poseidon2` in `lib/Poseidon.sol` exposes `public` functions, so it is deployed as its own library contract and linked into the contracts that hash. :::caution[Development fixtures are not for real funds] -The development Reserve has a fixed auditor key (789, 987), a mock asset, no screener, and the deployer as admin. Its registered user's key exchange is whatever `USER_KEY_EXCHANGE` holds. The fixture value `0x6b6579` is public, so anyone can decrypt that user's messaging. +The development Reserve has a fixed auditor key (789, 987), a mock asset, no screener, and the deployer as admin. Its registered user's key exchange is whatever `USER_KEY_EXCHANGE` holds. The fixture value `0x6b6579` is public, so anyone can derive that user's messaging keys and decrypt their spends. ::: ## After deployment From f467d7bcb382246086c83879c41d3b48207b45bd Mon Sep 17 00:00:00 2001 From: Shramee Srivastav <11048263+shramee@users.noreply.github.com> Date: Fri, 27 Nov 2026 09:17:32 +0530 Subject: [PATCH 12/17] docs(contracts): document registrar v3 signatures and per-leaf revoke Core fa7b92d binds each signature to its signer, the signer's USERS epoch, the leaf nonce and a per-leaf revocation count, under domain version 3. revoke(reserve, leaf) cancels every outstanding signature for the leaf. The typehash is recomputed with cast keccak. Co-Authored-By: Claude Opus 5.5 --- src/content/docs/contracts/registrar.mdx | 85 ++++++++++++++---------- 1 file changed, 51 insertions(+), 34 deletions(-) diff --git a/src/content/docs/contracts/registrar.mdx b/src/content/docs/contracts/registrar.mdx index 90c9ede..c4dc7cd 100644 --- a/src/content/docs/contracts/registrar.mdx +++ b/src/content/docs/contracts/registrar.mdx @@ -1,6 +1,6 @@ --- title: ManagerSigRegistrar -description: "The registrar that adds a member to a Reserve on an EIP-712 signature from a USERS holder: domain and struct, deadline, revocation, ERC-1271, and the registration-count binding." +description: "The registrar that adds a member to a Reserve on an EIP-712 signature from a USERS holder: domain and struct, the signer, leaf-nonce and revocation bindings, deadline, revoke and ERC-1271." sidebar: order: 5 --- @@ -14,7 +14,7 @@ A Reserve uses the registrar after two grants by its admin: 1. `grantPermission(USERS, registrar)`, so the registrar can call `Reserve.addUser`. 2. `grantPermission(USERS, signer)` for each account whose signatures it should accept. The admin holds `USERS` implicitly and can sign without a grant. -The signer names itself in each call, so several signers can serve one Reserve. +Each signature names its signer, so several signers can serve one Reserve. ## The signed message @@ -24,40 +24,52 @@ The registrar uses EIP-712: | --- | --- | | Domain type | `EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)` | | `name` | `MistReserveRegistrar` | -| `version` | `2` | +| `version` | `3` | | `chainId` | `block.chainid`, read on every call, so a chain fork gets its own domain | | `verifyingContract` | The registrar's address | -| Struct type | `RegisterUser(address reserve,uint256 leaf,uint256 registrations,uint256 deadline)` | -| `REGISTER_USER_TYPEHASH` | `0x6588b0d0279abb2e1a411801d4c8d83f482215f054953374f5b15da0702fce40` | +| Struct type | `RegisterUser(address reserve,uint256 leaf,uint256 leafNonce,uint256 revocations,address signer,uint256 signerEpoch,uint256 deadline)` | +| `REGISTER_USER_TYPEHASH` | `0x08047a61f834abacb9e6933736e7a17a949d36d81dc3bb91db74050ad7d1d06b` | -- **`leaf`** is `H2(owner, userKeyExchange)`, computed off-chain. `userKeyExchange` stays off-chain and must be a full-entropy key-exchange output, or the leaf can be brute-forced. -- **`registrations`** is `Reserve(reserve).registrations(leaf)` when the call lands. Every registration of the leaf increments it. -- **`deadline`** is the last valid timestamp, inclusive. +| Field | Value when the call lands | Moves when | +| --- | --- | --- | +| `reserve` | The Reserve to register on | Never | +| `leaf` | `H2(owner, userKeyExchange)`, computed off-chain | Never | +| `leafNonce` | `Reserve(reserve).leafNonce(leaf)` | The leaf is registered or removed | +| `revocations` | `revocations(reserve, leaf)` on the registrar | A `USERS` holder calls `revoke(reserve, leaf)` | +| `signer` | The account that signed | Never | +| `signerEpoch` | `Reserve(reserve).permissionEpoch(USERS, signer)` | The signer loses `USERS` | +| `deadline` | The last valid timestamp, inclusive | Never | -`registerUserDigest(reserve, leaf, deadline)` returns the digest to sign, with the current count filled in: `keccak256("\x19\x01" || domainSeparator() || structHash)`. +`userKeyExchange` stays off-chain and must be a full-entropy key-exchange output, or the leaf can be brute-forced. + +`registerUserDigest(reserve, leaf, signer, deadline)` returns the digest to sign, with the three counters filled in at their current values: `keccak256("\x19\x01" || domainSeparator() || structHash)`. A signer can produce the same digest with viem's `signTypedData`. This assumes `publicClient`, `walletClient`, `account`, `reserve`, `registrar`, `leaf` and `deadline` are already defined: ```ts -import { parseAbi } from "viem"; +import { keccak256, parseAbi, toHex } from "viem"; const reserveAbi = parseAbi([ - "function registrations(uint256 leaf) view returns (uint256)", + "function leafNonce(uint256 leaf) view returns (uint256)", + "function permissionEpoch(bytes32 role, address account) view returns (uint256)", +]); +const registrarAbi = parseAbi([ + "function revocations(address reserve, uint256 leaf) view returns (uint256)", ]); +const USERS = keccak256(toHex("USERS")); -// The count moves on every registration, so read it just before signing. -const registrations = await publicClient.readContract({ - address: reserve, - abi: reserveAbi, - functionName: "registrations", - args: [leaf], -}); +// All three counters can move, so read them just before signing. +const [leafNonce, signerEpoch, revocations] = await Promise.all([ + publicClient.readContract({ address: reserve, abi: reserveAbi, functionName: "leafNonce", args: [leaf] }), + publicClient.readContract({ address: reserve, abi: reserveAbi, functionName: "permissionEpoch", args: [USERS, account.address] }), + publicClient.readContract({ address: registrar, abi: registrarAbi, functionName: "revocations", args: [reserve, leaf] }), +]); const signature = await walletClient.signTypedData({ account, domain: { name: "MistReserveRegistrar", - version: "2", + version: "3", chainId: await publicClient.getChainId(), verifyingContract: registrar, }, @@ -65,12 +77,15 @@ const signature = await walletClient.signTypedData({ RegisterUser: [ { name: "reserve", type: "address" }, { name: "leaf", type: "uint256" }, - { name: "registrations", type: "uint256" }, + { name: "leafNonce", type: "uint256" }, + { name: "revocations", type: "uint256" }, + { name: "signer", type: "address" }, + { name: "signerEpoch", type: "uint256" }, { name: "deadline", type: "uint256" }, ], }, primaryType: "RegisterUser", - message: { reserve, leaf, registrations, deadline }, + message: { reserve, leaf, leafNonce, revocations, signer: account.address, signerEpoch, deadline }, }); ``` @@ -91,14 +106,25 @@ Anyone can call it. It checks, in order: | Check | Revert | | --- | --- | | `block.timestamp <= deadline` | `Registrar: signature expired` | -| The digest is not revoked | `Registrar: signature revoked` | | `signer` holds `USERS` on `reserve` | `Registrar: missing users permission` | -| The signature is valid for `signer` | `Registrar: invalid signature` | +| The signature is valid for `signer` over the digest at the current counters | `Registrar: invalid signature` | + +A signature whose leaf nonce, revocation count or signer epoch has moved since it was made no longer matches the digest, and fails the last check. It then calls `Reserve(reserve).addUser(leaf)` and returns the leaf. The Reserve emits `UserRegistered(leaf, index, root)` with the index that `removeUser` needs, and pushes its new users root to the Chamber, which changes the shared zkState root. Whoever holds a signature chooses when, before the deadline, the registration lands. +## What voids a signature + +| Event | Effect | +| --- | --- | +| The registration lands | `leafNonce` moves, so the signature cannot register the leaf twice | +| The member is removed | `leafNonce` moves, so no signature made before the removal can put the member back. Re-registering needs a new signature | +| A `USERS` holder calls `revoke(reserve, leaf)` | `revocations` moves, cancelling every outstanding signature for the leaf, from every signer, with any deadline. Signatures made afterwards work | +| The signer loses `USERS` | `signerEpoch` moves, on a revoke of its grant or when it hands the admin role on. Granting the role again does not revive its old signatures | +| The deadline passes | The call reverts with `Registrar: signature expired` | + ## Signatures | Signer | Accepted | @@ -117,18 +143,9 @@ The registrar accepts whatever a `USERS` holder with code approves. Grant `USERS ## Revoking ```solidity -function revoke(address reserve, uint256 leaf, uint256 deadline) external; +function revoke(address reserve, uint256 leaf) external; ``` -A `USERS` holder on `reserve` can revoke one authorisation before it is used. `revoke` computes the digest for `(reserve, leaf, deadline)` at the leaf's current registration count, marks it in `revoked`, and emits `SignatureRevoked(reserve, leaf, deadline, digest)`. Revocation is permanent. Any `USERS` holder can revoke a digest, whoever signed it. - -## Registration-count binding - -The signed message carries `registrations`, and `addUser` increments it on every registration. Two things follow: - -- A signature registers the leaf at most once. After it lands, the count has moved and the digest no longer matches. -- A member who was removed cannot return with any signature collected before their latest registration. Re-registering needs a new signature. - -A signature made while the member is registered carries the current count, so it stays valid after a removal and can re-register the member until its deadline. Do not sign ahead for a registered leaf. `revoke` is the only way to cancel a signature before its deadline. +Any `USERS` holder on `reserve` can call it, or it reverts with `Registrar: missing users permission`. It increments `revocations(reserve, leaf)` and emits `SignaturesRevoked(reserve, leaf, revocations)`. Every signature for that leaf made before the call stops working, whoever signed it. Removing a member is not done here: a `USERS` holder calls `Reserve.removeUser(index)` directly. See [Reserve](/contracts/reserve/#users-tree). From 474fa64fd9439c76714d9ead02e52b325fdd70e2 Mon Sep 17 00:00:00 2001 From: Shramee Srivastav <11048263+shramee@users.noreply.github.com> Date: Fri, 27 Nov 2026 09:17:32 +0530 Subject: [PATCH 13/17] docs(contracts): document the leaf nonce, permission epochs and the removal freeze Co-Authored-By: Claude Opus 5.5 --- src/content/docs/contracts/reserve.mdx | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/src/content/docs/contracts/reserve.mdx b/src/content/docs/contracts/reserve.mdx index 6389368..116b186 100644 --- a/src/content/docs/contracts/reserve.mdx +++ b/src/content/docs/contracts/reserve.mdx @@ -34,7 +34,7 @@ function acceptAdmin() external; The admin is named by the Chamber owner in `registerReserve` and cannot be zero. It holds every permission, grants and revokes them, and is the only account that moves the admin role. A live Reserve's admin should be a Safe. -- **Two steps.** `transferAdmin(newAdmin)` nominates, and emits `AdminTransferStarted`. The nominee calls `acceptAdmin()`, and the Reserve emits `AdminTransferred`. Nominating zero cancels. There is no delay. +- **Two steps.** `transferAdmin(newAdmin)` nominates, and emits `AdminTransferStarted`. The nominee calls `acceptAdmin()`, and the Reserve emits `AdminTransferred`. Nominating zero cancels. There is no delay. The previous admin loses its implicit permissions, and its permission epoch moves for every role it holds no explicit grant for. - **Grants survive a handover.** Explicit grants are not cleared. The new admin reviews the Reserve's `PermissionGranted` and `PermissionRevoked` events and revokes stale grants, including any held by the previous admin's address. Registrars and bots keep working through a handover. ## Permissions @@ -47,6 +47,9 @@ function hasPermission(bytes32 role, address account) public view returns (bool) Each role is held by any number of accounts. `hasPermission` is true for the admin on every role, and for any account with an explicit grant. The admin's implicit permissions cannot be revoked. An unknown role reverts with `Reserve: unknown permission`. +- **No-ops are silent.** Granting a role the account already holds, or revoking one it holds no explicit grant for, changes nothing and emits nothing. A grant to the zero address reverts with `Reserve: zero account`. +- **Permission epoch.** `permissionEpoch(role, account)` moves each time the account loses the role: when its explicit grant is revoked, and, for each role it holds no explicit grant for, when it hands the admin role on. The registrar binds a signer's `USERS` epoch into every signature, so re-granting an account never revives the signatures it made before it lost the role. + | Role | `bytes32` value | Functions | | --- | --- | --- | | `ASSETS` | `keccak256("ASSETS")` | `setAssetMinDeposit` | @@ -74,12 +77,14 @@ function removeUser(uint256 index) external onlyPermission(USERS); A member's leaf is `H2(owner, userKeyExchange)`, computed off-chain. Only the hash goes on-chain. The tree holds 4^10 = 1,048,576 leaf slots. Removals do not free slots, so every registration, including a re-registration, uses one, and `addUser` reverts with `merkle tree capacity exceeded` once all are used. -- **`addUser`** requires a non-zero leaf below the field order that is not currently registered. It appends the leaf, increments `registrations(leaf)`, emits `UserRegistered(leaf, index, root)` and pushes the new root with `Chamber.setReserveStateRoot`. -- **`removeUser`** takes the index from `UserRegistered`. It zeroes the leaf, clears `isRegisteredUser(leaf)`, emits `UserRemoved(index, leaf, root)` and pushes the new root. It reverts with `Reserve: no user at index` for an index past the last leaf or an already-zero leaf, and with `Reserve: last user` if the users root would become zero. A zero users root would switch messaging off. -- **Re-registration.** A removed leaf can be added again, at a new index. `registrations(leaf)` counts every registration, and the registrar binds its signatures to that count, so no signature collected before the latest registration can be used again. +- **`addUser`** requires a non-zero leaf below the field order that is not currently registered. It appends the leaf, increments `leafNonce(leaf)`, emits `UserRegistered(leaf, index, root)` and pushes the new root with `Chamber.setReserveStateRoot`. +- **`removeUser`** takes the index from `UserRegistered`. It zeroes the leaf, clears `isRegisteredUser(leaf)`, increments `leafNonce(leaf)`, emits `UserRemoved(index, leaf, root)` and pushes the new root. It reverts with `Reserve: no user at index` for an index past the last leaf or an already-zero leaf, and with `Reserve: last user` if the users root would become zero. A zero users root would switch messaging off, and the Chamber also refuses one. To remove a Reserve's only user, add another leaf first. +- **Re-registration.** A removed leaf can be added again, at a new index. `leafNonce(leaf)` moves on every registration and every removal, and the registrar binds its signatures to it, so no signature collected before a removal can put the user back. Re-registering needs a new signature. - **Lag.** A removal takes full effect within 10 minutes, when the last zkState root that holds the leaf leaves the Chamber's grace window. -A user removed from a Reserve with members cannot spend or withdraw there while removed. An exit spend that lets any owner withdraw in public is **Planned**. +:::caution[A removal freezes the user's notes] +A user removed from a Reserve with members cannot spend or withdraw there until a `USERS` holder registers them again, and any single `USERS` holder can make the removal. An exit spend that lets any owner withdraw in public is **Planned**. Core's operations notes say not to deploy these contracts to production, or not to let any Reserve remove users, until that exit spend is in the circuit and the verifier. +::: | View | Returns | | --- | --- | @@ -87,7 +92,8 @@ A user removed from a Reserve with members cannot spend or withdraw there while | `registeredUsersCount()` | Leaf slots used, removed users included. A removed slot is never reused | | `registeredUserProof(index)` | The 30-element membership proof for the leaf at `index` | | `isRegisteredUser(leaf)` | Whether the leaf is currently in the tree | -| `registrations(leaf)` | How many times the leaf has been registered | +| `leafNonce(leaf)` | A counter that moves on every registration and removal of the leaf | +| `permissionEpoch(role, account)` | A counter that moves each time the account loses the role | ## Auditor key From d84b23309dffd896f32de583b7ff1044f379d0ef Mon Sep 17 00:00:00 2001 From: Shramee Srivastav <11048263+shramee@users.noreply.github.com> Date: Fri, 27 Nov 2026 09:17:32 +0530 Subject: [PATCH 14/17] docs(contracts): follow core fa7b92d in the Chamber pages refundTo is paid only after rejection and can be changed while pending, the constructor takes the guardian, a users root cannot return to zero, and notes in different trees are merged through a spend with a dummy input. Co-Authored-By: Claude Opus 5.5 --- src/content/docs/contracts/chamber.mdx | 12 +++++++----- src/content/docs/contracts/how-they-fit.mdx | 6 +++--- src/content/docs/contracts/trees-and-roots.mdx | 2 +- 3 files changed, 11 insertions(+), 9 deletions(-) diff --git a/src/content/docs/contracts/chamber.mdx b/src/content/docs/contracts/chamber.mdx index 0d97cfb..40e1757 100644 --- a/src/content/docs/contracts/chamber.mdx +++ b/src/content/docs/contracts/chamber.mdx @@ -18,7 +18,7 @@ The Chamber is the state engine: it takes deposits, verifies each spend and appl | `SPEND_PAUSE_MAX` | 3 days | Length of one spend pause | | `SPEND_PAUSE_COOLDOWN` | 7 days | Minimum gap between the end of one spend pause and the next | -The immutable `chamberId` is `H2(block.chainid, address(this))`, computed in the constructor. The constructor takes `(owner_, verifier_)` and reverts with `invalid verifier` if the verifier address has no code. +The immutable `chamberId` is `H2(block.chainid, address(this))`, computed in the constructor. The constructor takes `(owner_, verifier_, guardian_)`. It reverts with `invalid verifier` if the verifier address has no code. A non-zero `guardian_` is set at once and emits `GuardianSet`; zero leaves the Chamber with no guardian until the owner sets one. ## Deposits @@ -56,7 +56,7 @@ The note binds the received amount, so an asset that takes a fee on the incoming | No screener | The note is appended to the transactions tree at once and recorded in `assets` | `(noteHash, 0)` | | A screener | The deposit is queued under `depositId = ++depositCount`, and `DepositQueued` is emitted. The note stays out of the tree until the screener decides | `(noteHash, depositId)` | -`refundTo` names who receives a reclaim. It cannot be zero (`Chamber: zero refundTo`). The four-argument form uses the depositor. A router that deposits for a user names the user, so a rejected deposit is never stranded behind a contract that cannot reclaim. `refundTo` matters only for a queued deposit. +`refundTo` names who is refunded if the screener rejects the deposit. It cannot be zero (`Chamber: zero refundTo`). The four-argument form uses the depositor. A router that deposits for a user names the user, so a rejected deposit is never stranded behind a contract that cannot reclaim. `refundTo` matters only for a queued deposit, and a third party named there is paid only after the screener has seen the deposit. An owner commitment is single-use per Reserve, asset and amount. Once a note is in a tree, a second deposit with the same values gives the same note hash and reverts. At a screened Reserve, an identical deposit made while the first is still queued queues beside it, and approval admits only the first. Use a fresh blinding for every deposit. @@ -68,6 +68,7 @@ A Reserve's screener is an off-chain service, such as a KYT bot or an API relaye function approveDeposits(uint256[] calldata depositIds, bytes32 evidence) external; function rejectDeposits(uint256[] calldata depositIds, bytes32 evidence) external; function reclaimDeposit(uint256 depositId) external; +function setDepositRefundTo(uint256 depositId, address refundTo) external; function depositRefundTo(uint256 depositId) public view returns (address); ``` @@ -75,7 +76,8 @@ function depositRefundTo(uint256 depositId) public view returns (address); | --- | --- | --- | | `approveDeposits` | The screener of each deposit's Reserve | Appends each pending note and emits `DepositApproved`. A note already in a tree is rejected instead, with `DepositDuplicateRejected`. Ids that are not pending are skipped. Paused with inflows | | `rejectDeposits` | The same | Marks each pending deposit rejected and emits `DepositRejected`. Rejection is final. Never paused | -| `reclaimDeposit` | The depositor or `refundTo` | Pays a pending or rejected deposit back to `depositRefundTo(id)`, which is `refundTo` if one was named and the depositor otherwise. Emits `DepositReclaimed`. Never paused | +| `reclaimDeposit` | Pending: the depositor only. Rejected: the depositor or `refundTo` | A pending deposit returns to the depositor. A rejected one goes to `depositRefundTo(id)`, which is `refundTo` if one was named and the depositor otherwise. Emits `DepositReclaimed`. Never paused | +| `setDepositRefundTo` | The depositor | Changes a pending deposit's `refundTo`, which cannot be zero, and emits `DepositRefundToSet`. Reverts with `Chamber: not pending` once the screener has decided | - **The screener is read at decision time.** A batch reverts with `Chamber: only reserve screener` if the caller is not the current screener of a pending deposit in it. A new screener therefore decides every deposit still waiting. With no screener set, waiting deposits can only be reclaimed. - **The queue is keyed by deposit id,** not by note hash. A note hash is public in the deposit calldata, so a hash-keyed queue would let anyone block a deposit by queueing the same note first. Duplicate notes may queue side by side, and approval admits only the first. @@ -135,7 +137,7 @@ A registered Reserve updates its own record through four setters. Each acts on ` | Setter | Called from | Effect | | --- | --- | --- | | `setReserveConfig(reserveConfig)` | `Reserve.updateAuditorKey` | Rewrites the Reserve's zkState leaf and makes the new zkState root current | -| `setReserveStateRoot(stateRoot)` | `Reserve.addUser`, `Reserve.removeUser` | The same, with the new users root. When the users root first becomes non-zero, every superseded zkState root stops being accepted | +| `setReserveStateRoot(stateRoot)` | `Reserve.addUser`, `Reserve.removeUser` | The same, with the new users root. When the users root first becomes non-zero, every superseded zkState root stops being accepted. A non-zero users root cannot return to zero (`Chamber: users root back to zero`) | | `setReserveScreener(screener)` | `Reserve.setScreener` | Sets or clears, with zero, the Reserve's screener | | `setReserveAssetMinDeposit(asset, minDeposit)` | `Reserve.setAssetMinDeposit` | Lists the asset with a minimum below 2^120, or delists it with zero | @@ -150,7 +152,7 @@ A registered Reserve updates its own record through four setters. Each acts on ` | `transactionsExist(notes)`, `noteIndexPlusOne(note)` | Whether each note was appended, and 1 plus a note's first global index (0 if never) | | `assetsFromNote(noteHash)` | `(amount, addr)` of a deposited note. Spend outputs have no entry | | `privateTxCommitments(privateTxKey)` | The record of a spend filed under that identifier | -| `pendingDeposits(id)`, `depositCount()`, `depositRefundTo(id)` | Queued deposits and their reclaim recipient | +| `pendingDeposits(id)`, `depositCount()`, `depositRefundTo(id)` | Queued deposits, and who a rejected deposit is refunded to | | `isRegisteredReserve(reserve)` | Whether this Chamber registered the address | | `spendsPaused()`, `spendPausedUntil()`, `inflowsPaused()`, `guardian()` | Pause state. See [Roles and security](/contracts/roles-and-security/) | diff --git a/src/content/docs/contracts/how-they-fit.mdx b/src/content/docs/contracts/how-they-fit.mdx index 63299e7..4f0de80 100644 --- a/src/content/docs/contracts/how-they-fit.mdx +++ b/src/content/docs/contracts/how-they-fit.mdx @@ -60,7 +60,7 @@ Four contracts carry the protocol. The Chamber keeps the record and verifies spe | Reserve | Chamber | `setReserveScreener(screener)` | Registered Reserve, its own record | | Reserve | Chamber | `setReserveAssetMinDeposit(asset, minDeposit)` | Registered Reserve, its own record | | ManagerSigRegistrar | Reserve | `addUser(leaf)` | `USERS` permission | -| ManagerSigRegistrar | Reserve | `registrations(leaf)`, `hasPermission(role, account)` | Views | +| ManagerSigRegistrar | Reserve | `leafNonce(leaf)`, `permissionEpoch(role, account)`, `hasPermission(role, account)` | Views | | ManagerSigRegistrar | A `USERS` holder with code | `isValidSignature(digest, signature)` | ERC-1271 view | | Reserve | ERC-20 asset | `safeTransferFrom`, `safeTransfer`, `balanceOf` | The asset's own rules | @@ -80,7 +80,7 @@ The four Chamber setters act on `msg.sender`'s record, and the Chamber accepts t 5. The Chamber checks the received amount against 2^120 and the Reserve's minimum, and hashes the note over the received amount. -6. Without a screener, the note is appended at once and `deposit` returns `(noteHash, 0)`. With one, the note is queued under a new deposit id and `deposit` returns `(noteHash, depositId)`. The screener later calls `approveDeposits` or `rejectDeposits`, and the depositor or `refundTo` can call `reclaimDeposit` while it is pending or rejected. +6. Without a screener, the note is appended at once and `deposit` returns `(noteHash, 0)`. With one, the note is queued under a new deposit id and `deposit` returns `(noteHash, depositId)`. The screener later calls `approveDeposits` or `rejectDeposits`. The depositor can reclaim a pending deposit, and a rejected one is reclaimed to `refundTo`. @@ -106,7 +106,7 @@ The four Chamber setters act on `msg.sender`'s record, and the Chamber accepts t 1. A member and the key holder agree a `userKeyExchange` off-chain. The member's leaf is `H2(owner, userKeyExchange)`. -2. A `USERS` holder signs an EIP-712 `RegisterUser` message for the leaf, with a deadline. +2. A `USERS` holder signs an EIP-712 `RegisterUser` message for the leaf that names itself as signer, with a deadline. 3. Anyone calls `ManagerSigRegistrar.registerUser(reserve, leaf, deadline, signer, signature)`. The registrar checks the signature and the signer's permission and calls `Reserve.addUser(leaf)`. diff --git a/src/content/docs/contracts/trees-and-roots.mdx b/src/content/docs/contracts/trees-and-roots.mdx index 0f7fa37..7116244 100644 --- a/src/content/docs/contracts/trees-and-roots.mdx +++ b/src/content/docs/contracts/trees-and-roots.mdx @@ -17,7 +17,7 @@ Every note, deposited or created by a spend, is appended to `txArray` and to the - **Rollover.** The leaf at a global index divisible by the capacity opens a new tree. For every tree after the first, the Chamber emits `TxTreeOpened(treeId, firstIndex)`. - **Roots stay valid.** Every root any transactions tree has had is recorded in `merkleRoots` and never retired. A proof built against an older root still verifies after the tree has grown, and a note in a full tree stays spendable. -- **One tree per spend.** A spend proves both inputs against one `transactions_root`, so two real notes in different trees cannot be spent together. +- **One tree per spend.** A spend proves both inputs against one `transactions_root`, so two real notes in different trees cannot be spent together. To merge them, the owner first spends one note with a dummy second input, which lands its outputs in the current tree. - **A spend can straddle trees.** If `new_note_1` fills the last slot of a tree, `new_note_2` opens the next one. - **`NoteAppended(index, note, root)`** is emitted for every leaf, with `root` the new root of that leaf's tree. From b5d3eb45c4a924c0e89e6efab175b99af52502dc Mon Sep 17 00:00:00 2001 From: Shramee Srivastav <11048263+shramee@users.noreply.github.com> Date: Fri, 27 Nov 2026 09:17:32 +0530 Subject: [PATCH 15/17] docs(contracts): document the Safe-owned deploy and the exit-spend blocker Co-Authored-By: Claude Opus 5.5 --- .../contracts/verifier-and-deployment.mdx | 31 ++++++++++++------- 1 file changed, 20 insertions(+), 11 deletions(-) diff --git a/src/content/docs/contracts/verifier-and-deployment.mdx b/src/content/docs/contracts/verifier-and-deployment.mdx index f746d9e..2f071d0 100644 --- a/src/content/docs/contracts/verifier-and-deployment.mdx +++ b/src/content/docs/contracts/verifier-and-deployment.mdx @@ -43,28 +43,37 @@ Regenerating the file changes nothing on-chain. Only the timelocked call does. S ## Deploy.s.sol +:::caution[Not before the exit spend] +Core's operations notes say not to deploy these contracts to production, or not to let any Reserve remove users, until the exit spend is in the circuit and the verifier. Until then a removal by any single `USERS` holder freezes the removed user's notes at that Reserve. The exit spend is **Planned**. +::: + The script reads its settings from the environment: | Variable | Default | Meaning | | --- | --- | --- | -| `PRIVATE_KEY` | Required | The deployer's key. The deployer is the Chamber's first owner | -| `CHAMBER_OWNER` | Zero | The final owner, a Safe. Required on chain ID 1 | -| `GUARDIAN` | Zero | The guardian, set if not zero | +| `PRIVATE_KEY` | Required | The deployer's key | +| `CHAMBER_OWNER` | Zero | The owner, a Safe. Required outside the development chains | +| `GUARDIAN` | Zero | The guardian, passed to the Chamber constructor. Required outside the development chains | | `DEV_FIXTURES` | `false` | Deploy a development Reserve, a mock asset and one registered user | | `USER_KEY_EXCHANGE` | 0 | The development user's key exchange. Required with `DEV_FIXTURES` | -On chain ID 1, `validate` refuses development fixtures and the fixture key exchange `0x6b6579`, and requires `CHAMBER_OWNER` to be set, to differ from the deployer and to have code. On any other chain these rules do not apply: an unset `CHAMBER_OWNER` leaves the deployer's key as the owner, and `GUARDIAN` is not checked. +`isTestChain(chainId)` is true for chain IDs 31337 and 11155111, the development chains. Every other chain is treated as production, and there `validate`: + +- refuses `DEV_FIXTURES` and the fixture key exchange `0x6b6579`; +- requires `CHAMBER_OWNER` to be set, to differ from the deployer, and to be a multisig: a contract whose `getThreshold()` returns at least 2; +- requires `GUARDIAN` to be set. + +On the two development chains none of this is checked, except that `DEV_FIXTURES` needs a non-zero `USER_KEY_EXCHANGE`. A development network has to be added to `isTestChain` before fixtures can be deployed there. The script then broadcasts, in order: 1. `new ChamberVerifier()`. -2. `new Chamber(deployer, verifier)`. +2. `new Chamber(initialOwner, verifier, GUARDIAN)`. `initialOwner` is `CHAMBER_OWNER`, unless `DEV_FIXTURES` is set or no owner is named, in which case it is the deployer. 3. `new ManagerSigRegistrar()`. -4. `chamber.setGuardian(GUARDIAN)`, if set. -5. With `DEV_FIXTURES`: a mock ERC-20, `registerReserve(deployer, 789, 987)`, `setAssetMinDeposit(asset, 1)`, a `USERS` grant to the registrar, and a registration of `H2(deployer, USER_KEY_EXCHANGE)` signed by the deployer with a deadline one hour out. -6. `chamber.transferOwnership(CHAMBER_OWNER)`, if set and not the deployer. The Safe calls `acceptOwnership()` after the 7-day delay. +4. With `DEV_FIXTURES`: a mock ERC-20, `registerReserve(deployer, 789, 987)`, `setAssetMinDeposit(asset, 1)`, a `USERS` grant to the registrar, and a registration of `H2(deployer, USER_KEY_EXCHANGE)` signed by the deployer with a deadline one hour out. +5. `chamber.transferOwnership(CHAMBER_OWNER)`, only if an owner is named and the deployer holds the Chamber, which happens with `DEV_FIXTURES`. The owner calls `acceptOwnership()` after the 7-day delay. -It writes the address book to `deployments/.json`, with the Chamber, verifier, registrar, development Reserve and mock asset addresses. These pages list no deployed addresses. +Outside the development chains the Chamber is therefore built owned by its Safe, with its guardian in place, and the deployer key never holds a power over it. It writes the address book to `deployments/.json`, with the Chamber, verifier, registrar, development Reserve and mock asset addresses. These pages list no deployed addresses. `Poseidon2` in `lib/Poseidon.sol` exposes `public` functions, so it is deployed as its own library contract and linked into the contracts that hash. @@ -74,8 +83,8 @@ The development Reserve has a fixed auditor key (789, 987), a mock asset, no scr ## After deployment -1. **Ownership.** After 7 days the Safe named in `CHAMBER_OWNER` calls `acceptOwnership()`. -2. **Guardian.** If none was set, the owner calls `setGuardian`. +1. **Ownership.** With development fixtures and a named owner, the owner calls `acceptOwnership()` after 7 days. Otherwise the Chamber already has its final owner. +2. **Guardian.** If none was named at construction, the owner calls `setGuardian`. 3. **Reserves.** The owner calls `registerReserve(admin, keyHash, keyInputPoint)` for each Reserve, naming a Safe as admin. 4. **Screener first.** The Reserve admin, or a `SCREENING` holder, calls `setScreener` before any asset is listed. 5. **Registration.** The admin grants `USERS` to the registrar and to each signer. From 6dccec4308b8e9a6c7ec2ff879f990827cc1d464 Mon Sep 17 00:00:00 2001 From: Shramee Srivastav <11048263+shramee@users.noreply.github.com> Date: Fri, 27 Nov 2026 09:17:32 +0530 Subject: [PATCH 16/17] docs(contracts): update roles, events and reverts for core fa7b92d Co-Authored-By: Claude Opus 5.5 --- .../docs/contracts/events-and-errors.mdx | 26 +++++++++++-------- .../docs/contracts/roles-and-security.mdx | 12 ++++----- 2 files changed, 21 insertions(+), 17 deletions(-) diff --git a/src/content/docs/contracts/events-and-errors.mdx b/src/content/docs/contracts/events-and-errors.mdx index 9062577..ea35db5 100644 --- a/src/content/docs/contracts/events-and-errors.mdx +++ b/src/content/docs/contracts/events-and-errors.mdx @@ -23,11 +23,12 @@ A spend with no commitments emits only its two `NoteAppended` events. Nullifiers | Event | Emitted when | | --- | --- | -| `DepositQueued(uint256 indexed depositId, uint256 noteHash, address indexed reserve, address indexed depositor, address asset, uint256 amount)` | A deposit at a screened Reserve is queued. `amount` is what the Reserve received | +| `DepositQueued(uint256 indexed depositId, uint256 noteHash, address indexed reserve, address indexed depositor, address asset, uint256 amount, address refundTo)` | A deposit at a screened Reserve is queued. `amount` is what the Reserve received, and `refundTo` who a rejection refunds | +| `DepositRefundToSet(uint256 indexed depositId, address refundTo)` | The depositor changes a pending deposit's `refundTo` | | `DepositApproved(uint256 indexed depositId, uint256 indexed noteHash, bytes32 evidence)` | The screener admits a queued deposit. A `NoteAppended` follows | -| `DepositRejected(uint256 indexed depositId, bytes32 evidence)` | The screener refuses a queued deposit | +| `DepositRejected(uint256 indexed depositId, bytes32 evidence)` | The screener refuses a queued deposit. A reclaim now pays its `refundTo` | | `DepositDuplicateRejected(uint256 indexed depositId, uint256 indexed noteHash)` | Approval finds the note already in a tree and rejects the deposit instead | -| `DepositReclaimed(uint256 indexed depositId, address indexed depositor, address to)` | A pending or rejected deposit is paid back to `to` | +| `DepositReclaimed(uint256 indexed depositId, address indexed depositor, address to)` | A pending deposit is paid back to the depositor, or a rejected one to `refundTo`, as `to` | An unscreened deposit emits only `NoteAppended`. @@ -52,7 +53,7 @@ An unscreened deposit emits only `NoteAppended`. | `OwnershipTransferQueued(address indexed newOwner, uint256 eta)` | The owner queues a transfer. Zero `newOwner` and `eta` mean it was cancelled | | `OwnershipTransferStarted(address indexed previousOwner, address indexed newOwner)` | The same moment, from `Ownable2Step` | | `OwnershipTransferred(address indexed previousOwner, address indexed newOwner)` | A transfer completes, from `Ownable` | -| `GuardianSet(address indexed guardian)` | The owner sets the guardian | +| `GuardianSet(address indexed guardian)` | The constructor names a non-zero guardian, or the owner sets one | | `InflowsPaused(address indexed by)`, `InflowsUnpaused(address indexed by)` | Inflows are paused or resumed | | `SpendsPaused(uint256 until)`, `SpendsUnpaused(address indexed by)` | Spends are paused until `until`, or resumed early | @@ -63,8 +64,8 @@ An unscreened deposit emits only `NoteAppended`. | `UserRegistered(uint256 indexed leaf, uint256 index, uint256 root)` | `addUser` appends a member. `index` is what `removeUser` takes | | `UserRemoved(uint256 indexed index, uint256 indexed leaf, uint256 root)` | `removeUser` zeroes a member's leaf | | `AuditorKeyUpdated(uint256 keyHash, uint256 keyInputPoint, uint256 reserveConfig)` | `updateAuditorKey` rotates the metadata | -| `PermissionGranted(bytes32 indexed role, address indexed account)` | The admin grants a role | -| `PermissionRevoked(bytes32 indexed role, address indexed account)` | The admin revokes a role | +| `PermissionGranted(bytes32 indexed role, address indexed account)` | The admin grants a role the account did not hold. Not emitted for a repeat grant | +| `PermissionRevoked(bytes32 indexed role, address indexed account)` | The admin revokes an explicit grant, which moves the account's permission epoch. Not emitted without a grant | | `AdminTransferStarted(address indexed admin, address indexed pendingAdmin)` | The admin nominates a successor, or cancels with zero | | `AdminTransferred(address indexed previousAdmin, address indexed newAdmin)` | The nominee accepts | @@ -72,7 +73,7 @@ An unscreened deposit emits only `NoteAppended`. | Event | Emitted when | | --- | --- | -| `SignatureRevoked(address indexed reserve, uint256 indexed leaf, uint256 deadline, bytes32 digest)` | A `USERS` holder revokes an authorisation | +| `SignaturesRevoked(address indexed reserve, uint256 indexed leaf, uint256 revocations)` | A `USERS` holder revokes every outstanding signature for a leaf. `revocations` is the new count | A successful `registerUser` emits nothing of its own. The Reserve's `UserRegistered` records it. @@ -93,10 +94,12 @@ Watch `VerifierUpdateProposed` and compare its code hash with the expected build | `amount exceeds 2^120` | The received amount, or a minimum deposit, is too large | | `Chamber: deposit below minimum` | The received amount is below the Reserve's minimum | | `transaction already exists` | The deposit's note hash is already in a tree | -| `Chamber: zero refundTo` | The `refundTo` overload with a zero address | +| `Chamber: zero refundTo` | The `refundTo` overload, or `setDepositRefundTo`, with a zero address | +| `Chamber: not pending` | `setDepositRefundTo` on a deposit the screener has decided, or an unknown one | +| `Chamber: only depositor` | `setDepositRefundTo`, or the reclaim of a pending deposit, by anyone but the depositor | | `Chamber: only reserve screener` | A screening batch holds a pending deposit the caller does not screen | | `Chamber: no queued deposit` | Reclaim of an approved, reclaimed or unknown deposit | -| `Chamber: only depositor or refundTo` | Reclaim by anyone else | +| `Chamber: only depositor or refundTo` | Reclaim of a rejected deposit by anyone else | | `Chamber: spends paused` | `handleZkp` during a spend pause | | `address input out of range` | A withdrawal address input is at or above 2^160 | | `bad commitments preimage` | The published commitments are not six in-field elements folding to the public input, or are present when it is 0 | @@ -107,6 +110,7 @@ Watch `VerifierUpdateProposed` and compare its code hash with the expected build | `transaction is spent` | A nullifier is already spent | | `private tx key used` | The identifier was filed by an earlier spend | | `Chamber: not a registered reserve` | A Reserve setter called by any other address | +| `Chamber: users root back to zero` | A users-root push that would return a non-zero users root to zero | | `invalid reserve admin` | `registerReserve` with a zero admin | | `invalid verifier` | A verifier address with no code, in the constructor or `proposeVerifier` | | `no pending verifier` | Execute or cancel with nothing proposed | @@ -130,6 +134,7 @@ Watch `VerifierUpdateProposed` and compare its code hash with the expected build | `Reserve: only pending admin` | `acceptAdmin` from anyone but the nominee | | `Reserve: missing permission` | A permissioned function without the role | | `Reserve: unknown permission` | Grant or revoke of a role that is not one of the four | +| `Reserve: zero account` | A grant to the zero address | | `Reserve: zero user leaf`, `Reserve: user leaf not in field` | `addUser` with a zero or out-of-field leaf | | `Reserve: user already registered` | `addUser` with a leaf that is in the tree | | `Reserve: no user at index` | `removeUser` past the last leaf or on a zeroed leaf | @@ -143,9 +148,8 @@ Watch `VerifierUpdateProposed` and compare its code hash with the expected build | Revert | Cause | | --- | --- | | `Registrar: signature expired` | Called after the deadline | -| `Registrar: signature revoked` | The digest was revoked | | `Registrar: missing users permission` | The signer, or the caller of `revoke`, lacks `USERS` on the Reserve | -| `Registrar: invalid signature` | The signature does not verify for the signer | +| `Registrar: invalid signature` | The signature does not verify for the signer over the current digest, including one voided by a revoke, a removal or the signer losing `USERS` | | `Registrar: bad signature length`, `Registrar: malleable signature`, `Registrar: bad signature v` | A malformed ECDSA signature from a signer with no code | ### Custom errors diff --git a/src/content/docs/contracts/roles-and-security.mdx b/src/content/docs/contracts/roles-and-security.mdx index 2ee21c8..f79a0f3 100644 --- a/src/content/docs/contracts/roles-and-security.mdx +++ b/src/content/docs/contracts/roles-and-security.mdx @@ -11,15 +11,15 @@ Each power over the contracts belongs to a named role, and most are bounded by a | Role | Held by | Can | Cannot | | --- | --- | --- | --- | -| Chamber owner | One address, set at deployment. A Safe for a live Chamber | `registerReserve`, `setGuardian`, `proposeVerifier`, `executeVerifierUpdate`, `cancelVerifierUpdate`, `transferOwnership`, `unpauseInflows`, `unpauseSpends` | Renounce ownership. Pause anything without being the guardian. Act on a Reserve after registering it | -| Guardian | One address, set by the owner. May be zero | `pauseInflows`, `unpauseInflows`, `pauseSpends`, `unpauseSpends` | Pause spends for more than 3 days, or again within 7 days of the last pause ending. Pause `reclaimDeposit` or `rejectDeposits` | +| Chamber owner | One address, set at construction. A Safe for a live Chamber | `registerReserve`, `setGuardian`, `proposeVerifier`, `executeVerifierUpdate`, `cancelVerifierUpdate`, `transferOwnership`, `unpauseInflows`, `unpauseSpends` | Renounce ownership. Pause anything without being the guardian. Act on a Reserve after registering it | +| Guardian | One address, named at construction or set by the owner. May be zero | `pauseInflows`, `unpauseInflows`, `pauseSpends`, `unpauseSpends` | Pause spends for more than 3 days, or again within 7 days of the last pause ending. Pause `reclaimDeposit` or `rejectDeposits` | | Reserve admin | One address per Reserve, named in `registerReserve` | Every permission below. `grantPermission`, `revokePermission`, `transferAdmin` | Move a Reserve's assets | | `ASSETS` | Any accounts the admin grants | `setAssetMinDeposit` | Move assets | -| `USERS` | Any accounts the admin grants, typically the registrar and its signers | `addUser`, `removeUser`, sign registrations, `revoke` a registration | Remove the last member | +| `USERS` | Any accounts the admin grants, typically the registrar and its signers | `addUser`, `removeUser`, sign registrations, `revoke` every signature for a leaf | Remove the last member. Use a signature made before it lost `USERS` | | `METADATA` | Any accounts the admin grants | `updateAuditorKey` | Read members' spends: the auditor key has no cryptographic role | | `SCREENING` | Any accounts the admin grants | `setScreener` | Decide deposits itself, unless it names itself screener | | Deposit screener | One address per Reserve, set by `SCREENING` | `approveDeposits`, `rejectDeposits` for that Reserve's pending deposits | Move funds. Stop a reclaim | -| Depositor, `refundTo` | Whoever deposited, and the address they named | `reclaimDeposit` on a pending or rejected deposit | Reclaim an approved deposit | +| Depositor, `refundTo` | Whoever deposited, and the address they named | The depositor reclaims a pending deposit, to itself, and can change `refundTo` while it is pending. Either reclaims a rejected deposit, paid to `refundTo` | Reclaim an approved deposit. `refundTo` cannot reclaim a pending one | | Note owner | A wallet or contract, for `auth_done = 0` notes | Submit the spend of its notes | Hand submission to anyone else: the Chamber requires the owner as caller | | Relayer | Anyone | Submit an `auth_done = 1` spend | Change any public input of it | @@ -35,7 +35,7 @@ The verifier decides which spends are valid, so replacing it is the most powerfu `cancelVerifierUpdate()` drops a pending proposal and emits `VerifierUpdateCancelled`. The 7-day delay is longer than the 3-day maximum spend pause, so a guardian pause alone cannot cover the whole window of a queued change. A user who can spend has time to exit first. A member removed from a Reserve with members cannot spend there, so that user has no exit until exit spends, which are **Planned**. -The code-hash check pins the verifier's code, not its behaviour. A verifier whose `verifyProof` read mutable external state would pass it, so reviewers read the proposed code, not only its hash. +The code-hash check pins the verifier's own code, not its behaviour. A proxy, or a verifier that delegatecalls or reads mutable state, could change behaviour under the same code hash. Core's operations notes say to propose only a verifier with no storage and no calls except to precompiles, as the generated `ChamberVerifier` is. ## Ownership timelock @@ -64,7 +64,7 @@ These are the trust assumptions, stated plainly. | Chamber owner | Proposes a verifier that accepts any proof. After 7 days it could authorise the withdrawal of every asset in every Reserve, because no on-chain ledger checks withdrawals against notes. The defence is the published code hash and the 7-day window to exit. The owner can also make itself guardian with `setGuardian` at once | | Guardian | Pauses deposits with no time limit. Replacing the guardian does not end the pause: the owner first rotates the guardian with `setGuardian`, then calls `unpauseInflows`. Halts all spends, withdrawals included, for up to 3 days, then must wait 7 days after that pause ends before the next | | Whoever ran the trusted setup | Could forge a proof for any public inputs, including a withdrawal, if they kept the setup's secret randomness. The keys come from a single-party setup. See [Circuits](/circuits/) | -| Reserve admin or `USERS` | Decides who can spend at a Reserve with members. Removing a member, or never registering a holder, leaves that holder's notes unspendable there. An exit spend for that case is **Planned** | +| Reserve admin or `USERS` | Decides who can spend at a Reserve with members. Any single `USERS` holder, a hot signing key included, can remove a member, which leaves that member's notes there unspendable until they are registered again. Never registering a holder does the same. An exit spend for that case is **Planned**, and core's operations notes say not to deploy to production, or not to let any Reserve remove users, until it lands | | `METADATA` | Each update replaces the shared zkState root. Proofs against the old root stay valid for 10 minutes | | `ASSETS` | Listing an asset that charges outgoing fees, rebases downward, blocklists the Reserve or is upgradeable can leave notes that claim more than the Reserve holds | | Screener | Keeps deposits out of the tree. Cannot take them: the depositor reclaims | From 0c95fe299b452eb8e09609e99a7e3b5b263f5e9c Mon Sep 17 00:00:00 2001 From: Shramee Srivastav <11048263+shramee@users.noreply.github.com> Date: Fri, 27 Nov 2026 09:22:09 +0530 Subject: [PATCH 17/17] docs(contracts): correct the fa7b92d review points The registrar entry no longer names the removed registration count, the owner can unpause inflows directly, the deploy transfer condition and permission epoch are stated exactly, and a rejected deposit is said to go to refundTo. Co-Authored-By: Claude Opus 5.5 --- src/content/docs/contracts/chamber.mdx | 2 +- src/content/docs/contracts/index.mdx | 2 +- src/content/docs/contracts/registrar.mdx | 4 ++-- src/content/docs/contracts/reserve.mdx | 4 ++-- src/content/docs/contracts/roles-and-security.mdx | 4 ++-- src/content/docs/contracts/verifier-and-deployment.mdx | 4 ++-- 6 files changed, 10 insertions(+), 10 deletions(-) diff --git a/src/content/docs/contracts/chamber.mdx b/src/content/docs/contracts/chamber.mdx index 40e1757..2c2a572 100644 --- a/src/content/docs/contracts/chamber.mdx +++ b/src/content/docs/contracts/chamber.mdx @@ -81,7 +81,7 @@ function depositRefundTo(uint256 depositId) public view returns (address); - **The screener is read at decision time.** A batch reverts with `Chamber: only reserve screener` if the caller is not the current screener of a pending deposit in it. A new screener therefore decides every deposit still waiting. With no screener set, waiting deposits can only be reclaimed. - **The queue is keyed by deposit id,** not by note hash. A note hash is public in the deposit calldata, so a hash-keyed queue would let anyone block a deposit by queueing the same note first. Duplicate notes may queue side by side, and approval admits only the first. -- **A screener cannot take funds.** It can keep a note out of the tree, but the depositor can always reclaim. +- **A screener cannot take funds.** It can keep a note out of the tree, but a pending deposit always returns to its depositor, and a rejected one to the `refundTo` the depositor chose. - `pendingDeposits(id)` returns `(depositor, status, reserve, asset, amount, noteHash)`, with status `None`, `Pending` or `Rejected`. Approval and reclaim clear the record, so `None` also covers settled and unknown ids. ## Spends diff --git a/src/content/docs/contracts/index.mdx b/src/content/docs/contracts/index.mdx index 236dbf4..36f7e04 100644 --- a/src/content/docs/contracts/index.mdx +++ b/src/content/docs/contracts/index.mdx @@ -54,7 +54,7 @@ The contracts are pinned to solc 0.8.35, the Paris EVM and 200 optimizer runs. ` { href: "/contracts/chamber/", title: "Chamber", body: "Deposits with refundTo, the asset list and minimum, screening and reclaim, handleZkp spends and the Reserve registry." }, { href: "/contracts/trees-and-roots/", title: "Trees and roots", body: "Transactions trees with rollover, fetching a note's leaves and proof, and the zkState root with its grace window." }, { href: "/contracts/reserve/", title: "Reserve", body: "The admin, the four permission roles, the users tree, the auditor key, the screener and the asset list." }, - { href: "/contracts/registrar/", title: "ManagerSigRegistrar", body: "The EIP-712 registration message, deadline, revocation, ERC-1271 and the registration-count binding." }, + { href: "/contracts/registrar/", title: "ManagerSigRegistrar", body: "The EIP-712 registration message, its leaf-nonce, revocation and signer-epoch bindings, the deadline, revoke and ERC-1271." }, { href: "/contracts/roles-and-security/", title: "Roles and security", body: "Every privileged role, the verifier and ownership timelocks, the guardian pauses and the trust each carries." }, { href: "/contracts/events-and-errors/", title: "Events and errors", body: "Every event with its parameters, what to monitor, and the revert reasons an integrator meets." }, { href: "/contracts/verifier-and-deployment/", title: "Verifier and deployment", body: "The generated ChamberVerifier, how it is replaced, and what Deploy.s.sol deploys and checks." }, diff --git a/src/content/docs/contracts/registrar.mdx b/src/content/docs/contracts/registrar.mdx index c4dc7cd..eb2661c 100644 --- a/src/content/docs/contracts/registrar.mdx +++ b/src/content/docs/contracts/registrar.mdx @@ -37,7 +37,7 @@ The registrar uses EIP-712: | `leafNonce` | `Reserve(reserve).leafNonce(leaf)` | The leaf is registered or removed | | `revocations` | `revocations(reserve, leaf)` on the registrar | A `USERS` holder calls `revoke(reserve, leaf)` | | `signer` | The account that signed | Never | -| `signerEpoch` | `Reserve(reserve).permissionEpoch(USERS, signer)` | The signer loses `USERS` | +| `signerEpoch` | `Reserve(reserve).permissionEpoch(USERS, signer)` | The signer's explicit `USERS` grant is revoked, or it hands the admin role on without one | | `deadline` | The last valid timestamp, inclusive | Never | `userKeyExchange` stays off-chain and must be a full-entropy key-exchange output, or the leaf can be brute-forced. @@ -122,7 +122,7 @@ Whoever holds a signature chooses when, before the deadline, the registration la | The registration lands | `leafNonce` moves, so the signature cannot register the leaf twice | | The member is removed | `leafNonce` moves, so no signature made before the removal can put the member back. Re-registering needs a new signature | | A `USERS` holder calls `revoke(reserve, leaf)` | `revocations` moves, cancelling every outstanding signature for the leaf, from every signer, with any deadline. Signatures made afterwards work | -| The signer loses `USERS` | `signerEpoch` moves, on a revoke of its grant or when it hands the admin role on. Granting the role again does not revive its old signatures | +| The signer's `USERS` grant is revoked, or it hands the admin role on without one | `signerEpoch` moves. Granting the role again does not revive its old signatures | | The deadline passes | The call reverts with `Registrar: signature expired` | ## Signatures diff --git a/src/content/docs/contracts/reserve.mdx b/src/content/docs/contracts/reserve.mdx index 116b186..17b2359 100644 --- a/src/content/docs/contracts/reserve.mdx +++ b/src/content/docs/contracts/reserve.mdx @@ -48,7 +48,7 @@ function hasPermission(bytes32 role, address account) public view returns (bool) Each role is held by any number of accounts. `hasPermission` is true for the admin on every role, and for any account with an explicit grant. The admin's implicit permissions cannot be revoked. An unknown role reverts with `Reserve: unknown permission`. - **No-ops are silent.** Granting a role the account already holds, or revoking one it holds no explicit grant for, changes nothing and emits nothing. A grant to the zero address reverts with `Reserve: zero account`. -- **Permission epoch.** `permissionEpoch(role, account)` moves each time the account loses the role: when its explicit grant is revoked, and, for each role it holds no explicit grant for, when it hands the admin role on. The registrar binds a signer's `USERS` epoch into every signature, so re-granting an account never revives the signatures it made before it lost the role. +- **Permission epoch.** `permissionEpoch(role, account)` moves when the account's explicit grant of the role is revoked, and, for each role it holds no explicit grant for, when it hands the admin role on. Either way, the account's signatures made before stop counting. The registrar binds a signer's `USERS` epoch into every signature, so re-granting an account never revives the signatures it made before it lost the role. | Role | `bytes32` value | Functions | | --- | --- | --- | @@ -93,7 +93,7 @@ A user removed from a Reserve with members cannot spend or withdraw there until | `registeredUserProof(index)` | The 30-element membership proof for the leaf at `index` | | `isRegisteredUser(leaf)` | Whether the leaf is currently in the tree | | `leafNonce(leaf)` | A counter that moves on every registration and removal of the leaf | -| `permissionEpoch(role, account)` | A counter that moves each time the account loses the role | +| `permissionEpoch(role, account)` | A counter that moves when the account's explicit grant is revoked, or when it hands the admin role on without one | ## Auditor key diff --git a/src/content/docs/contracts/roles-and-security.mdx b/src/content/docs/contracts/roles-and-security.mdx index f79a0f3..0afd44b 100644 --- a/src/content/docs/contracts/roles-and-security.mdx +++ b/src/content/docs/contracts/roles-and-security.mdx @@ -62,12 +62,12 @@ These are the trust assumptions, stated plainly. | Holder | Worst case if acting against users | | --- | --- | | Chamber owner | Proposes a verifier that accepts any proof. After 7 days it could authorise the withdrawal of every asset in every Reserve, because no on-chain ledger checks withdrawals against notes. The defence is the published code hash and the 7-day window to exit. The owner can also make itself guardian with `setGuardian` at once | -| Guardian | Pauses deposits with no time limit. Replacing the guardian does not end the pause: the owner first rotates the guardian with `setGuardian`, then calls `unpauseInflows`. Halts all spends, withdrawals included, for up to 3 days, then must wait 7 days after that pause ends before the next | +| Guardian | Pauses deposits with no time limit. The owner can call `unpauseInflows` itself, but a hostile guardian can pause again at once, so the owner replaces the guardian with `setGuardian` before unpausing. Replacing the guardian alone does not end the pause. Halts all spends, withdrawals included, for up to 3 days, then must wait 7 days after that pause ends before the next | | Whoever ran the trusted setup | Could forge a proof for any public inputs, including a withdrawal, if they kept the setup's secret randomness. The keys come from a single-party setup. See [Circuits](/circuits/) | | Reserve admin or `USERS` | Decides who can spend at a Reserve with members. Any single `USERS` holder, a hot signing key included, can remove a member, which leaves that member's notes there unspendable until they are registered again. Never registering a holder does the same. An exit spend for that case is **Planned**, and core's operations notes say not to deploy to production, or not to let any Reserve remove users, until it lands | | `METADATA` | Each update replaces the shared zkState root. Proofs against the old root stay valid for 10 minutes | | `ASSETS` | Listing an asset that charges outgoing fees, rebases downward, blocklists the Reserve or is upgradeable can leave notes that claim more than the Reserve holds | -| Screener | Keeps deposits out of the tree. Cannot take them: the depositor reclaims | +| Screener | Keeps deposits out of the tree. Cannot take them: a pending deposit returns to its depositor, and a rejected one to the `refundTo` the depositor chose | Further limits that hold for every user: diff --git a/src/content/docs/contracts/verifier-and-deployment.mdx b/src/content/docs/contracts/verifier-and-deployment.mdx index 2f071d0..f279b8f 100644 --- a/src/content/docs/contracts/verifier-and-deployment.mdx +++ b/src/content/docs/contracts/verifier-and-deployment.mdx @@ -71,7 +71,7 @@ The script then broadcasts, in order: 2. `new Chamber(initialOwner, verifier, GUARDIAN)`. `initialOwner` is `CHAMBER_OWNER`, unless `DEV_FIXTURES` is set or no owner is named, in which case it is the deployer. 3. `new ManagerSigRegistrar()`. 4. With `DEV_FIXTURES`: a mock ERC-20, `registerReserve(deployer, 789, 987)`, `setAssetMinDeposit(asset, 1)`, a `USERS` grant to the registrar, and a registration of `H2(deployer, USER_KEY_EXCHANGE)` signed by the deployer with a deadline one hour out. -5. `chamber.transferOwnership(CHAMBER_OWNER)`, only if an owner is named and the deployer holds the Chamber, which happens with `DEV_FIXTURES`. The owner calls `acceptOwnership()` after the 7-day delay. +5. `chamber.transferOwnership(CHAMBER_OWNER)`, only if `CHAMBER_OWNER` is named and differs from `initialOwner`. That happens with `DEV_FIXTURES` and an owner other than the deployer. The owner calls `acceptOwnership()` after the 7-day delay. Outside the development chains the Chamber is therefore built owned by its Safe, with its guardian in place, and the deployer key never holds a power over it. It writes the address book to `deployments/.json`, with the Chamber, verifier, registrar, development Reserve and mock asset addresses. These pages list no deployed addresses. @@ -83,7 +83,7 @@ The development Reserve has a fixed auditor key (789, 987), a mock asset, no scr ## After deployment -1. **Ownership.** With development fixtures and a named owner, the owner calls `acceptOwnership()` after 7 days. Otherwise the Chamber already has its final owner. +1. **Ownership.** If the script queued a transfer, the owner calls `acceptOwnership()` after 7 days. Otherwise the Chamber already has its final owner. 2. **Guardian.** If none was named at construction, the owner calls `setGuardian`. 3. **Reserves.** The owner calls `registerReserve(admin, keyHash, keyInputPoint)` for each Reserve, naming a Safe as admin. 4. **Screener first.** The Reserve admin, or a `SCREENING` holder, calls `setScreener` before any asset is listed.