Skip to content
76 changes: 76 additions & 0 deletions src/content/docs/circuits/constraints-and-setup.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
---
title: Constraints and trusted setup
description: "The measured constraint count of PrimaryTransactionCircuit, the proof system it runs on, and the status of its trusted setup: single-party keys, no multi-party ceremony."
sidebar:
order: 6
---

`PrimaryTransactionCircuit` compiles to 17,318 R1CS constraints. Its proving and verifying keys come from a single-party Groth16 setup. No multi-party ceremony has been run.

## Constraint counts

Core commits the count of every circuit and gadget in `core/circuits/build/.constraint-snapshot`. The figures below are that file at core `fa7b92d`, unchanged since `cf1413d`. Core's `TestConstraintSnapshotMatchesCompile` compiles each entry that core builds and fails if any count differs from the committed file.

| Circuit or gadget | Constraints |
| --- | --- |
| `PrimaryTransactionCircuit` | 17,318 |
| `Hash2` | 217 |
| `Hash3` | 241 |
| `Hash4` | 265 |
| `MerkleHash4`, one node | 283 |
| `MerkleProofVerification`, 10 levels | 2,821 |
| `HashAndAdd`, one plaintext | 265 |
| `HashAndAdd`, two plaintexts | 265 |
| `HashAndAdd`, three plaintexts | 529 |

Each gadget is measured on a small wrapper circuit that also asserts the result equals a public input, so each gadget figure includes that one constraint. Ten Merkle levels cost 2,821, not ten times 283.

The count is the same for every spend. Dummy inputs, messaging on or off, and either `auth_done` mode change only witness values, never the circuit's shape. Each conditional rule is a `Select` or a conditional equality, and every Merkle fold is computed whether or not its result is used.

The snapshot also lists circuits built in `core-deploy/experiments`: `CompliantTransactionCircuit`, `OuterGroth16Circuit`, `OuterGroth16TwoProofCircuit` and `PrimaryChamberWrappingCircuit`. None has a proving key, a verifier or a contract path. They are not part of the protocol.

## Proof system

| Item | Value |
| --- | --- |
| Proof system | Groth16 |
| Curve | BN254, the curve of the EVM's pairing precompiles |
| Library | gnark v0.16.4 |
| Public inputs | 14 |
| Proof on-chain | Eight `uint256` words, 256 bytes, passed to `Chamber.handleZkp` as `uint256[8] proof` |

Groth16 over BN254 is not post-quantum. The circuit does no elliptic-curve operations of its own: the curve is the proof system's.

## Trusted setup

The keys come from one run of gnark's BN254 Groth16 setup, `groth16_bn254.Setup` in `core/scripts/gen`. That is a single-party setup: no multi-party computation ceremony has been run for this circuit.

Groth16 security rests on the setup's secret randomness being destroyed. Anyone who kept it could forge a proof for any public inputs, including a withdrawal, and the Chamber would accept it. With a single-party setup, users trust that one party.

:::caution[Single-party development keys]
The current keys are for development. The specification requires a multi-party ceremony before production. It is **Planned**, and runs once, on the final circuit version.
:::

## Artifacts

`core-deploy/scripts/build.sh` builds every artifact from the circuit in one pass.

| Artifact | Path |
| --- | --- |
| Constraint system, proving key | `core-deploy/dist/prover/cs`, `core-deploy/dist/prover/pk` |
| Verifying key | `core-deploy/dist/vk.json` |
| Solidity verifier | Exported by gnark, then committed as `core/contracts/src/ChamberVerifier.sol` |
| End-to-end fixture | `core/testdata/e2e_fixture.json`, a real proof the Foundry suite verifies |
| Constraint snapshot | `core/circuits/build/.constraint-snapshot` |
| Prover WASM | `core-deploy/dist/mist.wasm`, which embeds the constraint system and proving key |

`scripts/gen` skips the setup when the compiled constraint system matches the stored one byte for byte and the stored keys load, and reuses them. Otherwise it runs a new setup.

## Changing the circuit

- **`core/circuits/src` is frozen once deployed.** Any change to its constraints invalidates the keys, the verifier and the fixture. New circuits are built in `core-deploy/experiments`.
- **Moving Go code can invalidate the proving key.** gnark records solver-hint function paths in the serialized constraint system. Renaming the package that defines `hintShouldSwap` changes those bytes, even with identical constraints. Every hint is registered in `gadgets.InitHints()`.
- **A gnark upgrade changes the serialized constraint system, not the circuit.** The constraint system is re-serialized with the new gnark, the setup is skipped, and the verifier regenerates identically.
- **A new verifier is not live when it is generated.** Regenerating `ChamberVerifier.sol` changes nothing on-chain. The Chamber owner proposes the new verifier, and it can go live only after a 7-day timelock. See [Contracts](/contracts/).

