diff --git a/src/content/docs/contracts/chamber.mdx b/src/content/docs/contracts/chamber.mdx new file mode 100644 index 0000000..2c2a572 --- /dev/null +++ b/src/content/docs/contracts/chamber.mdx @@ -0,0 +1,159 @@ +--- +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_, 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 + +```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 `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`). +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 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. + +## 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 setDepositRefundTo(uint256 depositId, address refundTo) 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` | 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. +- **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 + +```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. 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**. + +`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. 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 | + +`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 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/) | + +The transactions-tree and zkState views are on [Trees and roots](/contracts/trees-and-roots/). 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..ea35db5 --- /dev/null +++ b/src/content/docs/contracts/events-and-errors.mdx @@ -0,0 +1,164 @@ +--- +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, 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. 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 deposit is paid back to the depositor, or a rejected one to `refundTo`, as `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)` | 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 | + +### 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 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 | + +## 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 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 | + +## ManagerSigRegistrar events + +| Event | Emitted when | +| --- | --- | +| `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. + +## 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, 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 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 | +| `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 | +| `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 | +| `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` | `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 + +| 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 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 | +| `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 + +| Revert | Cause | +| --- | --- | +| `Registrar: signature expired` | Called after the deadline | +| `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 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 + +| 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 | +| `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 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/how-they-fit.mdx b/src/content/docs/contracts/how-they-fit.mdx new file mode 100644 index 0000000..4f0de80 --- /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 | `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 | + +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`. The depositor can reclaim a pending deposit, and a rejected one is reclaimed to `refundTo`. + + + +## 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 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)`. + +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/content/docs/contracts/index.mdx b/src/content/docs/contracts/index.mdx index e52171e..36f7e04 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. diff --git a/src/content/docs/contracts/registrar.mdx b/src/content/docs/contracts/registrar.mdx new file mode 100644 index 0000000..eb2661c --- /dev/null +++ b/src/content/docs/contracts/registrar.mdx @@ -0,0 +1,151 @@ +--- +title: ManagerSigRegistrar +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 +--- + +`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. + +Each signature names its signer, 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` | `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 leafNonce,uint256 revocations,address signer,uint256 signerEpoch,uint256 deadline)` | +| `REGISTER_USER_TYPEHASH` | `0x08047a61f834abacb9e6933736e7a17a949d36d81dc3bb91db74050ad7d1d06b` | + +| 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'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. + +`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 { keccak256, parseAbi, toHex } from "viem"; + +const reserveAbi = parseAbi([ + "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")); + +// 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: "3", + chainId: await publicClient.getChainId(), + verifyingContract: registrar, + }, + types: { + RegisterUser: [ + { name: "reserve", type: "address" }, + { name: "leaf", 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, leafNonce, revocations, signer: account.address, signerEpoch, 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` | +| `signer` holds `USERS` on `reserve` | `Registrar: missing users permission` | +| 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'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 + +| 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 | + +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] +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) external; +``` + +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). diff --git a/src/content/docs/contracts/reserve.mdx b/src/content/docs/contracts/reserve.mdx new file mode 100644 index 0000000..17b2359 --- /dev/null +++ b/src/content/docs/contracts/reserve.mdx @@ -0,0 +1,125 @@ +--- +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. 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 + +```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`. + +- **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 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 | +| --- | --- | --- | +| `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. 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 `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. + +:::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 | +| --- | --- | +| `registeredUsersRoot()` | The users root, zero while empty | +| `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 | +| `leafNonce(leaf)` | A counter that moves on every registration and removal of the leaf | +| `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 + +```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. 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..0afd44b --- /dev/null +++ b/src/content/docs/contracts/roles-and-security.mdx @@ -0,0 +1,80 @@ +--- +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 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` 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 | 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 | + +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 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 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 + +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` for the owner, and with `OwnableUnauthorizedAccount` for anyone else. + +## 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. Neither pause touches governance or registration either: `registerReserve`, every Reserve function and the registrar keep working. + +## 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. 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: a pending deposit returns to its depositor, and a rejected one to the `refundTo` the depositor chose | + +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. + +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 new file mode 100644 index 0000000..7116244 --- /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. 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. + +## 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 push emits `ZkStateRootUpdated(newRoot, previousRootExpiresAt)`. When a push leaves the root unchanged, nothing expires and `previousRootExpiresAt` is 0. + +| 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. 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..f279b8f --- /dev/null +++ b/src/content/docs/contracts/verifier-and-deployment.mdx @@ -0,0 +1,96 @@ +--- +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 + +:::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 | +| `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` | + +`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(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 `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. + +`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 derive that user's messaging keys and decrypt their spends. +::: + +## After deployment + +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. +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`. diff --git a/src/styles/diagram.css b/src/styles/diagram.css index dc2c930..a15ebf2 100644 --- a/src/styles/diagram.css +++ b/src/styles/diagram.css @@ -227,6 +227,21 @@ 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; +} +/* 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;