The specification plans three circuit changes, each its own circuit version with its own setup and verifier: exit spends, then sequential identifiers, then a relayer fee leg. All three are **Planned**.
15 changes: 15 additions & 0 deletions src/content/docs/circuits/index.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ sidebar:
order: 0
---

import RuledIndex from "../../../components/RuledIndex.astro";

Every MIST spend is one Groth16 proof of one circuit, `PrimaryTransactionCircuit`. It is written in Go with gnark and proven over BN254.

The circuit enforces the money rules. Nothing is printed or destroyed: value is pooled and moved from one set of notes to another, or withdrawn on-chain.
Expand Down Expand Up @@ -71,6 +73,19 @@ Costs are R1CS constraints, recorded in the constraint snapshot that core commit

The specification describes three circuit changes that are not built: a relayer fee leg, exit spends that let any owner leave a Reserve, and sequential messaging identifiers. Each lands as its own circuit version.

## Detailed pages

<RuledIndex
items={[
{ href: "/circuits/spend/", title: "What a spend proves", body: "The 2-in/2-out shape, dummy notes, every rule the circuit asserts, the two authorisation modes and withdrawal binding." },
{ href: "/circuits/public-inputs/", title: "Public inputs", body: "All 14 public inputs in order, their encoding and binding, and what one spend reveals." },
{ href: "/circuits/notes-and-hashes/", title: "Notes and hashes", body: "Chamber ID, custody binding, owner commitment, note hash, nullifier and the Poseidon2 parameters." },
{ href: "/circuits/merkle-trees/", title: "Merkle trees", body: "The 4-ary HM4 tree, prover-ordered insertion, the 30-element proof and the three trees that use it." },
{ href: "/circuits/reserve-messaging/", title: "Reserve messaging", body: "The zkState leaf, the users tree, the Hash-and-Add keystream, privateTxKey and the six commitments." },
{ href: "/circuits/constraints-and-setup/", title: "Constraints and trusted setup", body: "The measured constraint count, the proof system and the single-party setup." },
]}
/>

## Source

The circuit is `core/circuits/src/primary.go`. Its Poseidon2 and Merkle gadgets are in `core/circuits/gadgets`, and the native reference implementations in `core/circuits/lib`. The [specification](https://github.com/mistcash/mist/blob/main/spec/04_circuit_architecture.md) defines each check.
97 changes: 97 additions & 0 deletions src/content/docs/circuits/merkle-trees.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
---
title: Merkle trees
description: "The 4-ary HM4 Merkle tree behind the transactions, zkState and registered-users trees: the node hash, prover-ordered insertion, the 30-element proof and its cost."
sidebar:
order: 4
---

import Figure from "../../../components/diagrams/Figure.astro";
import Cell from "../../../components/diagrams/Cell.astro";

MIST's three Merkle trees share one shape: depth 10, four children per node, and a node hash that sorts its children. A membership proof is 30 field elements, three siblings for each level.

## Node hash

`HM4` hashes four children, with zero standing for a missing child. Sort them so that `a <= b <= c <= d`:

- If `a`, `b` and `c` are all zero, the node is `d`. A node with one non-zero child passes it through unchanged, and a node with none is zero.
- Otherwise the node is one evaluation of the width-4 Poseidon2 permutation over `(a, b, c, d)`, read as `state[0] + state[1]`.

Each node costs at most one permutation. `HM4(x, 0, 0, 0) == x`, so a tree with few leaves needs no padding levels: the levels above its height pass the value through to depth 10. An empty tree's root is zero.

## Prover-ordered insertion

In the circuit, each level takes the running value and three siblings `w0 <= w1 <= w2` from the proof. Three conditional swaps place the running value among them before the permutation runs.

<Figure
label="One Merkle level in the circuit. First, three siblings from the proof in ascending order. Second, three conditional swaps insert the running value among them, in sorted position for an honest prover. Third, the four values hash to the parent node, or pass a lone non-zero child through."
caption="One level of the fold. The coral cell is the running value, inserted among its siblings. Ten levels of this make one membership proof."
>
<ol class="mist-moves">
<li class="mist-move">
<p class="mist-label">1 Siblings</p>
<div class="mist-move__stage">
<Cell state="recorded" />
<Cell state="recorded" />
<Cell state="recorded" />
</div>
<p class="mist-move__note">Three siblings from the proof, ascending. A missing child is zero.</p>
</li>
<li class="mist-move">
<p class="mist-label">2 Insert</p>
<div class="mist-move__stage">
<Cell state="recorded" />
<Cell state="followed" />
<Cell state="recorded" />
<Cell state="recorded" />
</div>
<p class="mist-move__note">Three swaps, each on a boolean the prover supplies, place the running value.</p>
</li>
<li class="mist-move">
<p class="mist-label">3 Parent</p>
<div class="mist-move__stage">
<Cell state="recorded" />
</div>
<p class="mist-move__note">One permutation, read as state 0 plus state 1. The parent is the next level's running value.</p>
</li>
</ol>
</Figure>

Each swap bit comes from a solver hint that compares the running value with the sibling, so an honest prover inserts it in sorted position. The circuit constrains each bit only to be boolean. Membership still holds only for the sorted order: the Chamber, each Reserve and the native Go tree build every node over sorted children, so any other order hashes to a different parent and the fold misses the root.

## Proof shape

A proof has 10 levels of three siblings, ascending within each level, so 30 elements. Missing children are zero, and every level above the tree's height is all zeros.

| Source | Returns |
| --- | --- |
| `Chamber.merkleProof(index)` | The 30-element proof for global note index `index`, against the current root of that note's transactions tree |
| `Reserve.registeredUserProof(index)` | The 30-element proof for the user at `index`, against the Reserve's users root |
| `core/circuits/lib/merkle` | The native Go tree, `NativeHM4Tree`, with `NativeHM4ProveAt(idx)` |

The contracts return a flat array, level by level. The circuit takes the same values as `[10][3]`.

## Properties

- **Position independence.** Because `HM4` sorts its children, a proof shows that a leaf is in the tree, not where. Nothing in the protocol depends on a leaf's position today. A future rule that does must bind the index itself.
- **Pass-through.** A node's value is a valid leaf at any depth, the root included. This is not exploitable: spending a note needs a Poseidon2 preimage of a note hash, and the fixed 30-element proof pins the depth for the circuit.
- **Updates.** Zeroing a leaf, which is how a Reserve removes a user, recomputes its ancestors over the same zero-padded groups. The result equals a fresh tree built over the same leaves, with that one set to zero, only because `HM4` sorts.

## The three trees

| Tree | Held by | Leaf | Capacity | Roots a spend may use |
| --- | --- | --- | --- | --- |
| Transactions | The Chamber, one tree per `treeId` | A note hash | 4^10 = 1,048,576 per tree. When a tree fills, the next one opens | Every root any transactions tree has had |
| zkState | The Chamber | `H3(reserve, reserveConfig, usersRoot)`, one per Reserve | 4^10 Reserves | The current root, or one superseded less than 10 minutes ago and not retired by a Reserve's first registration |
| Registered users | Each Reserve | `H2(owner, userKeyExchange)`, one per member | 4^10 leaf slots, removed users included | Proven against the users root inside the Reserve's zkState leaf |

Both inputs of a spend share one `transactions_root`, so two real notes in different transactions trees cannot be spent together.

## Cost

| Operation | Constraints |
| --- | --- |
| One node, selector included | 283 |
| One membership lookup, 10 levels | 2,821 |

Counts are from core's committed constraint snapshot. Each is measured on a wrapper circuit that also asserts the result equals a public input, so each includes that one constraint: ten levels cost 2,821, not ten times 283. Every spend runs four folds, whatever its inputs: one per input note, one for the Reserve's zkState leaf and one for the sender's users leaf. A dummy's fold and the users fold at a Reserve without members are computed and their results ignored, so the circuit's shape never changes.
97 changes: 97 additions & 0 deletions src/content/docs/circuits/notes-and-hashes.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
---
title: Notes and hashes
description: "The MIST note model: Chamber ID, custody binding, owner commitment, note hash and nullifier, the two owner types, and the Poseidon2 parameters behind every hash."
sidebar:
order: 3
---

A note is a commitment to an owner, an asset and an amount, held under one Chamber and one Reserve. Every hash in it is Poseidon2 over the BN254 scalar field, and the circuit, the native Go helpers and the Solidity library compute the same values.

## Fields

| Field | Contents |
| --- | --- |
| `chamber` | The Chamber ID, not the bare Chamber address |
| `reserve` | The Reserve contract address |
| `blinding` | A random nonce, the note's spending secret |
| `owner` | A wallet or contract address, or a MIST Address |
| `asset` | The ERC-20 contract address |
| `amount` | Below 2^120. The circuit range-checks it and `Chamber.deposit` requires it |

Addresses enter the field as left-padded big-endian `uint160` values, with no reduction. A 160-bit value is smaller than the field, so nothing wraps.

## Chamber ID

Two chains can host a Chamber at the same address, so a note names its Chamber by ID:

```text
chamber = H2(chainId, chamberAddress)
```

The Chamber computes it in its constructor and stores it as the immutable `chamberId`. The chain ID is frozen at deployment.

## Note hash and nullifier

```text
custody = H2(chamber, reserve)
ownerCommitment = H2(blinding, owner)
noteHash = H4(custody, ownerCommitment, asset, amount)
nullifier = H4(custody, H2(blinding + 1, owner), asset, amount)
```

- **Custody binding.** `H2(chamber, reserve)` locks the note to one Chamber and one Reserve, the only instances that can move it. In the circuit, `chamber` and `reserve` are private inputs of the whole spend, and the binding is computed once for all four notes.
- **Owner commitment.** `H2(blinding, owner)` hides the recipient. Whoever creates a note needs only the commitment, never the recipient's blinding or owner. `Chamber.deposit` takes it as an argument and requires it to be below the field order. The circuit takes each output as an owner commitment and an amount.
- **Note hash.** The leaf appended to the transactions tree. `Chamber.hashNote(chamber_, reserve_, ownerCommitment_, asset_, amount_)` computes it on-chain. A deposited note hashes the amount the Reserve actually received, not the amount requested.
- **Nullifier.** The note hash with the blinding increased by one. A spend publishes it, and the Chamber records it as spent.

The nullifier does not use the MIST Address secret. Two consequences follow:

- **Anyone who knows a note's fields can watch for its spend.** That person can compute the nullifier, but spending still takes the owner's secret or the owner as caller. A sender who built the owner commitment from the recipient's blinding and owner knows every field. The nullifier stays private from the sender only when the recipient picks the blinding and hands over a finished owner commitment.
- **Sequential blindings link notes.** A note's nullifier equals the hash of a note with blinding `b + 1` and otherwise the same fields. A wallet that derives blindings in sequence for repeated notes with the same owner, asset and amount links them. Derive each blinding independently.

## Owners

| Owner | Value | Spent with | Authorised by |
| --- | --- | --- | --- |
| Wallet or contract address | The `uint160` address | `auth_done = 0` | The Chamber, which requires the owner as caller |
| MIST Address | `H2(p, 0x6f776e6572)`, with `p` a secret | `auth_done = 1` | The proof, as knowledge of `p` |

The keyword `0x6f776e6572` is the ASCII string "owner" (478745093490). A MIST Address is a hiding commitment, so publishing it reveals nothing about `p`. [What a spend proves](/circuits/spend/#authorisation) gives both modes in full.

## Poseidon2

Every width uses the same parameters: the BN254 scalar field, 8 full rounds, 56 partial rounds and S-box exponent 5. The round counts are set in `core/circuits/gadgets/gadgets.go` and `core/circuits/lib/hash/poseidon2.go`. The exponent is gnark-crypto's fixed S-box degree for BN254.

Each function feeds an input forward into one element of the final permutation state. The width-4 permutation serves three of them, `H4`, `HM4` and the keystream, told apart only by how the output is read:

| Function | Width | Output | Constraints |
| --- | --- | --- | --- |
| `H2(a, b)` | 2 | `state[1] + b` | 217 |
| `H3(a, b, c)` | 3 | `state[0] + a` | 241 |
| `H4(a, b, c, d)` | 4 | `state[0] + a` | 265 |
| `HM4`, the Merkle node | 4 | `state[0] + state[1]`, over sorted children | 283, selector included |
| Keystream block | 4 | `state[j + 1] - k`, for `j = 0, 1, 2` | 265 per block |

Constraint counts are from core's committed constraint snapshot. Each is measured on a small wrapper circuit that also asserts the result equals a public input, so each figure includes that one constraint.

The output read is the only thing that separates the three width-4 uses: there is no extra input, domain tag or round. The [specification](https://github.com/mistcash/mist/blob/main/spec/01_system_overview.md) gives the argument for why that is enough.

`Fold2` reduces a vector to one element by chaining `H2` from the left: `Fold2(v) = H2(... H2(H2(v0, v1), v2) ..., vn)`.

## Where each hash is used

| Value | Hash |
| --- | --- |
| Chamber ID | `H2(chainId, chamberAddress)` |
| Custody binding | `H2(chamber, reserve)` |
| Owner commitment | `H2(blinding, owner)` |
| Note hash, nullifier | `H4(custody, ...)` |
| MIST Address | `H2(p, 0x6f776e6572)` |
| Reserve config | `H2(keyHash, keyInputPoint)` |
| zkState leaf | `H3(reserve, reserveConfig, usersRoot)` |
| Registered-user leaf | `H2(owner, userKeyExchange)` |
| Messaging key | `H2(userKeyExchange, keyIndex)` |
| `auditor_commitments` | `Fold2([privateTxKey, c0, c1, c2, c3, c4])` |
| Merkle node | `HM4` |

[Merkle trees](/circuits/merkle-trees/) covers `HM4`, and [Reserve messaging](/circuits/reserve-messaging/) the keystream.
Loading