Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

The LEZ guide

The Logos Execution Zone is a programmable chain with two kinds of accounts, public and private, that programs can treat identically in the sense that privacy becomes a property of the transaction, not of the program (What LEZ is).

This guide follows the dev branch at the commit named in Sources. That commit is after the v0.4.1 release, so the guide covers the v0.4.x line the live testnet runs plus a few changes not yet released. A legacy testnet still runs the v0.2.4 line and its older whole-account interface; the automated market maker catalog entry describes a program deployed there.

PartForWhat it gives you
I. Understand LEZeveryonewhat this is and whether it fits your problem
II. Use LEZend usersthe wallet: accounts, transfers, reading state, collecting messages
III. Build on LEZprogram authorsfrom an empty shell to a deployed program, then the full programming model
IV. Privacy and patternsprogram authorswhat a private transaction reveals, what cannot be done privately, and the patterns designs are built from
V. The catalogprogram authorsworked designs, and which public and private combinations each one supports
VI. Integrate with LEZclient and service developersthe RPC surface, finality, the wallet library, the C ABI, events, running a node
VII. Reference and internalsanyone checking a factthe guest API, the derivations and constants, and how the engine and circuit work

New to LEZ: read Part I in order. To write a program, the quickstart gets something running and Part III explains it. To check a fact, Part VII has the tables.

Read this before designing anything

The privacy chapters say what a private transaction publishes and what cannot be done privately at all. Several limits are structural and shape the catalog’s designs. A design that ignores them can pass its tests and still leak or stall in use.

Conventions

LEE and LEZ are defined in What LEZ is, and an actor (an account and a program) in The model in one page.

Code in Parts I to III and VII is taken from the repository or matches it. Code in the catalog is illustrative: it follows the real API but has not been built or tested.

Repository paths are relative to the root of logos-blockchain/logos-execution-zone. Code in another repository is written as <org>/<repo>: <path>.

Amounts are u128 unless a program says otherwise. Timestamps are Unix milliseconds. Block ids start at 1.

What LEZ is

The Logos Execution Zone is a privacy-agnostic programmable chain where a program is by default oblivious to the privacy setting of an account it deals with.

The unusual part

On most chains, privacy belongs to a particular application built for it (a mixer, a shielded pool, a dedicated private token), and other applications reach it only through that one.

On LEZ, privacy, by default, is a property of the account and the transaction, not of the program. A program is a RISC Zero guest binary that receives a message, sees one account’s state, and returns a new state. The same compiled binary runs on the sequencer when the account is public, and inside the owner’s own prover when the account is private.

One program can serve both: a token that works for public balances may work for private ones, and a multisig with public members may work with hidden ones. The catalog explores that property, including where it runs out.

What it costs

Private execution happens on your machine. Proving a transaction can take a significant amount of time depending on your machine. You pay for privacy in latency, and a private transaction also pays a fee: from a reserve proven inside it, or through a declaration by one of its public signers (Private fees).

Private state is hidden on LEZ. The chain stores a commitment and an encrypted note rather than your plaintext data, so a private account reads as uninitialized until the wallet has scanned the chain for notes it can decrypt (Reading the chain).

Privacy restricts how users may interact with foreign accounts. A program cannot read a private account it does not own. A public program cannot react to private state unless the private side chooses to tell it. What you cannot do privately is the full list.

Where it sits

LEZ is a zone on the Logos blockchain, which describes itself as “a privacy-preserving, censorship-resistant blockchain for decentralized network states”.

A zone is a channel on that chain. The LEZ sequencer produces zone blocks and inscribes them into its channel. Deposits cross through the same channel. Withdrawals are disabled in this version: the bridge program rejects them. Finality has the mechanism.

The sequencer is a committee of staked keys, which on a local devnet is a single key. A key whose stake in the stake program reaches the channel’s minimum is a member, and members take turns inscribing blocks (Sequencer stake). Every node re-executes final blocks, and a sequencer reports the signer of one that fails through the producer’s fault (Finality). A Slash approved by two thirds of the committee, never fewer than two, burns a key’s whole stake; the stake program checks only the approvals, not the offence (slash_approval_threshold, lez/programs/sequencer_stake/core/src/lib.rs). Members gossip transactions to each other to save time, and pass slash and upgrade approvals the same way. A node that loses gossip keeps following and producing blocks from the L1 alone, but cannot gather other members’ slash approvals (Running a node).

LEE, the Logos Execution Environment, is the state machine, the program interface and the privacy circuit: the part that decides what a program is and what a proof must show. LEZ is the zone built on it: the sequencer, the wallet, the indexer, and most of the builtin programs. Three builtins sit in LEE instead, because the engine itself needs them: the native token (lee/state_machine/core/src/native_token.rs), the program loader (lee/program_loader), and the signature program, which has no handler and holds a commitment to each account’s signing key (lee/state_machine/core/src/signing_key.rs). Program authors work almost entirely with LEE types, from the lee_core crate.

Proofs are generated with RISC Zero. A program is a RISC-V binary for the zkVM, identified by an image id that is a hash of its bytecode unless hardcoded by the protocol for native programs.

What this guide will not tell you

Where this guide and the code disagree, the code is right; Part VII names the source files so you can check.

It does not cover the L1’s validators, staking or economics.

Where to go

The model in one page is next. The introduction routes you by what you came for: the wallet, a program, or a client.

The model in one page

An account is a nonce plus a map from program account ids to byte strings. Each entry in that map is the state of one actor: a pair of an account and a program. “Alice’s token actor” means the token program’s state on Alice’s account.

A transaction delivers one root message to one actor. The program’s handler runs with that actor’s state and the message, and returns an optional new state, synchronous and asynchronous messages, events and validity windows (one over block heights, one over timestamps).

A handler sees its own state on one account, plus the message, its sender and the grants it carries, and nothing else. To affect another actor it sends a message, and the receiver decides what to do with it.

A SyncMessage is delivered inside the same transaction, and if anything in it fails the whole transaction fails. An AsyncMessage to an actor the transaction can run (a public actor it declares, or one of the submitter’s own private actors when the submitter asks for it) is also delivered in the transaction, and if it fails the whole transaction fails (AsyncMessage). An AsyncMessage to another private address is stored on chain for its owner to collect later, in their own transaction, with their own proof.

Handlers of public actors run on the sequencer. Handlers of private actors run on the owner’s machine inside a zero-knowledge proof, and the sequencer checks the proof and runs the public side of the messages that crossed, without seeing the private state.

A program, by default, does not learn whether the accounts it was given are public or private. The same bytecode runs either way. Privacy, in the default case, is a property of the transaction, not of the program.

Properties

Four properties follow, and the designs in the catalog rest on them.

Public and private actors work together: since a program can serve both kinds of account, its public and private actors can exchange messages. A private balance pays a public pool in one transaction, and a public treasury pays a private member at a registered address through a stored message, without a separate shielded pool or a bridge between the two.

A program only reasons about itself, so you can audit a handler on its own, given which senders and reply formats it trusts.

A message can wait. An AsyncMessage addressed to a stranger’s private account sits on chain until its owner collects it, so a public program can pay a private person who is offline.

A private actor’s message is backed by its code: the proof covers the handler that produced it, so a public actor of the same program can trust the message as a statement about state it cannot see.

Terms used throughout

A declared actor is one the transaction lists as a public actor its execution may reach. The engine runs a public handler only for a declared actor (Declaring actors).

Settlement is the sequencer applying a transaction to live state in a block: its public handlers run, a private transaction’s private actions are recorded, and the fee is charged. Settlement decides whether a transaction takes effect; finality decides whether that can still be undone.

A witness is the evidence that a transaction may use an account. For a public signer it is a signature and a commitment to the account’s next key, carried in the transaction (Keys, nonces and rotation). For a private account it is what the prover holds to use the account (its key, the proof the account’s current version is on chain, the address openings it presents), an input to the proof that never leaves the prover’s machine (Authorization).

A fee fallback is a fee-only version of a private payer’s action, proven alongside the real one. If the public part fails at settlement, the sequencer applies it instead, so the fee is still paid. A proof carries one only when the payer held the whole reserve before the transaction ran; without it, and without a public signer paying, a failed public part leaves the transaction dropped and unpaid (Private fees).

To shield is to move native tokens from a public account into a private one; to deshield is the reverse. These are wallet words: to the protocol both are private transactions.

A mention is a wallet library term, not a protocol one: one account a client lists for a private transaction, with the program whose actor on it is meant and whether the account authorizes (Submitting a private transaction).

Where to go from here

Build on LEZ starts from an empty shell and ends with a program you wrote running on chain. Accounts, actors and state covers this page at full depth.

Public and private, in plain terms

Every account on LEZ is one or the other, chosen when it is created.

A public account

Its contents (balance, every program’s state on it, nonce) are on chain in the clear, readable by anyone. Reading one is a query:

wallet account get --scope all --account-id Public/<id>

Transactions touching it are executed by the sequencer. Every user transaction pays a fee, charged per transaction rather than per account (Fees lists the few exceptions).

A private account

The chain does not hold its plaintext contents. It holds a commitment, which is a hash, and an encrypted note that only the owner’s keys can open.

So your wallet does not read the account directly: it scans the chain for notes it can decrypt and builds a local picture:

wallet account sync-private
wallet account get --scope all --account-id Private/<id>

Run them the other way round and the wallet prints its last record, which may be stale, or Account is Uninitialized for an account it holds keys for but has no state for yet (Reading the chain).

Transactions touching a private account are executed on your own machine and proved there. The sequencer verifies the proof without learning the private information used in it.

What a private transaction still shows

What a private transaction reveals takes each published field in turn. In short:

HiddenPublished
the contents of a private accountthat a transaction happened, and when
the ids of private accounts, unless the transaction names one (The boundary)every effect on a public account, in full: amounts, recipients, everything
which private accounts a transaction touchedthe number of private actions (accounts, collected messages, an outside fee payer), padded by the reference wallet (Private actions)
what private handlers received and repliedwhich programs ran, by default (Program claims)
messages between private actors delivered inside the transactionthe validity windows the handlers set (Validity windows)
events from private handlers, which are droppedeach stored message, sealed so only its recipient can open it, or in the clear if the sender chose (Sealed async messages)
how much private work the proof coveredthe fee, as a reserve or a public signer’s declaration, priced from the transaction’s size, a flat verification charge and its public work, not its private work
a public refund account, if the transaction names one

A private account’s id appears only if the transaction puts it there: a private sender that shows its real id instead of a blinded address, a message published in the clear and addressed to the real id, or a recovery binding registered for it. Otherwise the records a private account leaves (a nullifier, a commitment, an encrypted note) carry no id and do not link to the account or to each other.

The largest leak in practice is a public effect: if a private transaction pays a public address, the amount and the recipient are public.

The reference wallet shows each private sender under a fresh blinded address for every message and grant, so they do not look related. Two exceptions: grants for an actor the client gave a blinded address use that address, and the fee payer’s native balance keeps one address per transaction, the one its refund is bound to.

Outside the transaction itself: timing, how a transaction correlates with others, who submitted it at the network level, and any pseudonym reused twice.

What follows from the model

These follow from the model, except the limit on native credits per proof below, which is the reference wallet’s.

Nobody can make a private actor act: advancing a private account needs a proof only its key holders can produce. A program cannot reach into a private account on a schedule, on a trigger, or on anyone else’s transaction.

A message to a stranger’s private actor must be stored rather than delivered, since the sender cannot run the recipient’s handler. It waits on chain until the owner collects it with their own transaction and proof; if they never do, nothing goes back to the sender (A stored message is never returned).

One transaction can collect several stored messages. With the reference wallet, a proof clears up to five native credits (stored transfers of the native token), and each other message costs a proof of its own (Collecting costs a proof).

Events from private handlers are dropped, so if anything off chain must learn a fact, a public actor has to announce it.

The mistake to avoid

“Is this program private?” has no answer. The same program can serve both kinds of account, so privacy is decided per transaction, by which accounts it touches, and by the client that builds it.

A design can hold all its state privately and still leak everything through its shape. The common failure is deriving an address deterministically from a value that some specific party already knows, then treating the address as private. The issuer of a credential knows which accounts it issued to. The organizer of a vote knows the option keys they published. In both cases a deterministic derivation turns “private” into “recognizable by exactly the party the design was hiding from”.

Setting up the wallet

The wallet is the command-line client for LEZ: it holds your keys, builds and signs transactions, proves private ones, and reads state back.

Before you start

Clone the repository and work from its root:

git clone https://github.com/logos-blockchain/logos-execution-zone
cd logos-execution-zone

Install Rust, the RISC Zero toolchain and the system packages listed in the quickstart’s What you need; Docker is needed to build programs and to run the L1 node of the full stack, not for the standalone sequencer.

The transcripts in this part come from a local devnet. The standalone sequencer in Start a node is enough to follow them; Running a node has the full stack with the L1 node and indexer.

Your first tokens come from:

  • on a local devnet, its genesis (lez/sequencer/service/networks/local.json), which funds two public accounts whose secrets the wallet-import-test-accounts recipe in the Justfile imports (Making accounts);
  • on the public testnet, the L1: mint tokens on the L1 with the blockchain wallet in Logos Basecamp, then bridge them to LEZ with that wallet’s channel deposit into the LEZ testnet channel. The deposit’s metadata names the public LEZ account to credit, as the base58 of a Borsh-encoded DepositMetadata carrying the account’s initial key (lez/programs/bridge/core/src/deposit.rs), and the bridge credits it once the deposit is final on the L1. Check the metadata before sending: a deposit whose metadata does not decode is never credited, and with withdrawals disabled those tokens cannot be recovered. The LEZ wallet has no deposit command, and the repository has no faucet. Someone who already holds LEZ tokens can also send you some: give them the initial key wallet account new public printed, which they pass as --to-initial-key (Sending), or the public keys show-keys prints for your private account.

Installing and first run

cargo install --path lez/wallet --force --locked

The wallet keeps its configuration (wallet_config.json) and keys (storage.json) in the directory LEE_WALLET_HOME_DIR names, or in ~/.lee/wallet when it is unset. Give each network its own home:

export LEE_WALLET_HOME_DIR=~/lez-wallets/devnet

Make pointing it at a node the first wallet command you run. With no configuration it writes one pointing at https://testnet.lez.logos.co, right for the public testnet and wrong for a local devnet:

wallet change-network local

local is http://127.0.0.1:3040, testnet is the public one, and anything else is taken as a sequencer URL. just run-wallet <args> instead sets LEE_WALLET_HOME_DIR to the repository’s debug configuration in lez/wallet/configs/debug, which already points at the local node. A new wallet starts its private sync at the tip of the network it is set up against. When change-network is the first command, it is applied before that setup, so the cursor starts at the tip of the node you named. On an existing wallet change-network does not move that cursor, which stays at the old network’s height; Reading the chain says how to scan again. Then check it can reach the node:

wallet check-health

The first command you run, change-network included, sets the wallet up: it asks for a password twice (or takes LEE_WALLET_PASSWORD when that is set, even to an empty value) and prints a recovery phrase, the only way to restore the accounts generated from it (not imported keys, groups or labels): write it down. A shared account’s keys come from a random group secret instead, so keep each group secret too (What the owner must keep). An empty password leaves the store unencrypted, fine for a local devnet; a non-empty one is required by every later command, or read from LEE_WALLET_PASSWORD.

The commands

CommandWhat it does
wallet accountcreate, import, label, list, read and sync accounts, resolve a label to its id, and show an account’s keys
wallet auth-transfersend native tokens, at any public/private combination
wallet chain-infocurrent-block-id, block, transaction
wallet pendinglist and receive messages waiting in a mailbox
wallet program-loaderdeploy and update programs
wallet programsend one public transaction to any program, naming the actors it touches and which of them the signature authorizes. There is no command for a private call to an arbitrary program: that needs code (Sending a message)
wallet bridgewithdraw to L1. Withdrawals are disabled in this version: the bridge program panics with Withdraws are disabled in the current version of LEZ
wallet groupgroup keys: new, list, remove, invite, join, new-sealing-key
wallet keycardKeycard signing, not in the default build and not usable in this version: a Keycard holds one fixed key, while the wallet signs each nonce of a public account with a new one (Keys, nonces and rotation)
wallet configget, set and description of configuration fields
wallet change-networkpoint the wallet at a different node
wallet set-passwordset, change or remove the storage password
wallet restore-keysrestore keys from a mnemonic at a given depth
wallet check-healthconfirm the wallet reaches the node and its privacy circuit id matches the node’s

Eight flags are global and work on any subcommand. The fee flags act on the fee model in How fees are priced:

FlagWhat it does
--dry-runsimulate the transaction the command would send and report its cost instead of sending it (what it checks)
--gas-limit GASdeclare this execution gas limit on a public transaction, instead of the cycles a simulation measures plus the configured margin
--max-fee AMOUNTcap a public transaction’s fee, instead of its reserve at the headroom’s base fees. The sequencer rejects a cap below what a dry run reports
--tip AMOUNTtip on top of the base fees, declared on a public transaction or paid inside a proof
--fee-headroom BLOCKSprice the fee for base fees that rise as fast as allowed for this many blocks after the current ones, instead of the configured headroom (5 by default)
--fee-payer ACCOUNT_ID_WITH_PRIVACYpay a private transaction’s fee from this account: Private/<id> for an owned private account, whether or not the transaction mentions it, or Public/<id> for a public account the transaction already signs with
--refund-to ACCOUNT_IDrefund a private transaction’s fee surplus to this public account instead of privately to the payer (Private fees)
--allow-revertsend a public transaction even though its simulation reverts; it still pays its fee. The simulation misses validity windows

--fee-payer needs the privacy prefix (Public/ or Private/), while --refund-to takes a bare base58 public id without one. --refund-to is meant for a transaction that already credits that account publicly, such as a deshield (shield and deshield): any other target links the transaction to it, which the wallet logs as a warning (shown only with RUST_LOG=warn or a more verbose level, since the wallet logs errors alone by default).

On a public transaction, pinning both --gas-limit and --max-fee (without --dry-run) skips the simulation, so the wallet checks neither the fee nor whether the action reverts.

wallet help, and --help on any subcommand, prints the authoritative arguments. Shell completions are in the repository’s completions/ directory.

Where to go next

Accounts and transfers creates accounts and moves tokens between them, Reading the chain gets state back out, and Pending messages collects a message someone sent you while you were offline.

To write programs rather than use them, skip to the Quickstart.

Accounts and transfers

The transcripts below were captured on a local devnet (Before you start) at d81e637aa, except the public dry run, captured on a standalone sequencer. Your ids and heights will differ, and the heights here jump where the session paused. Three things are shortened: the Transaction data is … line every send prints (tens of thousands of characters; SUPPRESS_VERBOSE_PRINTS turns it off), viewing keys (1184 bytes, cut with …), and repeated account ids in commands (7VDm7YRP...). The first-run password prompts and recovery phrase are left out.

Making accounts

A wallet with no store sets one up on the first command, and starts synced at the chain tip rather than at genesis:

$ wallet account import public --secret 10a26a9aec7d34b82364eeae45c5294dbb0a764b000b94eeb9b58511dc487c4d
Persistent storage not found, need to execute setup
New wallet starts synced at block 22
Imported public account Public/7VDm7YRPvimbZgCzuFqCGf6RwPsTV3XY5W9DzT71oain

That secret is one of the two the wallet-import-test-accounts recipe in the Justfile imports. It changes with the devnet’s genesis, so take it from the recipe. On a local devnet it is where your first tokens come from. Nothing before block 22 is scanned; Reading the chain covers the ways back.

$ wallet account new public --label alice
Generated new account with account_id Public/2wVCroZMktk9AiXnoum4zhZABxrGrFNfH2sMbQPigMUK at path /0
With initial key 000b801cd3c10935026199bfe4714b96c7835626a6c51ae166bcbff30af6ca37de

$ wallet account new private --label bob-private
Generated new account with account_id Private/YeJGB32itVaAGNBDWRCWsbYDgYkjuM8ck16SaRJDtKq at path /0
With npk 7972829f024b2d557461b1c9327af5df3cc1b722da26dc44749c5eca80e39690
With vpk 9cf468cf5c4cd2014226e804179…

$ wallet account list
Public/7VDm7YRPvimbZgCzuFqCGf6RwPsTV3XY5W9DzT71oain
/0 Public/2wVCroZMktk9AiXnoum4zhZABxrGrFNfH2sMbQPigMUK [alice]
/ Public/CQTkqXve5aZDXdS3SaLJeYXTWCvbtFTNmYw7Ube4eDjA
/ Private/93tFbzLqybuNUAsEE9TajiZ9F2pjnPVdizmiuWziyDCK
/0 Private/YeJGB32itVaAGNBDWRCWsbYDgYkjuM8ck16SaRJDtKq [bob-private]

The leading token is the derivation path the account came from, blank for an imported key. A label is unique across the wallet and works in --from, --to and --account-id, but not in --fee-payer or --refund-to, which take ids (global flags). A public account’s id is derived from its initial key, the key for nonce 0; the wallet signs each later nonce with a new key from the same secret (Keys, nonces and rotation). The first payment to an unused public account must carry that key: the wallet attaches it for an account it holds, and --to-initial-key attaches it for someone else’s (Admission).

Sending

wallet auth-transfer send --from <account> --amount <n> <recipient flags>
RecipientFlagWhat it takes
Any public account, or a private one this wallet owns--toa base58 account id with its Public/ or Private/ prefix, or a label. A Public/ id needs no ownership; a Private/ one does, because the wallet has to prove the account’s current state, which only its keys open
Someone else’s private account--to-npk and --to-vpkthe nullifier public key as 32-byte hex, and the ML-KEM-768 viewing key as hex, 1184 bytes
Someone else’s private account, from a file--to-keysa path to a keys file holding npk and vpk on separate lines. Replaces the two flags above
A public account that has never been used--to-initial-keythe recipient’s initial key

--from and --amount are always required. --to-keys conflicts with --to-npk and --to-vpk, and --to-initial-key conflicts with all the others, both enforced by the argument parser. --to together with --to-keys, or with both --to-npk and --to-vpk, fails later, when the recipient is resolved: Provide only one variant: either account account_id of receiver or their public keys. Use --to for an account this wallet owns, and the keys for anyone else’s.

--to takes a value starting m/ as a Keycard key path, which this version refuses, and anything that is not a prefixed id as a label, so a /0 copied out of account list fails with No account found for label `/0`.

Pricing it first

Any command takes --dry-run, which simulates and reports instead of sending. For a public transaction:

$ wallet --dry-run auth-transfer send --from Public/7VDm7YRPvimbZgCzuFqCGf6RwPsTV3XY5W9DzT71oain --to alice --amount 500000
Dry run: nothing sent
  fee payer:        7VDm7YRPvimbZgCzuFqCGf6RwPsTV3XY5W9DzT71oain
  declared gas:     0
  metered cycles:   0
  wire bytes:       621
  base fees:        exec 8 / stor 8 (height 3)
  fee at head:      4968 (tip 0)
  reserve at head:  4968 (max fee 8073)
  signer authority: 7VDm7YRPvimbZgCzuFqCGf6RwPsTV3XY5W9DzT71oain under 11111111111111111111111111111111
  action:           applies

action is the line to read: it says applies, or REVERTS with a reason, and a reverting transaction still pays. --allow-revert sends one anyway. Only a transaction a public signer pays gets the line; a private send whose public part fails in its simulation ends with that error instead. A private dry run that passes can still revert at settlement, which runs against live state under a lower cycle cap (Three runs of one engine). signer authority names the actor the signature authorizes and its program: 11111111111111111111111111111111 is the native token’s id (32 zero bytes in base58), so this is the payer’s native balance.

Public to public

One transaction, no proof:

$ wallet auth-transfer send --from Public/7VDm7YRPvimbZgCzuFqCGf6RwPsTV3XY5W9DzT71oain --to alice --amount 500000
Transaction hash is f08765ec784e5ef6ff0794bdec54c7ba2d384c5e163e8be4fdb6e3a43852e62a
Transaction is included in block 23

$ wallet account get --scope balance --account-id alice
Label: alice
Balance 500000, nonce 0

Alice’s nonce stays 0 because only the accounts that signed advance it, and she only received.

Shielding into a private account you own

A shield moves tokens from a public account into a private one; a deshield moves them out of a private account into a public one. Both are privacy-preserving transactions, which take longer and cost more. Price it first, and name who pays:

$ wallet --dry-run auth-transfer send --from Public/7VDm7YRP... --to bob-private --amount 20000000 --fee-payer Public/7VDm7YRP...
Dry run: nothing sent
  fee payer:        7VDm7YRPvimbZgCzuFqCGf6RwPsTV3XY5W9DzT71oain
  declared gas:     409764
  metered cycles:   0
  wire bytes:       235661
  base fees:        exec 8 / stor 8 (height 25)
  fee at head:      5163400 (tip 0)
  reserve at head:  5163400 (max fee 8390525)
  signer authority: 7VDm7YRPvimbZgCzuFqCGf6RwPsTV3XY5W9DzT71oain under 11111111111111111111111111111111
  action:           applies

--fee-payer decides who pays, and takes a prefixed id. Left out, the wallet takes the first of these that exists:

  1. an owned private account that holds the fee, whether the transaction mentions it or not;
  2. the first owned private account the transaction mentions, paying out of what the transaction credits it, unless the transaction has a public part that can fail (a shield does) or the credit falls short;
  3. the best funded public signer.

This shield would get the public signer anyway (bob-private is still empty); the commands here name it explicitly. Name the payer when it matters which.

Public/<id> has the public signer declare and pay the fee, usually what you want when shielding: the private account you are paying into does not exist yet and holds nothing.

Private/<id> has an owned private account pay from inside the proof. For a shield it must already hold the fee: the fee fallback that pays if the shield’s public part fails has to fit in what the account held before, so the wallet refuses up front: Fee payer <id> holds 0, short of the fee of 5174824: fund it first, or have a public signer pay the fee. Collecting a stored message is the exception; the next section shows why.

fee at head is the fee at the current base fees, reserve at head is the amount held, and max fee is the cap after headroom (How fees are priced). --fee-headroom moves the cap, --max-fee sets it, and --tip adds to the fee.

$ wallet auth-transfer send --from Public/7VDm7YRP... --to bob-private --amount 20000000 --fee-payer Public/7VDm7YRP...
Transaction hash is e0e69ea0e1dfe01ad2bcba1b587b73783fc93592d69c1e91cc149ef9d7bea79a
Transaction is included in block 28

$ wallet account sync-private --yes
Latest block is 29
Syncing to block 29. Blocks to sync: 5
Synced to block 29 in 45.763916ms

$ wallet account get --scope balance --account-id bob-private
Label: bob-private
Balance 20000000, nonce 54714446476954508813235880172123505360

The full 20,000,000 arrives because the public signer paid the fee from its own balance, not from the credit. Had a private account paid, the balance would be the amount less its reserve.

Sync before reading a private account, whose nonce is a hash, not a counter (Reading the chain). --yes answers the prompt the sync shows whenever there are blocks to scan; a script never blocks on it, because the confirmation returns true when not attached to a terminal.

Paying a private account you do not own

The recipient exports their keys in their own wallet:

$ wallet account show-keys --account-id Private/265rYQM792Z5G2Fzf7jRTgmCZTnT2CzCA5a3stjBRY1W
a8046f9bc12ee0d4f0ff91dcb09f65289e165edeb40cd9f283ee2a3cd73bfa72
f0107e0a183184fac624394d3bf826c0b70e9ce23e84410244079e27778bcb48…

Two lines, npk then vpk, 64 and 2368 hex characters. Redirect it to a file and send that file to whoever is paying you; it is what --to-keys takes. show-keys works only for private accounts.

A private account id is SHA256(prefix ‖ npk ‖ vpk), so one key pair is exactly one regular private account, with no identifier to choose.

The sender pays as before, with the public signer covering the fee:

$ wallet auth-transfer send --from Public/7VDm7YRP... --to-keys dave.keys --amount 20000000 --fee-payer Public/7VDm7YRP...
Transaction hash is 52cad0d899c6df1dd4ebad96312dc3f48f318072427158f26b74dba28122f65d
Transaction is included in block 36

Only a holder of the account’s keys can produce the proof that advances it, so the credit is stored on chain (Pending messages). The recipient collects it:

$ wallet pending list
Latest block is 37
Syncing to block 37. Blocks to sync: 2
Synced to block 37 in 22.572667ms
Message 19: to 265rYQM792Z5G2Fzf7jRTgmCZTnT2CzCA5a3stjBRY1W at program 11111111111111111111111111111111, from 7VDm7YRPvimbZgCzuFqCGf6RwPsTV3XY5W9DzT71oain at program 11111111111111111111111111111111, 17 bytes

$ wallet pending receive --position 19 --fee-payer Private/265rYQM792Z5G2Fzf7jRTgmCZTnT2CzCA5a3stjBRY1W
Latest block is 37
Transaction hash is 93a1598c3222ff4adca90c51b59651ea7f6ddf152cb24c8a7df17a94ba3c696c
Transaction is included in block 38

$ wallet account sync-private --yes
Latest block is 39
Syncing to block 39. Blocks to sync: 2
Synced to block 39 in 18.735208ms

$ wallet account get --scope balance --account-id Private/265rYQM792Z5G2Fzf7jRTgmCZTnT2CzCA5a3stjBRY1W
Label: dave
Balance 14829672, nonce 296197159399728484730127573470210145222

Dave’s account held nothing and still paid its own fee: 20,000,000 less its reserve of 5,170,328 is 14,829,672. The reserve is the fee at head here, because the wallet reserves no more than the payer held before the root (nothing) and never less than the fee at head; what happens to a surplus is in Private fees. The fee runs after the transaction’s root, here the collected message, so its credit is already in the account. A shield’s credit is there too, but its public part can fail, so the wallet keeps its reserve within what the payer held before; a collection does nothing publicly except pay the fee, so the wallet lets the payer pay out of what it receives.

--position takes the number pending list prints, the message’s leaf position in the commitment tree, shared with account commitments. It is not an index into your own list, so the first message you are shown is almost never at position 0, and one that is not yours, or that you already collected, fails with No pending message at this position.

So a payment to a stranger usually costs two fees, one on each side; here the recipient’s came out of what they were sent. A credit swept into a later private send of theirs costs no extra fee.

Reading the result

wallet account get --scope balance --account-id Public/<id>
wallet account sync-private --yes
wallet account get --scope balance --account-id Private/<id>

Reading the chain covers the rest.

Reading the chain

A public account

wallet account get --scope all --account-id Public/<id>

--scope takes three forms:

--scopeReads
balancethe native balance only. This is the default
allevery program’s state on the account
<program account id>one program’s state

Prefer a single program’s id once an account has accumulated state: a full read can exceed the RPC response limit (jsonrpsee’s default 10 MiB, which neither the sequencer nor the wallet raises).

--raw gives the underlying bytes as hex instead of the wallet’s decoding:

wallet account get --raw --scope all --account-id Public/<id>
{
  "actor_states": { "<program account id>": "486f6c61206d756e646f21" },
  "nonce": 0
}

A Label: line per label precedes the JSON, so the output is not pure JSON. actor_states is keyed by program, because each program owns its state on the account and cannot touch another’s. Decode a value with whatever that program uses; for plain bytes, echo <hex> | xxd -r -p.

Without --raw the wallet decodes only the native balance: it prints Balance <n>, nonce <n> (or Balance not read when the scope is another program), then each other program’s non-empty state as hex under Record of program <id>.

A private account

Sync first, then read:

wallet account sync-private
wallet account get --scope all --account-id Private/<id>

The chain holds only a commitment and an encrypted note, so the wallet shows a private account from its own record. Two things update that record: sync-private, which scans the chain for notes the wallet can decrypt, and the inclusion of a transaction the wallet CLI itself sent, for the accounts that transaction changed (finish_transaction, lez/wallet/src/lib.rs). A transaction sent any other way, such as by a client built on the wallet library, shows only after a sync. Until then the wallet prints its last record; for an account it holds keys for but has no state for yet, --scope all prints Account is Uninitialized and --scope balance prints Balance 0, nonce 0. sync-private asks before reading any blocks when run at a terminal; --yes skips the prompt.

The server does not have the keys, so no query returns a private account’s state, for you or anyone else.

A private account’s nonce is a hash chain rather than a count, so it changes unpredictably with each update and says nothing about how often the account has been used.

Scanning from genesis

A new wallet starts synced at the chain tip, so sync-private never reads the blocks before it. That is right for keys the wallet just made, and wrong for anything older. Importing a private account, or adding a shared account of a group this wallet did not create, rewinds the sync cursor of a wallet that started at the tip, so the next sync-private reads from block 1. To rediscover every private account the wallet’s keys open, from block 1:

wallet account sync-private --rescan

It does not move the sync cursor and keeps every other record. It fails with History ends before block N when the cursor is past the end of the chain, as for a wallet set up against one network and then pointed at a younger one; start a new wallet home for that chain.

The chain itself

wallet chain-info current-block-id
wallet chain-info block --id <n>
wallet chain-info transaction --hash <32-byte hex>

current-block-id is the tip, not the last finalized block; Finality explains the difference.

When something is missing

A submitted transaction you cannot find is usually one of three things.

  1. It has not been included yet. Wait for a block.
  2. It was refused, so nothing happened and there is nothing to find. A private transaction whose public part fails at settlement is refused if the failure is a malformed input or nothing pays for it. If its proof carries a fee fallback, or a public signer declares the fee, it is included instead: the public part reverts and the fee is still paid. Whenever the public part can fail, the wallet adds one of the two or stops before proving.
  3. It touched a private account and you have not synced.

Programmatic access

The public reads here have RPC equivalents, and more besides, including event queries and a subscription for finalized blocks. See Reading state from a client.

Pending messages

Advancing a private account requires a proof, and only a holder of its keys can produce one. So a message someone else’s transaction sends to your private account cannot be written there: it is stored on chain, addressed to you, in the mailbox.

Using it

wallet pending list
wallet pending receive --position <n>

list shows the messages waiting for accounts this wallet owns. receive collects one: it runs the handler on your machine, proves it, and submits the result as your own transaction.

--position is the message’s position in the commitment tree, as list prints it.

What to expect

Collecting costs a proof, so it takes as long as any private transaction (What it costs).

Any privacy-preserving send, including a pending receive, first claims up to four pending native credits (stored messages that credit a native balance) addressed to the private accounts it signs for or to its fee payer, largest first, in the private-action slots the transaction has left. So collecting one message can clear up to five. The wallet only does this when it is synced to within 64 blocks of the tip; further behind, it claims none and says so in an info log line, Pending credits are not claimed: the wallet is not synced to the head (run with RUST_LOG=info to see it, or the Claiming pending credits before the root line when it does claim). When a private account pays the fee, a --dry-run reports how many it would claim and how much of them reaches the fee payer; with a public signer paying, it does not show the claims.

An uncollected message is not in your balance, so wallet account get does not show it; wallet pending list does. If a balance looks wrong, check the mailbox first.

A credit can also leave your mailbox without a receive, swept by a later private send that signed for that account or that it paid for.

Nothing comes back from a stored message you never collect: the sender’s transaction finished when it was stored, and there is no refund (A stored message is never returned). That matters when you are the sender.

Why the sender cannot write to you

Writing to an account means executing against its current state, and a private account’s state is known only to the holders of its keys. Updating it also spends the current version’s nullifier, which only the nullifier secret key can derive. A sender has neither.

The asymmetry is deliberate: anyone can address you, nobody can act as you. Private accounts, addresses and the mailbox has the mechanism, including how a sender addresses you without learning your account id.

Public accounts do not have this

If the recipient is a public account, the sequencer can run its handler, so delivery happens inside the sender’s transaction and nothing waits.

Quickstart: your first program on LEZ

From an empty shell to a program you wrote changing an account, all on a local sequencer with nothing on a public network. Expect about half an hour, most of it spent building.

A program is Rust: it compiles to a RISC Zero guest, its entry point is the actor_entrypoint! macro and its types come from the lee_core crate. Clients, wallets and services in any language talk to LEZ over JSON-RPC or the C ABI and never compile a guest.

What you need

A clone of the repository (Before you start), Rust (the workspace pins a toolchain in rust-toolchain.toml), the RISC Zero toolchain at the version the workspace uses (rzup install, then rzup install r0vm 3.1.0 and rzup install cargo-risczero 3.1.0; the wallet runs r0vm to prove private transactions and refuses one whose major and minor version differ from its risc0-zkvm crate), Docker for reproducible guest builds, and the system packages the repository’s README.md lists: on Debian or Ubuntu build-essential clang libclang-dev libssl-dev pkg-config, on macOS pkg-config openssl.

Install the wallet from the repository root:

cargo install --path lez/wallet --force --locked

--locked builds against the repository’s Cargo.lock.

Start a node

The quickest node for writing programs is the sequencer alone, without L1 or indexer:

just run-sequencer-standalone

It produces a block every 15 seconds. Running a node has the full stack, with an L1 node and the indexer, and what standalone leaves out.

Point the wallet at it

wallet change-network local
wallet check-health

Run change-network first, or every command below goes to the public testnet rather than your node. On first run the wallet asks for a password twice; an empty one is fine for a local devnet. Setting up the wallet has the networks and the password rules.

You should see ✅All looks good!.

Build the example programs

RISC0_DOCKER_CONTAINER_TAG=r0.1.91.1 \
CARGO_TARGET_DIR=target/examples/program_deployment/methods \
  cargo risczero build --manifest-path examples/program_deployment/methods/guest/Cargo.toml

export EXAMPLES=$(pwd)/target/examples/program_deployment/methods/riscv32im-risc0-zkvm-elf/docker

Both variables matter: the tag pins the builder image, which decides the image id, and the target directory makes the EXAMPLES path correct (Building).

Each program lands at $EXAMPLES/<name>.bin. Run the rest from examples/program_deployment.

What you are about to deploy

hello_world.rs is the whole program, fourteen lines including the comment:

use lee_core::program::{ReceiveInput, Response};

// Hello-world example program.
//
// This program reads an arbitrary sequence of bytes as its message
// and appends those bytes to this program's own actor state on the receiving account.

lee_core::actor_entrypoint!(handle_message);

fn handle_message(input: &ReceiveInput, greeting: Vec<u8>) -> Response {
    let mut bytes = input.pre_state.to_vec();
    bytes.extend(greeting);
    Response::set_state(bytes)
}

Every program built with actor_entrypoint! has this shape, except a raw handler, which decodes the message itself. The macro expands to main, and the handler gets a &ReceiveInput and your message type, here Vec<u8>, decoded (Handlers and messages). input.pre_state is this program’s state on the receiving account and nothing else: not the balance, not another program’s state.

A Response is returned, not mutated. Response::set_state(bytes) replaces this actor’s state; keep_state() leaves it; both can carry messages to other actors. The handler can write nowhere else; that is the model’s central rule (The model in one page).

Its manifest needs only lee_core, borsh and risc0-zkvm (Toolchain shows them for a crate outside this repository).

Two accounts

You need an account for the program to write to, and a funded account to pay the fees.

wallet account new public --label first

The payer has to hold native tokens already, and a new account holds none. On a local devnet, import one of the genesis-funded secrets the wallet-import-test-accounts recipe in the Justfile uses:

wallet account import public --secret <one of the two secrets in that recipe>

Take them from the recipe: they change with the devnet’s genesis.

New accounts start uninitialized. Confirm it:

wallet account get --scope all --account-id Public/<first account id>

It prints Account is Uninitialized. The Public/ prefix tells the wallet which state to query.

Run it

cargo run --bin run_hello_world $EXAMPLES/hello_world.bin <first account id> <payer account id>

The runners take bare base58 ids, without the Public/ or Private/ prefix the wallet prints. The runner deploys the program and then sends it a message, so there is no separate deploy step. Each run deploys a new copy with its own program id, so a second run does not extend the first run’s state (deploy_program, examples/program_deployment/src/lib.rs). It returns once the sequencer has accepted the message, not once a block includes it, so wait for the next block (up to 15 seconds locally) before reading the account or running another command that pays from the same account. Run too soon and the read says Account is Uninitialized, or the next send is refused because the payer’s nonce is already pending. Watch the sequencer’s terminal to see the block land.

Then read the account back:

wallet account get --raw --scope all --account-id Public/<first account id>
{
  "actor_states": {
    "<hello_world program account id>": "486f6c61206d756e646f21"
  },
  "nonce": 0
}

actor_states maps each program account id to that program’s state here. The command prints a Label: line above the JSON when the account has one, so the output does not pipe straight into jq. Decode the value:

echo 486f6c61206d756e646f21 | xxd -r -p

It prints Hola mundo!.

Without --raw the wallet prints the native balance and the nonce, then each other program’s state as hex under a Record of program <id> line.

The same program, privately

wallet account new private --label first-private
wallet auth-transfer send --from Public/<payer account id> --to first-private --amount 1000000000
cargo run --bin run_hello_world_private $EXAMPLES/hello_world.bin <private account id> <payer account id>

The payer pays to deploy, but a private execution pays its fee from inside the proof, out of a private account, and the new one holds nothing: without the transfer the runner fails with Fee reserve of … fails (unless the wallet owns another private account that holds the fee, which then pays it). The public sender pays for the transfer, and one billion covers every private run in this guide’s examples.

This takes minutes rather than seconds (ten on a laptop is not unusual): your machine executes and proves the program instead of the sequencer executing it.

Reading it back needs a sync first, because the chain holds only a commitment and an encrypted note:

wallet account sync-private
wallet account get --raw --scope all --account-id Private/<private account id>

The wallet reads a private account from its own copy, which it updates when a sync finds a note for it or when a transaction the wallet CLI sent is included. So before the sync it shows the balance the auth-transfer send left, but no hello_world state: the runner sends through the wallet library and records nothing about the private account (Reading the chain). After it, the state reads the same Hola mundo! as the public run, and the nonce is a large number rather than 0: a private account’s nonce is a hash chain, not a counter.

What just happened

Accounts, actors and state explains what an actor is, and Handlers and messages what else a handler may return.

The same binary served both runs, because a program is not told whether its account is public or private. The privacy model rests on that property; its limits are in What a private transaction reveals.

Deploying without a runner

The runners call deploy_program (examples/program_deployment/src/lib.rs), which creates the header and segment accounts, chunks the ELF, and marks the program immutable. To do it yourself, create the accounts, then use the loader:

wallet account new public --label my-header
wallet account new public --label my-seg-0   # and seg-1, seg-2, ...
wallet program-loader deploy \
  --elf $EXAMPLES/hello_world.bin \
  --header my-header \
  --segments my-seg-0 my-seg-1 my-seg-2 \
  --immutable \
  --payer Public/<payer account id>

Program code is stored in accounts: a header and segments (Deployment). Create one segment account per 96 KiB of the guest ELF inside the .bin (the wallet splits only that part, not the kernel the .bin also carries), and name a funded --payer; Deploying has the rules and the errors.

Next

The example programs walks the rest of the repository’s examples, each adding one idea: authorization, a message enum, sending to another actor, program-derived accounts, and gating on time.

The example programs

Five programs, each adding one idea to the one before, with full source (program 2 shows only the function that changes) to type into a crate of your own.

They live at examples/program_deployment/methods/guest/src/bin/, with a runner each under src/bin/. Run everything from examples/program_deployment, with EXAMPLES exported as in the quickstart.

The runners of programs 1 and 2 end with two arguments: the account to send to, and a funded public account to pay the fee. Program 4’s runner takes an optional fifth argument, the id of an already deployed hello_world to call (such as the one run_hello_world printed), and deploys a new instance without it; those of programs 3 and 5 differ, as their sections show. Each private run also pays its fee from a funded private account, so fund one first as in the quickstart. Each runner returns once the sequencer accepts its transaction, so wait a block before the next command.

1. hello_world

Appends its message to its own state. The whole program:

use lee_core::program::{ReceiveInput, Response};

lee_core::actor_entrypoint!(handle_message);

fn handle_message(input: &ReceiveInput, greeting: Vec<u8>) -> Response {
    let mut bytes = input.pre_state.to_vec();
    bytes.extend(greeting);
    Response::set_state(bytes)
}
cargo run --bin run_hello_world $EXAMPLES/hello_world.bin <account> <payer>

One message in, one actor’s state in, a new state out. Covered by Accounts, actors and state.

2. hello_world_with_authorization

One line more:

fn handle_message(input: &ReceiveInput, greeting: Vec<u8>) -> Response {
    assert!(input.is_authorized(), "Missing required authorization");

    let mut bytes = input.pre_state.to_vec();
    bytes.extend(greeting);
    Response::set_state(bytes)
}
cargo run --bin run_hello_world_with_authorization \
  $EXAMPLES/hello_world_with_authorization.bin <account> <payer>

Authorization comes from a transaction signature for a public account, from its authorization secret key (ask, Keys) for a private one, or from the seed of a program-derived account (PDA) that the sending program attaches (program 5). Covered by Authorization.

Point the unauthorized runner at it:

cargo run --bin run_hello_world $EXAMPLES/hello_world_with_authorization.bin <account> <payer>

The sequencer’s terminal shows the guest’s own panic, panicked at …/hello_world_with_authorization.rs:15:5: followed by Missing required authorization, and the transaction is still included and pays its fee, with no change to the account.

3. hello_world_with_move_function

A message enum instead of raw bytes, and the first program that touches two accounts.

use lee_core::{
    account::{AccountId, Actor},
    program::{ReceiveInput, Response},
};

#[derive(borsh::BorshSerialize, borsh::BorshDeserialize)]
enum Message {
    Write(Vec<u8>),
    MoveData { data: Vec<u8>, to: AccountId },
    Append(Vec<u8>),
}

lee_core::actor_entrypoint!(handle_message);

fn handle_message(input: &ReceiveInput, message: Message) -> Response {
    match message {
        Message::Write(data) => append(input, &data),
        Message::MoveData { data, to } => {
            assert_eq!(
                input.pre_state.as_ref(),
                data.as_slice(),
                "the source account does not hold the bytes the instruction moves out of it"
            );
            Response::set_state(Vec::new()).send_sync(
                Actor::new(to, input.receiver.program_account_id),
                &Message::Append(data),
            )
        }
        Message::Append(data) => {
            assert!(
                input.from_own_program(),
                "only a move of this program appends to its destination"
            );
            append(input, &data)
        }
    }
}

fn append(input: &ReceiveInput, data: &[u8]) -> Response {
    Response::set_state([input.pre_state.as_ref(), data].concat())
}

This runner takes the payer first, then the function and its arguments. Each run without --program-id deploys a new instance of the program, with its own state (Programs, deployment and identity), so pass the id the first run prints to the two after it:

cargo run --bin run_hello_world_with_move_function $EXAMPLES/hello_world_with_move_function.bin \
  <payer> write-public <public account> mundo!
cargo run --bin run_hello_world_with_move_function $EXAMPLES/hello_world_with_move_function.bin \
  <payer> --program-id <program id> write-private <private account> Hola
wallet account sync-private
cargo run --bin run_hello_world_with_move_function $EXAMPLES/hello_world_with_move_function.bin \
  <payer> --program-id <program id> move-data-public-to-private <public account> <private account>

The sync matters, since the move builds on the private account’s local state, and must wait for the block holding write-private. A move built on the state from before it spends a nullifier write-private already spent: the sequencer drops it at settlement, when it applies the block (Transaction failed settlement, skipping it in its log), while the runner still returns, or refuses it outright with Nullifier already seen once that spend is in the head. Afterwards the public account’s state is empty and, after another sync, the private one reads Holamundo!.

The program is identical in all three runs and is not told which accounts are public: the runner decides when it builds the transaction (why this matters, Transactions, public and private).

MoveData carries the data the caller claims the source holds, and the source refuses unless its state is exactly that. The claim is pinned against the state rather than trusted, an idea that recurs throughout the pattern language.

Append guards with input.from_own_program(), so it runs only on a move from this program. Write and MoveData have no authorization check, so in this example anyone can append to or empty this program’s state on any public account; a real program would check is_authorized() there. Routing on the sender is pattern 2, Route on the sender first.

4. simple_tail_call

The first program that talks to another program.

use lee_core::{
    account::Actor,
    program::{ReceiveInput, Response},
};

lee_core::actor_entrypoint!(handle_message);

fn handle_message(_input: &ReceiveInput, callee: Actor) -> Response {
    let greeting: Vec<u8> = b"Hello from tail call".to_vec();

    Response::keep_state().send_sync(callee, &greeting)
}
cargo run --bin run_hello_world_through_tail_call \
  $EXAMPLES/simple_tail_call.bin $EXAMPLES/hello_world.bin <account> <payer>

keep_state() because it changes nothing of its own; it exists only to send. The callee arrives in the message rather than as a constant, because a program’s address is not known until it is deployed.

The private form takes the same arguments, and your machine executes and proves both programs:

cargo run --bin run_hello_world_through_tail_call_private \
  $EXAMPLES/simple_tail_call.bin $EXAMPLES/hello_world.bin <private account> <payer>

Covered by Handlers and messages.

5. tail_call_with_pda

A program authorizing an account that no key controls.

use lee_core::{
    account::{AccountId, Actor},
    program::{PdaSeed, ReceiveInput, Response, SyncMessage},
};

const PDA_SEED: PdaSeed = PdaSeed::new([37; 32]);

lee_core::actor_entrypoint!(handle_message);

fn handle_message(input: &ReceiveInput, callee_account_id: AccountId) -> Response {
    let greeting: Vec<u8> = b"Hello from tail call with Program Derived Account ID".to_vec();

    Response::keep_state().send(
        SyncMessage::new(
            Actor::new(input.receiver.account_id, callee_account_id),
            &greeting,
        )
        .with_pda_seeds(vec![PDA_SEED]),
    )
}
cargo run --bin run_hello_world_with_authorization_through_tail_call_with_pda \
  $EXAMPLES/tail_call_with_pda.bin $EXAMPLES/hello_world_with_authorization.bin <payer>

It prints the derived account id, readable like any other account.

Actor::new takes the account first and the program second, so callee_account_id is the callee program’s id. The runner sends the root message to the account derived from this program’s deployed address and PDA_SEED via AccountId::for_public_pda, and declares the callee’s actor on that same account. Attaching that seed with with_pda_seeds asks the protocol to treat the account as authorized for the outgoing message, which it does only when the account id equals for_public_pda of the sending program’s account id and that seed. The callee is hello_world_with_authorization, which refuses without authorization: the seed grant is what makes it succeed.

This is how a program controls funds: a vault is an account whose authority is a program and a seed rather than a key. Covered by Authorization.

The protocol’s own test programs

Under test_programs/guest/src/bin/, built with risc0_build::embed_methods() in a build.rs rather than the Docker builder, so they are not reproducible but need no Docker.

ProgramMechanismChapter
cooldown.rsrefuses to run until a cooldown has elapsed, by reading the clock and recognising its reply by the senderSystem programs
time_locked_transfer.rsthe deadline in the message becomes a timestamp_window on the response, so the transfer can only land in a block at or past it, with no clock messageSystem programs
live_payout.rsreads another actor’s live native balance by asking for it and handling the reply, then pays a tenth of itReplies
clock_reader.rsthe smallest clock reader: forwards whatever it is sent to the clock and stores the reply as its stateSystem programs
grant_relay.rsforwards a grant along a chain of programs, re-attaching it at each hop, and spends it only at the endAuthorization
listener.rsthe raw form of actor_entrypoint!, where the handler takes only ReceiveInput and decodes nothingHandlers and messages
scripted.rsa handler driven by a Script value, for arbitrary sequences in protocol testsHandlers and messages

For time, time_locked_transfer.rs shows a validity window (only a deadline needed) and cooldown.rs a read with a reply (the time must be stored or branched on).

For authority, read grant_relay: the guest is a one-line wrapper, and a function in test_guest_core/src/guests.rs holds the whole forwarding rule. It re-attaches every grant in input.grants on each hop, and at the last hop spends those over native balance actors.

What no example covers yet

Apart from scripted, which can send async messages in protocol tests, none of these sends an async message, collects a stored one from a mailbox, has a private actor send to a public one, or uses a group-held account. Those are the mechanisms in Handlers and messages and Private accounts with no runnable example outside protocol tests.

Accounts, actors and state

The account

An account is a nonce and a map (lee/state_machine/core/src/account.rs):

pub struct Account {
    pub nonce: Nonce,
    pub data: AccountData,
}

pub struct AccountData {
    pub actor_states: BTreeMap<AccountId, ActorState>,
}

The key is a program’s account id. The value is a byte string that only that program’s handler is given and can change (the exception is the signature program, which holds a commitment to the account’s current signing key, has no handler and is written by the engine; see Keys, nonces and rotation). Three programs holding state on an account make three entries.

There is no balance field: the native balance is the entry under the native token program (NATIVE_TOKEN_PROGRAM_ID), ordinary actor state.

The actor

An actor is one entry of one account:

pub struct Actor {
    pub account_id: AccountId,
    pub program_account_id: AccountId,
}

Read it as “this program, on this account”:

ActorMeaning
(alice, native token)Alice’s native balance. Actor::native_balance(alice) builds it.
(alice, token)Alice’s holding in the token program.
(vault_pda, multisig)A multisig’s configuration, on an account the multisig program controls.
(clock account, clock)The clock. clock_core::clock_actor() builds it.

Every message is addressed to an actor: the program id says which code runs, the account id which state it runs on.

The one rule

A handler reads and writes the state of the actor it is running for, and nothing else.

It does not see the account’s other entries or other accounts: the engine passes it no state but its own. Another actor’s state can reach it only inside a message, as that sender’s claim (Replies). If the token program needs Bob’s holding to grow, Alice’s token actor sends a message to Bob’s token actor, and Bob’s actor updates itself.

This rule keeps handlers small: each has one state to validate and one to produce.

Account ids

An account id is 32 bytes; its derivation decides who controls the account.

KindDerived fromControlled by
Public, key-ownedits first signing keya signature by its current key
Public PDAa program’s id and a seedthat program, by granting the seed
Private, regulara nullifier public key and a viewing public keythe holder of the secret keys
Private PDAa program’s id, a seed, and the two public keysthe program for spending, the key holder for operating
Builtin programfixed by the protocol (a constant, or a name for system programs, the built-ins deployed as bytecode: Built-in programs)the protocol; the sequencer committee upgrades system programs

To operate a private PDA is to hold its keys, and so be the one who can run its handlers in a private transaction: read and update its state and collect its messages. Spending from it still needs a seed grant from the program.

The exact derivations are in Account-id derivations. PDAs are explained in Authorization.

A private account can also be named by a blinded address: a hash of the account id and a secret factor. Without the factor, the address alone does not reveal the account. Blinded addresses give a private actor pseudonyms; see Private accounts.

Public and private state

The two kinds of account hold the same Account structure, kept in different places.

  • Public. The chain stores the account in the clear; anyone can read every actor state on it.
  • Private. The chain stores only a commitment to the account; the owner keeps the contents. Each update publishes a nullifier for the old commitment and a new commitment.

A program, by default, does not need to choose which kind it runs on. The user who builds the transaction decides, by using a public or a private account. The same handler code handles both. It can still infer the kind where its inputs give it away. A message can say so and the program can route on it, but that is the sender’s claim, not the engine’s. A program that knows the seed can also tell its public PDA from a private one: an account id equal to AccountId::for_public_pda of its own program account id and that seed is the public PDA, since a private PDA’s id also hashes the owner’s keys and so never matches.

What an account is not

  • Not owned by a program. It is a container on which many programs keep state.
  • Not a balance. The balance is one actor among several.
  • Not readable by other programs’ handlers (clients can read public accounts). A handler asks for a value with a message and receives a reply (Handlers and messages).

Handlers and messages: SyncMessage and AsyncMessage

A program is one function

use lee_core::program::{ReceiveInput, Response};

lee_core::actor_entrypoint!(handle_message);

fn handle_message(input: &ReceiveInput, greeting: Vec<u8>) -> Response {
    let mut bytes = input.pre_state.to_vec();
    bytes.extend(greeting);
    Response::set_state(bytes)
}

The whole hello-world program (examples/program_deployment/methods/guest/src/bin/hello_world.rs) appends the message to its own state.

actor_entrypoint! only expands to the guest’s main: it reads the input, decodes the message with Borsh into the handler’s second parameter, calls the handler, and commits the result. The form actor_entrypoint!(raw handler) skips the decoding and gives the handler only the input, for programs that decode differently depending on the sender.

What the handler receives

pub struct ReceiveInput {
    pub receiver: Actor,          // the actor this run is for
    pub from: Option<Actor>,      // the sending actor; None when the transaction's author sent it
    pub grants: BTreeSet<Actor>,  // see the Authorization chapter
    pub pre_state: ActorState,    // this actor's state before the message
    pub message: MessageData,     // the message bytes
}
  • receiver tells the handler which actor it is. One program serves many accounts, and some behave differently per account (the clock refuses every message outside its one fixed account).
  • from is filled in by the system; a program cannot forge it. A stored message keeps its original sender when it is collected.
  • pre_state is empty for an actor that has never been written.

What the handler returns

pub struct Response {
    pub post_state: Option<ActorState>,
    pub sync_messages: Vec<SyncMessage>,
    pub async_messages: Vec<AsyncMessage>,
    pub events: Vec<ProgramEvent>,
    pub validity: ValidityWindows,
}

Build it with chained methods:

Response::set_state(new_bytes)      // or Response::keep_state()
    .send_sync(other_actor, &message)    // deliver now
    .send_async(some_actor, &message)     // deliver now if possible, otherwise store
    .event(event)
    .block_window(100..)            // only valid from block 100 on

To refuse a message, the handler panics. A panic fails the whole transaction: when a public handler panics, the state changes are dropped but the payer is still charged (in a private transaction, only when the proof carries a fee fallback or a signer declares the fee; otherwise the transaction is dropped unpaid); when a private handler panics, no proof can be made, so there is no transaction to submit.

SyncMessage

A SyncMessage is delivered inside the transaction it was emitted in, or the transaction fails.

  • The receiver’s handler runs before the transaction ends.
  • If it fails, everything fails, including the sender’s state change.
  • A SyncMessage can carry PDA seeds, which authorize the receiver, and grants its sender holds (see Authorization).

A SyncMessage returns no value. For an answer, the receiver sends a second message back and the sender’s handler runs again to receive it (Replies).

Who can be reached by a SyncMessage:

  • any public actor the transaction declares, that is, lists among the actors it may reach (Declaring actors); a public account that does not exist yet must also be admitted (Admission);
  • a private actor whose owner is building this transaction.

A SyncMessage to anyone else’s private actor fails the transaction: only the owner can run a private handler, and they are not here.

AsyncMessage

An AsyncMessage is a message that is allowed to wait.

DestinationWhat happens
a public actor the transaction declaresdelivered in this transaction
one of the submitter’s own private actors, when the submitter promotes it (asks for it to run now)delivered in this transaction
any other private addressstored on chain for its owner to collect later

An AsyncMessage delivered in this transaction fails like a SyncMessage: if its handler fails, the whole transaction fails, the sender’s state change included. It differs in two ways: it carries no PDA seeds and no grants, and it runs after the SyncMessages of the same response and everything they trigger. Only a stored message leaves its sender unaffected: the sender’s transaction completes whatever later happens to the message.

By default the reference wallet promotes every async message to a private account the transaction includes, so wallet auth-transfer send to your own private account credits it at once. wallet pending receive can also promote chosen ones by index (--promote-public, --promote-private): the engine numbers, from 0, the async messages the transaction’s handlers send to undeclared destinations, counting those from public and from private senders separately. wallet program call builds only public transactions, so delivering a program’s message to your private actor at once needs the wallet library, with that account mentioned (it need not be authorized).

For a stored message, the sender’s transaction completes and the message waits in a global mailbox until the destination’s owner builds a transaction whose root is that stored message; their handler runs then.

Rules for stored messages:

  • A public sender’s stored message is published in the clear with a recovery note, so the destination needs a recovery binding (an encrypted note on chain that tells the owner which of their accounts the address belongs to): one already on chain, or one a privacy-preserving transaction introduces. A private sender seals it (encrypts it to the recipient’s keys) and needs no binding, unless it chooses to publish in the clear. See Recovery bindings.
  • Only private addresses can hold stored messages. An AsyncMessage to a public account that the transaction did not declare cannot be stored and fails the transaction: in the clear it fails with UnboundAsyncDestination, and a seal cannot be addressed to it.
  • The sender cannot be told about failure, and nothing returns to it (A stored message is never returned). Design receiving handlers so that a legitimate message always succeeds.

Choosing between them

You wantUse
all-or-nothing with the other actorSyncMessage
to grant a PDA seedSyncMessage
to reach a stranger’s private accountAsyncMessage
the same code to work whether the receiver is public or privateAsyncMessage
the receiver to be free to act later, or neverAsyncMessage

The native token shows this. Transfer debits the sender and sends Credit to the recipient as an async message (lee/state_machine/core/src/native_token.rs). For a declared public recipient the credit lands in the same transaction; for a private recipient it waits in their mailbox. The transfer code does not know which.

Order of execution

A transaction’s messages form a tree. The root is the message the transaction is built to deliver: a SyncMessage from its author (with from set to None), or a stored message being collected (TransactionEntry, lee/state_machine/core/src/execution_state.rs). Each message a handler sends and the transaction delivers is a child of the message that ran it. A stored message ends its branch; the transaction that collects it delivers it as its root or as a claim (a further stored message swept into the same transaction, as Pending messages describes for native credits). Claims run before the root, each as its own entry, and a proven fee’s transfer runs after the root’s subtree.

Messages are processed depth first: of several messages a handler returns, the first and everything it triggers complete before the second is delivered. Within one response, SyncMessages run before any AsyncMessages delivered in the same transaction.

A handler can therefore be entered more than once in a transaction; the second time, pre_state is the state its first run wrote.

Replies

There is no read access to another actor’s state, so reading takes two messages. The native token shows the shape:

Message::ReadState => {
    let reader = input
        .from
        .ok_or(TransferError::UnroutableRead { account_id })?;
    // The reply returns the grant the reader lent, so its handler can act on it.
    Response::keep_state()
        .send(SyncMessage::new(reader, &StateReply::from(input)).with_lent_grant(input))
}

The asking actor sends ReadState and the balance actor answers with its state. The asking program must handle the reply and check who sent it. The fee program does it this way (lez/programs/fee/src/main.rs):

if input
    .from
    .is_some_and(|from| from.program_account_id == NATIVE_TOKEN_PROGRAM_ID)
{
    let reply: StateReply =
        borsh::from_slice(&input.message).expect("a native state reply must decode");
    return pay_out(input, &reply);
}

It decodes a StateReply only from the native token program; without that check anyone could forge a reply.

A message submitted by the transaction’s author has no sender, so nothing can reply to it: ReadState sent that way fails.

Message types

Messages are bytes in a format the receiver’s program defines and the sender must use. A program therefore needs a handler for every message it can receive, not for those it sends.

A layout that keeps handlers honest:

/// Anyone may send these.
enum Message { Transfer { .. }, ReadState }

/// Only actors of this same program may send these.
enum Internal { Credit(u128) }

/// Sent to other programs; never received.
enum Outbound { StateReply(..) }

The handler looks at input.from first, then decodes with the type that sender is allowed to use. The fee program does this (the reply check above); the native token instead uses one enum and checks the sender inside the match arm.

Validity windows

A handler can limit when its transaction is valid:

Response::keep_state().timestamp_window(deadline..)

An open-ended range (from.. or ..to) goes to block_window or timestamp_window. A closed range can be empty, so it goes to try_block_window or try_timestamp_window, which return an error for an empty one.

The windows of all handlers in a transaction are intersected, and the sequencer checks the result against the block being built. A lower bound is inclusive and an upper bound is exclusive. An empty intersection fails the transaction.

Events

A handler can emit events: an 8-byte selector and data. Events from public handlers are attached to the transaction for indexers; those from private handlers are dropped.

Small helpers

  • input.from_own_program(): true when the sender is an actor of the receiver’s own program.
  • write_once(pre_state, data): returns data, and panics if the state already holds something different, for values that must be set once.

Transactions, public and private

A transaction delivers one root message and runs everything that message triggers. A public transaction is signed by its accounts and executed by the sequencer. A private transaction carries a proof that the private handlers ran correctly, and the sequencer executes only the public handlers.

Public transactions

A public transaction contains:

PartContent
Rootthe actor to deliver to, and the message bytes
Declared actorsevery public actor the execution may reach, each marked Authority::Signer (a grant at the root when its account signs, see Authorization) or Authority::None
Authorized accountsthe accounts that sign
Nonces and witnessesone witness entry per signer, in nonces order: its signature data and a commitment to the account’s next key. See Keys, nonces and rotation
Fee declarationpayer, gas limit, tip, maximum fee (How fees are priced)
Admission evidenceproof that a not-yet-existing account id is a real public address

The sequencer checks the signatures and nonces, reserves the fee, runs the root and everything it triggers, and applies the result. If execution fails, or its effects would write system state a user transaction may not (the clock, the fee accounts, the bridge account other than a rise in its balance, bridge state on any account, or the system upgrader’s registry), the state changes are dropped, but the payer still pays and every signer’s nonce still advances. A transaction malformed before execution (a bad signature, an undeclared root) is refused instead and pays nothing.

A failed execution is charged the full gas limit, except UnboundAsyncDestination and a nonzero guest exit code, which pay the cycles that ran (charged_cycles, lee/state_machine/src/validated_state_diff/mod.rs); a revert for writing system state also pays only the cycles that ran. The reference wallet declares the simulated cycles plus a margin, so a revert its simulation missed, such as a validity window, pays the simulated cycles plus that margin (25% by default), and a guest panic sent with --allow-revert pays the configured limit. The transaction receipt says only success: false and the fee, not why.

Declaring actors

The engine runs a public handler only for an actor the transaction declared. To an undeclared actor, a SyncMessage fails the transaction; an AsyncMessage is stored for later if the address is private (or, in a privacy-preserving transaction, delivered at once when it is one of the submitter’s own private actors and the submitter promotes it, AsyncMessage), and fails if it is public, since there is nowhere to store it.

So the builder of the transaction decides, by declaring or not, whether the destination is handled now.

Admission

Before any public actor receives a message, its account must be admitted: shown to derive from a public key or a PDA. It passes if one of these is true:

  • it already exists on chain;
  • it signed the transaction;
  • the transaction carries evidence for it: the public key or the program-and-seed that hashes to its id;
  • the sender granted a seed that derives it (a program-derived account, PDA).

Admission stops messages from creating state at ids nobody can ever control. In practice, the first payment to a fresh public account must carry that account’s public key, or the transaction reverts and the payer is still charged. The reference wallet simulates first, so it refuses to send such a transfer (declared public but not admitted) unless given --allow-revert; --to-initial-key attaches the key.

Fees

A public transaction pays for execution and for the bytes it adds to the block. The fee is reserved before execution and the unused part refunded after (How fees are priced). Exempt shapes: genesis transactions, sequencer injections with an empty witness set, meaning bridge deposits and system upgrades, and sequencer-stake operations. The clock and fee-distribution transactions are stripped before classification and never pay. Any other user transaction that omits its fee is rejected, with MissingFeeDeclaration for a public one and MissingPrivateFee for a private one.

Private transactions

A private transaction involves at least one private account. For each one, its owner hands the prover a private witness: the account’s keys and what is needed to spend its current version (PrivateWitness, lee/state_machine/core/src/circuit_io.rs). It stays on the machine that proves, which for the reference wallet is the owner’s. This is a different thing from a public witness entry, which is published signature data. An authorized private witness can mark actors of its account, listed in signer_programs, for a grant at the root (Authorization).

A private transaction’s public part is:

PartContent
Proofone receipt of the privacy circuit
Private actionsper private account touched: a nullifier, a new commitment, an encrypted note
Boundarythe messages that crossed between private and public actors, in order
Async messagesstored messages sent by private actors, each sealed to its recipient or published in the clear
Recovery bindingsnewly registered receive addresses
Public rootthe root message, if it targets a public actor
Validity windowsthe intersection of its private handlers’ windows; public handlers’ are checked at settlement
Program claimswhich program images the proof relied on
Proven feewhen the proof pays the fee: its tip, its refund target, and optionally a fee fallback (Private fees)

It may also carry signatures, when a public account in it must be authorized, and a signer can then pay through a fee declaration in place of the proven fee (Private fees).

Three runs of one engine

The same execution engine runs three times:

  1. Dry run, on the user’s machine. All handlers run, public and private, and the wallet learns which messages will cross between public and private actors.
  2. Private part, on the user’s machine and inside the circuit. Only private handlers run; each message that crosses to the public side is written to the boundary instead of being executed.
  3. Public part, on the sequencer. Only public handlers run; each time a message crosses, the sequencer compares it with the next boundary entry, and a mismatch fails the transaction.

The two halves check each other:

  • A message from private to public is a demand. The proof says “my handler sent exactly this”, and the sequencer carries it out.
  • A message from public to private is an assumption. The proof says “I assumed the public side would send exactly this”, and the sequencer confirms it did.

A demand runs against live state, so transactions prepared against the same public balance compose at settlement: two transfers prepared against a recipient balance of 400 settle, the first against 400 and the second against 437.

The dry run meters the public part against DEFAULT_PUBLIC_CYCLE_BUDGET (32M cycles), but settlement allows at most MAX_GAS_EXEC (10M), so a public part between the two passes the dry run and fails at settlement out of gas, charged or dropped as any failure is (What the handler returns).

An example

Alice pays 10 from her private balance to Bob’s public balance.

  1. Root: Transfer { to: bob, amount: 10 } to (alice_private, native). This actor is private, so the root is not published.
  2. In the proof: Alice’s handler debits her and sends Credit(10) to (bob, native) as an async message. Bob’s actor is public and declared, so the message crosses.
  3. Boundary: one private-to-public entry holding the credit, plus the fee credit into the fee inbox (Private fees).
  4. On the sequencer: the proof verifies. Bob’s handler runs with Credit(10) from the boundary and his balance grows.

An observer sees Bob receive 10 from “some private balance actor” and a new commitment, but not Alice’s account, her balance or her other activity.

Collecting a stored message

A stored message is collected by a private transaction, as its root or as a claim (Order of execution). The proof shows the message is in the chain’s commitment tree and spends a nullifier only the receiver can derive, so it is collected at most once (Collecting). Nothing crosses to the public side unless the handler sends something there.

Proving cost

The user’s machine produces one inner proof per message delivered to a private actor, and one proof for the circuit that checks them all. Two things reduce the count:

  • Public handlers are never proven; the sequencer runs them.
  • The native token needs no inner proof; the circuit computes it directly.

So collecting a native credit is one proof. A token transfer between two of your own private accounts is three when the credit is delivered in the same transaction: two handler runs and the circuit.

Private fees

A private transaction pays through a reserve proven inside itself: one native credit crossing into the fee inbox, settled at the block’s base fees. The reserve is an upper bound rather than the fee: a surplus above MIN_PRIVATE_REFUND is refunded to the proof’s refund target, or else to the payer’s alias (the blinded address the payer presents) when a recovery binding for it is on chain, and a smaller or unrefundable one is kept as tip (lez/chain_state/src/apply.rs). A refund to the payer’s alias is a stored credit, collected like any other (Collecting); a refund target is a public account and is credited at once. A private transaction with a public signer can instead pay through that signer’s fee declaration, as a public one does (lez/chain_state/src/classify.rs). Use --dry-run on a wallet command to price one before sending.

A proof can also carry a fee fallback: the payer’s private state after the fee transfer alone, which it can build only when the payer’s pre-state covers the reserve by itself (ProvenFee, FeeFallback, lee/state_machine/core/src/circuit_io.rs). If the public part then fails, settlement applies the fallback instead of the private actions, so the transaction reverts and still pays. A proof without one has no such revert: unless a public signer declares the fee, its failure drops the transaction unpaid.

How fees are priced

Two resources are priced: execution gas, the cycles public handlers run, and storage gas, the transaction’s serialized bytes, with a private transaction’s proof always counted as PROOF_BYTES (223,047). Each has a base fee per unit, held by the fee program; a dry run prints both on its base fees: line, as exec 8 / stor 8, and 8 is the floor of each (BASE_FEE_EXEC_MIN, BASE_FEE_STOR_MIN, lez/programs/fee/core/src/market.rs). After every block each base fee moves toward a target use per block, 5M cycles and 500,000 bytes: up when the block used more, down when it used less, by at most an eighth per block (next_base_fee, market.rs; FeeState::apply_block, lez/programs/fee/core/src/state.rs). A block holds at most twice the target, MAX_GAS_EXEC (10M cycles) and MAX_GAS_STOR (1M bytes).

A fee is execution gas × exec base fee + bytes × stor base fee + tip, at the base fees the block opens with (fee_for, lez/programs/fee/core/src/assess.rs). The tip goes to the block’s producer, the rest to the fee escrow (Fee).

  • Public. The reserve prices the declared gas limit. The transaction is invalid if that reserve exceeds its maximum fee or the gas limit exceeds MAX_GAS_EXEC (validate_static_tx, lez/programs/fee/core/src/validity.rs). It is charged for the cycles that ran, at most its gas limit, or the whole limit on most failures (Public transactions), and the rest of the reserve is refunded.
  • Private, paid in the proof. Execution gas is a fixed proof verification charge (PRIVATE_VERIFY_GAS, 409,764) plus the public part’s cycles, and the public part may run only as many cycles as the reserve pays for past the tip and the block has left. Paid by a signer’s declaration, it is priced as a public one.

Base fees can rise between pricing and inclusion. The reference wallet reads the quote (the head’s base fees) and prices at the base fees after --fee-headroom blocks (5 by default) of the steepest climb, every block full: about 80% above the quote, 62.5% from the floor of 8, where the steps round down (base_fee_ceilings, lez/wallet/src/lib.rs). For a public transaction that sets the default --max-fee; for a private one it sets the reserve, clamped to the payer’s balance. Either way the fee is charged at the block’s base fees; a private transaction also loses a surplus too small to refund (Private fees). The flags are in Setting up the wallet.

Choosing the form

You do not choose it in the program. The wallet builds a public transaction when every account involved is public, and a private one otherwise. A program written with AsyncMessages for payouts and SyncMessages for atomic steps works in both without changes.

The input echo: why a handler’s proof binds to its input

The problem

A zero-knowledge receipt proves that some program ran and produced some output, not what it was given: a handler proven on a made-up balance, sender or grant set produces a valid receipt.

In the public case this does not matter: the sequencer runs the handler itself and supplies the real input. In the private case the handler runs on the user’s machine, and the user chooses the input.

The fix

A handler run outputs not the Response alone but a Transition, which carries the input next to the response (lee/state_machine/core/src/program/mod.rs):

pub struct Transition {
    pub input: ReceiveInput,
    pub response: Response,
}

The guest commits the whole Transition to its journal (the public output a RISC Zero receipt proves). The program author does nothing: actor_entrypoint! reads the input, passes it to the handler, and commits it unchanged next to the handler’s response. Only a guest that writes its own main must commit its input itself.

What must match, byte for byte, is the whole ReceiveInput: the receiver, the sender, the grant set, the starting state and the message. It is checked in two places.

On the sequencer, for a public actor. It runs the guest, decodes the Transition it committed, and the engine compares (process_actor_message, lee/state_machine/core/src/execution_state.rs):

let transition = environment.handle_message(&input, &view)?;
if transition.input != input {
    return Err(ExecutionError::TransitionInputMismatch { .. });
}

In the privacy circuit, for a private actor. The prover hands the circuit only the handler’s response. The circuit attaches the input the engine itself computed, and requires a receipt for exactly those bytes (lee/privacy_preserving_circuit/src/private_backend.rs):

let transition = response.into_transition(input.clone());
env::verify(image_id, &lee_core::to_borsh_frame(&transition));

A receipt made by running the handler on any other input committed different bytes, so it does not verify.

So the proof of a private transaction says: this program, given this receiver, sender, grant set, starting state and message, produced this response.

What this buys

  • The starting state is real. The circuit separately proves that the private account’s state is the one committed on chain, and the echo ties the handler run to it.
  • The sender is real: the engine supplies from from the message being delivered, so a program cannot be shown a sender that did not send.
  • Authorization is real: the engine computes the grant set, and the handler ran with it.
  • Private output can be trusted in public: a message leaving a private actor was produced by the proven handler from proven input. This is the property behind the proof-carrying message pattern, which most of the catalog uses.

What the echo assumes

The guest writes the echo, and nothing outside it can force it to be honest: a zkVM receipt binds a program to its journal, not to what the host fed it. A program with a hand-written main could read one input, compute a response from it, and commit a different input next to that response.

So the guarantee is conditional: for a program whose code echoes faithfully, a prover cannot feed it a false input. Programs built with actor_entrypoint! echo faithfully by construction, and a prover cannot substitute other code, because the proof binds each program account to the image deployed there, or, for a shadow program, to the image its id is derived from (Program identity in a private transaction).

A program that lies in its echo gains nothing beyond what any dishonest program already has.

  • In a public transaction it fails: the committed input differs from the real one the sequencer supplied, and the engine rejects the transition.
  • In a private transaction it lets its own prover produce any response. That is the same as a program with a “do whatever the caller says” instruction. The response can still only write the state of that program’s own actor and send messages whose from.program_account_id is that program, which is what a receiver’s sender check, from_own_program() included, reads.

The echo protects those relying on an honest program from dishonest provers, not anyone from a dishonest program. Relying on a message from an actor means trusting that actor’s program, and “it uses the standard entry point” is one line of that review.

What it does not hide

The echo is inside the proof, not published. An observer of a private transaction sees neither the input nor the response of a private handler, only what crosses to the public side, listed in What a private transaction reveals.

A short rule

A handler never needs to re-check that its input is genuine, only that it is acceptable: the right sender, the right authorization, a valid state transition.

Authorization and program-derived accounts

A handler receives a set of grants, input.grants, and one question derived from it, input.is_authorized(), which asks whether the set contains the receiver.

A grant is an Actor (an account id paired with a program account id) in a set carried by one delivery, so authority is per actor and per message, not per account or per transaction.

Where a grant comes from

Only the engine mints one (Executor::root_grants, authorize and queue_fee, lee/state_machine/core/src/execution_state.rs). There are four sources:

SourceGrantsReaches
A signer markeach declared actor marked Authority::Signer whose account signedthe transaction’s sync root call only
A private witness’s marksthe actors an authorized private witness lists in signer_programs (for a public root, only those the transaction declares in private_signers)the sync root call only
A PDA seedthe destination actor of the seeded messagethat one message
The fee entrythe payer’s native balance actorthe fee delivery only

A program cannot mint a grant, only pass on one it holds: by naming it on an outgoing sync message with with_grants, or by handing back the one it was lent with with_lent_grant. Attaching a grant the sender does not hold fails the transaction with UnheldGrant.

A grant reaches a callee only because the caller attached it, and each hop must hold what it attaches, so a chain is explicit, with no fixed hop limit: gas bounds the hops of the public part. grant_relay (test programs) is that rule as working code. An AsyncMessage never carries a grant, and neither does a claim, a stored message collected as the root, or a promoted async message (AsyncMessage).

In the wallet CLI an actor authorizes only when it is written :sign, as in wallet program call --program <id> --to <account>:sign ... (Sending a message), and the root program can pass on everything it is handed (rules).

Program-derived accounts

A PDA is an account with no key, its id derived from a program’s id and a seed:

AccountId::for_public_pda(&program_account_id, &seed)

Only that program can issue a grant over it, by attaching the seed to a SyncMessage:

const PDA_SEED: PdaSeed = PdaSeed::new([37; 32]);

fn handle_message(input: &ReceiveInput, callee: AccountId) -> Response {
    let greeting: Vec<u8> = b"Hello from tail call with Program Derived Account ID".to_vec();
    Response::keep_state().send(
        SyncMessage::new(Actor::new(input.receiver.account_id, callee), &greeting)
            .with_pda_seeds(vec![PDA_SEED]),
    )
}

Abbreviated from examples/program_deployment/methods/guest/src/bin/tail_call_with_pda.rs. The engine checks that the seed, hashed with the sending program’s id, gives the receiving account; if so, the receiver sees is_authorized == true.

A private PDA works the same way, at a different address: AccountId::for_private_pda uses its own prefix and also hashes the holder’s public keys, so the public and private PDA of one program and seed differ, and several groups can each have their own private PDA for the same program and seed.

Custody

Custody is the main use of a PDA. A program holding funds keeps them in the native balance actor of a PDA it controls, and releases them with a seed grant, as lee_core::native_token::custody_transfer does:

pub fn custody_transfer(from: AccountId, seed: PdaSeed, to: AccountId, amount: Balance) -> SyncMessage {
    SyncMessage::new(Actor::native_balance(from), &Message::Transfer { to, amount })
        .with_pda_seeds(vec![seed])
}

The bridge pays deposits this way (lez/programs/bridge/src/main.rs). No key can sign for those funds: they move only through the program’s code, and the sequencer committee can replace the bridge’s code, as it can that of any system program not made immutable.

When several users share one program, derive the seed from something that identifies the instance, or one user’s instance could grant the seed of another’s.

Knowing who sent a message

Authorization is about the receiving account, identity about the sender: separate checks.

  • input.from is the sending actor, or None when the transaction’s author submitted the message.
  • input.from_own_program() is true when the sender is an actor of the same program.

Use the first to accept messages only from a known actor, the second for a program’s internal messages:

Message::Credit(amount) => {
    if !input.from_own_program() {
        return Err(TransferError::ForeignCredit { account_id });
    }
    ...
}

A credit must come from the native token program itself, or anyone could mint.

An account id alone identifies nobody. Anyone can deliver a message to any program’s actor on any public account, without that account’s authorization. A program that forwards whatever it receives would then send messages “from” that account. So to know that a specific person is speaking, a handler compares the whole sending Actor: the account, and a program it trusts to have checked is_authorized(). The usual choice is the program itself: each participant speaks through their own actor of the program (a “seat”), and the receiving side checks from_own_program() plus the account id.

What a grant does not mean

It does not mean “the owner asked for this message”. It means this delivery carries a grant over me: I am an actor the signature marked and this is the root call, the program my PDA derives from attached its seed, or someone holding my grant attached it here.

That gap is the model’s main footgun.

A program you handed a grant to: Alice signs a transaction marking her balance actor and sends the root to program P. P holds a grant over that actor for the root delivery, and it can attach it to anything it sends, so a hostile or buggy P can debit her through the native token program. It cannot act with authority over an actor Alice did not mark: it holds no grant over her token holding, her other programs or her other accounts.

A grant you lend is spendable before it comes back. If the root hands a counterparty a grant for a round trip, the counterparty can use it meanwhile, and it returns on the callback only if the counterparty chooses to attach it.

A stored message carries no authority. A claim, a stored message collected as the root and a promoted async message all arrive with an empty grant set, so a collected message cannot debit its recipient even if the recipient marks the account: a Transfer { to: mallory, .. } stored at Alice’s private balance actor cannot move her funds, however she collects it. Collecting consumes a message; it does not consent to it. Consent is marking an actor and sending a root call yourself.

Rules that follow:

  • For program authors. If an operation must be started by the owner and nobody else, check both input.is_authorized() and input.from.is_none(). At a sync root from is None, and the grant exists only because the actor was marked, so the pair says the owner started it. If another program may start it, decide which one and check input.from.
  • For program authors sending on. send_sync attaches no grant, so a program using it builds cleanly and then fails at runtime wherever the callee checks authorization (the native token refuses with UnauthorizedSender). Use SyncMessage::new(..).with_grants([actor]) when the callee needs authority, and with_lent_grant(input) when replying to a reader so it can act on what it read.
  • For transaction builders. Mark the fewest actors the call needs: the root program holds everything you mark and can pass it on.
  • For users. A transaction is only as trustworthy as the programs you hand grants to, and the damage is bounded by the actors you marked.

Keys, nonces and rotation

The wallet does not keep one key for a public account: every transaction it signs names a fresh key for the account’s next nonce, and the chain tracks only the current one. Per-nonce rotation came with bunker mode: the chain stores only a hash of the current public key, and the key itself appears only beside a signature (lee/state_machine/src/signature/schnorr.rs). Since the wallet never signs twice with one key, a public key it has revealed on chain is already retired and no longer controls the account.

What a public account is

You hold one 32-byte secret, and the wallet derives a key pair per nonce from it.

The account id is fixed for life, derived from the nonce-0 key alone:

id = SHA256(prefix ‖ SHA256(type prefix ‖ commitment of the nonce-0 key))

That is a double hash with a per-key-type prefix, AccountId::for_initial_key (lee/state_machine/core/src/account.rs). Every stored key names its scheme, a KeyType (lee/state_machine/core/src/signing_key.rs): the list is append-only and holds only Schnorr today, so more schemes can be added later.

Because the id commits to the first key and nothing else, rotation changes what signs without changing where you are.

Where the current key lives

In an actor state. The signature system program holds each account’s current key type and a commitment to its signing key, written at settlement (lee/state_machine/core/src/signing_key.rs, applied in lee/state_machine/src/state/mod.rs). There is no guest code behind that program: it exists to own that state.

So “what key does this account use now” is a state read, not something you can compute from the id.

Watching it happen

--scope all prints the signature program’s record alongside the balance, captured on a local devnet:

$ wallet account get --scope all --account-id Public/7VDm7YRP...
Balance 9999944009032, nonce 9
Record of program 4bfm5whUyngutaHD2uj1kwa6PWtKK6U7URfwq3vHypry
00e927d53f9453e95c048342959d29e116b739e9d263f686a9aecbb9f3bfe00d5d

Send one transaction from it:

$ wallet auth-transfer send --from Public/7VDm7YRP... --to alice --amount 1
Transaction hash is 34bbded2aa32730d4f8b9f84a383c52b5537c5529829f1da1893f3dbb96eb8fd
Transaction is included in block 590

Then read it again:

$ wallet account get --scope all --account-id Public/7VDm7YRP...
Balance 9999944004599, nonce 10
Record of program 4bfm5whUyngutaHD2uj1kwa6PWtKK6U7URfwq3vHypry
005cf79f6021860f8401a84798f0398260c28b4e71647b3dd38a64a24727427a0d

The nonce went from 9 to 10 and the key changed from 00e927d5… to 005cf79f…, while the account id did not move. The next signature is checked against that record, held by the signature program 4bfm5whU…, so rotation needs no announcement: it is a state transition like any other. It happens even when a transaction reverts after its fee is charged: the effects are dropped, but every signer’s key rotates and its nonce advances.

What a transaction carries

One witness entry per public signer, in the same order as nonces (Public transactions). This public witness is signature data, unrelated to the private witness a private account’s owner hands the prover. Each entry holds that signer’s authentication data and a commitment to its next key, and every signer signs a message that covers the transaction plus all signers’ next key commitments together (lee/state_machine/src/transaction_message.rs).

Entries pair with nonces positionally and carry no account id of their own, so a count that does not match the signers is refused outright, and an entry in the wrong position fails authentication rather than a name check. A signature also commits to the next key, so you cannot sign now and decide later what the account rotates to.

Signatures also cover the zone id, a hash of the zone’s L1 channel id and its genesis, so the same transaction cannot be replayed on another zone (The zone a signature is for).

What this breaks

The protocol accepts a next key equal to the current one, but the wallet derives a fresh key for every nonce, which hardware holding one fixed key cannot do, so the wallet refuses Keycard accounts outright with Keycard accounts are not supported: a Keycard key cannot rotate.

An initial key is also how a never-used account is admitted: you pay one with --to-initial-key, and name one in wallet program call as ik:<hex>. An account that has transacted is addressed by its id as usual.

Sending several transactions at once

Because each signature commits to the next key, a queue of transactions from one account is a chain, not a set. The mempool enforces that:

  • one pending transaction per account and nonce, and the first one seen wins
  • a transaction whose nonce is ahead of the account’s is admitted only on top of a pending one, and only against the key that pending transaction commits to
  • at most mempool_max_per_account of them, 16 by default (lez/sequencer/core/src/config.rs)

So build a batch in order, against the keys each step rotates to. Submitted out of order, the later ones are refused rather than queued.

Private accounts, addresses and the mailbox

What is on chain

For a private account the chain holds no plaintext contents, only:

  • commitments: one per version of the account, a hash of the account id and its contents;
  • nullifiers: one per version that has been replaced;
  • encrypted notes: the new contents, encrypted to the owner’s viewing key.

An update spends the old version (publishing its nullifier) and creates a new one (publishing a commitment and a note). An observer cannot link a nullifier to the commitment it spends.

Keys

KeyLets the holder
Nullifier secret key (nsk)spend a version, so update the account and collect messages
Viewing keydecrypt notes, so read the account and find incoming messages
Authorization secret key (ask)supply an authorized private witness, which can then mark the actors it authorizes

The commands that make these: wallet account new private for a regular one, wallet account new private-accounts-key to print an npk and vpk pair for a sender who will address you by keys rather than by id, and wallet account new private-gms for a shared one (Shared private accounts).

The witness a user supplies for a regular private account comes in three strengths (lee/state_machine/core/src/circuit_io.rs):

pub enum RegularKey {
    Authorized(AuthorizationSecretKey),  // can spend
    Nullifying(NullifierSecretKey),      // can only receive and update
    FeeOnly(AuthorizationSecretKey),     // authorizes only the fee entry
}

Only Authorized lets the witness mark actors, which then hold grants at the sync root. Nullifying can update the account and collect messages, so it suffices for receiving, but authorizes nothing.

Kinds of private account

  • Regular. Id derived from the public keys. Authorized by ask.
  • Private PDA. Id derived from a program, a seed and the holder’s public keys. It has no ask: only a seed grant from the program authorizes it. The holder can operate it but cannot spend from it alone.

Addresses and pseudonyms

A private account can receive at a blinded address instead of its account id:

account_id.blinded(&factor)   // a hash of the id and a 32-byte secret factor

Each factor gives a different address. From the addresses alone, an observer cannot link two of them to each other or to the account, though the program account id beside an address stays public. The owner proves in zero knowledge that an address opens to their account.

Blinded addresses work in both directions:

  • Receiving. An async message sent to the address is collected by the account behind it.
  • Sending. A private actor can present an address instead of its account id as the sender; the receiver sees a stable pseudonym and can reply to it.

Use a fresh address per counterparty, per campaign or per conversation.

Who a blinded address hides you from depends on who writes to it:

  • Observers and public senders see only the address, and a public sender needs nothing else.
  • A private sender seals the message to you, and for that it needs your public keys and the factor (seal_message, lee/state_machine/core/src/sealing.rs). Those keys give your account id, so a private counterparty you hand an address to knows which account it is, and can link every address of yours it was given.

So a blinded address hides you from the public, not from private senders. The wallet CLI seals to a blinded address only for an account it holds the keys of, when a handler run by a collection sends a message onward (--seal-destination with --address-opening on wallet pending receive), and to a counterparty given by its npk and vpk it seals at the plain account id. The C ABI takes openings (the factors that open an address) for any mention (an actor the client lists for the transaction), a foreign one included (FfiAccountMention).

Recovery bindings

An address can receive stored messages in the clear (from a public sender, or a private one that publishes in the clear) only once a recovery binding for it is on chain, or is introduced by the same privacy-preserving transaction. Registration publishes a recovery binding (lee/state_machine/core/src/recovery.rs):

pub struct RecoveryBinding {
    pub address: AccountId,
    pub note: EncryptedNote,
}

The note, encrypted to the owner’s viewing key, tells the owner which of their accounts the address belongs to and with which factor. This is how a wallet restored from a seed finds the messages sent to its addresses.

The binding is created from the recipient’s public keys and factor, so the recipient or anyone holding those can publish it, in a private transaction, and once on chain it is reused.

  • A sender holding the recipient’s keys can introduce the binding in the same transaction and needs no prior registration, but only a privacy-preserving transaction can carry one (PublicExecution holds only the root call). So a wallet sending from a public account to a key pair whose address has no binding on chain yet builds a privacy-preserving transaction and pays for a proof, rather than failing.
  • A clear publication to an address with no binding, and none introduced alongside it, fails with UnboundAsyncDestination on the terms of any failure, and when charged pays only the cycles that ran.
  • The reference wallet checks the destinations it is given: it introduces the binding when it holds the recipient’s keys and otherwise refuses to build. Its simulation does not check a publication a handler makes to any other address.
  • A sealed message from a private sender needs no binding, because its own note tells the recipient which address it was for.

The mailbox

An AsyncMessage that is not delivered in its own transaction becomes a publication:

pub enum Publication {
    Clear(MessageBody),
    Sealed(SealedMessage),
}
  • Clear. Sent by a public actor, which always publishes in the clear, or by a private one that chose to. Sender, destination address and message bytes are readable by everyone. The owner finds it through the address’s recovery binding.
  • Sealed. Sent by a private actor. The chain holds a commitment and an encrypted note that only the recipient (and the sender, who wrote it) can read.

Every publication is added to the chain’s commitment tree.

Collecting

The owner’s wallet scans publications, decrypts what it can, and lists what belongs to it:

wallet pending list
wallet pending receive --position <n>

Collecting is a private transaction whose root is the stored message. The handler of the receiving actor runs with from set to the original sender. The proof publishes a nullifier for the message, a hash of the receiver’s nullifier secret key, the message’s commitment and its position (Nullifier::for_message, lee/state_machine/core/src/nullifier.rs), and settlement refuses one already spent, so it cannot be collected twice.

  • Collection is voluntary: a message never collected has no effect, and it never expires.
  • One message is the root. A transaction may claim others before it. The reference wallet sweeps up to four pending native credits into any privacy-preserving transaction it builds, for the private accounts it authorizes and its fee payer, fewer when the transaction’s own accounts and root leave fewer of its padded action slots, and none when it is synced more than 64 blocks behind the head (MAX_SWEPT_CLAIMS, MAX_SWEEP_SCAN_BLOCKS, lez/wallet/src/lib.rs).
  • The owner sees the message first. wallet pending list shows each message’s destination, sender and size, and wallet pending receive runs the message through the destination actor’s program.
  • Collecting never authorizes: a claim arrives with no grants, so a collected message cannot debit its recipient whatever keys the collection used (Authorization).

Shared private accounts

A group can own private accounts together (lee/key_protocol/src/key_management/group_key_holder.rs). The group shares one 32-byte secret, the Group Master Secret, from which every member derives the same keys for:

  • a shared regular account, which every member can spend;
  • a private PDA of a given program and seed, which every member can operate and only the program can authorize. The keys are derived from the program’s image id, so they stay the same wherever that program is deployed.

The secret is passed to a new member sealed to their sealing key, a separate key pair of the viewing key’s kind that wallet group new-sealing-key makes once per wallet. The member shares its public half, the inviter runs wallet group invite --key, and the member runs wallet group join --sealed (SealingSecretKey, group_key_holder.rs).

wallet account new private-gms makes either form: a shared regular account with --derivation-id (a value every co-owner must supply to derive the same account; random if omitted), or a group PDA with --pda --seed --program-id. A group PDA’s keys come from the program’s image id and the seed, but its account id from the program’s account id, the seed and those keys. The CLI takes only the image id and assumes the program sits at the image id’s own bytes (AccountId::from_builtin_program, lez/wallet/src/lib.rs), where only programs seeded into test states sit, so for a deployed program the account id it derives does not match the chain (What works with the reference wallet today). The second form is the basis of hidden shared vaults: see Multisig.

Two limits: every member sees everything in a shared account, and a member cannot be removed without moving to a new group secret.

What the owner must keep

The chain has the notes, so a wallet restored from its seed can find its own accounts and its mailbox again by scanning. Shared accounts are the exception: their keys come from the group secret, which is random rather than derived from the seed. Keep the seed and each group secret.

Programs, deployment and identity

What a program is

A program is a RISC Zero guest binary with one entry point: the handler. Its image id is a hash of the binary; its account id is where it is deployed, the id that appears in every Actor.

The same binary can be deployed at several addresses, and each deployment is a separate program: separate actors, separate PDAs.

Deployment

Programs are deployed through the program loader, a built-in program that runs as engine code, with no bytecode, at a fixed address (PROGRAM_LOADER_ACCOUNT_ID). The loader stores, as its own actor state:

  • a header at the program’s address;
  • the bytecode, split over a chain of segment accounts.
pub struct ProgramHeader {
    pub image_id: ProgramId,              // recomputed from the bytecode, never taken on trust
    pub program_first_segment: AccountId,
    pub immutable: bool,                  // once true, the header can never change
}

A program has at most 20 segments (MAX_PROGRAM_SEGMENTS). The wallet splits the user ELF at 96 KiB per segment (MAX_SEGMENT_DATA_LEN), but that is a client chunk size, not a limit the loader enforces: a segment is bounded only by the per-transaction cap of max_block_size less the block overhead. Deploying has the commands, the account rules and the errors.

Loader messages are allowed only in transactions that carry no proof, so a code change never lands inside a transaction whose proof already committed to specific program images.

Upgrades

A header that is not immutable can be pointed at new bytecode. For the author this has two consequences.

  • State layout. The new code reads actor states written by the old code. Version the layout from the first release.
  • Old messages. An AsyncMessage sent by the old version may sit in a mailbox for months and be collected after the upgrade. The new handler must still decode and accept every message the old version could have sent.

Marking a program immutable removes both problems and enables undisclosed execution, below.

Built-in programs

Built-in system programs live at ids derived from fixed names, as public PDAs of the system upgrader program (Sequencer stake):

AccountId::from_system_program_name(&SystemProgramName::new(b"clock"))

They are listed in System programs. The native token has a reserved id and no bytecode: the engine and the privacy circuit compute it directly, so it needs no inner proof.

Program identity in a private transaction

When a private handler runs, the proof must say which code it was. There are two ways (ProgramImageClaim, lee/state_machine/core/src/circuit_io.rs):

ClaimWhat is publishedChecked by the sequencer
Disclosedthe program’s account id and image idthat this image is deployed at this id
Undiscloseda root of the commitment treethat the root is a known one

An undisclosed claim proves that the code is some immutable program, without saying which. An immutable program’s header is mirrored into the commitment tree, so membership can be proven in zero knowledge. Only immutable programs can run this way.

A third form is a shadow program: one never deployed, addressed at an id derived from its image id alone (AccountId::for_shadow_program), so the circuit resolves its code from that id and the proof publishes no claim for it (lee/privacy_preserving_circuit/src/main.rs). It can run only on private actors: the sequencer cannot load it, so a message reaching it in public execution fails with UnknownProgram. wallet pending receive --shadow-program <elf> runs one.

Choosing between the first two is a privacy decision:

  • Disclosed: observers learn that your private transaction used this program.
  • Undisclosed: they learn only that it used some immutable program, and only if that program never crosses the boundary in the transaction.

Every boundary entry names an Actor ({ account_id, program_account_id }), and blinding hides the account id but not the program account id (lee/state_machine/core/src/execution_state.rs). So a message across the boundary, in either direction, publishes the private actor’s program account id, the image resolves from it, and the undisclosed claim hides nothing.

Staying off the boundary is necessary but not sufficient. The claim proves membership of the set of immutable programs, and every deployment is public, so an observer guesses among only as many programs as are immutable on chain.

Undisclosed is also not a property of the program but a choice each prover makes per transaction (ProgramCatalog::with_undisclosed, lee/state_machine/src/privacy_preserving_transaction/circuit/mod.rs), and the default is Disclosed, which reveals the program. The wallet CLI never selects Undisclosed (the C ABI lets a caller choose it per program, FfiProgramKind). Marking a program immutable makes undisclosed available to a prover who wants it; it does not hide the program, and an author cannot choose for their users.

Where a program keeps its state

Three places, and most programs use more than one.

  • On users’ accounts. One actor per user: balances, holdings, seats, badges.
  • On PDAs. Shared state the program controls: vaults, pools, registries, configuration.
  • On fixed accounts. For built-ins: the clock account, the fee state.

Where state lives compares them.

System programs and the block

The block

A block is a list of transactions. The sequencer adds two of its own at the end: the fee distribution, then the clock tick. The clock transaction must be exactly the one expected for the block’s id and timestamp, or the block is invalid (lez/chain_state/src/apply.rs).

User transactions cannot modify the clock account or the three fee accounts (state, escrow, inbox), with one exception: a private transaction’s in-proof fee credit to the fee inbox. A transaction that pays a declared fee and would change one of them is reverted and still pays that fee; any other such transaction makes the block that carries it invalid.

Native token

The native token is a small, complete actor program, built into the engine rather than deployed (lee/state_machine/core/src/native_token.rs).

pub enum Message {
    Transfer { to: AccountId, amount: Balance },
    Credit(Balance),
    ReadState,
}
  • Transfer debits the balance actor it is sent to, which needs a grant the caller attaches, and sends Credit to the destination as an async message.
  • Credit is accepted only from the native token program itself.
  • ReadState replies to the sender with a StateReply (its own type, not a variant of this one), handing back the grant the reader lent (with_lent_grant) so the reader can act on what it read.

There is one actor per account: Actor::native_balance(account_id). A program that holds funds uses custody_transfer with a PDA seed (see Authorization).

Clock

The clock program (lez/programs/clock) is one actor at a fixed account, CLOCK_PROGRAM_ACCOUNT_ID, holding { block_id, timestamp }. The sequencer sends it Tick as the last transaction of every block, so every other transaction in block N sees block N-1’s time.

A program reads it, and the read is rounded down:

MessageReplyRounded to
ReadBlockId { granularity }Reply::BlockId(u64)a multiple of granularity blocks
ReadTimestamp { granularity }Reply::Timestamp(ms)a multiple of granularity milliseconds

With a granularity of 50 at block 57 you are told 50: the reader chooses the coarseness per read.

Reading has two constraints. Only an actor can read the clock, so a transaction whose root goes straight to it fails. And the reply arrives as a message, so the reader needs actor_entrypoint!(raw ..): the typed entrypoint would try to decode the reply as the reader’s own message type.

test_programs/guest/src/bin/cooldown.rs, abbreviated to its control flow, sends a read to the clock, recognises the reply by its sender, and only then does its work:

lee_core::actor_entrypoint!(raw handle_message);

fn handle_message(input: &ReceiveInput) -> Response {
    let clock = clock_core::clock_actor();
    if input.from != Some(clock) {
        return Response::keep_state().send_sync(
            clock,
            &clock_core::Message::ReadTimestamp { granularity: 1 },
        );
    }
    let Reply::Timestamp(now) = Reply::from_message(&input.message) else {
        panic!("Cooldown reads only the clock's timestamp");
    };
    // ... compare `now` against the stored timestamp, then record it
}

Reply::from_message decodes without verifying who sent it, so a program that skips the input.from check accepts a forged reply from anything that can reach it.

Reading costs validity. A private transaction that read the clock stays valid only while the rounded value is still the one it read. A granularity of 1 expires almost immediately.

Gating on time without reading

Most deadlines need no read. A response can carry a validity window, and the block being built either satisfies it or the transaction’s effects do not apply: a public transaction outside its window is reverted with OutOfValidityWindow and still pays its fee. A private transaction’s proof carries its private handlers’ windows, checked before anything runs: if they exclude the block, the sequencer skips the transaction and it pays nothing. Its public handlers’ windows are checked at settlement and fail like a public handler’s panic (What the handler returns): reverted and charged when the proof carries a fee fallback or a public signer declares the fee, dropped unpaid otherwise. The reference wallet’s simulation does not check windows, so it will send a transaction that is not yet or no longer valid. test_programs/guest/src/bin/time_locked_transfer.rs, without its doc comment and imports:

lee_core::actor_entrypoint!(handle_message);

fn handle_message(
    input: &ReceiveInput,
    (amount, deadline, receiver): (u128, Timestamp, AccountId),
) -> Response {
    let payer = Actor::native_balance(input.receiver.account_id);
    Response::keep_state().timestamp_window(deadline..).send(
        SyncMessage::new(
            payer,
            &native_token::Message::Transfer {
                to: receiver,
                amount,
            },
        )
        .with_grants([payer]),
    )
}

It keeps no state and never learns the time: the deadline arrives in the message, and timestamp_window(deadline..) makes the transaction valid only from that moment on.

Actor::native_balance(..) addresses the balance actor: a program moves balance by sending to it, not by writing a number.

.with_grants([payer]) passes the grant over payer on to the message it sends (Authorization).

A window is cheaper, needs no reply, and covers “not before” and “not after”. Read the clock only when the program has to store the time or branch on it.

Fee

The fee program holds the fee market’s state (How fees are priced) and distributes each block’s fees: base revenue to the fee escrow, tips and a smoothed payout from the escrow to the producer, the sequencer that built the block. The node is the only caller whose effects apply, and the program refuses a call from another program: Distribute runs in the block’s fee transaction, and Refund runs as a settlement step of a fee-paying transaction that left part of its reserve unspent. Distribute uses the reply pattern: it asks the fee inbox’s native balance actor for its state and pays out when the reply arrives (lez/programs/fee/src/main.rs).

Bridge

The bridge pays out deposits made on L1 from its custody PDA (lez/programs/bridge/src/main.rs). The sequencer injects one transaction per L1 deposit, once the deposit is final on L1, or earlier in a pinned block: a zone block inscribed in the same L1 transaction as a transfer that re-creates the deposit’s notes unchanged, so the block lands on L1 only where the deposit does. Other sequencers and the indexer rebuild each injected deposit from their own view of L1 and refuse a block whose deposit they cannot rebuild byte for byte (check_injected_deposits, lez/chain_state/src/apply.rs).

Withdrawals are not available: wallet bridge withdraw exists, but the program refuses it with Withdraws are disabled in the current version of LEZ, so value moves onto a zone but not yet back off it.

  • The root goes to a receipt actor: a PDA derived from the deposit’s id.
  • The handler requires the receipt to be empty, writes a marker, and pays the recipient from the bridge’s custody PDA.
  • A second delivery of the same deposit finds the marker and fails.

A receipt actor keyed by an id is a simple way to make something happen at most once.

Because of admission, a deposit names its recipient by evidence, not by bare id: the account’s initial key, or the program and seed of a PDA (DepositRecipient, lez/programs/bridge/core/src/deposit.rs).

Sequencer stake

The stake program holds the committee’s stakes and the channel configuration. Staking, unstaking, slashing and channel parameter changes all go through it. When two thirds of the accredited keys hold a standing vote for the same values, those values replace the current ones in that transaction and every vote is cleared. A vote for the values already in force is refused, and only finality_depth is fixed at genesis. A key’s stake is released once the configuration removing it is finality_depth L1 blocks deep, not zone blocks; Finality says how it relates to the L1’s security_param.

It is also where system upgrades are approved. system_upgrader is one of the five programs every zone seeds at genesis, with the clock, fee, bridge and stake programs (builtin_programs, lez/programs/src/lib.rs), the only one seeded immutable, and every other system program’s address is its PDA. Its messages are Schedule, Apply, Cancel and Install. All but Apply carry committee approvals; Apply carries none and is valid only in the block at the activation_height the approved Schedule set. The program is lez/programs/system_upgrader; the operator side is the approve_system_change binary (lez/sequencer/service/src/bin/approve_system_change.rs) and the submitSystemApproval and getSystemProposals RPCs.

getSystemProposals reports the threshold alongside the queue, and on a fresh devnet it answers {"threshold":2,"proposals":[]}. That 2 is a floor, not a count: the threshold is two thirds of the committee but never fewer than two, so a single-key committee cannot upgrade itself unilaterally. Channel params voting needs two thirds with a floor of one, which is why a lone sequencer can change parameters but cannot approve a system change. Exercising it needs a second staked key.

What is not there

  • No randomness beacon.
  • No oracle among the built-in programs (logos-blockchain/lez-programs has a twap_oracle program).
  • No scheduler. Nothing runs unless a transaction delivers a message. Designs that need something to happen “at time T” rely on someone sending a transaction after T.

Toolchain: build, deploy, test

The worked example is examples/program_deployment.

A program crate

A guest program is a binary crate that depends on lee_core. Its source is a handler and one macro line:

use lee_core::program::{ReceiveInput, Response};

lee_core::actor_entrypoint!(handle_message);

fn handle_message(input: &ReceiveInput, greeting: Vec<u8>) -> Response {
    let mut bytes = input.pre_state.to_vec();
    bytes.extend(greeting);
    Response::set_state(bytes)
}

The second parameter can be any type that implements BorshDeserialize, in practice an enum of the messages the program accepts.

A guest crate outside this repository depends on lee_core by git, pinned to the release your node runs:

[dependencies]
lee_core = { git = "https://github.com/logos-blockchain/logos-execution-zone", tag = "v0.4.1" }
borsh = { version = "1.5.7", features = ["derive"] }
risc0-zkvm = { version = "3.1.0", default-features = false, features = ["std"] }

The same three lines serve the guest build and host unit tests. For a node built from a checkout, replace tag with rev = "<commit>", the node’s commit.

Put the message types in a separate core crate, as the shipped programs do (lez/programs/clock/core, or logos-blockchain/lez-programs: programs/token/core). Wallets, tests and other programs need the types without the guest code.

Building

RISC0_DOCKER_CONTAINER_TAG=r0.1.91.1 \
CARGO_TARGET_DIR=target/<methods dir> \
  cargo risczero build --manifest-path <methods dir>/guest/Cargo.toml

The output is one .bin file per binary in the guest crate, under target/<methods dir>/riscv32im-risc0-zkvm-elf/docker/.

Two caps bound the program’s memory layout, not its size on chain: at most 8 loadable segments (MAX_LOAD_SEGMENTS) and at most 4 MiB of loadable memory (MAX_LOADABLE_MEMORY). The loader checks both when it computes the image id in the header transaction, so a deployment exceeding either fails there, after its segments are already written and paid for. Large static arrays and a big .bss hit them. The 20-segment limit is separate: it bounds the bytecode chain the loader writes.

Pin the image tag: the image decides the image id, so a different builder gives a different id for identical source. Without the tag you get your installed cargo-risczero’s default image, which changes between its releases, and a default older than the pin can fail outright: cargo-risczero 3.0.5 defaults to r0.1.88.0, whose rustc 1.88 is too old for dependencies of this workspace’s guests, so the build stops before producing a .bin. CARGO_TARGET_DIR keeps each guest crate’s output apart, under target/<methods dir> relative to the directory you run the build from; without it the output lands in the guest crate’s workspace target directory (target/riscv32im-risc0-zkvm-elf/docker/ at the root, for a guest inside this repository), shared with every other guest built there. just build-artifact sets both, so a bare cargo risczero build copied from elsewhere gives a different result.

The directory you run the build from is also the Docker build context. The guest’s workspace, its root manifest and Cargo.lock included, and every path dependency of it, such as a sibling core crate, must lie inside it. For a crate outside this repository, run from the root of a workspace holding the guest and its core crate. A host crate that depends on a checkout of this repository by path belongs in a separate workspace: the container loads every member, and the checkout is outside the context.

Deploying

wallet account new public --label hello-header
wallet account new public --label hello-seg-0   # and seg-1, seg-2, ...
wallet program-loader deploy --elf path/to/hello_world.bin \
  --header hello-header --segments hello-seg-0 hello-seg-1 hello-seg-2 --immutable \
  --payer Public/<funded account>

deploy takes no positional path. The accounts must already exist with an empty program_loader state; the wallet chunks the ELF but never creates accounts. --payer pays every segment and header transaction; without it the wallet picks a payer from those new, empty accounts and the deploy fails on its fee reserve. You need one segment account per 96 KiB of the user ELF inside the .bin (MAX_SEGMENT_DATA_LEN), so a typical program takes several; a wrong count fails before anything is sent, with Program bytecode splits into 3 segment(s) but 2 were supplied. A deploy that fails partway cannot be resumed over the same accounts. wallet program-loader --help lists the arguments.

The wallet prints every transaction it waits for in full, segment bytes included, so a deploy can print over a megabyte. The program id is on the last line, Program deployed. Header account id: <id>. Set SUPPRESS_VERBOSE_PRINTS=1 to drop these dumps from every wallet command.

Accounts

wallet account new public  --label my-account
wallet account new private --label my-private-account
wallet account get --scope all --account-id Public/<id>
wallet account get --scope all --account-id Private/<id>

The Public/ or Private/ prefix tells the wallet which state to read: a public account from the sequencer, a private one from the wallet’s own synced copy. Without --raw, the wallet prints each actor state on the account separately.

Sending a message

wallet program call sends one public transaction to any deployed program, with the message already Borsh-encoded as hex:

wallet program call --program <program id> --message-hex <hex> \
  --to <account>[:sign] --payer Public/<funded account>

The program id is the header account id that program-loader deploy prints. --to is the actor the message goes to, and :sign makes the signature authorize it, which is what input.is_authorized() sees. Repeat --actor for every other actor the call touches. An actor is <account>[@program][:sign], with @program defaulting to --program, so --actor Public/<id>@11111111111111111111111111111111 declares that account’s native balance (that is the native token’s id, 32 zero bytes, which base58 writes as 32 ones). wallet program call --help gives the rest of the syntax, including PDAs; a PDA seed is 32 bytes, as base58 or as 0x and 64 hex digits. For the hello world program the message is a Vec<u8>, so Hola is its four-byte little-endian length then the bytes: 04000000486f6c61.

A private call, or a client of your own, needs code (What works with the reference wallet today). Each example has a small runner that loads the wallet, deploys the program (some can instead reuse one they are given), selects the program’s actor on an account, and submits a transaction:

cargo run --bin run_hello_world -- ...
cargo run --bin run_hello_world_private -- ...

The program is the same; the public runner builds and signs a PublicTransaction itself, and the private one hands a ProgramCatalog to the wallet’s send_privacy_preserving_tx. Read examples/program_deployment/src/bin/ for the code; it is the template for your own client. The runners do not sync: before proving on a private account, sync the wallet (wallet account sync-private, or sync_to_latest_block in the library). A proof built on state that a newer transaction already spent fails after the full proving time: refused with Nullifier already seen once that spend is in the head, or before then dropped from the block while the runner still returns (hello_world_with_move_function).

Receiving stored messages

Pending messages collects what other actors stored for your private accounts.

Testing a handler

A handler is an ordinary function: test it without a prover, chain or wallet by building the input by hand. The clock program’s tests show the shape (lez/programs/clock/src/main.rs):

const CLOCK: AccountId = AccountId::new([1; 32]);

fn data(block_id: u64) -> ClockAccountData {
    ClockAccountData { block_id, timestamp: 1_700_000_057 }
}

fn tick(block_id: u64) -> Message {
    Message::Tick { timestamp: 1_700_000_057, block_id }
}

fn run_on(account_id: AccountId, from: Option<Actor>, pre: ClockAccountData, message: Message)
    -> Transition
{
    let receiver = Actor::new(account_id, CLOCK);
    let input = ReceiveInput {
        receiver,
        from,
        grants: std::collections::BTreeSet::new(),
        pre_state: ActorState::from(pre.to_bytes()),
        message: borsh::to_vec(&message).unwrap(),
    };
    handle_message(&input, message).into_transition(input)
}

#[test]
#[should_panic(expected = "The clock program runs only on the clock account")]
fn another_account_is_refused() {
    let _transition = run_on(AccountId::new([2; 32]), None, data(9), tick(10));
}

Test each message as three questions:

  1. With an honest sender and authorization, is the new state right and are the right messages sent?
  2. With the wrong sender, is it refused?
  3. Without authorization, is it refused?

Because a handler sees only its own state and its input, these tests cover each handler on its own, but not the conversation between actors. For that, run a local sequencer and the wallet, as the integration tests under integration_tests/ do.

Proving in development

Set RISC0_DEV_MODE=1 to skip real proving while developing; private transactions then build in seconds. The proofs are fakes, so the sequencer accepts them only if it runs with RISC0_DEV_MODE=1 too; otherwise it refuses them with Invalid privacy preserving execution circuit proof. Never use it on a real network.

Versioning

Decide on the first day how your actor state and your messages are versioned. Both outlive the code: state stays on accounts, and async messages stay in mailboxes. See Upgrades.

What a private transaction reveals

A private transaction hides what happens inside private actors, not everything. Each section below is a published part, from ProvenExecution (lee/state_machine/core/src/circuit_io.rs) or the message around it, and what an observer learns from it.

The boundary

The list of messages that crossed between private and public actors, all in the clear. For each crossing an observer sees:

  • the destination actor;
  • the sender, at the address it presented;
  • the full message bytes;
  • the grants and PDA seeds that came with it.

This is the main leak, by design: the sequencer runs the public handler, so it must see the message.

You control the sender address: a private sender can present a blinded address, so the public side sees a pseudonym, not the account.

Rule of thumb: anything a private actor says to a public actor is public. Only who said it can be hidden.

The public context

Published in full: the public actors the transaction declares, the accounts it authorizes, which AsyncMessages it asked to deliver in the transaction, and, when the root is public, the private actors it holds grants over, at the addresses they presented. An observer learns which public actors the transaction was prepared to touch, even ones never reached.

The public root

Published if it targets a public actor, not if it targets a private one.

Private actions

For each private account the transaction touched, one entry:

  • a nullifier, which marks an old version as spent;
  • a commitment to the new version;
  • an encrypted note with the new contents.

None of the three names an account or links to earlier entries. Each action also carries the commitment-tree root it was proven against, which shows roughly when the proof was built.

The reference wallet pads every private transaction up to seven private actions and every note to at least 512 bytes (lez/wallet/src/account_manager.rs); a note for a larger account ships at its own length. For transactions it builds, an observer cannot tell one private action from seven. Eight is the zone’s hard cap (MAX_PRIVATE_ACTIONS in lez/programs/fee/core/src/market.rs, enforced in lez/chain_state/src/classify.rs), so a count of eight is the only one that shows as itself. The count covers more than the accounts touched: a message being collected, any pending credits the wallet claimed alongside, and a fee payer brought in from outside the transaction.

A proven fee carries a fallback when the payer’s balance before the transaction covers it alone, so its presence shows the payer held at least the public reserve. The fallback repeats the payer’s nullifier, which picks out the payer’s action within the transaction but links nothing across transactions (FeeFallback, lee/state_machine/core/src/circuit_io.rs).

Sealed async messages

A stored message sent by a private actor is published as a commitment and an encrypted note. Sender, destination and contents are hidden. An observer learns that this transaction sent a sealed message, and its padded size.

Clear publications

A stored async message from a private actor is published sealed or in the clear, at the sender’s choice; one from a public actor is always in the clear. A private sender that publishes in the clear can pay an address with a recovery binding without holding the recipient’s viewing keys, at the cost of publishing the body in full: destination, contents, and from as the sender presented it. The reference wallet presents a fresh blinded alias there, hiding the sender’s canonical address. The alias is fresh per message except for the fee payer, which keeps one alias per transaction, so a sender that also pays the fee is linked to the fee payment. Settlement only requires that the destination is bound, on chain or by a recovery binding in the same transaction (lee/state_machine/src/validated_state_diff/mod.rs).

There is no CLI flag or FFI call for it, and the wallet never picks clear on its own: async_destinations only seals or adds recovery bindings. A wallet library caller requests it, through NativeTokenTransfer::transfer_clear or by listing the message in AsyncDelivery::clear_messages (lez/wallet/src/lib.rs).

When a public account pays a private one, everyone sees the amount and the destination address. Paid at its account id, the payment publishes that id. Paid at a fresh blinded address, it does not, but every payment to that address is linked. Either destination needs a recovery binding when the payment is stored for later.

Recovery bindings

A newly registered receive address is published with its encrypted note. An observer learns that an address was registered, and by which transaction.

Validity windows

Published. A tight window narrows when the transaction was built and can hint at what it does (a deadline, a vote period).

Program claims

A disclosed claim names the program and its image. An undisclosed claim only says “some immutable program”, but a private actor that messages a public one still shows its program as the sender’s. See Program identity.

The native token and the program loader run as protocol code and are never claimed (lee/privacy_preserving_circuit/src/main.rs), and the reference prover claims only the programs a proof ran (lee/state_machine/src/privacy_preserving_transaction/circuit/mod.rs). So a wallet-built proof with no claims ran only protocol code or a shadow program, which in practice marks a native send or collection. A shadow program is never deployed, and the proof publishes no claim for it.

Signatures and nonces

A public account authorized by signature has its id and nonce published, which links it to everything else the transaction shows.

What is not published

  • The contents and ids of private accounts.
  • Messages between private actors that were delivered inside the transaction.
  • The inputs and responses of private handlers.
  • Events emitted by private handlers, which are dropped.

Metadata outside the transaction

  • Timing. When a transaction lands, and how it correlates with others.
  • Network. Who submitted it, unless the user takes care.
  • Patterns. A pseudonym used twice is linkable to itself.
  • Fees. A private transaction pays either through a reserve proven inside itself, which crosses to the fee inbox, or through a fee declaration by one of its public signers, which links that signer to the transaction as any signature does (lez/chain_state/src/classify.rs). The reserve amount is public. The payer is that crossing’s sender, presented like any boundary sender: blinded by default, canonical if the prover chooses. The reserve is an upper bound, not the fee, since a surplus is refunded (Private fees). The refund target is published: by default the payer’s blinded alias, or a public account the prover names (--refund-to in the wallet), which links that account to the transaction.

Worked example: a private voter

Dana holds a ballot in a private actor and votes in a public election.

FieldWhat an observer sees
Boundaryone message to the public tally: Vote { proposal: 7, choice: Yes }, from a blinded address of the voting program
Private actionsseven entries that name no account
Program claimthe voting program, disclosed
Signaturesnone

They learn that a valid ballot voted Yes on proposal 7, not that it was Dana’s.

Worked example: a public salary to a private employee

A public company account sends a native credit of 3,000 to an employee’s blinded address as an async message.

FieldWhat an observer sees
The public transactionthe company’s account, the amount, the destination address
The publicationthe same, stored
Later, a private transactionseven entries that name no account; only timing ties it to the publication

They learn that the company paid 3,000 to an address, not who owns it, or when or whether it was collected. To hide the amount too, the company pays from a private account, which seals the message.

What you cannot do privately

Nobody can make a private actor act

A private handler runs only inside a proof made by a holder of the account’s keys. A stored message that the owner never collects never runs.

Consequence: You cannot build “anyone can trigger this” on private state. A liquidation, a timeout or a penalty cannot reach into a private account.

Way around: Put what must be enforceable in a public actor, where a private participant posts a bond and the public actor acts on a deadline: answer in time, or lose the bond. See the public referee pattern in The pattern language.

One owner’s private accounts per transaction

A transaction can run private handlers only for accounts whose keys the submitter holds, so two people’s private accounts cannot both act in one transaction.

Consequence: No atomic private-to-private exchange between two parties.

Way around: A public escrow actor in the middle, with a timeout. Or a group-owned private account, when the parties trust each other with visibility.

A SyncMessage cannot reach a stranger’s private actor

Only an AsyncMessage can, and an AsyncMessage waits.

Consequence: You cannot ask “does Bob’s private account hold a badge?” and get an answer in the same transaction.

Way around: Bob proves it himself, in his own transaction, to a public actor.

Private state belongs to one key holder

There is no private state that two mutually distrusting parties can both update.

Way around: A group secret gives shared private accounts, with three costs: every member sees everything, membership cannot shrink without moving to a new secret, and any member can stall the others, since each update replaces the account’s commitment, so a member who keeps updating it makes everyone else’s pending transactions stale.

Whatever crosses to public is public

A private actor’s message to a public actor is published in full. See What a private transaction reveals.

Consequence: A private bidder’s bid to a public auction is visible, unless the message carries only a commitment to it.

Way around: Commit now, reveal later. Hide the sender behind a blinded address.

A public sender’s stored message is in the clear

A public actor that sends an async message to a private address publishes it.

Way around: Route value through a private actor first, so the async message is sealed.

A reply from public to private is fixed at proving time

The prover never reads public state. When a public actor replies to a private one inside a private transaction, the wallet predicts the reply from the public state it reads while building, the proof commits to that prediction, and settlement checks the live reply against it (The boundary). If the state the reply depends on changes before the transaction lands, the reply differs and the transaction fails.

Consequence: A private actor cannot reliably read fast-changing public state, such as the clock read at a fine granularity or a busy pool’s reserves.

Way around: Read coarse or slow-moving values. Or do not read: assert a range and let the transaction fail if the range no longer holds.

Collecting costs a proof

The protocol lets one transaction collect several stored messages: one as its root, the others as claims queued ahead of it, within the zone’s cap of eight private actions per transaction (MAX_PRIVATE_ACTIONS, lez/programs/fee/core/src/market.rs). The reference wallet claims only native credits this way, up to four into a private transaction it builds for the receiving account (Collecting), and collects any other message as the root of its own transaction. So with the reference wallet, draining N native credits takes about N/5 proofs, and N other messages take N.

Consequence: Designs that send many small non-credit messages to a private actor are expensive for the receiver.

Way around: Accumulate on the public side and send one message. Or let the sender batch.

A stored message is never returned

A stored message is not delivered in the transaction that sent it, so nothing that happens to it later can change that transaction. If the recipient never collects it, or its handler refuses it, the protocol returns nothing to the sender.

Way around: Receiving handlers for value must accept every legitimate message, or offer the owner a repair path. A sender who may want value back needs a return path in the program: a deadline after which they may reclaim, enforced by a public actor.

Events are dropped privately

A private handler’s events are not published.

Way around: If an indexer must see something, send it to a public actor that emits the event.

No randomness, no oracles

A handler is deterministic and sees only its input (the message, its own state on the receiving account, the sender and its grants) and the replies it gets. There is no randomness beacon and no price feed. Built-in programs answer two questions: the clock gives the block id and timestamp (ReadBlockId, ReadTimestamp), and the native token gives an account’s balance (ReadState). Neither brings in anything from outside the chain.

Way around: Commit-reveal between participants for randomness. A public actor fed by a trusted signer for external data.

Linkability is the user’s job

  • A blinded address reused is linkable to itself.
  • A signature links its account to the whole transaction.
  • Timing links transactions that look related.

Things that are fine

  • Paying a private account from its keys or an address it gave you, while it is offline.
  • A private actor acting on a public program under a pseudonym.
  • A public program trusting a statement about private state, when the statement comes from its own code.
  • Mixing public and private actors of the same program in one transaction, when you own the private ones.
  • Keeping a whole application’s state in a group-owned private account.

The pattern language

The recurring moves of actor programs on LEZ, which the catalog cites by number. Patterns 1 to 6 are about writing a correct handler. Patterns 7 to 12 are where public and private actors meet. Patterns 13 to 18 are about time, custody and exactly-once.

1. Tell, do not write

A handler changes only its own actor. To change another actor, send it a message and let its handler decide.

Example. A native Transfer does not write the recipient’s balance. It debits its own and sends the recipient’s balance actor Credit (lee/state_machine/core/src/native_token.rs).

2. Route on the sender first

Before decoding a message, look at input.from, decide which messages this sender may send, then decode with that type.

Why. Messages are untyped bytes. A reply format and a request format can collide. The sender is the one field a program cannot forge.

3. Internal messages

A message that only the program’s own actors may send is guarded with input.from_own_program().

Example. Credit in the native token. Without the guard, anyone could mint.

4. Know who is speaking: the owner, or a seat

The owner: an operation only the account’s owner may start checks input.is_authorized() and input.from.is_none(). The flag alone says the owner’s credential is in the transaction, not that the owner sent this message. See Authorization.

A seat: when a shared actor needs to know which participant is speaking, each participant gets an actor of the same program on their own account. The participant talks to their seat, which does the owner check above. The seat talks to the shared actor, which checks input.from_own_program() and the seat’s account id.

Why a seat. A sender’s account id proves nothing by itself: any program can be run on any public account without its owner. A seat is a sender whose code you wrote.

5. Reply with context

To read another actor’s value, send a request that carries your own context, and have the other actor reply with the value and the context back.

// request, in an actor you write
enum Request { Query { payload: Vec<u8> } }
// reply, sent to input.from
enum Reply { Answer { value: u64, payload: Vec<u8> } }

The asking handler runs twice: once to ask, once to continue. The returned context saves it from storing intermediate state. Always check that the reply’s sender is the actor you asked.

The shipped readers do not return context. The clock’s ReadTimestamp replies Reply::Timestamp(ms) (lez/programs/clock/core/src/lib.rs) and the native token’s ReadState replies StateReply { state }, so a handler that reads them keeps its context in its own state.

6. Receive without failing

A handler that receives value by AsyncMessage must accept every legitimate message, because a stored message is never returned.

Example. The native token’s Credit reads an empty balance as zero, so the first credit creates the balance. It refuses only a credit that no native Transfer sent, and an overflow.

7. The proof-carrying message

A private actor of program P sends a message to a public actor of P. The public actor checks input.from_own_program().

Because the private handler ran inside the proof, the public actor now knows a fact about hidden state: “an actor running my code, in a state my code allowed, decided to send this”. It does not know which account.

Anonymous votes, hidden multisig members, credentials and honest hidden-information games all use it.

8. Pseudonym

A private actor presents a blinded address as its sender. The public side sees a stable name it can store, count and reply to, plus the program and the message, but not the account.

  • One address per relationship: linkable inside it, unlinkable across.
  • A fresh address per action: unlinkable by address, though timing, amounts and fees can still link actions.

Pattern 7 says what kind of actor spoke. Pattern 8 says which one, under a name of its choosing.

The name hides the account from observers and public actors, but not from a private party who sends to that address: sealing a message needs the recipient’s keys and blinding factor, which reveal the account. See Private accounts.

9. Async message for strangers

Send value and notifications to other people with an AsyncMessage, not a SyncMessage. The same code then serves public recipients (delivered at once) and private ones (stored).

10. Accept by answering

A request is an AsyncMessage that asks for something: pay this, sign that, swap these. It carries no authority and cannot act. The recipient accepts by sending a transaction of their own that marks the actors the answer needs, and declines by doing nothing.

The handler has two halves. The asking message is unauthenticated and only records the request. The answering message arrives as a root call, so it checks input.is_authorized() && input.from.is_none() and then attaches the grant it was handed to whatever it has to send.

Collecting the request is not consent: a design that waits for collection to authorize something never receives that authority, so it fails without acting.

11. Anyone may poke

A public actor exposes a message that anyone can send and that only moves the actor forward by its own rules: release what is due, close what has expired, pay what is owed.

Why. A program runs only when a transaction reaches it. Poke messages let any interested party, or a paid keeper, supply the transaction.

12. The public referee

A private participant cannot be forced to act, so a public actor holds a bond and a deadline. The participant answers the challenge in time, with a proof-carrying message, or the referee pays the bond to the other side.

Use it for games, disputes, and any protocol with a “your move” step.

13. Seed-authorized custody

Funds live in the balance actor of a PDA. Only the program can move them, by granting the seed on a SyncMessage. Derive the seed from the instance’s identity so instances cannot spend each other’s funds. If a caller supplies the seed and it is stored, check on that first write that it derives the actor’s own account (for a private PDA the derivation also takes the npk and vpk). A stored seed that does not derive the account locks the funds permanently: every later payout fails.

14. The receipt actor

To make something happen exactly once, address it to an actor whose account is derived from the thing’s unique id. The handler requires an empty state and writes a marker.

Example. The bridge’s deposit receipt.

15. Write once

Configuration that must never change is written with write_once, which accepts the first value and any identical repeat, and refuses anything else.

16. Windows for expiry

A handler that must not run outside a period (before it starts or after a deadline) returns a validity window. No message, no clock, no state.

17. Clock assertion

A handler that depends on time passing either carries a validity window (pattern 16), which covers most deadlines, or reads the clock with ReadTimestamp and handles the reply. Read with the coarsest granularity that is precise enough: a private transaction stays valid only while the rounded value it read still holds.

18. Group-owned private PDA

Shared hidden state: a private PDA whose keys come from a group secret. Any member can operate it; only the program can authorize spending from it. Combine with pattern 13 for a hidden vault.

Anti-patterns

  • Marking more actors :sign than the call needs. The root program holds every grant you mark and can pass any of them on.
  • A reply with fast-changing data to a private actor. The proof goes stale as soon as the value changes.
  • One enum for everything a program sends and receives. It forces handlers for messages that should never arrive.
  • State that grows without bound. Nothing prunes it, and every later run pays to load it.
  • Deriving meaning from an address. An address is a name. Check the sender and the state.

Where state lives

Every piece of state a program keeps is an actor on some account. The kind of account decides who can read it, who can change it, and who has to be online for it to change.

PlacementWho readsWho can run the handlerWho authorizesReached by
Public, key-ownedeveryonethe sequencer, in any transaction that declares itthe owner’s signatureSyncMessage or AsyncMessage, from any transaction that declares it
Public PDAeveryonethe sequencer, in any transaction that declares itthe program, by seedSyncMessage or AsyncMessage, from any transaction that declares it
Private, regularthe ownerthe owner, in their own proofthe owner’s authorization key (ask)SyncMessage from the owner’s own transaction; AsyncMessage from anyone
Private PDAthe key holderthe key holderthe program, by seedsame as private
Group-owned private PDAevery group memberany group memberthe program, by seedsame as private
The mailboxclear: everyone; sealed: the recipient (and the sender)nobody; messages waitnot applicableAsyncMessage

Choosing

Must anyone be able to move it forward? Then it is public. Pools, tallies, auctions, referees and anything with a deadline belong on a public PDA.

Is it one person’s secret? Then it is a private actor on their account. Balances, ballots, badges, hands of cards, a ship’s position.

Is it a group’s secret? Then it is a group-owned private PDA. A hidden treasury, a shared ledger.

Is it in transit? Then it is a message. Value on its way to someone is a stored AsyncMessage, not a field in somebody’s state.

Mixed placements in one program

Many designs use two placements and connect them with messages.

  • Public hub, private spokes. A public actor holds the shared state. Each participant holds a private actor of the same program. Spokes speak to the hub with proof-carrying messages (pattern 7). The hub speaks to spokes with AsyncMessages (pattern 9). Voting, credentials and the space game have this shape.
  • Private hub, any spokes. A group-owned private PDA holds the shared state. Participants send it AsyncMessages. One member at a time collects them. The hidden multisig has this shape.

The same program can support both, if its members always speak by AsyncMessage and its hub never assumes it is public. The multisig entry works this through.

A note on “who can read”

  • Reading a public actor from off chain is free. Reading it from a program takes a request and a reply.
  • A private actor is read by the wallets that hold its viewing key: its owner’s, or every member’s for a group-owned PDA. Another program sees its state only when its handler sends it, as the native token’s ReadState reply does (lee/state_machine/core/src/native_token.rs), and a reply to a public actor is public.
  • A sealed message is read by its recipient’s wallet, before any handler runs. The recipient chooses what to collect, though the reference wallet also claims pending native credits on its own (Collecting).

How to read the catalog

Each entry opens with a Shows line naming the patterns it demonstrates, by number as in “(pattern 7)”, defined in The pattern language. The sections follow; not every entry has all of them:

  • Goal. What the program does for its users.
  • Actors. Which actors exist, where each lives (see Where state lives), and who authorizes it.
  • Messages. The message types, with who may send each.
  • Handler. Illustrative Rust. It follows the real API and has not been built or tested. Helper names such as decode and Ship::from_bytes stand for ordinary serialization code.
  • What to notice. The points the example exists to make.
  • Public and private. What changes, and what an observer sees, for each mix of participants.
  • Going further. What a real version would add, and what does not work.

Reading the diagrams

Most entries include a diagram of an example execution:

  • One column per participant: a wallet, an actor, the sequencer, the mailbox. An actor named in blue is private, one in amber is public.
  • One row per message, in order, grouped into phases.
  • The line says what kind of message it is: solid amber for a signed public transaction, dashed blue for a private one (a proof), solid black for a call inside a transaction, dashed black for an AsyncMessage delivered in the same transaction, dotted amber or blue for a message stored in the mailbox in the clear or sealed, and red for a step that is refused. A box on one column is a step one party takes alone, on its own machine or to its own state.
  • In the rendered guide, click a row or step through with the arrow keys to see what happens and what an observer of the chain learns at that step. Observer’s view greys out every step that never reaches the chain.

The entries

Most entries are the smallest program that shows their idea. A real token has freezing, metadata and allowances; the one here has three messages.

EntryThe one idea
Private donationspaying someone who is offline and unknown
Payment requestswhy collecting a message is not consent, and what is
Multisigone program in every public/private combination
A minimal tokeneach actor changes only itself
Automated market makera pool deployed on the legacy testnet, and how it fits the actor model
Payment streamsa public actor that anyone can move forward
Payment channelsmany off-chain payments, two transactions
Private votinga public tally that trusts hidden voters
Credentialsproving a fact about yourself under a pseudonym
Rate-limiting nullifiersa public registry that members can join anonymously
Escrow and sealed bidsa public actor between two private parties
Deep Space Radioall of it, as a game
Battleshipa player who cannot lie about what they hide
Idea catalogmany shorter designs, and what does not fit

What works with the reference wallet today

The protocol supports every design in the catalog except those the Idea catalog lists as not fitting the model. The reference wallet (lez/wallet) lacks four things some of them need, and those need a client built on the wallet library:

  • A stable blinded address. The wallet presents a private sender at a fresh blinded address for each message (WalletPresenter, lez/wallet/src/account_manager.rs; the fee payer keeps one alias per transaction). A design that recognises a private party by the address it registered (a multisig seat, an escrow party, an auction paddle, a Battleship board, a radio call sign) works with the wallet only for public parties.
  • Registering an address. No CLI command publishes a recovery binding for an address on its own, and the CLI pays a private account only at an id it holds or by the recipient’s keys, never at a bare blinded address.
  • Private calls. wallet program call sends only public transactions. The CLI runs a deployed program privately only to collect a stored message (wallet pending receive); auth-transfer send runs only the native token privately.
  • Group PDAs of a deployed program. wallet account new private-gms --pda, and the library’s create_shared_pda_account behind it, take the program’s account id to be its image id’s bytes (AccountId::from_builtin_program), where only test programs sit, so for a deployed program the derived account does not match the chain. A client derives the id itself with AccountId::for_private_pda and the program’s account id (Shared private accounts).

A caution

Privacy claims here assume the protocol as it is, including interim choices of the reference wallet: it pads every private transaction up to seven private actions, and claims only native credits alongside a send. Re-check them against What you cannot do privately when those change.

Private donations

Shows: the mailbox · async message for strangers (9) · pseudonym (8)

Goal

A cause publishes one address that anyone can donate to, from a public or a private account. Nobody can see who runs the cause, what it holds, or when it spends. Donors who give from a private account hide who they are, and hide the amount too when they can seal the gift.

No new program is needed: only the native token and the mailbox. The reference CLI has no command to register the address or to pay it, so today the cause and its donors need a client built on the wallet library (What works with the reference wallet today).

Actors

ActorPlacementAuthorized by
the donor’s balancepublic or privatethe donor
the cause’s balanceprivatethe cause’s keys

The cause publishes a blinded address of its private account and registers it once, in a private transaction (a recovery binding, see Private accounts). Without the binding, a credit sent to the address in the clear fails with UnboundAsyncDestination and the donor is still charged; the reference wallet checks for the binding and refuses to build such a transfer.

Messages

Only the native token’s own:

  • Transfer { to, amount }, sent by the donor to their own balance actor;
  • Credit(amount), sent as an async message by the donor’s balance actor to the cause’s address.

How it runs

  1. Donate. The donor sends Transfer { to: cause_address, amount }; their balance actor debits and sends Credit as an async message. The address is not a declared public actor, so the credit is stored.
  2. Wait. The credit sits in the mailbox. The cause does not need to be online.
  3. Collect. The cause’s wallet finds the credit and collects it in a private transaction; its balance grows inside a new commitment.

A public donor sends a plain signed transfer, with no proof.

A library caller pays the address with NativeTokenTransfer::transfer_clear (lez/wallet/src/program_facades/native_token_transfer/mod.rs), which leaves it undeclared. wallet auth-transfer send --to Public/<address> does not work: it declares the address as a public account, which no key or seed admits, so the simulation reverts with declared public but not admitted and nothing is stored for the cause (with --allow-revert the transaction is included, reverts and still pays its fee).

Placements

DonorWhat an observer seesProofs
Publicthe donor’s account, the amount, the cause’s addressnone to donate, one to collect
Privateif sealed, a sealed message; if not, the amount and the cause’s address, from the donor’s blinded address; in both cases, the feeone to donate, one to collect

What leaks

  • From a public donor: who gave, how much, and to which address. The total given to that address can be summed by anyone.
  • From a private donor who seals: that some private transaction sent a sealed message, and its fee. Sealing needs the cause’s keys and factor; a private donor who has only the published address sends the credit in the clear, so the amount and the address show, under the donor’s blinded address.
  • Never, to an observer: which account is behind the address, whether or when the credits were collected, and what the cause’s balance is. A donor who seals holds the cause’s keys, and so knows its account id.

Going further

  • One address per campaign. A different blinded address for each campaign, all paying into the same account; observers cannot link the public totals. A private donor who seals the gift needs the cause’s keys and the factor, so they can tell that two campaigns are the same cause.
  • One address per donor, for donors who want a private relationship.
  • What does not work: automatic refunds, since a stored credit is never returned. If a campaign fails, the cause sends the money back itself.

Payment requests

Shows: accept by answering (10)

Goal

Bob asks Alice for money; Alice sees the request, decides, and pays with one action.

A stored message carries no authority, so collecting a request can never pay it. Alice consents by answering the request with a transaction of her own, marking the one actor the payment needs.

Actors

ActorPlacementAuthorized by
Alice’s balanceprivatea grant Alice marks on her own transaction
Alice’s mandate actorprivateAlice
Bob’s requester actorpublic or privateBob

Messages

The request is a record that someone asked:

enum Message {
    /// Bob -> Alice's mandate, async. Anyone may send one; it carries no authority.
    Ask { to: AccountId, amount: u128 },
    /// Alice -> her own mandate, as a transaction root. Pays a recorded ask.
    Pay { index: u32 },
}

Bob needs a program to send the Ask for him, because an async message comes from an actor:

/// The whole requester program: send the given bytes to the given actor, async.
fn handle_message(input: &ReceiveInput, (to, message): (Actor, Vec<u8>)) -> Response {
    assert!(input.is_authorized() && input.from.is_none(), "only the owner sends requests");
    Response::keep_state().send(AsyncMessage { to, message })
}

Alice’s mandate records asks, and pays one only when she is the one asking it to:

fn handle_message(input: &ReceiveInput, message: Message) -> Response {
    match message {
        // Anyone may ask. Recording is all this does.
        Message::Ask { to, amount } => {
            let mut asks = Asks::from_bytes(&input.pre_state);
            asks.push(to, amount);
            Response::set_state(asks.to_bytes())
        }
        // Only Alice, and only as a root call: `from` is None at a root, and the
        // grant over her balance exists only because her transaction marked it.
        Message::Pay { index } => {
            assert!(input.is_authorized() && input.from.is_none(), "only the owner pays");
            let mut asks = Asks::from_bytes(&input.pre_state);
            let (to, amount) = asks.take(index);
            let payer = Actor::native_balance(input.receiver.account_id);
            Response::set_state(asks.to_bytes()).send(
                SyncMessage::new(payer, &native_token::Message::Transfer { to, amount })
                    .with_grants([payer]),
            )
        }
    }
}

How it runs

  1. Request. Bob’s requester sends Ask to Alice’s mandate as an async message. It is stored, then collected into her mandate’s state. If the ask is published in the clear (always from a public requester, and from a private one that does not seal it), the mandate’s address needs its recovery binding on chain, or introduced by the same privacy-preserving transaction, or the ask is charged and reverted with UnboundAsyncDestination. Nothing has happened to Alice’s money, and nothing could have.
  2. Read. Alice’s client reads the recorded asks from her mandate’s state: “pay 10 to this account”. The mandate does not record who asked.
  3. Decide.
AliceEffect
ignores itnothing, forever
sends Pay without marking her mandatethe handler refuses: is_authorized() is false
sends Pay marking the mandate but not her balance actorattaching the grant fails with UnheldGrant, so the Transfer is never sent
sends Pay marking both the mandate and her balanceher balance is debited and a credit goes to Bob

The ask is removed from the mandate’s state when paid, so it cannot be paid twice.

Why it works

A Transfer needs a grant over the balance actor it debits. Only Alice’s own transaction can mint that grant, by marking the actor, and her mandate can pass it on because the root call handed it one.

So the authority to pay exists only once Alice makes it, and reaches one actor: her native balance. The mandate cannot touch her token holdings, other programs or other accounts, because she did not mark them.

With the wallet CLI, a public Alice pays in one command, and the :sign marks are the consent. Both actors need one: the mandate because its own handler checks is_authorized(), and the balance because that is the grant it passes on. An unmarked actor gets Authority::None and no grant. With no --payer, a signing account pays the fee. A private Alice, as in the table above, needs a client of her own (What works with the reference wallet today).

wallet program call --program <mandate> --to alice:sign \
  --actor alice@<native token id>:sign --message-hex <Pay{index}>

Public and private

RequesterWhat an observer sees of the request
Publicwho asked, the payer’s address, the amount
Privatea sealed message, if it seals; in the clear, the same as public, with the sender shown as the address it presents

The payment itself is a private transaction. If Bob is public, the credit to him crosses to the public side and is visible, with Alice shown only as the address her client presents for her balance (a fresh blinded alias, or her account id if her client chooses to present it). If Bob is private, the ask carries only his address, so Alice’s wallet needs more from him off chain: his keys and factor to seal the credit, or an address of his whose recovery binding is on chain, to send it in the clear.

A public payer can be asked this way too, and answers with a signed public transaction marking their mandate and balance actor, as in the command above.

Going further

  • Limits on chain. Let the mandate accept an allowance: a sender and a maximum, set by Alice in an authorized call. It can then pay matching asks on a later root call without her reviewing each one, still spending only through the grant her transaction supplies.
  • Requests for anything. The same move works for anything an owner might approve: a swap offer, a vote delegation, a multisig proposal. Record the ask, authorize the answer.
  • What does not work: forcing payment. Nobody can make Alice answer.

Multisig, in every public/private combination

Shows: the seat (4) · the proof-carrying message (7) · pseudonym (8) · async message for strangers (9) · seed-authorized custody (13) · group-owned private PDA (18)

Goal

A vault that pays out only when k of its n members approve. The same program must work with the vault and each member public or hidden, in any mix.

The three choices

  1. The vault is a PDA: its state and funds live on an account with no spending key. Only the multisig program can move the funds, by granting the PDA’s seed (pattern 13), as long as the program is immutable. For a hidden vault, the PDA is private and its keys come from a group secret (pattern 18).

  2. A member is a seat. Each member has an actor of the multisig program on their own account: (member_account, multisig). The member tells the seat to approve, and the seat tells the vault. The vault checks that the message comes from its own program and from a registered seat (patterns 4 and 7).

  3. Seats speak by AsyncMessage. An AsyncMessage to a public vault the transaction declares is delivered at once; one to a hidden vault is stored for a member to collect. The seat’s code is the same either way (pattern 9).

A hidden member is a seat at a blinded address. For a hidden vault, only the member who operates it writes its state.

Actors

ActorWhat it holdsPlacement
(vault, multisig)threshold, seat list, approvals so farpublic PDA, or group-owned private PDA
(vault, native)the fundssame account as above
(member, multisig): a seatwhich vault it belongs toon each member’s account, public or private

The member list holds seat addresses. A private member registers a blinded address, so the list never names their account (pattern 8).

Messages

enum Message {
    /// To a seat, by its owner: approve paying `amount` to `to` out of `vault`.
    Approve { vault: AccountId, to: AccountId, amount: u128 },
    /// From a seat to the vault.
    Approved { to: AccountId, amount: u128 },
}

There is no separate “propose” step: a payment exists once one member has approved it.

Handler

fn handle_message(input: &ReceiveInput, message: Message) -> Response {
    let program = input.receiver.program_account_id;
    match message {
        // A member's seat: check the owner, tell the vault.
        Message::Approve { vault, to, amount } => {
            assert!(input.is_authorized() && input.from.is_none(), "only the member uses the seat");
            Response::keep_state()
                .send_async(Actor::new(vault, program), &Message::Approved { to, amount })
        }

        // The vault: count approvals from its registered seats.
        Message::Approved { to, amount } => {
            assert!(input.from_own_program(), "only seats speak to a vault");
            let seat = input.from.unwrap().account_id;
            let mut vault = Vault::from_bytes(&input.pre_state);
            assert!(vault.seats.contains(&seat), "not a member");

            let approvals = vault.approvals.entry((to, amount)).or_default();   // a set of seats
            approvals.insert(seat);
            if approvals.len() < vault.threshold {
                return Response::set_state(vault.to_bytes());
            }

            // Threshold met: pay from the vault's own balance, by seed.
            vault.approvals.remove(&(to, amount));
            Response::set_state(vault.to_bytes()).send(native_token::custody_transfer(
                input.receiver.account_id, vault.seed, to, amount))
        }
    }
}

The vault’s settings (seats, threshold, seed) are written once when it is created. That first write must check that the seed derives the vault’s own account, or no payout could ever be made. For a hidden vault the derivation also takes the group’s npk and vpk (AccountId::for_private_pda), so the settings store them too.

A seat is recognised by its address, so a private member’s wallet must present the address it registered with every time, reusing its blinding factor. The reference wallet does not, and cannot create a deployed program’s group PDA, so private members and a hidden vault both need a client of your own (What works with the reference wallet today).

The payout is the native token’s Transfer, which sends the credit to the recipient as an async message. So the recipient can be public or private too, with no extra code, provided it can be reached: a public recipient must be declared by the paying transaction, a public vault’s credit to a private recipient is published in the clear and needs the address’s recovery binding on chain, and a hidden vault’s credit is sealed, which needs the recipient’s keys and factor in the operating member’s wallet (Approved carries only the address).

The four placements

Public vault, public members

An ordinary multisig. Each approval is a signed public transaction: the member’s seat runs, its AsyncMessage to the declared vault is delivered at once, and the last approval pays in the same transaction.

Public vault, hidden members

The vault’s balance and pending payments are public. A hidden member approves with a private transaction: their seat runs inside the proof and its AsyncMessage crosses to the public vault, carrying the seat’s blinded address as sender.

The vault learns that seat number three approved; nobody learns who holds it. Public and hidden members can sit on the same vault.

Hidden vault, hidden members

The vault is a group-owned private PDA. Approvals are sealed AsyncMessages, stored on chain for any member holding the group secret to collect. The protocol allows several per transaction, but the reference wallet collects one non-credit message per transaction. When the collected approval is the k-th, the same transaction pays.

An observer sees sealed messages, private actions it cannot link, each transaction’s timing, its fee reserve and the alias that paid it, and that it ran the multisig program (the reference wallet always discloses the program). If the recipient is private as well, the payment publishes nothing that names the vault, its members or the recipient. A hidden vault paying a public recipient reveals the amount and the recipient, and still hides the vault.

Hidden vault, public members

This works but is the weak combination. The vault’s address needs a recovery binding on chain before the first approval (a public transaction cannot introduce one), or the approval is charged and reverted with UnboundAsyncDestination. A public seat’s AsyncMessage is stored in the clear, so each approval is a readable message from a known account to the vault’s address. The vault’s balance stays hidden; its membership and what it approves do not.

What the group secret does and does not give

Every member of a hidden vault holds the same keys for it. That lets any of them operate the vault, not spend from it. A PDA has no spending key, and the program grants the seed only when the threshold is met. This holds while the program cannot be changed: whoever can authorize a mutable program’s header account can replace its code (UpdateHeader, lee/program_loader/src/lib.rs).

So the shared secret is a liveness tool, not a trust assumption about funds.

What leaks

PlacementBalancePending paymentsWho approvedThat a payout happened
public vault, public membersyesyesyesyes
public vault, hidden membersyesyespseudonyms onlyyes
hidden vault, hidden membersnononoonly to a public recipient
hidden vault, public membersnoyes, in the approvalsyesonly to a public recipient

Costs

A hidden vault’s payment that needs k approvals takes k private transactions from members, and, with the reference wallet, k collecting transactions by whoever operates the vault. Each is a proof.

Two members who advance the vault at the same moment both spend the same state: one transaction lands, the other fails and must be rebuilt. A hostile member can do this on purpose: the group secret cannot take funds, but it can stall the vault.

Going further

  • Signatures instead of seats. Members sign the payment off chain and one message carries k signatures: one transaction per payment, at the price of signature checks in the handler.
  • Any action, not only payments. Let an approval carry { target, message } for the vault to send with its seed, so the vault can hold tokens, vote, or sit on another multisig.
  • What does not work: a hidden vault that anyone can execute. Only a key holder can run a private handler, so a hidden vault always needs one of its members to operate it.

A minimal token

Shows: tell, do not write (1) · internal messages (3) · async message for strangers (9) · receive without failing (6)

Goal

A token with balances and transfers in one screen of code: the native token’s design (lee/state_machine/core/src/native_token.rs) with minting added.

Actors

ActorWhat it holdsAuthorized by
(holder, token)a balancethe holder
(ISSUER, token)a balance, and the right to mintthe issuer

One actor per holder. No central ledger.

Messages

#[derive(BorshSerialize, BorshDeserialize)]
enum Message {
    /// Needs the holder's authorization.
    Transfer { to: AccountId, amount: u128 },
    /// Needs the issuer's authorization, at the issuer's actor.
    Mint { to: AccountId, amount: u128 },
    /// Only from another actor of this program.
    Credit(u128),
}

Handler

fn handle_message(input: &ReceiveInput, message: Message) -> Response {
    let me = input.receiver;
    let balance = decode_balance(&input.pre_state);     // empty state reads as zero
    let token_actor = |account_id| Actor::new(account_id, me.program_account_id);

    match message {
        Message::Transfer { to, amount } => {
            assert!(input.is_authorized(), "not your balance");
            let rest = balance.checked_sub(amount).expect("insufficient balance");
            Response::set_state(encode_balance(rest))
                .send_async(token_actor(to), &Message::Credit(amount))
        }
        Message::Mint { to, amount } => {
            assert!(input.is_authorized() && me.account_id == ISSUER, "only the issuer mints");
            Response::keep_state().send_async(token_actor(to), &Message::Credit(amount))
        }
        Message::Credit(amount) => {
            assert!(input.from_own_program(), "a credit comes from the token itself");
            let total = balance.checked_add(amount).expect("balance overflows");
            Response::set_state(encode_balance(total))
        }
    }
}

What to notice

The sender debits itself and tells the recipient. No handler ever touches two balances. Outside Mint, supply is conserved, because the only way to send Credit is one of the two arms above.

Credit trusts its sender, not a signature: from_own_program() is its only check on who sent it.

The credit is an AsyncMessage: to a public recipient the transaction declares, it lands in the same transaction; to a private recipient it waits in their mailbox. The handler does not know which.

Receiving needs no setup: an empty state reads as zero, so the first credit creates the balance.

The sender does not need the recipient to be online. A private recipient needs no state yet, but a public sender’s credit goes out in the clear, so the address needs its recovery binding on chain or introduced by the same privacy-preserving transaction; a public recipient must be declared, and one that does not exist yet must also be admitted.

Public and private

SenderRecipientWhat an observer sees
PublicPubliceverything
PublicPrivatesender, amount, destination address
PrivatePublicamount, recipient; the sender is hidden or a pseudonym
PrivatePrivatea sealed message

The program has no code for these cases: they come from which accounts the user picks.

Going further

  • The shipped token (logos-blockchain/lez-programs: programs/token) adds token definitions with an optional mint authority, NFTs and burning. It is not an actor program: it pins lee_core at v0.2.5-rc2, the whole-account interface, so its Transfer names both holdings, creates the recipient’s holding when it is empty, and refuses one of another definition or kind. It sends no messages.
  • Custody by other programs. Transfer needs only a grant over the balance it debits, so a program can move tokens it holds on a PDA by granting the seed (pattern 13).
  • The same check is the footgun. A grant does not say who sent the Transfer. Read what it does not mean before copying this handler.

Automated market maker

Shows: seed-authorized custody (13) · async message for strangers (9) · windows for expiry (16)

What is deployed

logos-blockchain/lez-programs: programs/amm is a constant-product pool deployed on the legacy testnet, which runs the v0.2.4 line. It is not an actor program: it is written against the v0.2.x interface, where a program receives whole accounts, returns their new contents and calls other programs with ChainedCall. Read its repository for its accounts and instructions; nothing in this guide applies to it directly.

The same pool as actors

A sketch, not built:

  • The pool is a public PDA of the AMM program (pattern 13). Its AMM actor holds the pair and the reserves; its balance actors for the two tokens hold the funds, and only the AMM can move them, by granting the seed. It is public because traders need its price and anyone must be able to trade against it (Where state lives).
  • A trader swaps with a root call to the pool’s AMM actor that marks the trader’s input balance actor as a signer (:sign in the CLI). The AMM sends that balance actor a SyncMessage Transfer to the pool, carrying the grant, as the mandate does in Payment requests. It computes the output from its reserves and pays it out of the pool’s other balance by seed (custody_transfer for the native token). The credit travels as an AsyncMessage, so a private trader receives it too (pattern 9): the trader’s transaction can promote it to their own private balance at once, or leave it stored, published in the clear, in which case the transaction introduces the address’s recovery binding.
  • A minimum output in the message limits slippage, and a validity window enforces the trader’s deadline (pattern 16).

What it leaks

Every pool actor is public, so each swap publishes its pair, direction and size, and the reserves after it. A private trader hides only who traded, behind a blinded address. Swaps of an unusual amount can be linked to each other by that amount.

The idea catalog records the stronger version as a negative result: an AMM with hidden reserves does not work under this model.

Payment streams

Shows: anyone may poke (11) · seed-authorized custody (13) · clock assertion (17) · async message for strangers (9)

Goal

A salary paid by the second. The recipient can be private and offline. Nobody runs a server for the payer.

Actors

ActorWhat it holdsPlacement
(stream, streams)recipient, rate, start time, seed, amount released so farpublic PDA
(stream, native)the money not yet releasedsame account

The stream is public: anyone must be able to move it forward, and only a public actor allows that.

Messages

enum Message {
    /// Once, by whoever sends it first. The payer checks it, then funds the stream.
    Open { recipient: AccountId, rate_per_ms: u128, start: Timestamp, seed: PdaSeed },
    /// By anyone, at any time.
    Release { now: Timestamp },
}

Handler

Message::Release { now } => {
    let mut stream = Stream::from_bytes(&input.pre_state);
    let due = (now - stream.start) as u128 * stream.rate_per_ms - stream.released;
    stream.released += due;

    Response::set_state(stream.to_bytes())
        // Only valid from `now` on, checked against the block being built.
        .timestamp_window(now..)
        // Pay from the stream's own balance. The credit is an AsyncMessage.
        .send(native_token::custody_transfer(
            input.receiver.account_id, stream.seed, stream.recipient, due))
}

Open writes the stream’s settings once (write_once). It also checks that the seed is its own (pattern 13): AccountId::for_public_pda(&program, &seed) == input.receiver.account_id. Funding is a plain transfer to the stream’s account. Open needs no authorization, so whoever sends it first sets the stream: the payer reads the recorded settings before funding, as in Payment channels.

What to notice

The handler does not read the time: the caller states now and the validity window confirms it. Reading the clock with ReadTimestamp would also work, at the cost of a reply. Stating an earlier time releases less. Stating a later time fails.

Release needs no authorization: the recipient sends it when they want their money, and so can anyone else. The handler only does what the schedule allows, so who asks does not matter.

No account key can touch the funds: they sit on a PDA, and only this program can grant its seed, which it does only in Release, as long as the program is immutable.

The payout is an AsyncMessage, so the handler is the same for a public or a private recipient.

A Release whose due exceeds the stream’s balance fails, since the custody transfer cannot debit it (InsufficientBalance); stating an earlier now releases at most what the stream holds.

How it runs with a private recipient

  1. The payer opens and funds the stream, naming the recipient’s address. A private recipient’s address needs its recovery binding on chain, because Release pays it in the clear from a public actor.
  2. Someone pokes Release. The credit is stored on chain.
  3. The recipient collects when convenient.

With a public recipient there is no third step:

Public and private

PayerRecipientWhat an observer sees
PublicPubliceverything
PublicPrivatepayer, rate, amounts, destination address
PrivatePrivaterate, amounts, and both parties’ blinded addresses

A private payer funds the stream under a blinded address. The schedule is public in every case, because the stream is. Privacy here is about who, not how much.

Going further

  • Vesting. Add a cliff: release nothing before it.
  • Inheritance. A vault that pays an heir’s address once its owner has sent no Heartbeat for a year. Same three patterns.
  • What does not work: streaming out of a private account by poke. Only its owner can run a private handler. For per-payment privacy, see Payment channels.

Payment channels

Shows: seed-authorized custody (13) · pseudonym (8) · async message for strangers (9) · anyone may poke (11)

Goal

Many small payments between two parties with one transaction to start and one to finish, in the style of Bitcoin’s Lightning. The payments in between are signed messages exchanged off chain: instant, free, and invisible to everyone else.

One-way, from a payer to a recipient.

Actors

ActorWhat it holdsPlacement
(channel, channels)the payer’s voucher key, the recipient’s address, the amount paid out so far, an expirypublic PDA
(channel, native)the channel’s fundssame account

Messages

enum Message {
    /// Once, by anyone: needs no authorization.
    Open { voucher_key: VerifyingKey, recipient: AccountId, refund_to: AccountId,
           capacity: u128, expiry: Timestamp, seed: PdaSeed },
    /// By anyone holding a voucher.
    Redeem { total: u128, signature: Signature },
    /// By anyone, after the expiry.
    Close,
}

Off chain

A voucher is the payer’s signature over (channel, total): “this channel owes the recipient total so far”.

To pay 1 more, the payer signs a voucher with total + 1 and sends it to the recipient directly. Nothing touches the chain. The recipient keeps only the latest voucher, since it is worth more than all earlier ones.

Handler

Message::Redeem { total, signature } => {
    let mut channel = Channel::from_bytes(&input.pre_state);
    let voucher = borsh::to_vec(&(input.receiver.account_id, total)).unwrap();
    channel.voucher_key.verify_strict(&voucher, &signature).expect("bad voucher");

    let due = total.checked_sub(channel.paid).expect("an older voucher");
    channel.paid = total;
    Response::set_state(channel.to_bytes())
        .send(native_token::custody_transfer(
            input.receiver.account_id, channel.seed, channel.recipient, due))
}

Message::Close => {
    let channel = Channel::from_bytes(&input.pre_state);
    let rest = channel.capacity - channel.paid;
    Response::keep_state()
        .timestamp_window(channel.expiry..)          // only valid after the expiry
        .send(native_token::custody_transfer(
            input.receiver.account_id, channel.seed, channel.refund_to, rest))
}

Open writes the settings once and checks that the seed is its own (pattern 13): AccountId::for_public_pda(&input.receiver.program_account_id, &seed) == input.receiver.account_id.

Funding is a plain transfer of capacity to the channel’s account. This handler does not read that balance (it could, with the native token’s ReadState), so the recipient checks off chain that the account holds capacity before accepting vouchers.

Checking a signature inside a handler is ordinary code; the stake program does it for its approvals (lez/programs/sequencer_stake/src/main.rs).

What to notice

The recipient can only redeem what the payer signed. As long as the program is immutable, the payer cannot take money back before the expiry, because no account key controls the PDA. The recipient redeems before the expiry, and the payer gets the rest after it. So the recipient carries two risks: an underfunded channel, and vouchers not redeemed before Close.

Redeem needs no authorization: the voucher is the authorization, and whoever submits it, the money goes to the recipient’s address.

The voucher key is not an account key: it is made for this one channel, so it links to nothing.

A private recipient or payer need not submit the transaction: anyone holding a voucher can redeem, anyone can close after the expiry, and the money waits for its owner.

How it runs

With a public payer and a public recipient, everything is visible and the payout lands at once:

With both private, the payer is hidden and the payouts wait to be collected:

Public and private

Both parties can be private: the recipient and the refund are addresses, and payouts are AsyncMessages. The channel is public, so it credits a private address in the clear: that address needs its recovery binding on chain, or introduced by the same privacy-preserving transaction, or the Redeem or Close reverts (its submitter still pays the fee) and can be sent again once the binding is published.

Funding from a private account

  1. Open. Someone writes the channel’s settings. Open needs no authorization and writes once, so the recipient can send it, using the voucher key and refund address the payer gave them.
  2. Check. The payer reads the public record and confirms every setting: voucher key, recipient, refund address, capacity, expiry. Write-once means it cannot change afterwards.
  3. Fund. The payer sends one private transaction: Transfer { to: channel, amount: capacity } to their own private balance. The debit happens in the proof; the credit crosses to the channel’s public balance.

The payer never sends a public transaction. Observers see the channel receive its capacity from a private balance, shown at whatever address the payer’s wallet presented: the reference wallet presents a private sender at a blinded address, which does not reveal the account.

The order matters: a payer who funds before checking can be robbed by whoever wrote the settings first.

The refund address is a blinded address of the payer, registered beforehand. Close sends the remainder to it as an async message, and the payer collects privately.

An observer sees
that a channel exists, and its capacityyes
the total redeemed, and whenyes
how many payments there were, and their sizesno
who the payer isno
who the recipient isno

Compare a payment stream, which publishes every release. A channel publishes only the totals the recipient redeems, often just one.

Going further

  • Two-way channels. Both parties sign each new pair of balances, with a counter. Closing starts a waiting period (a clock assertion) during which the other side can present a newer signed state.
  • A fully hidden channel. Put the channel on a private PDA owned by the two parties as a group (pattern 18). Either can operate it, the program still enforces the signatures, and even the capacity is hidden. The price is a race: every update to a private account replaces its commitment, so a payer who keeps touching the account can make the recipient’s pending redemption stale, again and again, until the expiry. A public channel has no such race.
  • Routed payments. Lightning routes a payment across several channels with hashlocks, and a channel here can hold a hashlocked amount the same way. The routing network is off-chain software that this guide has not designed.
  • What does not work: a voucher worth more than the channel, since it is only as good as the funds behind it. The recipient checks the capacity and the expiry before accepting.

Private voting

Shows: the owner check (4) · the proof-carrying message (7) · pseudonym (8) · write once (15) · windows for expiry (16)

Goal

An election where the eligible voters and the running tally are public, and nobody can tell how any voter voted, or whether they voted at all, beyond what the tally itself shows (a unanimous result, or a vote from every ballot issued).

Actors

ActorWhat it holdsPlacement
(election, voting)the question, the deadline, the tally, a count of ballots issuedpublic PDA
(voter, voting): a ballotwhich election, and whether it has been usedprivate, on each voter’s account

Messages

enum Message {
    /// To the election, by the organiser: send one ballot to each address.
    Open { voters: Vec<AccountId>, deadline: Timestamp },
    /// Election to voter: you may vote.
    Ballot,
    /// To a ballot, by its owner.
    CastVote { choice: u8 },
    /// Voter to election: one valid vote.
    Vote { choice: u8 },
}

How it runs

  1. Open. The organiser sends Open with the voters’ addresses. The election is a PDA, so no signature authorizes Open: the empty-state check makes the first Open final, and whoever sends it first sets the voter list and deadline. Voters read both back before trusting the election. The election actor sends one Ballot to each as an async message, stored from a public actor: everyone can see who is eligible. Each voter’s address needs its recovery binding on chain first (a public transaction cannot introduce one), or Open is charged and reverted with UnboundAsyncDestination.

  2. Collect the ballot. Each voter collects their Ballot; their private ballot actor checks that it comes from an actor of the voting program, and records the election.

  3. Vote. The voter sends CastVote to their ballot actor in a private transaction. The handler checks that the ballot is unused, marks it used, and sends Vote to the election. The wallet presents the ballot under a fresh blinded address.

  4. Tally. The election’s handler checks from_own_program() and the deadline, and adds one to the chosen option.

Handler

fn handle_message(input: &ReceiveInput, message: Message) -> Response {
    let me = input.receiver;
    match message {
        // Voter side: receive the ballot. Only an election of this program can issue one.
        Message::Ballot => {
            let election = input.from.filter(|_| input.from_own_program()).expect("not a ballot");
            Response::set_state(write_once(&input.pre_state, encode(&(election, false))))
        }

        // Voter side: use the ballot. Only the owner can, and only once.
        Message::CastVote { choice } => {
            assert!(input.is_authorized() && input.from.is_none());
            let (election, used): (Actor, bool) = decode(&input.pre_state);
            assert!(!used, "already voted");
            Response::set_state(encode(&(election, true)))
                .send_sync(election, &Message::Vote { choice })
        }

        // Election side: count. The sender is a ballot actor of this program.
        Message::Vote { choice } => {
            assert!(input.from_own_program(), "not a ballot");
            let mut election = Election::from_bytes(&input.pre_state);
            election.tally[choice as usize] += 1;
            Response::set_state(election.to_bytes())
                .timestamp_window(..election.deadline)
        }

        // Election side: open once, and send one `Ballot` to each voter as an async message.
        Message::Open { voters, deadline } => {
            assert!(input.pre_state.is_empty(), "already open");
            let election = Election::new(deadline, voters.len());
            voters.iter().fold(Response::set_state(election.to_bytes()), |response, voter| {
                response.send_async(Actor::new(*voter, me.program_account_id), &Message::Ballot)
            })
        }
    }
}

Why a voter cannot cheat

  • Vote without a ballot. The ballot actor’s state is empty, so CastVote fails; only a Ballot from the voting program can write a ballot state.
  • Vote twice. used is true after the first vote, and the second run starts from that state, because the proof ties each run to the account’s real, latest state.
  • Forge a Vote directly. The election accepts Vote only from an actor of the voting program, whose only code path that sends Vote is the one above.
  • Use someone else’s ballot. A ballot is state on the voter’s own private account; nobody else can run its handler.

The election never checks a signature, a membership proof or a nullifier: the engine does all of that.

What leaks

Observer learnsYes or no
who is eligibleyes
the tally, liveyes
that some ballot voted for option X at time Tyes
which voter that wasno
whether a given voter has votedno, unless the number of votes is zero or reaches the number of ballots issued
whether a given voter collected their ballotno

Timing and the fee are the remaining risks. In a small election, a vote that appears seconds after one voter comes online is a strong hint, and a fee declared by a public signer, or a fee refund sent to a named public account, links that account to the vote.

Placements

VoterWorksNotes
Privateyesas described
Publicyestheir vote is public: the ballot actor is public state and the vote is a signed transaction

The program does not care: a voter who wants an open vote uses a public account.

A public voter’s ballot cannot be stored: only private addresses have a mailbox. The organiser’s Open transaction has to declare each public voter’s ballot actor so the ballot is delivered at once. If one is missing, its ballot becomes a clear publication to an address that has no recovery binding, and the whole Open is charged and reverted with UnboundAsyncDestination.

Going further

  • Hidden tally until the end. Votes carry a commitment, opened after the deadline by a second message.
  • Delegation. A voter forwards their ballot to a delegate’s address.
  • What does not work: coercion resistance. A voter can prove how they voted by showing their transaction and its secrets.

Credentials and tickets

Shows: the proof-carrying message (7) · pseudonym (8) · async message for strangers (9) · write once (15)

Goal

An issuer gives a person a badge, which the person later shows to a venue. The venue learns that the badge is real and which issuer gave it, and nothing else about who shows it: the holder hides among everyone that issuer gave a badge to.

Actors

ActorWhat it holdsPlacement
(issuer, badges)nothing; it only issuespublic
(holder, badges): a badgewhich issuer gave itprivate, on the holder’s account
a venueits own businesspublic, any program

Messages

enum Message {
    /// To the issuer's actor, by the issuer.
    Issue { to: AccountId },
    /// Between badge actors: "you now hold a badge from me".
    Badge,
    /// To a badge, by its holder.
    Show { venue: Actor },
}

/// What the venue receives.
struct Attested { issuer: AccountId }

Handler

fn handle_message(input: &ReceiveInput, message: Message) -> Response {
    let me = input.receiver;
    match message {
        Message::Issue { to } => {
            assert!(input.is_authorized() && input.from.is_none(), "only the issuer issues");
            Response::keep_state().send_async(Actor::new(to, me.program_account_id), &Message::Badge)
        }
        Message::Badge => {
            let issuer = input.from.filter(|_| input.from_own_program()).expect("not a badge");
            Response::set_state(write_once(&input.pre_state, encode(&issuer.account_id)))
        }
        Message::Show { venue } => {
            assert!(input.is_authorized() && input.from.is_none(), "only the holder shows");
            let issuer: AccountId = decode(&input.pre_state);
            Response::keep_state().send_sync(venue, &Attested { issuer })
        }
    }
}

The venue’s side is two checks. Anyone can run Issue on their own account and become an issuer, so the venue decides which issuers it trusts:

let badge = input.from.expect("an attestation has a sender");
assert_eq!(badge.program_account_id, BADGES_PROGRAM, "not from a badge");
let Attested { issuer } = decode(&input.message);
assert!(TRUSTED_ISSUERS.contains(&issuer), "not an issuer this venue trusts");

How it runs

  1. Issue. The issuer’s actor sends Badge to the holder’s address as an async message. The issuer is public, so the message is published in the clear, and the holder’s address needs its recovery binding on chain first, or the issue is charged and reverted with UnboundAsyncDestination.
  2. Collect. The holder’s badge actor stores the issuer. It accepts Badge only from the badges program.
  3. Show. The holder sends Show in a private transaction. The badge sends a SyncMessage to the venue under a blinded address, which the reference wallet draws fresh for each message.
  4. Admit. The venue sees a message from the badges program naming an issuer it trusts.

Why the venue can believe it

The only code that sends Attested is the Show arm, and it sends the issuer it read from its own state. That state can only have been written by the Badge arm, which only accepts the badges program as sender. The issue ran publicly on the sequencer; for a private holder, the collection and the show ran inside the holder’s proofs.

The venue checked no signature and no membership proof, only which program spoke, so any program can accept badges without knowing how they are stored.

Public and private

HolderWhat the venue learns
Private“a badge from this issuer”, from a one-time address
Publicthe same, and who you are

What leaks

  • At issue time: that the issuer gave a badge to an address.
  • At show time: the venue, the issuer, the time.
  • Not revealed: which badge it was, or a link between two visits, since the reference wallet presents a fresh blinded address for each show (timing aside). A holder that presents the same address twice links those visits.

Going further

  • Tickets. Add a used flag to the badge state and set it in Show, so the badge works once.
  • Rate limits. Keep a counter per day in the badge state and refuse Show past the limit. Because every run starts from the account’s real latest state, the limit cannot be exceeded, however the holder arranges their transactions. This limits actions that go through the chain. For messages that never touch it, see Rate-limiting nullifiers.
  • Attributes. Store a birth date in the badge and have Show send only AgeAtLeast(18), computed inside the proof.
  • What does not work: asking about someone else. A venue cannot query whether a private holder holds a badge; only the holder can show it.

Rate-limiting nullifiers

Shows: the seat (4) · the proof-carrying message (7) · pseudonym (8)

Goal

A rate-limiting nullifier (RLN) lets a network accept anonymous messages and still limit how many each member sends. Logos has an RLN membership registry program for LEZ (logos-co/logos-lez-rln).

Two halves:

  • On chain: a membership registry. A member pays a fee and registers a commitment to a secret. The registry keeps the commitments in a Merkle tree and publishes the root.
  • Off chain: the rate limit. Every message carries a zero-knowledge proof that its sender is in the tree, plus a small piece of the sender’s secret. A sender within their limit reveals nothing about their secret or which member they are; one who exceeds it reveals the whole secret, and anyone who learns the secret can have the member removed.

What follows is a toy version of the registry, cut down from the real one: the Logos program, an actor program built against LEZ v0.4.0.

Off chain, in brief

A member holds a secret a0. Their commitment is H(a0). They registered with a rate_limit: the number of messages they may send per epoch.

For each message they pick a slot number below their limit and compute:

a1 = H(a0, epoch, slot)      // a different line for each slot of each epoch
x  = H(message)
y  = a0 + a1 · x             // one point on that line
nullifier = H(a1)            // the same for every message that uses this slot

This nullifier is RLN’s own, unrelated to the nullifiers that spend LEZ private accounts.

The proof shows that the sender’s leaf is under the on-chain root, that slot is below the registered limit, and that the point and the nullifier were computed honestly. It does not show which member.

Sending more than rate_limit messages in an epoch forces a slot to be used twice. Two messages in one slot give two points on one line, and two points give a0. The network notices because the two messages carry the same nullifier.

None of this touches the chain: peers verify the proofs against the root they read from the registry. The arithmetic follows RLN v2 as this guide understands it; the guide has not examined the proving code (zerokit, which logos-lez-rln calls from lez-rln/src/proof_circuit.rs).

Actors

ActorWhat it holdsPlacement
(registry, rln)price, treasury, the members and their limits, the Merkle rootpublic PDA
(payer, rln): a seatnothingon the payer’s account, public or private

The registry stores commitment → rate_limit for each member. A leaf of the tree is H(commitment, rate_limit), so the off-chain proof can use the limit.

Messages

enum Message {
    /// To a seat, by its owner.
    Register { registry: Actor, id_commitment: [u8; 32], rate_limit: u64,
               fee: u128, treasury: AccountId },
    /// From a seat to the registry: "I paid `fee` to `treasury` for this member."
    Enroll { id_commitment: [u8; 32], rate_limit: u64, fee: u128, treasury: AccountId },
    /// To the registry, by anyone who knows a member's secret.
    Slash { identity_secret: [u8; 32] },
}

Handler

fn handle_message(input: &ReceiveInput, message: Message) -> Response {
    match message {
        // The seat: check the owner, pay the fee, tell the registry.
        Message::Register { registry, id_commitment, rate_limit, fee, treasury } => {
            assert!(input.is_authorized() && input.from.is_none(), "only the owner registers");
            let payer = Actor::native_balance(input.receiver.account_id);
            Response::keep_state()
                .send(
                    SyncMessage::new(payer, &native_token::Message::Transfer { to: treasury, amount: fee })
                        .with_grants([payer]),
                )
                .send_sync(registry, &Message::Enroll { id_commitment, rate_limit, fee, treasury })
        }

        // The registry: a seat of this program says it paid. Check the price, add the member.
        Message::Enroll { id_commitment, rate_limit, fee, treasury } => {
            assert!(input.from_own_program(), "only a seat enrolls");
            let mut reg = Registry::from_bytes(&input.pre_state);
            assert!((MIN_RATE..=MAX_RATE).contains(&rate_limit));
            assert_eq!(treasury, reg.treasury, "paid the wrong account");
            assert_eq!(fee, reg.price_per_unit * rate_limit as u128, "paid the wrong amount");
            assert!(reg.members.insert(id_commitment, rate_limit).is_none(), "already a member");
            reg.root = merkle_root(&reg.members);
            Response::set_state(reg.to_bytes())
        }

        // The registry: whoever knows the secret may remove the member.
        Message::Slash { identity_secret } => {
            let mut reg = Registry::from_bytes(&input.pre_state);
            reg.members.remove(&hash1(&identity_secret)).expect("not a member");
            reg.root = merkle_root(&reg.members);
            Response::set_state(reg.to_bytes())
        }
    }
}

How it runs

  1. Register. The member tells their seat to register. The seat pays the fee from the account it sits on and tells the registry, both SyncMessages in one transaction: if the registry refuses, the payment is undone. The member’s transaction marks both the seat and their native balance actor, or attaching the grant fails with UnheldGrant.
  2. Send messages. Off chain, with proofs against the registry’s root.
  3. Overspend. Two messages in one slot expose the secret.
  4. Slash. Anyone sends the secret to the registry; the member is gone and the root changes.

What to notice

The registry never sees the money move and does not read the treasury’s balance. It trusts Enroll { fee, treasury } because it comes from a seat of its own program, and the only code in this program that sends Enroll has just sent that transfer. It only checks that the amount and the destination are right.

Slashing needs no evidence, only the secret; the registry does not see the two offending messages. The protocol leaks a secret only when its member overspends.

The fee is the deterrent. The Logos program charges price_per_unit × rate_limit to a treasury and pays nothing back, so a slashed member loses a paid membership. There is no stake and no reward for the slasher.

In the toy, Slash carries only the secret, and the registry reads the rest from its state. The Logos program’s Slash also names the commitment and a leaf index hint.

What private actors bring

In this toy, the registration can be anonymous. The Logos program’s Register names its payer account in the clear and needs that account’s signature, so its registrations are not.

RLN hides which member sent a message, not who the members are. When the seat is on a public account, the registration is a signed transaction: everyone sees that this account paid for this commitment.

  • The membership list is a list of accounts that use the network.
  • When a member is slashed, the published secret gives the commitment, and the commitment gives the account that paid for it.

Put the seat on a private account, and pay the transaction’s fee privately too, and neither link is published.

  • The seat runs inside the member’s proof. Its payment and its Enroll cross to the public side from a blinded address.
  • The registry accepts it for the same reason as before: it comes from a seat of its own program. Here that fact is proven, not observed.
  • The chain sees a commitment enter the tree and the treasury receive a fee. It does not see who paid.
SeatChain sees at registrationA slash reveals
Publicpayer, commitment, rate limit, feethe commitment, and so the payer
Privatecommitment, rate limit, feethe commitment only

The handler has no code for this: the same three arms run, and the member chooses by which account they use.

What private actors do not bring.

  • A private registry. The members and the root must be public, because every peer verifies proofs against the root.
  • The rate limit itself: that is the off-chain proof, and no actor takes part in it.
  • A hidden rate limit: the limit is in the leaf and in the fee.

A commitment registered a minute before a burst of messages is easy to connect to that burst, so register early.

Going further

  • Expiry and renewal. The Logos program gives each membership an active period and a grace period, lets anyone renew it during the grace period by paying the registration price again, and lets anyone erase an expired one. Each needs the time: the Logos program takes the submitter’s reading now_ms and returns the timestamp validity window [now_ms, now_ms + CLOCK_CLAIM_TOLERANCE_MS) (pattern 16), since a claim that must equal the clock exactly fails whenever the clock moves.
  • A real tree. The toy recomputes the root from the member list; the Logos program keeps a fixed-depth incremental Poseidon tree and updates one path per change.
  • A cap. The Logos program limits the sum of all rate limits.
  • A reward for slashing. Keep fees on a PDA and send part as an async message to an address the slasher names. A private slasher stays unknown.
  • A private counter is not RLN: it limits only actions that go through the chain (Credentials), and RLN exists for messages that never do.

Escrow and sealed bids

Shows: the public referee (12) · seed-authorized custody (13) · the proof-carrying message (7) · windows for expiry (16)

Two different people’s private accounts cannot act in one transaction (see limits), so when two private parties exchange value, a public actor stands between them, holds the value from one transaction to the next, and has a deadline.

Part 1: escrow

Goal

Alice pays Bob for a delivery. Bob is paid when Alice confirms; if she never does, an arbiter decides. Any of the three can be private.

Actors

ActorWhat it holdsPlacement
(deal, escrow)the addresses of buyer, seller and arbiterpublic PDA
(deal, native)the paymentsame account

Messages

enum Message {
    /// Once, by whoever sends it first. The buyer checks it, then funds the deal's account.
    Open { buyer: AccountId, seller: AccountId, arbiter: AccountId, amount: u128, seed: PdaSeed },
    /// A party tells their own seat what they want. The seat tells the deal.
    Release { deal: AccountId },
    Refund { deal: AccountId },
}

Handler

The program plays two roles, told apart by the sender.

fn handle_message(input: &ReceiveInput, message: Message) -> Response {
    let program = input.receiver.program_account_id;
    match (input.from, &message) {
        // Role 1, a party's seat: check the owner, pass the message on.
        (None, Message::Release { deal } | Message::Refund { deal }) => {
            assert!(input.is_authorized(), "only the owner uses this seat");
            Response::keep_state().send_sync(Actor::new(*deal, program), &message)
        }

        // Role 2, the deal: a seat of this program is speaking.
        (Some(seat), message) => {
            assert!(input.from_own_program(), "only seats speak to a deal");
            let deal = Deal::from_bytes(&input.pre_state);
            let who = seat.account_id;
            let to = match message {
                Message::Release { .. } if who == deal.buyer || who == deal.arbiter => deal.seller,
                Message::Refund { .. } if who == deal.seller || who == deal.arbiter => deal.buyer,
                _ => panic!("not yours to decide"),
            };
            Response::keep_state().send(native_token::custody_transfer(
                input.receiver.account_id, deal.seed, to, deal.amount))
        }

        (None, Message::Open { seed, .. }) => {
            assert_eq!(AccountId::for_public_pda(&program, seed), input.receiver.account_id);
            Response::set_state(write_once(&input.pre_state, Deal::from(&message).to_bytes()))
        }
    }
}

What to notice

The deal identifies a party by a seat of its own program, never by an account id alone, which identifies nobody. The seat checks the owner’s authorization, and from_own_program() proves the sender was a seat.

A private party stays hidden: their seat presents a blinded address, the one Open recorded. The seat must present that same address every time, which the reference wallet does not (What works with the reference wallet today).

Payouts are AsyncMessages to those same addresses. The deal is public, so a payout to a private party is published in the clear and needs that address’s recovery binding on chain, unless the paying transaction is a private one that introduces it.

The arbiter is another address, which can be a person or a multisig with hidden members.

Open needs no authorization and writes once, so whoever sends it first sets the deal. The buyer reads the recorded parties and amount before funding the deal’s account.

How it runs

What leaks

The amount, the timing, and which of the three addresses ended the deal. Not who is behind a private party’s address.

Part 2: a sealed-bid auction

Goal

Bidders submit bids nobody can see. After the deadline every bid is revealed and the highest wins. A paddle’s bid cannot be changed after it is placed.

Actors

ActorWhat it holdsPlacement
(auction, auctions)the deadline, and the revealed bids by pseudonympublic PDA
(bidder, auctions): a paddlethe bidder’s secret amountprivate, on each bidder’s account

How it runs

  1. Bid. The bidder tells their paddle an amount. The paddle stores it, once, and sends the auction Joined under a blinded address.
  2. Reveal. After the deadline, the bidder tells the paddle to reveal. The paddle sends Reveal { amount } with the amount it stored.
  3. Settle. Anyone pokes the auction; the highest revealed amount wins. This sketch only names the winner. To make the winner pay, every bidder deposits the same amount at Joined, at least the largest allowed bid, so the deposit says nothing about the bid; settlement pays the seller from the winner’s deposit and refunds the rest.

The paddle’s handler

Message::Bid { auction, amount } => {
    assert!(input.is_authorized() && input.from.is_none());
    Response::set_state(write_once(&input.pre_state, encode(&(auction, amount))))
        .send_sync(auction_actor(auction), &Internal::Joined)
}
Message::RevealBid => {
    assert!(input.is_authorized() && input.from.is_none());
    let (auction, amount) = decode(&input.pre_state);
    Response::keep_state().send_sync(auction_actor(auction), &Internal::Reveal { amount })
}

The auction accepts Joined before the deadline and Reveal after it, both only from its own program. It must also accept a Reveal only from an address that sent Joined, or a bidder could skip Joined and reveal an amount chosen after seeing the others. So a paddle must present the same blinded address for both messages, which the reference wallet does not (What works with the reference wallet today).

What to notice

There is no commitment to open. In the classic design a bidder publishes a hash and later reveals the amount and a salt, and the contract re-hashes. Here the bid sits in the paddle’s private state, written once, and the reveal is the paddle’s own code reading that state inside a proof. The auction trusts the amount because of who sent it.

A bidder who never reveals is not counted. That leaves a loophole: one person can run several paddles from several private accounts, place a different bid with each, and reveal only the one that suits them. Closing it takes a deposit at Joined, forfeited without a reveal, and large enough to outweigh the gain.

What leaks

How many bids there are and when each arrived; after the deadline, every revealed amount, under a pseudonym. Not who the bidders are.

Going further

  • Deadlines without a clock message. Release after a timeout: the handler returns a validity window that starts at the deadline (pattern 16).
  • Swaps. An escrow that holds both sides’ deposits and pays each to the other when the second arrives.
  • What does not work: a private order book. Matching needs someone to see both sides.

Deep Space Radio: a game of private ships

Shows: the owner check (4) · the proof-carrying message (7) · pseudonym (8) · async message for strangers (9) · clock assertion (17); and, under Going further, accept by answering (10) · the public referee (12) · group-owned private PDA (18)

Goal

A space game. Every player commands a ship whose position and cargo are hidden from everyone else. Stations are public places. Players talk by radio, which can carry cargo.

Each game mechanic is a protocol feature under another name:

In the gameIn the protocol
a shipa private actor
fog of warprivate state
the laws of physicsthe handler, proven on every move
a stationa public actor
a radio messagean AsyncMessage
an encrypted channela sealed AsyncMessage from a private sender
a call signa blinded address
accepting a tradeanswering with an authorized root call
dockinga SyncMessage from private to public

Actors

ActorWhat it holdsPlacement
(player, space): a shipposition, cargo, time of last moveprivate
(station, space)its location, the call signs docked therepublic PDA

Messages

/// From the player to their own ship.
enum Command {
    Spawn { now: Timestamp },
    Move { to: Position, now: Timestamp },
    Radio { to: AccountId, text: String, cargo: u64 },
    Dock { station: AccountId },
}

/// Between actors of the game.
enum Internal {
    Signal { text: String, cargo: u64 },
    Docking { at: Position },
}

Movement: the laws of physics are a handler

Command::Move { to, now } => {
    assert!(input.is_authorized() && input.from.is_none(), "only the captain commands");
    let mut ship = Ship::from_bytes(&input.pre_state);
    let elapsed = now - ship.last_move;
    assert!(ship.position.distance(&to) <= elapsed * MAX_SPEED, "too far, too fast");
    ship.position = to;
    ship.last_move = now;
    Response::set_state(ship.to_bytes())
        .timestamp_window(now..)        // `now` cannot be in the future
}

Observers see a private transaction, not the move. A move that breaks the speed limit cannot be proven, so cannot happen.

Without a Spawn, a ship’s first Move counts from time zero and may go anywhere. Spawn runs once and sets the first position (a fixed start) and last_move. Its window bounds the claimed time on both sides, since a lower bound alone would let a captain claim to have spawned long ago:

Command::Spawn { now } => {
    assert!(input.is_authorized() && input.from.is_none(), "only the captain commands");
    assert!(input.pre_state.is_empty(), "already spawned");
    let ship = Ship { position: START, cargo: 0, last_move: now };
    Response::set_state(ship.to_bytes())
        .try_timestamp_window(now..now + SPAWN_SLACK)   // `now` is at most SPAWN_SLACK old
        .expect("SPAWN_SLACK is not zero")
}

Every command checks that it comes from the captain and from nobody else. is_authorized() alone is not enough: if the captain marks the ship in a call to another program, that program holds the ship’s grant and can attach it to its own Command::Radio { to: thief, cargo: everything }. A stranger’s command collected from the mailbox fails the check anyway, because a stored message arrives with no grant.

Radio

Command::Radio { to, text, cargo } => {
    assert!(input.is_authorized() && input.from.is_none(), "only the captain commands");
    let mut ship = Ship::from_bytes(&input.pre_state);
    ship.cargo = ship.cargo.checked_sub(cargo).expect("you do not carry that much");
    Response::set_state(ship.to_bytes())
        .send_async(Actor::new(to, input.receiver.program_account_id), &Internal::Signal { text, cargo })
}

// On the receiving ship, when its captain collects the message:
Internal::Signal { cargo, .. } => {
    assert!(input.from_own_program(), "not a ship");
    let mut ship = Ship::from_bytes(&input.pre_state);
    ship.cargo += cargo;
    Response::set_state(ship.to_bytes())
}

Different ways to use the same two arms:

  • Encrypted, ship to ship. The sender is private and seals the AsyncMessage, which needs the recipient’s keys, and the factor behind its address when that address is blinded. Only the recipient reads it, and observers cannot tell who is talking to whom.
  • Call signs. The ship sends under a blinded address: observers and stations see a call sign and cannot link two call signs of one ship. The protocol lets a ship reuse a call sign, for a station’s records or a combat challenge; the reference wallet does not (What works with the reference wallet today). A ship that wants a reply must give the other captain its keys and the factor behind the call sign, and that captain then knows which ship it is: call signs hide a ship from the galaxy, not from the ships it talks with.
  • Distress call. A Signal under a call sign that is never used again.
  • Cargo pod. A Signal with cargo. The sender’s hold shrinks when it is sent, and the receiver’s grows when it is collected. Uncollected cargo drifts in space.
  • Listening is free, answering is a choice. The captain’s wallet reads every message sent to the ship; the ship only changes when the captain collects one.

Docking: proving where you are

Command::Dock { station } => {
    assert!(input.is_authorized() && input.from.is_none(), "only the captain commands");
    let ship = Ship::from_bytes(&input.pre_state);
    Response::keep_state()
        .send_sync(Actor::new(station, input.receiver.program_account_id), &Internal::Docking { at: ship.position })
}

// On the station:
Internal::Docking { at } => {
    assert!(input.from_own_program(), "not a ship");
    let mut station = Station::from_bytes(&input.pre_state);
    assert_eq!(at, station.location, "you are not here");
    station.docked.push(input.from.unwrap().account_id);   // a call sign
    Response::set_state(station.to_bytes())
}

The station is public. It learns that a real ship is at its dock, under a call sign, but not which ship, where it came from, or what it carries. The ship cannot lie about its position: at is read from its state by the game’s own code, inside the proof.

Docking is the one moment a ship reveals where it is, and the player chooses it.

What an observer sees

EventOn chain
a movea private transaction: unlinkable notes, and its validity window, which shows the now the move claimed
ship-to-ship radioa sealed message
dockingthe station, a call sign, the dock’s position

Going further

  • Trading. An offer is a Signal that asks for something back. It records the offer and nothing more; the other captain accepts by sending their own call that marks whatever the trade has to move (pattern 10).
  • Broadcasts. A public beacon actor that logs what ships send it.
  • Combat. Nobody can make a ship collect a torpedo, so contested space needs a public referee holding bonds (pattern 12): a challenged call sign answers “hit” or “miss” in time, by a message its handler computes from the real position, or it loses the bond.
  • Fleets. A fleet is a private PDA owned by a group (pattern 18). Any officer holding the group’s keys can run its handler. A PDA has no signing key, so a root call never authorizes it and the captain check always fails: the fleet takes orders from its officers’ own ships instead, as a seat does (pattern 4).

What does not work

  • Real time. Every action is a proof, so the game suits minutes per move.
  • Automatic detection. Two ships at the same place do not know it until one of them acts.

Battleship: players who cannot lie

Shows: the proof-carrying message (7) · the seat (4) · the public referee (12)

Goal

Two players hide their fleets and take turns shooting. Each must say truthfully whether a shot hit.

On most chains this needs a commitment at the start and a full reveal at the end, and a liar is only caught after the game. Here a player cannot answer falsely: the game’s handler computes the answer from the player’s real hidden fleet, inside a proof.

Actors

ActorWhat it holdsPlacement
(match, battleship)the two boards’ addresses, whose turn it is, the shot waiting for an answer, the results so farpublic PDA
(player, battleship): a boardthe match it plays in, and the fleetprivate, on each player’s account

The match is public because it is the referee. The boards are private because they are the secret.

Messages

/// From a player to their own board.
enum Command {
    Place { game: Actor, fleet: Fleet },
    Fire { at: Square },
    Answer,
}

/// Between actors of the game.
enum Internal {
    Joined,                              // board -> match: take a seat
    Shot { at: Square },                 // board -> match
    WhatWasFired,                        // board -> match
    Incoming { at: Square },             // match -> board, as the reply
    Result { at: Square, hit: bool },    // board -> match
}

The board’s handler

// Every command: only the owner, and never a collected message.
let owner = input.is_authorized() && input.from.is_none();
let (game, fleet): (Actor, Fleet) = decode(&input.pre_state);   // every arm but `Place`

Command::Place { game, fleet } => {
    assert!(owner && fleet.is_legal(), "ships overlap or leave the grid");
    Response::set_state(write_once(&input.pre_state, encode(&(game, fleet))))
        .send_sync(game, &Internal::Joined)
}

Command::Fire { at } => { assert!(owner); Response::keep_state().send_sync(game, &Internal::Shot { at }) }

// "Answer" asks the match which square was fired at...
Command::Answer => { assert!(owner); Response::keep_state().send_sync(game, &Internal::WhatWasFired) }

// ...and the match replies in the same transaction.
Internal::Incoming { at } => {
    assert_eq!(input.from, Some(game), "only my match tells me about shots");
    let hit = fleet.occupies(at);
    Response::keep_state().send_sync(game, &Internal::Result { at, hit })
}

The match’s side

The match is bookkeeping, with one rule: it pins each board’s address when the board joins, and afterwards accepts messages only from those two addresses.

let board = input.from.filter(|_| input.from_own_program()).expect("not a board").account_id;
match message {
    Internal::Joined => game.take_free_seat(board),          // remember this address
    Internal::Shot { at } => { assert_eq!(board, game.shooter()); game.pending = Some(at); }
    Internal::WhatWasFired => { assert_eq!(board, game.defender()); /* reply Incoming */ }
    Internal::Result { at, hit } => { assert_eq!(board, game.defender()); /* record; swap turns */ }
}

How it runs

  1. Place. Each player places a fleet on their own board. The handler checks that it is legal, writes it once, and takes a seat at the match.
  2. Fire. The shooter’s board sends Shot to the match.
  3. Answer. The defender’s board asks the match what was fired, receives Incoming, and sends back Result, all in one private transaction.

What to notice

The player does not choose hit: the handler computes it from the stored fleet, and a proof of any other answer does not exist.

The seat is what makes the fleet the same fleet. A player may own several private accounts, each with a different legal fleet. Without the pinned address, a defender could answer each shot from whichever board says “miss”. The match accepts answers only from the address that joined, and the board behind that address wrote its fleet once.

The board must present the address it joined with every time, which the protocol allows and the reference wallet does not (What works with the reference wallet today).

The match never sees a fleet, and never needs a commitment to one.

The answer is one transaction with a conversation inside it: the private board sends a SyncMessage to the public match, the match replies, the board sends again. The proof covers the board’s two runs; the sequencer runs the match’s two.

The defender must be the one to act: the match cannot push a shot into a private board. That is why the board asks.

The match knows a board only by the address it joined with, which can be a pseudonym.

What leaks

Every shot and every result, as in the board game (whether each square fired at holds a ship), and the two boards’ addresses. The rest of each fleet, including the loser’s surviving ships, stays hidden.

Going further

  • Deadlines. A defender who never answers stalls the game, so each player posts a bond with the match, and anyone can claim it for the other player once the answer is late.
  • Other games, same recipe. A private actor per player for the secret, a public match as referee that pins each player’s seat, every answer a message from that seat.
    • Card games: a card can only be played if it is in the hand, and only once. The hard part is dealing without a trusted dealer.
    • Wordle or Mastermind: the secret is written once before the first guess, so it cannot be adapted.
    • Strategy with fog of war: see Deep Space Radio.
  • What does not work: randomness from the chain. A handler is deterministic, so dice need a commit-and-reveal between the players.

Idea catalog: more designs, and what does not work

Each design names the patterns it uses in parentheses, numbered as in The pattern language, and its catch where it has one. The second half lists things that do not fit the model, with the reason.

Money

Payroll. A company PDA holds the month’s salaries. One public transaction sends a credit to each employee’s address as an async message, and employees collect privately. Amounts are public unless the payroll actor is group-owned and private, in which case an officer runs it and the async messages are sealed. (9, 13, 18)

Tip jar. A creator publishes one blinded address per platform. Tips are plain transfers. (9, 8)

Savings lock. A PDA vault that pays its owner’s address only after a date. The owner cannot break it, because no key controls a PDA, as long as the vault program is immutable. (13, 17)

Allowance for a child account. A mandate actor on the parent’s account that accepts bills from one address up to a limit per period. See Payment requests. (10)

Crowdfunding with a threshold. A public campaign PDA collects deposits under pseudonyms. At the deadline, anyone pokes it: if the goal is met it pays the creator, otherwise it sends each deposit back to the address it came from as an async message. A refund to a private backer is published in the clear, so that backer’s address needs a recovery binding on chain. Private backers stay hidden; each deposit and the total are public. (8, 11, 13)

Private lending between friends. A group-owned private ledger. No enforcement beyond the group. (18)

Bounties. A public PDA holds a reward and a hash. The first message carrying the preimage is paid at the address it names. To stop front-running, the claim first commits to the answer and the claimant’s address, then reveals. (13, 14)

Governance

Anonymous feedback box. A public actor that accepts one message per badge per period. (7, 8, rate limit from Credentials)

Petition. The petition counts proof-carrying signatures, one per badge. The count is public, the signers are not. (7)

Council with secret ballots and public members. Votes go through private seats under fresh addresses. Everyone knows who may vote; nobody knows how each voted, unless the tally gives it away (a unanimous vote). (7, 8)

Whistleblower channel. A newsroom publishes its keys. A source sends a sealed message from a throwaway private account, with a bond. To be answered, the source includes that account’s keys, so the newsroom can seal a reply to it. The newsroom learns one throwaway account, which on chain links to the source only through its funding, its timing and its fee; fund it privately. (8, 9)

Jury selection. Jurors hold badges. A case actor picks jurors by pseudonym from those who volunteered. Jurors vote under the same pseudonym for the case and are paid at it. (7, 8, 12)

Identity and access

Age check. See Credentials. (7)

Allow-listed token sale. The sale accepts purchases only with an Attested message from a badge, limited to one per badge. (7)

Anonymous forum karma. A forum sends karma badges to pseudonyms as async messages. Users collect them into their account and show a total under a new pseudonym. (7, 8, 9)

Guest list with plus-ones. A private ticket records its issuer and may send one more ticket, carrying that issuer, once, to a friend’s address. The door admits a ticket of its own program only for an issuer it trusts, as the venue does in Credentials. (7, 15)

Address forwarding. A private actor that forwards everything it receives to a new address, written once. Old addresses keep working, but the old owner must still collect each message to forward it, so the old keys stay in use. (15)

Coordination and games

Secret Santa. A public organiser actor assigns each participant another participant’s address without learning who is behind any address. A gift sent from a public account needs only the address. A gift sent privately needs the recipient’s keys, so that giver learns the recipient’s account. (8, 9)

Prediction market with hidden positions. The market and its prices are public; positions are private actors. Buying and redeeming cross the boundary under pseudonyms. (7, 8, 13)

Treasure hunt. Clues are stored messages sealed to whoever solved the previous clue. (9)

Turn-based strategy. See Deep Space Radio and Battleship.

Correspondence chess with a clock. A public match actor, validity windows for each move’s deadline. (12, 16)

Infrastructure

Keeper network. A registry of pokable actors and the fee each pays. Keepers earn by sending the transactions nobody else bothers to send. (11)

Relayer for private fees. A private transaction can pay its fee through a fee declaration by one of its public signers, so a public relayer can sign and pay it, and be repaid by an AsyncMessage inside the same transaction. The relayer’s signature links its account to the transaction. (9)

Message board with expiry. A public actor that keeps the last N messages and drops older ones, so its state stays bounded.

Name registry. A public actor per name, derived from the name’s hash (pattern 14), holding an address. Paying “alice” means reading the address and sending to it. A private owner updates the address under a pseudonym.

Notification inbox. A convention, not a handler: stored messages of a Notify { topic, text } type addressed to a user under an agreed notification program id, which wallets display and never collect. Programs get a standard way to tell a private user something.

What does not work, and why

An automated market maker with hidden reserves. Whoever trades must see the reserves, so they are public, or one party holds the keys and must run every trade.

A private order book matched by the chain. Matching compares two parties’ secrets, and no single transaction can run both parties’ private handlers.

Liquidating a private position. Only a holder of the account’s keys can run its private handler, so collateral that must be seizable has to sit in a public actor.

Reading someone’s private balance with their permission. There is no view grant in the protocol. The owner can share their viewing key, which shows everything, or prove a specific claim about the balance with a badge-style program.

Private recurring payments with the payer offline. A private account does nothing while its owner is away; pre-fund a public stream.

Refunding a stored credit automatically. A stored message is never returned, so the sender needs a return path in the program, enforced by a public actor.

A program that scans the mailbox. Handlers see one message; scanning is done by wallets, off chain.

Guaranteed delivery. An AsyncMessage guarantees that the message is stored, never that it is collected.

Randomness. No beacon exists. Two parties can produce a shared random value by commit and reveal; a single party cannot produce one that others trust.

Hiding that you use a program. A disclosed program is named in every private transaction that runs it. Of deployed programs, only immutable ones can run undisclosed.

Unbounded fan-out to private recipients. Each recipient pays a proof per message collected (the reference wallet clears up to five native credits per proof, and any other message costs a proof of its own). A design that sends a thousand people a message a day will be ignored by most of them.

Reading state from a client

The sequencer accepts transactions; the indexer answers questions about what happened. A client talks to both, and almost everything an application displays comes from the indexer’s JSON-RPC surface.

Source: lez/indexer/service/rpc/src/lib.rs for the interface, lez/indexer/service/protocol/src/lib.rs for the types.

The surface

Sixteen methods and two subscriptions.

MethodReturns
getAccount(account_id)the account’s full state, or null
getAccountAtBlock(account_id, block_id)the same, as of a height
getAccountSummary(account_id)the nonce, the balance and the size of each actor state, not its bytes. An unknown account returns nonce 0, balance 0 and no actor states, not null; balance is null only when the native state does not decode
getAccountView(actor)the account’s nonce and one program’s actor state, projected out of the account. Takes an Actor (an account id and a program account id) to know which program’s state to return
getAccountViewAtBlock(actor, block_id)the same, as of a height
getBlockById(block_id)a block
getBlockByHash(hash)a block
getBlocks(before, limit)blocks paging backwards from a cursor, newest first; not a range. A limit above 100 is refused with InvalidParams
getTransaction(hash)a transaction
getTransactionReceipt(hash)how it went: success, plus a fee breakdown of execution gas, storage gas, base fee, tip and refund. None for an unknown hash, and for a block’s trailing fee and clock transactions
getTransactionsByAccount(account_id, offset, limit)an account’s transaction history, paged. A limit above 100 is refused with InvalidParams
getEvents(filter)program events; see Events
getLastFinalizedBlockId()the finality watermark; see Finality
getStatus()node status
getSchema()the indexer’s own schema, which is the authoritative shape reference
checkHealth()liveness
SubscriptionStreams
subscribeToFinalizedBlocksblock ids as they become irreversible, not the blocks; fetch a body with getBlockById
subscribeToEvents(filter)EventRecord as events are indexed

The indexer reads finalized L1 blocks, so a transaction already landed on the zone returns null here until its block finalizes, and the indexer can report CaughtUp with nothing indexed. For the answer now, ask the sequencer’s getTransactionReceipt; it answers from its head, which can still change until the block is final (Finality).

Read the receipt rather than inferring an outcome. success is false for a reverted transaction, which is still in its block and still paid, so “absent” and “failed” are different answers. Receipts are covered by the block hash: part of the block, not an indexer annotation. A receipt does not say why a transaction reverted: settlement drops the reason. The wallet library simulates a publicly paid transaction before sending it and refuses one that reverts with ExecutionFailureKind::SimulatedRevert(reason); a dry run reports the same reason (Pricing it first). Both run against the head at that moment, so a transaction that passes and then reverts on chain leaves no reason anywhere.

Call getSchema during development rather than transcribing shapes from this page: it is generated from the server’s own types, so it cannot drift.

A first request

A local indexer listens on port 8779 (Running a node). A call is a JSON-RPC POST; parameters can be positional, and an account id is bare base58, without the wallet’s Public/ prefix:

curl -s http://127.0.0.1:8779 -H 'Content-Type: application/json' \
  -d '{"jsonrpc":"2.0","id":1,"method":"getAccount","params":["7VDm7YRPvimbZgCzuFqCGf6RwPsTV3XY5W9DzT71oain"]}'

The account id above is a sample; use one of yours. The answer is under result, null for an account that does not exist, in the shape below; a failure is still HTTP 200, with an error member instead. This repository publishes no testnet indexer endpoint: the wallet’s testnet network names only the sequencer, https://testnet.lez.logos.co.

The sequencer’s own RPC

The indexer is for history; the sequencer answers about now. A client writing directly against it rather than through the wallet library needs these, none of which the indexer has:

MethodReturns
sendTransaction(tx)submits it, as base64 of its borsh bytes, and returns its hash
getFeeState()the fee market’s current base fees and the band the next block’s can move within, for sizing max_fee
getZoneId()the zone a signature must be for
getChannelId()the L1 channel this zone is written to
getProofsAndRoot(commitments, message_positions)two lists of membership paths, one per commitment and one per message leaf (null for one not in the tree), plus the root they are all under
getPublications(from_position, limit)a page of published messages from a position, which a scanning client reads to find its own
getMessagePath(position)the path for one published message
getRecoveryBinding(address)the binding that lets an owner recognise a stored message
getProgramIds()one hardcoded entry for the privacy circuit, the single id wallet check-health compares. Its implementation carries a TODO to read programs from state, so it is not a program inventory
getSystemProposals(), submitSystemApproval(..)the system upgrade queue and a committee approval
getSequencerStatus()whether the sequencer is still bootstrapping from the channel or online

A submission can be refused before it reaches the mempool:

ConditionAnswer
the decoded size its base64 implies exceeds 1,835,008 (the largest block size any chain can set)-32602, message Invalid params, with payload of up to N bytes exceeds 1835008 in the error’s data, since it fails while the parameters decode
it is malformed or calls a sequencer-only programInvalidParams (-32602), the cause in the message
it would not fit in a block under this chain’s max_block_sizethe same
its fee fails the fee screenthe same
a signer’s nonce is below its account’s, or a signer fails authentication at the head or against a pending transactionthe same
a slot it claims is already pending, or a signer is at its pending limitthe same
a private transaction’s commitment, nullifier or recovery binding is already in the headthe same
the mempool is full-31900
a private fee reserve the head base fee has outgrown-31901: price it again and resubmit
the sequencer is not online yet-31902

It also answers reads at its head, so a client needing only current state can talk to one service: getAccount, getAccountView, getAccountBalance, getAccountsNonces, getBlock(block_id), getBlockRange(start, end), getLastBlockId, getTransaction(hash) (the transaction and its block id), and getTransactionReceipt(hash), plus checkHealth. The code marks all but checkHealth for removal once the wallet reads through the indexer. Blocks and transactions come back as base64 of their borsh bytes, not JSON, so reading them takes the Rust types.

The shape an account comes back in

An account is a nonce and a map from program account id to that program’s actor state. The native balance is one of those entries, under the native token program, not a field of its own:

{
  "nonce": 0,
  "data": { "actor_states": { "<program account id>": "<base64 bytes>" } }
}

actor_states is keyed by program, so a client reads only the entries it cares about. The bytes are whatever that program writes, and decoding them is the client’s job: the indexer does not know a program’s state layout. wallet account get --raw --scope all --account-id <account id> prints the same entries, flattened to actor_states and nonce with hex bytes.

Prefer getAccountSummary or getAccountView for list views: a full read of an account with large actor states can exceed the response limit.

The two things the indexer cannot do

It cannot read private accounts. The chain holds only a commitment and an encrypted note, and the server does not have the keys, so no RPC method returns a private account’s state. The only path is a client holding them: the wallet library (Building on the wallet library) and its sync-private scan.

It cannot tell you about a refused transaction, because there is nothing to query. A private transaction whose public part fails at settlement is refused when the failure is not chargeable or nothing pays for it; with a fee fallback in its proof, or a fee a public signer declares, it is included as a paid revert (Reading the chain). A client polling for one it submitted must treat “not found” as a possible terminal state, not “not yet”: nothing records the refusal, and a transaction still waiting in the mempool looks the same, so the client decides how long to wait before treating it as refused. The wallet’s poller gives up after a fixed number of timed polls, not blocks (It lags the sequencer).

It lags the sequencer

For submission and immediate confirmation use the wallet library’s poller: poll_tx(tx_hash) returns the transaction and the block it landed in, and poll_block_range walks a range (lez/wallet/src/poller.rs). Its patience is the wallet config’s (up to seq_tx_poll_max_blocks polls seq_poll_timeout apart), and running out ends in Transaction not found in preconfigured amount of blocks, which is not a verdict.

The division that works: submit and confirm through the wallet library, display and search through the indexer.

The explorer

lez/explorer_service is a Leptos front end over the same RPC surface, run as Running a node shows, and a worked example of the read path (it calls get_last_finalized_block_id, among others). It is not a stable integration surface and may change or go away.

Finality

A LEZ transaction passes through two states, and a client that treats the first as the last will eventually show a user something that gets taken away.

It is included when the sequencer settles it into a zone block, running its public part against live state. A failure that something pays for is included as a revert and still charged; one that nothing pays for, or a malformed transaction, is dropped (Reading the chain). For a private transaction this can be long after proving. It is final when the Logos L1 channel carrying that zone block has itself become immutable.

Only the second is irreversible, and only it is what the indexer’s getLastFinalizedBlockId reports.

Where finality comes from

LEZ does not decide its own finality. It is a channel on the Logos blockchain and inherits that chain’s ordering, and so its notion of immutability.

The L1 runs Cryptarchia, a proof-of-stake consensus whose finality is probabilistic rather than absolute. Its Config carries a security_param, documented in the code as “the k parameter in the Common Prefix property. Blocks deeper than k are generally considered stable and forks deeper than that trigger the additional fork selection rule, which is however only expected to be used during bootstrapping” (logos-blockchain/logos-blockchain: consensus/cryptarchia-engine/src/config.rs).

The latest immutable block is computed from security_param: the engine walks from the current immutable block towards the tip and takes the first block the tip is no more than security_param ahead of, lib_to_tip_blocks (logos-blockchain/logos-blockchain: consensus/cryptarchia-engine/src/lib.rs).

k is not a constant, nor one value per deployment: it is read from the era schedule at the block’s own slot, so it can differ between eras of a chain. The starting values:

Deploymentsecurity_param
Node default30
Local stack (just run-bedrock, the root compose file)3
Testnet deployment template120

Sources: logos-blockchain/logos-blockchain: nodes/node/era/schedule/0.yaml (era 0 of nodes/node/standalone-deployment-config.yaml) and deployment/ceremony/genesis/testnet/deployment-template.yaml; for the local stack, bedrock/deployment-settings.yaml in this repository.

The local stack has 4-second slots with a block expected in half of them (slot_activation_coeff 1/2), so a local block is final after about half a minute. This repository does not carry the testnet’s slot timing.

No L1 block becomes mathematically irreversible. Depth buys confidence, and k is the depth at which the node treats a block as immutable.

The channel parameter finality_depth (Voting channel parameters) is a different number and does not decide when a zone block is final. It is how many L1 blocks must sit on top of the block where the stake program’s configuration stopped listing a sequencer key before that key’s whole stake can be released. Its doc comment says it must exceed security_param, which the code does not check; it is fixed at genesis: 35 in local.json, 180 in devnet.json and testnet.json (lez/programs/sequencer_stake/core/src/lib.rs).

How a zone block becomes final

A zone is a channel. The sequencer writes its blocks into it as inscriptions, each referencing the previous message by MsgId, so the channel is itself a chain (logos-blockchain/logos-blockchain: core/src/mantle/ops/channel/{mod.rs,inscribe.rs}). Deposits and withdrawals are operations on the same channel, though LEZ rejects withdrawals in this version.

The sequencer then watches the channel: in the code’s words, the channel serving a block “is what makes it irreversible” (lez/sequencer/actors/executor/src/actor/state/bootstrapping.rs). When the L1 finalizes channel messages, the zone blocks they carried move into a final tier. The sequencer collects the newly final blocks and any re-delivered ones into a set it calls irreversible and takes the highest block id:

// Every block at or below the highest finalized one is irreversible, so
// stored blocks there can be marked finalized.
let last_finalized = irreversible.iter().map(|block| block.header.block_id).max();

Everything at or below that height is irreversible, so finality is a single watermark, not a per-block flag.

What final means today

A final zone block has a fixed place in the channel but has not been checked by the L1, which orders the channel’s inscriptions without executing them. Each inscription is signed by one accredited sequencer key, and every node re-executes final blocks itself. A node accepts a bridge deposit mint in one only if it is the mint the node rebuilt from a deposit it saw finalize on L1 and, where the node knows both positions on L1, one that finalized before that block’s channel message. A final block that does not apply is skipped: the final tip stays at the last block that applied, the next valid block at the following height extends it, and where the block was the next entry past the tip and the fault is the producer’s, its signer is reported for slashing (lez/chain_state/src/chain.rs, lez/sequencer/core/src/faults.rs). An invalid block in a final channel message therefore changes no state; it wastes that channel message.

Before the channel message is final, the zone’s recent history can change. The L1 can settle on a different lineage of inscriptions, and zone blocks on the other one leave the head. The sequencer returns their user transactions to the mempool (lez/sequencer/core/src/lib.rs), so an included transaction can disappear and come back in a later block, or not.

What a client should do

Read the watermark from the indexer, or subscribe to it:

getLastFinalizedBlockId      -> Option<BlockId>
subscribeToFinalizedBlocks   -> stream of finalized block ids

For anything with value attached, show the transaction once included, label it pending, and treat it as done only once its block id is at or below the watermark. The wait is k L1 blocks plus however long the channel takes to carry the zone block, substantial on a 120-deep testnet.

For a transaction with no value attached, inclusion is usually enough.

What a program author should assume

Nothing in a handler can observe finality. A handler sees one message and one actor’s state, and runs on the sequencer or in a proof; in neither case does it know how deep its block is. Time is available only by asserting against the clock, which is itself zone state (System programs).

So finality is a client concern, not a program concern, except at the bridge: a deposit observed in a finalized block is paid out of custody permanently, because its receipt is then in the irreversible tier, and the sequencer drops the pending record tracking it. Until then the payout is reversible along with its block.

Settlement is not finality

A private transaction’s effects on public accounts are applied by the sequencer at settlement, against live state, after the proof is verified (Transactions). That is why a prepared private transaction can be built now and still settle correctly later. Settlement decides whether a transaction takes effect at all; finality decides whether that effect can still be undone.

Only finality involves the L1.

Building on the wallet library

WalletCore is the Rust client: it holds keys, builds and signs transactions, proves private ones, scans for notes a user can decrypt, and submits. Every runner under examples/program_deployment/src/bin/ is a short client built on it, and so a worked example.

Source: lez/wallet/src/lib.rs, with account handling in lez/wallet/src/account_manager.rs.

The shape of a client

let mut wallet_core = WalletCore::from_env()?;

// accounts
let (account_id, _) = wallet_core.create_new_account_public(None);   // or Some(chain_index)
let nonces = wallet_core.get_accounts_nonces(&[account_id]).await?;
wallet_core.store_persistent_data()?;

// reading
wallet_core.get_account(AccountIdWithPrivacy::Public(account_id)).await?;
wallet_core.get_account_public(account_id).await?;   // or this, for a bare id
wallet_core.get_account_balance(account_id).await?;
wallet_core.get_account_view(Actor::new(account_id, program_account_id)).await?;
wallet_core.get_last_block_id().await?;
wallet_core.get_block(block_id).await?;
wallet_core.get_transaction(tx_hash).await?;

// the mailbox
wallet_core.get_publications(from_position, limit).await?;
wallet_core.owned_pending_messages().await?;
wallet_core.find_pending_message(..).await?;

// submitting
wallet_core.send_pub_tx(..).await?;
wallet_core.send_privacy_preserving_tx(mentions, root, message_bytes, &programs).await?;

store_persistent_data is not optional: keys created in memory and not stored are lost, which is why the examples’ deploy_program helper calls it after creating the header and segment accounts.

A native transfer

The facades in lez/wallet/src/program_facades/ build, sign or prove, and submit a builtin program’s call:

use wallet::{
    AccountIdentity, WalletCore,
    program_facades::{CreditDelivery, native_token_transfer::NativeTokenTransfer},
};

let mut wallet_core = WalletCore::from_env()?;
let (tx_hash, _) = NativeTokenTransfer(&wallet_core)
    .transfer(AccountIdentity::Public(from), AccountIdentity::Public(to), amount, CreditDelivery::Automatic)
    .await?;

from and to are AccountIds and amount a u128. Either side may be private, which makes it a private transaction proven in process; CreditDelivery::DeferredPrivate leaves a private recipient’s credit in the mailbox; a PrivateForeign recipient’s always waits there. transfer checks the sender’s balance first and returns InsufficientFundsError without sending. It returns the hash and, per private account, the shared secret (SharedSecretKey) its new note is encrypted under, not an outcome: wait for inclusion and read the receipt (It lags the sequencer). When a private account took part, call wallet_core.sync_to_latest_block().await? after inclusion so the wallet records the spent and new notes; it also stores. from_env reads LEE_WALLET_HOME_DIR and, for an encrypted store, LEE_WALLET_PASSWORD, prompting on the terminal when it is unset.

Depending on it from outside the repository

No crate is published. Depend on wallet (and lee, lee_core, common for their types) by path into a checkout matching the node you talk to, and copy that checkout’s [patch.crates-io] section, Cargo.lock and rust-toolchain.toml so the graph resolves as it does there. If your own core crate pins lee_core by git (A program crate), add a [patch."https://github.com/logos-blockchain/logos-execution-zone"] entry pointing lee_core at the same checkout, or the two do not unify. The guest binaries the wallet embeds are committed under artifacts/ and read by build scripts from the checkout, so a client build compiles no guest and needs neither Docker nor RISC0_SKIP_BUILD.

Naming an account

An account is named by an AccountIdentity, with nine variants:

VariantUse
Public(id)a public account this wallet owns and will sign for
PublicNoSign(id)a public account to touch without signing, even if owned
PublicForeign { .. }someone else’s public account, known by its initial key
PublicPda { .. }a public program-derived account
PublicKeycard { .. }a public account signed by a Keycard; refused in every build, because a Keycard key cannot rotate (lez/wallet/src/keycard_support.rs)
PrivateOwned(id)a private account whose keys and kind the wallet holds
PrivateForeign { .. }a private account known only by its public keys: a destination you can send async messages to but cannot witness
PrivateShared { .. }a shared regular private account with externally supplied keys, as from a group key
PrivatePdaShared { .. }a shared private PDA, likewise

The distinction that catches people: PrivateForeign is send-only. You can address an async message to it but cannot produce a witness for it, because a witness needs the account’s nullifier secret key (or the authorization secret key it derives from), which only the holder has. That asymmetry is why the mailbox exists (Private accounts).

Select a program’s actor state on an identity before using it:

let account = AccountIdentity::PrivateOwned(account_id)
    .select_program_actor_state(program_account_id);

Submitting a private transaction

wallet_core
    .send_privacy_preserving_tx(vec![account], 0, Program::serialize_message(msg)?, &programs)
    .await?;

The first argument lists the transaction’s account mentions: a mention is one account together with the program whose actor state it selects and whether it authorizes (AccountMention, a wallet type, not a protocol one). The second is the index in that list of the mention the root message goes to. Program::serialize_message(msg) is borsh::to_vec(&msg), returned as a MessageData (a Vec<u8>) inside a Result, the encoding a guest decodes, so Borsh bytes from anywhere work. A mention from select_program_actor_state authorizes; call .without_authorization() on it for an account the transaction touches but does not authorize, such as a recipient (PublicNoSign(id) is the public shorthand).

The programs argument must list every program the call graph may reach, each marked disclosed, undisclosed or shadow (Programs, deployment and identity). A disclosed or undisclosed program is keyed by its deployed account id; a shadow program, never deployed, by AccountId::for_shadow_program(&image_id), and a message reaching it in the public part fails with UnknownProgram. A program the execution dispatches to that was not supplied cannot be proven.

Proving happens in process (how long it takes). RISC0_DEV_MODE=1 skips real proving during development and must never be used against a real network.

A refused submission comes back with its cause; The sequencer’s own RPC lists the refusals and their codes. The library keeps the message and drops the code and data: a refusal is ExecutionFailureKind::SequencerClientError(message), so the size cap arrives as only Invalid params. The exception is -31901, PrivateFeeBelowHead, which a private send reprices and resends up to twice before returning.

Deployment from Rust

The examples’ helper is the shortest correct deployment and, unlike the CLI, creates the accounts.

pub async fn deploy_program<C: WalletSequencerClient>(
    wallet_core: &mut WalletCore<C>,
    bytecode: Vec<u8>,
    payer: AccountId,
) -> anyhow::Result<AccountId>

WalletCore is generic over its sequencer client, so a function taking one needs that parameter and a struct holding one must name the client type. WalletCore::from_env() returns a WalletCore<SequencerClient>, the HTTP client. The helper decodes the ProgramBinary, computes the user ELF’s length divided by MAX_SEGMENT_DATA_LEN, rounded up, creates a header account and that many segment accounts, and calls ProgramLoader(wallet_core).deploy(header, &segments, bytecode, true, Some(payer)), hardcoding immutable. wallet program-loader deploy creates none of the accounts, so the CLI needs them to exist first.

payer must already exist and hold funds: the new header and segment accounts cannot pay for their own creation.

Source: examples/program_deployment/src/lib.rs.

The zone a signature is for

Every signature covers a zone id, a domain-separated SHA-256 of the channel id and genesis hash, so a transaction signed for one zone cannot be replayed on another. Each genesis gets its own zone from a salt, so a chain recreated on the same channel is normally a different zone and the old chain’s signatures stop verifying; Starting clean has the case where it is not.

A client that pins zone_id in its wallet configuration is safe against being pointed at a different chain; one that leaves it unset trusts whatever its sequencer reports from getZoneId. Pin it for anything holding value.

Where to start reading

Start with A native transfer. For a call to your own program, run_hello_world.rs is the minimal public client, and run_hello_world_private.rs the same thing privately. The public runner builds and signs its transaction by hand (fee, nonces, admission evidence); the private one builds an account mention from an AccountIdentity and passes it with a ProgramCatalog to send_privacy_preserving_tx.

The C ABI

lez/core_ffi exposes the wallet and a sequencer over a C ABI for callers not writing Rust (Building on the wallet library is the Rust API), with a generated header at lez/core_ffi/core_ffi.h.

The crate builds three ways, declared in lez/core_ffi/Cargo.toml:

crate-typeFor
cdyliba shared library to load at runtime
staticliblinking into a binary or an iOS or Android build
rlibdepending on it from Rust, though the Rust API is better

It has two independent halves: sequencer_ffi_* runs a node in your process, and wallet_ffi_* drives a wallet.

Building and linking it

cargo build --release -p core_ffi compiles the L1 stack, risc0, the L1’s zone SDK (logos-blockchain-zone-sdk) and the sequencer, because this crate exposes a node as well as a wallet. Expect tens of minutes cold, and a 568 MB libcore_ffi.a or a 94 MB libcore_ffi.dylib. A caller that only sends transactions still builds all of it.

Linking on macOS needs extra frameworks, because the prover pulls in Metal:

cc -o app app.c target/release/libcore_ffi.a \
   -framework Security -framework CoreFoundation -framework SystemConfiguration \
   -framework Metal -framework Foundation -lc++

Without Metal and Foundation the link fails on undefined _MTLCreateSystemDefaultDevice.

Which sequencer the wallet talks to

Every wallet constructor takes a sequencer pointer that decides where transactions go (client_for, lez/core_ffi/src/wallet/lifecycle.rs):

You passThe wallet uses
a pointer from sequencer_ffi_start_sequencerthat in-process sequencer directly, with no network in between
nullan HTTP client built from the sequencer address in the wallet’s config file

Null is not an error: it points an FFI wallet at a remote node, which most callers want. A real pointer embeds a node and a wallet in one process, and must outlive every handle built from it.

The sequencer side

Seventeen functions. Lifecycle is sequencer_ffi_setup, then sequencer_ffi_start_sequencer and sequencer_ffi_stop_sequencer, mirroring the setup and start subcommands of sequencer_service, with options as JSON. sequencer_ffi_is_healthy answers like the node’s /health route, and sequencer_ffi_init_logger turns on logging.

Ten reads ask the in-process sequencer, not the indexer: account, block, block by hash, block by transaction hash, block range, last block, transaction, transactions by account (at most 100 per call, more returns InvalidArgument), events, executor status. Plus sequencer_ffi_send_transaction, and sequencer_ffi_free_query_block_id_by_transaction to free what one read returns.

For history rather than current state, use the indexer (Reading state from a client explains the split).

The wallet side

Seventy functions, in groups mostly matching the CLI:

GroupWhat it covers
Lifecyclecreate_new, open, save, destroy, restore_data, set_password, storage_is_encrypted
Accountscreate public and private, import either, list, resolve, read, balance, account view, initial key
Transferssix shapes: public, shielded, deshielded, private, shielded_owned, private_owned
Keysexport and rebuild private account keys, including from raw bytes
PDAsderive a public or private PDA account id
Pendinglist and receive
Program loadercreate and update a header, write a segment, deploy, update
Generic transactionssend an arbitrary public or private transaction, message already encoded
Feesget_fee_state, set_fee_params, set_dry_run, set_allow_revert
Syncsync_to_block, get_last_synced_block, get_current_block_height, poll_transaction_status
Labelsadd, check availability, list for an account
Shared accountscreate_new_group, create_sealing_key, create_private_shared_account, invite_shared_account, join_shared_account (which needs the wallet’s sealing key first, else Unapplicable)
Bridgewithdraw to L1, which the bridge program rejects in this version

wallet_ffi_create_new starts a fresh wallet at the chain tip, as the CLI does, falling back to genesis when the node is unreachable. On a first run nothing before the tip is scanned unless you call wallet_ffi_rescan_private_accounts, which rediscovers private accounts from genesis.

The six transfer shapes cover the public and private combinations, which take different arguments: an account id for a recipient you can name, key material for one you cannot. The _owned pair is for a private recipient this wallet owns, credited in the transaction instead of waiting in the mailbox.

With set_dry_run on, a send simulates and reports its cost instead of going out; this is how a non-Rust client prices a transaction. Accounts and transfers explains the numbers.

Two conventions that will bite you

Check the error before you dereference. Most sequencer reads and sequencer_ffi_send_transaction return a PointerResult, a value pointer plus an error field; the pointer is valid only when the error is clear. Its doc comment says “Pointer is not guaranteed” (lez/core_ffi/src/primitives/result.rs). Most wallet calls instead return an FfiOperationError and write through out pointers, which hold nothing usable unless it is Success.

Free what you are given. Twenty-one *_free_* functions are declared: eight wallet_ffi_free_* (account data, account identity, account lists, label lists, pending message lists, programs, transaction results, transfer results); one sequencer_ffi_free_*; and twelve for the shared types such as strings and keys (eleven primitives_ffi_free_* plus primitves_ffi_free_ffi_account_opt, which the header misspells and a C caller must match). Free a string with primitives_ffi_free_cstring and private account keys with primitives_ffi_free_private_account_keys, not a wallet_ffi_ call: header doc comments naming wallet_ffi_free_string or wallet_ffi_free_private_account_keys point at undeclared functions. Nothing is reference counted or freed for you.

What is verified here

The build and link recipe above, creating a wallet from C with a null sequencer pointer, and freeing its mnemonic with primitives_ffi_free_cstring are exercised. The rest is documented from the header and the Rust behind it, not from a C caller, so a signature in core_ffi.h overrides any description here.

Getting the header

core_ffi.h is generated with cbindgen and committed, so you can read it without building. It is the authoritative signature list, 99 declarations long.

The indexer has a separate header at lez/indexer/ffi/indexer_ffi.h, not covered here.

Events

An event is how a program tells the outside world that something happened, without putting it in state.

Emitting

pub struct ProgramEvent {
    /// Selector bytes allowing to distinguish event type. By convention, the
    /// first 8 bytes of `sha256("<program>::<EventName>")`.
    pub selector: [u8; 8],
    /// The arbitrary event-data emitted in the program output.
    pub data: Vec<u8>,
}

A handler attaches one with Response::event(..). The selector lets a consumer filter by event type without decoding the data; the record’s program_account_id says which program emitted it.

Source: lee/state_machine/core/src/program/mod.rs.

Consuming

The indexer records each event with its context:

pub struct EventRecord {
    pub block_id: BlockId,
    pub tx_index: u32,
    pub tx_hash: HashType,
    pub program_account_id: AccountId,
    pub selector: Selector,
    pub data: Vec<u8>,   // base64 over the wire
}

The indexer keeps no events by default: event_filter defaults to keeping nothing, and a query or subscription the filter does not cover is refused as UncoveredEventQuery, not answered with an empty list. Under any filter but archival, that includes one naming no program, and one naming no selector for a program declared with a selector list. The indexer warns at startup: “Configured event filter keeps no events”. Set "event_filter": "archival" to keep everything, as the debug and docker all-in-one configurations do, or name the sources: {"sources": [{"program_id": "<base58 program account id>", "selectors": ["<16 hex chars>"]}]}, omitting selectors to keep all of that program’s events. An empty selectors list, or a program named twice, is refused at startup. Coverage is tracked per block range, so changing the filter later splits history into segments, and a ranged query is answered only if every segment it touches covers it.

Query them with getEvents or stream them with subscribeToEvents. A live stream has no block range, so the filters differ:

pub struct GetEventsFilter {
    pub from_block: Option<BlockId>,
    pub to_block: Option<BlockId>,
    pub tx_hash: Option<HashType>,
    pub program_account_id: Option<AccountId>,
    pub selector: Option<Selector>,
}

pub struct EventSubscriptionFilter {
    pub tx_hash: Option<HashType>,
    pub program_account_id: Option<AccountId>,
    pub selector: Option<Selector>,
}

Every field is optional, except that a getEvents call must carry tx_hash or from_block or is rejected. With tx_hash set, the block range fields are ignored. The normal filter is program_account_id plus selector: one program’s one event type.

A ranged query is checked against the tip first, so FromPastTip, ToPastTip or Inverted come first: on a fresh indexer, blocks 0 to 2000 give to_block 2000 exceeds the indexed tip 0, not a span error. Only a range inside the tip that asks for more than 1000 blocks at once fails with SpanExceeded. The response is separately capped at 8 MiB of estimated encoded size, past which the call fails with EventResponseTooLarge, so a client reads history in pages of ranges.

Source: lez/indexer/service/protocol/src/lib.rs and lez/indexer/service/src/service.rs.

The rule that shapes designs

Events emitted by a private handler are dropped: not encrypted, not deferred, discarded. A private actor’s handler runs inside a proof, and its events do not leave it. Public actors in the same privacy-preserving transaction keep theirs, recorded like any public transaction’s events.

So an announcement an indexer or a UI must see has to come from a public actor. Usually the private actor sends a message to a public one, which emits the event in its own handling: the private side proves the fact, the public side publishes it.

See also What you cannot do privately.

What events are not

They are not state. Nothing reads them back on chain, no handler can see another actor’s events, and a program cannot condition on one. A fact that must be enforced belongs in an actor’s state, where a handler can assert on it. Events are for observers.

Running a node

A local stack is three processes: a Logos blockchain node (Bedrock, the L1 node), the LEZ indexer and the LEZ sequencer. The sequencer needs a channel on the L1 node, which it creates once during setup.

The canonical commands are in the repository README.md under “Run the sequencer and node”.

With just

just run-bedrock        # the L1 node, from Docker

Then just run-indexer and just run-sequencer in their own terminals; both build with --release, and run-sequencer sets up its home from local.json on the first run. The Justfile also carries run-wallet, wallet-import-test-accounts (which gives you a funded account), resolve-bedrock-node, run-monitoring, run-explorer, build-artifacts, test, clean, and the decentralized-sequencing tools committee-watch, channel-health and inscribe-garbage. just --list is authoritative.

Standalone

just run-sequencer-standalone

The sequencer alone, built with the standalone feature, which swaps its L1 client for a mock: the simplest node for writing and testing programs, with no Docker, L1 node or indexer. The first run sets up a home at lez/sequencer/service/sequencer_home, and later runs reuse it; the recipe’s first argument names another.

Without just, run setup as in Manually with --release and your own home (it writes files and contacts no L1), then start a build with the feature:

cargo run --release --features standalone -p sequencer_service -- start <home> \
  --rpc-listen-address 127.0.0.1:3141 --metrics-listen-address 127.0.0.1:9141

A second node on one machine must move both ports: the RPC defaults to 127.0.0.1:3040 and the ops server to 0.0.0.0:9000. Point a wallet at it with the new RPC address.

It produces blocks every 15 seconds and serves every wallet and RPC call, but publishes nothing. No block reaches an L1, so none is ever final (Finality), the indexer has nothing to read, and nothing that starts on the L1, such as a bridge deposit, arrives.

Manually

Use the full stack when you need the indexer’s queries or blocks written to an L1. Start each process in its own terminal, in this order. The L1 node first:

just run-bedrock

The node binary is resolved from LEZ’s locked Cargo dependency, not built here. The resolver accepts a release only when its tag, asset checksum and commit match the Cargo-resolved revision; otherwise it builds that exact checkout. See bedrock/README.md.

Then the indexer:

RUST_LOG=info cargo run -p indexer_service lez/indexer/service/configs/debug/indexer_config.json

Then the sequencer, set up once and started thereafter:

cargo run -p sequencer_service -- setup lez/sequencer/service/sequencer_home \
  --config lez/sequencer/service/networks/local.json \
  --funding-public-key 2e03b2eff5a45478e7e79668d2a146cf2c5c7925bce927f2b1c67f2ab4fc0d26 \
  --create-channel

RUST_LOG=info cargo run -p sequencer_service -- start lez/sequencer/service/sequencer_home

That public key is the local Bedrock node’s funded key, fixed for the debug configuration. --create-channel makes the zone exist and is used once: a zone is a channel on the L1, and the sequencer writes into it as inscriptions (Finality).

Optionally the explorer:

cargo install cargo-leptos
cd lez/explorer_service && cargo leptos serve --release

The directory matters: the leptos configuration lives in that crate’s manifest, not the workspace root. just run-explorer runs cargo leptos serve from there, without --release. The explorer is also a service in the root compose file, the easier route if you run the stack that way.

Or all of it in one container stack

A single docker-compose.yml at the repository root runs everything: a development Bedrock node, a four-sequencer committee, the indexer and the explorer, with --profile monitoring adding Prometheus, Grafana, Loki, Tempo and Alloy. Resolve the Bedrock node first with just resolve-bedrock-node, since its image is built from the resolved binary, then run docker compose up. Every host port, image, key path and cross-service URL in the compose file is a variable with a default; .env.local lists them all, and copying it to .env lets you change any.

State lives in named volumes, so the stack resumes across restarts. docker compose down -v gives a fresh chain, and discards the L1 chain too.

Watching it

The sequencer serves /ping, /health and /metrics from one ops server, on a port separate from the RPC so it can be firewalled on its own, by default 0.0.0.0:9000.

That server binds before the sequencer starts, deliberately: /ping and /metrics answer during startup, while /health returns 503 with status "starting" until the sequencer is up, then 200 with "ok", 503 with "failing" if any of its tasks dies, and 503 with "stopping" once it is shutting down. Gossip is excluded from health on purpose: a node that has lost gossip still runs on L1 alone.

The indexer has no HTTP health route. Its equivalent is the checkHealth JSON-RPC method, and a caller must check that the response carries a result, because a JSON-RPC error still arrives as HTTP 200.

Stopping it

Both services shut down on Ctrl-C or on SIGTERM, which a container runtime sends first. The sequencer then stops the ops server and its actors in order (scheduler, RPC server, gossip, supervisor, slasher, L1 client, storage) and waits for each, rather than dropping the handles and exiting: a dropped store stays open for an unbounded stretch, so a quick restart can find its own home locked. Sequencer shutdown complete says it finished properly.

Every flag is also an environment variable

Each start option also reads SEQUENCER_<OPTION>. A flag wins over its environment variable, and both win over the config file. A test checks the mapping for every argument, so the list cannot drift: SEQUENCER_HOME, _CONFIG, _CREATE_CHANNEL, _WAIT_FOR_CHANNEL, _CHANNEL_SIGNING_KEY_FILE, _FUNDING_PUBLIC_KEY, _BEDROCK_NODE_URL, _CHANNEL_ID, _RPC_LISTEN_ADDRESS, _METRICS_LISTEN_ADDRESS, _GOSSIP_LISTEN_ADDR and _GOSSIP_BOOTSTRAP_PEER.

--wait-for-channel makes a node with no genesis poll until the channel’s creator opens it instead of failing, so startup order does not have to be exact; a node that finds the channel already there drops its own genesis and replays the channel’s, so a restarting creator cannot diverge from it. The RPC has no caller authentication, so --rpc-listen-address should only be widened past 127.0.0.1 behind a firewall.

Which network

lez/sequencer/service/networks/ holds local.json, devnet.json and testnet.json, and you choose a network by pointing setup --config or start --config at one. There is no --network flag.

Only local.json carries funded genesis accounts and a small minimum stake, so develop against it. The repository has no faucet and testnet.json funds no account; Setting up the wallet says where testnet tokens come from.

Starting clean

Three directories hold state, and leaving any of them behind gives a confusing half-restart:

  • the L1 node’s state: a state directory in the logos-blockchain checkout for a native node, or for Docker the bedrock_state volume, which compose prefixes with the project name (by default the directory it runs from), so just run-bedrock, run from bedrock/, and the root compose file keep separate ones
  • lez/sequencer/service/sequencer_home, including genesis_salt inside it (below)
  • rocksdb-<channel id>, under the directory you started the indexer from, because --data-dir defaults to the working directory. The RPC port is the --port flag, 8779 by default; neither is a config file key, and the config rejects unknown fields, so a stray key makes the indexer refuse to start

The genesis salt gives each genesis its own zone. The configuration may set it (no shipped network config does); otherwise one is drawn on first use and kept in the home. Recreating the chain from a kept home reuses it, so when the rest of the genesis is fixed, as with a founding set’s signed stake entries in the config, the zone id repeats and the previous chain’s signatures replay (The zone a signature is for). A solo sequencer that stakes itself at genesis signs that stake with fresh randomness each time, so its genesis hash and zone change even with the salt kept. setup --create-channel refuses a kept salt whose store is gone, unless the config sets one; start does not check, and just run-sequencer skips setup when the home already has a sequencer_config.json. Delete the file when you mean to start a new chain.

just clean removes the LEZ side and also takes the Docker stack down with its volumes, resetting the Dockerised L1 chain too.

One upgrade trap: the genesis fingerprint hashes the zone, commitments, nullifiers, publications and recovery bindings as well as the account set, so a sequencer home or indexer store written by a build that hashed only the account set fingerprints differently. The indexer does not stop: it logs that the stored fingerprint does not match and keeps running on its own genesis, the confusing half-restart above. Wipe both stores when you upgrade across that.

Voting channel parameters

Channel parameters can change after genesis by committee vote, under the rule in Sequencer stake; vote-params casts one:

$ sequencer_service vote-params --sequencer-key 0a4cad59... --max-block-size 524288
Voting for ChannelParams { minimum_sequencer_stake: 149, posting_timeframe: 300, posting_timeout: 25, max_block_size: 524288, finality_depth: 35 }: a1c31e0c...
Included in block 273
The channel params are now ChannelParams { ... max_block_size: 524288 ... }, by this vote or others that landed first

On a one-sequencer devnet it carries at once, because one key is two thirds of a committee of one. The finality_depth it shows is not the depth at which zone blocks become final (Finality), and a vote cannot change it.

Parameters you leave out keep their current values, so a vote is a whole parameter set, not a delta. It is signed by the stake’s ownership account, not the signing key passed to --sequencer-key: for a channel you created, that account comes from the home’s sequencer_stake_signing_key, and the wallet must hold it or you get The wallet holds no key for the stake's ownership account <id>; import it with wallet account import public. withdraw-params-vote takes a standing vote back; a vote that already carried, as on a one-sequencer devnet, is no longer standing, and withdrawing it fails with This channel signing key has no vote to withdraw.

Guest API cheat sheet

Most of what a handler uses is in lee_core::program and lee_core::account (lee/state_machine/core/src/program/mod.rs, account.rs).

Entry

lee_core::actor_entrypoint!(handle_message);       // message decoded with Borsh
lee_core::actor_entrypoint!(raw handle_message);   // handler decodes it

fn handle_message(input: &ReceiveInput, message: MyMessage) -> Response { .. }
fn handle_message(input: &ReceiveInput) -> Response { .. }                    // raw form

A panic anywhere fails the whole transaction.

Input

pub struct ReceiveInput {
    pub receiver: Actor,
    pub from: Option<Actor>,
    pub grants: BTreeSet<Actor>,
    pub pre_state: ActorState,
    pub message: MessageData,      // Vec<u8>
}

input.from_own_program()           // sender is an actor of the receiver's program
input.is_authorized()              // grants.contains(&receiver)
FieldValue
receiverthe actor this run is for
fromthe sending actor, at the address it presented. None when the transaction’s author submitted the message. A collected stored message keeps its original sender.
grantsthe actors whose grants this delivery carries, and which this handler may attach to its own sync messages
pre_statethe actor’s state before this message; empty if never written

Actors and ids

Actor::new(account_id, program_account_id)
Actor::native_balance(account_id)

AccountId::for_public_pda(&program_account_id, &seed)
AccountId::from_system_program_name(&SystemProgramName::new(b"clock"))
account_id.blinded(&factor)

PdaSeed::new([u8; 32])

Response

Response::keep_state()
Response::set_state(bytes)                 // anything Into<ActorState>

    .send_sync(to, &message)                                     // SyncMessage, message Borsh-encoded
    .send_async(to, &message)                                    // AsyncMessage, message Borsh-encoded
    .send(SyncMessage::new(to, &message).with_pda_seeds([seed]))
    .send(SyncMessage::new(to, &message).with_grants([actor]))   // pass on a grant you hold
    .send(SyncMessage::new(to, &message).with_lent_grant(input)) // pass on your grant over `to`, if any
    .send(AsyncMessage { to, message: raw_bytes })

    .event(ProgramEvent { selector, data })

    .block_window(from..)                  // also ..to and ..
    .timestamp_window(from..)
    .try_block_window(from..to)?           // Err(InvalidWindow) when from >= to
    .try_timestamp_window(from..to)?
MessageDeliveredCarries seedsIf the receiver fails
SyncMessagenowyesthe whole transaction fails
AsyncMessage to a declared public actornownothe whole transaction fails
AsyncMessage to one of the submitter’s private actors, promotednownothe whole transaction fails
AsyncMessage to any other addressstorednothe sender is not affected

Window bounds: the start is inclusive, the end is exclusive.

Helpers

write_once(&pre_state, data)     // returns data; panics if the state holds something different

Native token

use lee_core::native_token::{self, Message};

Message::Transfer { to, amount }        // needs is_authorized; sends Credit async
Message::Credit(amount)                 // only from the native token program
Message::ReadState                      // replies to the sender with StateReply

native_token::custody_transfer(from_pda, seed, to, amount)   // a SyncMessage with the seed attached

Clock

use clock_core::{Message, Reply};

// read it, rounded to a granularity you choose, and handle the reply
let clock = clock_core::clock_actor();
Response::keep_state().send_sync(clock, &Message::ReadTimestamp { granularity: 60_000 })
// ... the reply arrives as Reply::Timestamp(ms); the reader needs actor_entrypoint!(raw ..)

// or gate on time without reading at all
Response::keep_state().timestamp_window(deadline..)

Errors you can trigger

Errors lists what a handler or a transaction can trigger, which error type each is, and where it surfaces.

Testing

A handler is a function. Build a ReceiveInput and call it:

let input = ReceiveInput {
    receiver: Actor::new(account, PROGRAM),
    from: None,
    grants: BTreeSet::from([Actor::new(account, PROGRAM)]),
    pre_state: ActorState::from(state_bytes),
    message: borsh::to_vec(&message).unwrap(),
};
let transition = handle_message(&input, message).into_transition(input);
assert_eq!(transition.response.post_state, Some(expected));
assert_eq!(transition.response.sync_messages, vec![..]);

Account-id derivations

All ids are 32 bytes. Each derived account id is the SHA-256 of an input that starts with a 32-byte domain prefix, so ids of different kinds do not collide.

Account ids

KindInputs after the prefixPrefix beginsSource
Public, key-ownedthe commitment to the account’s nonce-0 key, double hashed with a per-key-type prefix/LEE/v0.3/AccountId/Public/AccountId::for_initial_key. The key can change at every nonce; the id commits only to the first. See Keys, nonces and rotation
Public PDAprogram account id, seed/LEE/v0.2/AccountId/PDA/AccountId::for_public_pda
Private, regularnullifier public key, viewing public key/LEE/v0.3/AccountId/Private/lee/state_machine/core/src/nullifier.rs
Private PDAprogram account id, seed, nullifier public key, viewing public key/LEE/v0.3/AccountId/PrivatePDA/AccountId::for_private_pda
Blinded addressaccount id, 32-byte factor/LEE/v0.3/AccountId/Blinded/AccountId::blinded
System programa public PDA of system_upgrader, whose seed hashes the name, padded to 32 bytes, after /LEE/SystemUpgrader/v1/Name/LEE/v0.2/AccountId/PDA/AccountId::from_system_program_name, PdaSeed::for_system_program
Shadow programthe image id’s eight u32 words, each as 4 little-endian bytes/LEE/v0.3/AccountId/Shadow/AccountId::for_shadow_program
Immutable-program mirrorthe program header’s account id/LEE/v0.3/AccountId/ImmutMirror/AccountId::for_immutable_mirror

The functions without a file are in lee/state_machine/core/src/program/mod.rs, except AccountId::for_initial_key, which is in lee/state_machine/core/src/account.rs.

Fixed ids

IdValueMeaning
NATIVE_TOKEN_PROGRAM_ID32 zero bytesthe native token
PROGRAM_LOADER_ACCOUNT_ID32 bytes of 0xFEthe program loader
SYSTEM_UPGRADER_ACCOUNT_ID32 bytes of 0xFDsystem_upgrader, the owner every system program’s id derives from
CLOCK_PROGRAM_ACCOUNT_ID/LEZ/ClockProgramAccount/0000000the account the clock’s actor lives on, not the clock program’s id, which derives from its name. One account; a read picks its own granularity

What follows from the derivations

  • A public PDA is the same for everyone: program and seed fix it.
  • A private PDA is per key holder: two groups using the same program and seed get different accounts, because their keys differ.
  • A blinded address is per factor. One account has as many addresses as its owner cares to make, and without the factors nobody can tell from the addresses that they name the same account.
  • A program deployed twice has two ids, so two disjoint PDA families.

Keys

One mnemonic feeds two trees that share only the BIP-39 seed. Both are hardened-only.

KeyDerivation
seedmnemonic.to_seed(passphrase), 64 bytes. The reference wallet uses an empty passphrase
public tree root secretfrom the seed, keyed by a master domain string
public tree child secretfirst32(HMAC-SHA512("/LEE-Keys/v1/Child/Public" ‖ index_be) keyed by the parent secret). Hardened only, and there is no chain code: the parent secret is the HMAC key
a public account’s keyderived per nonce from that secret, so the signing key rotates with use. See Keys and rotation
private tree root ssk, cccHMAC-SHA512 keyed "/LEE-Keys/v1/Master/Private" over the seed, split in two: ssk the first 32 bytes, chain code ccc the last 32
private tree child ssk, cccHMAC-SHA512("/LEE-Keys/v1/Seed/Private" ‖ SHA256("/LEE-Keys/v1/Parent/Private" ‖ nsk ‖ d ‖ z) ‖ index_be) keyed by the parent’s ccc, split the same way. nsk, d, z are the parent’s
askSHA256("/LEE-Keys/v1/Authorization/Secret" ‖ ssk ‖ index_be), where index is the node’s child index (0 at the root)
nskSHA256("/LEE-Keys/v1/Nullifier/Secret" ‖ ask)
npkSHA256("/LEE-Keys/v1/Nullifier/Public" ‖ nsk)
vsk = (d, z)HMAC-SHA512("/LEE-Keys/v1/Viewing/Secret" ‖ ssk ‖ index_be) keyed "/LEE-Keys/v1/Viewing/Seed", split in two
vpkthe ML-KEM-768 encapsulation key from seed (d, z)

A standalone KeyChain (KeyChain::new_mnemonic or KeyChain::new_os_random) derives its ssk as first32 of HMAC-SHA512 keyed "LEE_seed" iterated 2048 times over the seed; the wallet’s trees do not use it. Sources: lee/key_protocol/src/key_management/secret_holders.rs, lee/key_protocol/src/key_management/key_tree/keys_private.rs, lee/key_protocol/src/key_management/key_tree/keys_public.rs.

Group keys

A group secret derives keys for shared accounts (lee/key_protocol/src/key_management/group_key_holder.rs):

ForDerived from
a group-owned private PDAthe secret, the program’s image id, the seed
a shared regular accountthe secret, a derivation seed

The two use different domain prefixes. Every member derives the same keys, hence the same account ids.

Protocol constants and limits

Values read from the code on dev at commit 09ff4d0ca. Check them against your checkout.

ConstantValueWhere
Program segments per programat most 20MAX_PROGRAM_SEGMENTS, lee/program_loader/src/lib.rs
Bytecode per segment account96 KiB, the wallet’s chunk size, not a limit the loader enforcesMAX_SEGMENT_DATA_LEN, same file
Execution budget of a public transactionits declared gas_limit, at most 10M cycles. The same 10M caps a whole block: the sequencer adds a transaction only while its declared gas_limit fits in what the gas charged to the block’s earlier transactions leftMAX_GAS_EXEC, lez/programs/fee/core/src/market.rs
Default public cycle budget in LEE, used on execution paths that carry no transaction budget (the private dry-run simulator among them)32M cycles (32 × 2^20)DEFAULT_PUBLIC_CYCLE_BUDGET, lee/state_machine/src/program/mod.rs
Private actions per wallet-built private transactionpadded to 7PADDED_PRIVATE_ACTIONS, lez/wallet/src/account_manager.rs
Note padding512 bytesCIPHERTEXT_PAD_SIZE, same file
Clockone account; each ReadBlockId or ReadTimestamp names its own granularitylez/programs/clock/core/src/lib.rs
Note encryptionML-KEM-768 key encapsulation, then ChaCha20lee/state_machine/core/src/encryption
Private actions per private transactionat most 8, counting each private account, the collected root message, each claim and each padding dummyMAX_PRIVATE_ACTIONS, lez/programs/fee/core/src/market.rs
Stored messages one transaction collectsone as its root, plus claims queued ahead of it, within the cap aboveclaims, lee/state_machine/core/src/execution_state.rs
Submitted transaction sizeat most 1,835,008 bytes as estimated from the base64 length, the largest max_block_size any chain can set; the sequencer’s RPC refuses a larger submission before decoding itMAX_SUBMITTED_LEN, lez/common/src/transaction.rs
Boundary steps of a submitted private transactionat most 1024 in its boundary and in its fee fallback’s; the sequencer’s RPC and gossip validation refuse a longer one, while transactions inside blocks are decoded without this checkMAX_BOUNDARY_STEPS, lee/state_machine/src/encoding/privacy_preserving_transaction.rs

Limits that are missing

No constant caps these two, though both may change:

  • The size of an actor’s state.
  • The number of messages one transaction may send. Execution is bounded by the cycle budget, not by a count; the only count is the submission check on a private transaction’s boundary steps above, which bounds only the messages crossing between private and public execution.

Design as if both were capped: keep state small and bounded, and keep conversations short.

Interim choices

ChoiceEffect on a design
The wallet claims only pending native credits, at most four per send and only in the slots of the seven its private accounts and received root leave (MAX_SWEPT_CLAIMS, lez/wallet/src/lib.rs)a proof clears up to five credits; any other stored message costs a proof of its own
Padding to seven private actionspast seven the wallet pads with nothing and warns: the transaction is built, but its exact count is not hidden

Errors

Four error types matter to a caller. ExecutionError comes from the engine during execution and reaches a caller wrapped in LeeError::InvalidProgramBehavior (except EmptyValidityWindowIntersection, which becomes LeeError::OutOfValidityWindow). InvalidTransaction comes from the checks before execution and reaches a caller as LeeError::InvalidInput carrying its message. ClassifyError comes from fee classification, before execution; a client sees its message, not its name. LeeError is everything else: proving, validation, serialization, settlement.

Sources: lee/state_machine/core/src/execution_state.rs, lee/state_machine/src/transaction_message.rs, lez/chain_state/src/classify.rs and lee/state_machine/src/error.rs.

Common errors

ErrorWhat happened
ProgramExecutionFailed("Guest panicked: <msg>")your handler’s assertion failed, and <msg> is yours. Write assertions that name the check
UndeclaredActora SyncMessage to an actor the transaction did not declare and so cannot run
UnheldGranta SyncMessage attaches a grant its sender does not hold
UnsignedAuthority (InvalidTransaction, as is the next, from lee/state_machine/src/transaction_message.rs)an actor marked Signer whose account did not sign
DuplicateActorthe same actor declared twice
UnmarkedPrivateSignera declared private signer that no authorized witness marks
TransitionInputMismatcha handler’s proof was made for a different input
BoundaryMismatch, CrossMessageMismatchthe public side did not do what the proof assumed
LoaderOutsidePublicExecutiona message to the program loader inside a private transaction
UnboundAsyncDestinationan AsyncMessage from a public actor to an address with no recovery binding on chain and none introduced by the same transaction, so it cannot be stored; this includes any undeclared public account. Raised at settlement, so it is a LeeError, not an ExecutionError
UnadmittedPublicActora public actor the transaction touched without admitting it: a message to a public account that does not exist and came with no evidence
MissingFeeDeclaration (ClassifyError, as are the next four)a user public transaction whose lee::public_transaction::Message was built with the fee-exempt Message::try_new instead of Message::try_new_with_fees
MissingPrivateFeea privacy-preserving transaction with no fee reserve crossing to the fee inbox
TooManyPrivateActionsmore than eight private actions in one transaction
InvalidFeeFallbackthe fallback a proof names does not pay exactly the reserve priced for it
InvalidRefundTargeta refund aimed at a restricted account: the clock, the fee state, escrow or inbox account, or the bridge
OutOfGasthe transaction exceeded its declared gas_limit
OutOfValidityWindowthe block or timestamp fell outside the window the handler set, or two handlers’ windows do not overlap (EmptyValidityWindowIntersection, which a caller sees as this)
UnknownPrograma message in public execution to a program the sequencer cannot load, such as a shadow program’s public effect. Named at the transaction root it is refused uncharged; reached later it is chargeable, so it reverts and pays wherever the transaction can revert (Where an error surfaces)
MaxAccountNonceReachedan account’s nonce is exhausted
InvalidPrivacyPreservingProofa disclosed program image no longer matches the program deployed at that account id (it was upgraded after proving), or the proof did not verify against the journal the sequencer rebuilt: a proof for other inputs, a journal altered after proving, a receipt that is not succinct, or a dev-mode receipt at a sequencer not running in dev mode

Engine errors in full

ErrorMeaning
PublicActorStateUnavailablethe engine was asked to run a public actor’s handler where no public state is supplied, as inside the proof (below)
DuplicateWitnesstwo private witnesses derive the same account
FamilyBindingConflicttwo different accounts resolve under the same program and PDA seed in one transaction
PublicFamilyMemberDeclaredthe transaction uses a private PDA and declares the public PDA of the same program and seed
AliasCollisiona blinded address is also a declared account, or names two different accounts
MissingSenderPresentationno presentation (plain or blinded) was supplied for a private sender
LoaderOutsidePublicExecutionthe program loader reached in a private or mixed transaction
UndeclaredActora delivery to an actor that is neither declared public nor private
UnadmittedPublicActora delivery to a declared public account that was not admitted
UnreachedPromotiona promotion selects an async message the execution never sent
TransitionInputMismatcha handler echoed an input it was not given
EmptyValidityWindowIntersectionthe handlers’ validity windows do not overlap
PublicAndPrivatean account is declared public and also has a private witness
MissingPredictedCrossMessages, UnusedPredictedCrossMessagesthe prover’s predicted messages from the public side are missing for a public segment, or supplied for one the execution never entered
UndeclaredCrossMessageSendera predicted message comes from an actor that is not declared public
UnmarkedPrivateSignera declared private signer that no authorized witness marks
UnheldGranta sync message attaches a grant its sender does not hold
UnwitnessedFeePayer, FeePayerWithoutAuthorizationthe fee payer is not a witnessed private account, or its witness lacks the authorization key
BoundaryMismatch, CrossMessageMismatch, IncompleteBoundarya boundary step, or the message at it, does not match the execution, or the execution did not consume the boundary exactly

The predicted message and boundary errors (MissingPredictedCrossMessages, UnusedPredictedCrossMessages, UndeclaredCrossMessageSender, BoundaryMismatch, CrossMessageMismatch, IncompleteBoundary) mean the prover and the sequencer disagree about what crossed, usually because a client built the transaction by hand rather than through the wallet.

PublicActorStateUnavailable means an execution holding no public state, such as the prover’s, reached a public actor’s handler. A correctly built private transaction never does: the proof holds no public actor state and runs no public handler. A message to a public actor crosses the boundary, and what the public side sends back is predicted at proving time and checked by the sequencer at settlement against live state (A reply from public to private is fixed at proving time, The boundary).

LeeError in full

InvalidInput, OutOfGas, InvalidProgramBehavior, MessageSerializationError, InvalidPrivateKey, Io, BoundaryTooLong, InvalidPublicKey, InvalidHexPublicKey, ProgramWriteInputFailed, ProgramExecutionFailed, ProgramExitedWithCode, ProgramProveFailed, TransactionDeserializationError, Core, CircuitOutputDeserializationError, InvalidPrivacyPreservingProof, CircuitProvingError, InvalidProgramBytecode, ProgramAlreadyExists, MaxAccountNonceReached, OutOfValidityWindow, UnknownProgram, UnboundAsyncDestination.

Tooling errors

Program bytecode splits into N segment(s) but M were supplied (SegmentChainError::CountMismatch, in lee/program_loader) from a deploy whose --segments count does not match the chunk count. The wallet checks it before sending anything and reports the number expected. Deploying has the rest of the deploy rules.

Where an error surfaces

It depends on where the handler ran. For a public transaction it runs on the sequencer, so a panic appears in the sequencer’s output as the guest printed it:

thread 'main' (1) panicked at …/hello_world_with_authorization.rs:15:5:
Missing required authorization

The transaction is still included and pays its fee. So does one whose effects would change a guarded system account (the clock, a fee account, bridge state or the system registry, outside the system transactions that own them): it reverts rather than being refused.

For a private transaction the handler runs on your machine, so a panic comes back as a local prover error before anything is submitted. This example does not show it privately: run with run_hello_world_private on a private account the wallet owns, hello_world_with_authorization succeeds, because the owner’s witness authorizes the account. That is the faster loop, and why developing against a private account with RISC0_DEV_MODE=1 is often quicker than against a public one.

A private transaction refused before or at proof verification is not included: nothing changed, nothing was charged, and it can be resubmitted. One whose proof verifies but whose public part then fails in a chargeable way is included as a revert and pays, through its proven fee fallback or its declared fee; with neither it is refused. Two failures after verification are still refused: a public root naming a program the sequencer cannot load, and effects that would change a guarded system account in a transaction that pays inside its proof.

Glossary

Account. A nonce and a map from program account ids to actor states.

Actor. One program’s state on one account: the pair (account_id, program_account_id). Every message is addressed to an actor.

Actor state. The bytes an actor holds. Only that actor’s handler writes them.

Address. An id at which a private account receives messages: its account id, or a blinded form of it.

Admission. The check that a public account may receive a message: it exists, it signed, evidence for it is supplied, or the sender granted its seed.

AsyncMessage. A message that may wait. Delivered immediately when the transaction can run the receiver, stored on chain otherwise.

Authorization. input.is_authorized(): this delivery carries a grant over the receiver.

Base fee. The per-unit price of execution gas or storage gas the fee program holds, moving after each block toward a target (How fees are priced).

Blinded address. A hash of an account id and a secret factor: a pseudonym for a private account.

Boundary. In a private transaction, the ordered list of messages that crossed between private and public actors. Published in the clear.

Channel. An ordered stream of messages on the Logos L1, each referencing the one before. A zone writes its blocks into its channel as inscriptions (What LEZ is).

Collecting. Building a private transaction whose root, or a claim delivered before it, is a stored message, so the receiving handler runs.

Commitment. A hash published in place of a private account’s contents, or of a stored message.

Declared actor. A public actor a transaction lists up front, the only kind whose handler the engine runs publicly (Terms used throughout).

Dry run. --dry-run on any wallet command: simulate the transaction the command would send, on your own machine, outside any proof, against a snapshot of public actor state, and report its cost instead of sending it. For a private transaction the same run also fixes what the proof is then built against (the messages that will cross, the promotions selected, the sender presentations used). A public transaction is metered against the --gas-limit value, or else the configured one, capped at MAX_GAS_EXEC; a run that exhausts it is reported as a revert. A private transaction’s public part is metered against DEFAULT_PUBLIC_CYCLE_BUDGET (32M cycles), more than settlement allows (at most MAX_GAS_EXEC, 10M), so a private dry run that passes can still revert at settlement.

Echo. A handler’s proof includes the input it ran on, so the engine can check it was the right input.

Fee fallback. A fee-only version of a private payer’s action, proven alongside it, which settlement applies if the public part fails (Terms used throughout).

Grant. Authority over one actor, carried by one delivery. The engine mints it from a signer mark on the root call, an authorized private witness’s marks, a PDA seed, or the fee entry. A program can pass on a grant it holds (with_grants, with_lent_grant) but cannot create one.

Group secret. A shared secret from which a group derives the keys of accounts it owns together.

Handler. A program’s one function: input and message in, response out.

Headroom. How many blocks of the steepest base fee climb the reference wallet prices ahead of the quote (--fee-headroom, 5 by default) (How fees are priced).

Image id. The hash of a program’s binary.

LEE, LEZ. The execution environment, and the zone built on it.

Mailbox. The set of stored messages on chain.

Mention. In the reference wallet library, one account a transaction names (AccountMention). Not a protocol term (Terms used throughout).

Nullifier. A value published when a version of a private account, or a stored message, is used up, so it cannot be used twice.

Operate. Of a private PDA: hold its nullifier and viewing keys, so you can witness it, run its handlers privately and read its state, but not authorize it, which only the program’s seed grant does (Account ids).

PDA. Program-derived account. An account with no signing key, controlled by a program through a seed. A private PDA still has nullifier and viewing keys.

Poke. A message anyone may send that moves a public actor forward by its own rules.

Private part, public part. The two halves of a private transaction: private handlers proven on the user’s machine, public handlers run by the sequencer.

Program. A deployed RISC Zero guest binary, identified by the account id it is deployed at.

Promotion. Delivering an AsyncMessage to an undeclared destination inside its own transaction, at the submitter’s request, because the destination is one of the submitter’s own private actors. An AsyncMessage to a declared public actor is delivered at once without being a promotion.

Proof-carrying message. A message from a private actor to a public actor of the same program, trusted by the public side because the program’s own code produced it inside a proof.

Publication. A stored message: clear when the sender chose to publish it that way, sealed when the sender was private.

Quote. The base fees at the chain head, which the reference wallet reads before pricing a transaction (How fees are priced).

Recovery binding. An on-chain record that registers an address and lets its owner recognise it.

Root. The message a transaction is built to deliver, at the top of its message tree (Order of execution).

Sealed async message. A stored message encrypted to its recipient.

Seat. A participant’s own actor of a shared program, through which they speak to the program’s shared actor.

Seed grant. A program authorizing one actor of one of its PDAs, the destination of the seeded message, by attaching the seed to a SyncMessage. The PDA’s other actors are untouched.

Sequencer committee. The sequencer keys the stake program accredits by stake. They take turns producing zone blocks, vote channel parameters and approve system program upgrades (Sequencer stake).

Settlement. The sequencer applying a transaction to live state in a block. Settlement is not finality (Terms used throughout).

Shadow program. A program never deployed, run only inside a private transaction under an id derived from its image id (AccountId::for_shadow_program). The proof names it by a shadow witness and publishes no claim for it; the sequencer cannot load it, so a message reaching it in public execution fails with UnknownProgram (Program identity in a private transaction).

Shield, deshield. Wallet terms for a private transaction moving native tokens from a public account into a private one, or back (Terms used throughout).

SyncMessage. A message delivered immediately, in the same transaction. If it fails, the transaction fails. It returns no value.

Transition. A handler’s input together with its response: what a handler’s proof commits to.

Validity window. A range of blocks or timestamps outside which a transaction is invalid.

Witness. The evidence that a transaction may use an account: a public signer’s entry in the witness set, or what the prover holds to use a private account (Terms used throughout).

Zone. One chain of LEZ blocks, written into an L1 channel. Its zone id, a hash of the channel id and the genesis hash, is covered by every signature, so a transaction signed for one zone does not verify on another (The zone a signature is for); a chain recreated from a kept genesis salt can repeat the id (Starting clean).

Sources

The guide describes the code on dev at commit 09ff4d0ca: the v0.4.1 release plus eight later changes no release carries yet, which harden the sequencer’s block building, admission and size caps, charge a transaction that breaks a system-account guard, refuse a deposit mint the node has not seen on L1, let only an injected deposit write bridge state, refuse composite receipts, keep the genesis salt in the sequencer home, and add shared accounts to the C ABI. The live testnet may not have them. One wallet fix described in Setting up the wallet, a first change-network applied before setup, is not on dev yet.

How it was checked

  • Run on a local devnet: Setting up the wallet, Accounts and transfers, Reading the chain, the quickstart, the example programs, the toolchain, the key record in Keys, nonces and rotation, the channel parameter vote in System programs, Running a node, Reading state and Events. Their terminal output was captured from those runs.
  • Built and linked from C: The C ABI, which says what that verified.
  • Read from the code: the model chapters in Parts I and III, the privacy chapters, and the reference. Each claim names its source file.
  • Backed by tests: most claims in The execution engine and The privacy circuit cite a named test in lee or lee_core, which RISC0_DEV_MODE=1 cargo nextest run -p lee -p lee_core runs. Dev mode skips real proof generation, so these runs check the circuit’s logic, not the proofs’ cryptographic soundness.
  • Designs, not programs: the catalog’s programs are worked designs; their snippets show a handler’s shape and are not compiled. Where an entry describes a real program, it says which repository holds it.
  • On every pull request, CI checks that each repository path the guide cites exists, links resolve, snippets marked verbatim still match their source, and diagrams regenerate unchanged.

In the repository

TopicFile
Handler interface, messages, responses, validity windows, account-id derivationslee/state_machine/core/src/program/mod.rs
Accounts, actorslee/state_machine/core/src/account.rs
The execution engine: delivery, authorization, the boundarylee/state_machine/core/src/execution_state.rs
Native tokenlee/state_machine/core/src/native_token.rs
Private witnesses, the public fields of a private transactionlee/state_machine/core/src/circuit_io.rs
Recovery bindings, sealed messageslee/state_machine/core/src/recovery.rs, sealing.rs
The privacy circuitlee/privacy_preserving_circuit/src/
Settlement, admission, publication of async messageslee/state_machine/src/validated_state_diff/
Group keyslee/key_protocol/src/key_management/group_key_holder.rs
Shipped programslez/programs/ (bridge, clock, fee, sequencer stake, system upgrader); token and AMM are in logos-blockchain/lez-programs
Block rules for system transactionslez/chain_state/src/apply.rs, lez/common/src/transaction.rs
Wallet: sending, collecting, groupslez/wallet/src/
Worked example and tutorialexamples/program_deployment/

Outside the repository

  • logos-co/logos-lez-rln on GitHub: the Logos RLN membership registry, an actor program. The RLN entry is a toy version of it. Read: its README, instruction set, message types and registration logic. Not read: its Merkle program in full, and the off-chain modules that make and verify the proofs.

Not covered

  • The AMM and the associated-token-account program under the actor model.
  • Performance: proving times and proof counts in this guide are not benchmarks.

Where this guide came from

This guide grew out of an earlier book on the actor interface, written before it shipped. Its chapters form Parts III to V here. That book used earlier names: Call is now SyncMessage, Cast is AsyncMessage, Response::call and Response::cast are send_sync and send_async, define_actor_logic! is actor_entrypoint!, and WholeTransaction is WholeExecution.

The execution engine

One engine runs every transaction: the sequencer runs it directly for a public transaction, a prover runs the same code inside the circuit for a private one. The program receives the same input either way; ReceiveInput has no field saying which.

a_generated_call_graph_runs_the_same_whole_and_split asserts a generated call graph gives the same result run whole and split across the boundary (lee/state_machine/core/src/execution_state/tests.rs).

Source: lee/state_machine/core/src/execution_state.rs, about 1,700 lines, with settlement in lee/state_machine/src/validated_state_diff/mod.rs, the public execution environment in lee/state_machine/src/validated_state_diff/public_backend.rs, and the RISC Zero executor wrapper that runs one handler in lee/state_machine/src/program/mod.rs.

The shapes

pub enum TransactionEntry<R>      // the root: a sync message, or a consumed async one
pub struct PublicExecutionContext // actors, authorized accounts, promotions, private signers
pub struct WholeExecution<'w>     // a transaction with both halves
pub struct PrivatePart<'w>        // the half that runs under proof
pub struct PublicPart             // the half the sequencer runs
pub struct Delivery<S>            // one message on its way to one actor
pub enum BoundaryStep             // a crossing between the halves
pub enum Placement                // whether an actor is public or private
pub struct TransitionView<'e>     // one handler invocation, as the engine sees it

A transaction is not “public” or “private” as a whole: it is a sequence of segments on either side of a boundary (WholeExecution), and the engine tracks which half it is in.

Delivery order

A work stack, processed depth first, in the order Order of execution gives.

a_parents_async_messages_precede_its_childrens_and_never_run_their_recipients states the async ordering for recipients the transaction does not declare: a parent’s async messages come before its children’s, and each is stored rather than run. An async message to a declared public actor, or one the submitter promotes, is delivered in the transaction instead, carrying no grant, and its failure fails the transaction (AsyncMessage). On the private side, a_promoted_private_async_message_keeps_its_own_presentation_and_crosses_after_the_calls asserts async crosses the boundary after the calls, not with them.

A handler that sends two messages cannot assume they interleave: the first subtree finishes entirely first. a_failing_descendant_of_c1_stops_the_transaction_before_c2 asserts the consequence: a failure deep inside the first subtree stops the transaction before the second message is delivered.

Re-entry works by staging: a handler invoked again inside the same transaction sees the state the earlier invocation left, not the state the transaction started with.

No depth cap

The engine bounds neither the message tree’s depth nor its fan-out. What bounds a transaction instead:

ExecutionBound
Publicthe transaction’s declared gas_limit, at most MAX_GAS_EXEC (10M cycles, also the cap on a whole block), shared across every transition in the transaction
Privateprover time for the private part, and the settlement budget below for the public part. Sequencer RPC and gossip validation also refuse a submitted private transaction whose boundary (or fee fallback boundary) has more than MAX_BOUNDARY_STEPS (1024) steps, bounding the messages that cross between the halves

A private transaction’s public part is metered at settlement:

  • when a public signer pays the fee, against its declared gas_limit less the proof’s verification cost;
  • otherwise, against what the block has left of MAX_GAS_EXEC, and no more than the fee reserve pays for past the tip.

a_long_self_send_chain_completes_in_every_part asserts a chain of 128 self-sends on a public actor runs all 129 invocations both whole and in the public part of the split run, and a_long_self_send_chain_fits_the_public_budget (lee/state_machine/src/state/tests/chained_calls.rs) asserts a root plus 64 self-sends fits LEE’s default public budget, DEFAULT_PUBLIC_CYCLE_BUDGET (32M cycles), which is larger than the 10M a LEZ transaction may declare. transitions_share_one_budget (lee/state_machine/src/validated_state_diff/tests.rs) confirms the budget is shared across every transition, not granted per handler.

The missing cap is one of the limits that are missing and may be added in a later release.

The boundary

Each crossing between public and private is a BoundaryStep carrying a message whose sender and recipient are Actors, and an Actor is { account_id, program_account_id }.

Blinding a sender replaces the account id and leaves the program account id in the clear, so a boundary crossing always reveals which program was on the private side. This is why an undisclosed program’s identity survives only a transaction that never crosses the boundary; Programs, deployment and identity covers what that means for an undisclosed claim.

The engine predicts the messages that will cross, and the circuit checks the prediction. The mismatch errors (MissingPredictedCrossMessages, UnusedPredictedCrossMessages, BoundaryMismatch, CrossMessageMismatch, IncompleteBoundary) all mean the prover and the sequencer disagree about what crossed. a_nested_mixed_graph_is_predicted_bracketed_and_replayed_through_every_part exercises the mechanism on a nested graph, and a_nested_boundary_settles_both_public_writes checks that a crossing nested inside another still settles both public writes.

Settlement

For a private transaction the sequencer does not re-run the private handlers: it verifies the proof, then runs the public part (the handlers of the public actors the transaction reaches) in the order the traversal emitted them, against live state.

A prepared private transaction still settles later against public state that has since moved, because that state was never in the proof. Every guard on public state must be strong on its own: the sequencer will not re-derive the reasoning that produced it.

The privacy circuit is the other half: what the proof covers.

How this chapter was checked

Most claims above cite a named test. Sources says how to run them and what a pass does and does not prove.

The privacy circuit

The circuit is a RISC Zero guest that replays a private transaction and emits the object the chain publishes. Most privacy claims in this guide are about what that object contains.

Source: lee/privacy_preserving_circuit/src/{main.rs,output.rs,private_backend.rs}, with the published shapes in lee/state_machine/core/src/circuit_io.rs.

What it receives

PrivacyPreservingCircuitInput {
    input,                      // ProvingInput: root, claims, fee, public context, witnesses, dummies, padding, recoveries, promotions
    program_image_witnesses,
    shadow_program_witnesses,
    responses,
    sender_presentations,
    publication_modes,
    predicted_cross_messages,
}

The root is a TransactionEntry: a sync message the sender initiated, or an async message consumed out of a mailbox, whose spend the circuit also computes, as it does for each received message in claims delivered before the root.

What it does

It runs the sequencer’s execution engine with a backend that holds no public state: the_prover_never_reads_a_public_actor_state proves a transaction with a public root while supplying no public actor state. For each handler invocation outside the native token program, the backend verifies a separately proved receipt against the image id claimed for that account, composing it as an assumption rather than re-executing it. a_receipt_for_other_inputs_does_not_bind_in_the_circuit asserts a receipt produced for different inputs does not satisfy the composition.

Four checks close holes a dishonest prover would otherwise have.

Reserved accounts cannot claim guest bytecode. The native token program and the program loader run protocol code, and the circuit asserts no image witness names either: “A reserved program account has no deployable bytecode to claim”. Tested by a_guest_image_claim_for_the_reserved_id_is_refused and a_private_call_into_the_program_loader_is_refused.

An account cannot be claimed twice. If the same account id arrives in more than one image witness, program-image or shadow, the circuit panics.

Claims are minimal and complete. only_the_programs_the_private_part_runs_are_claimed asserts nothing extra is claimed; missing_responses_are_rejected_by_the_circuit and surplus_responses_are_rejected_by_the_circuit assert the handler responses match the execution.

Undisclosed claims are checked rather than trusted. The sequencer compares a disclosed image claim against chain state at settlement; for an undisclosed one the circuit itself checks the header is immutable and derives the membership root.

The circuit recomputes native token operations from protocol code rather than verifying a separate receipt, which is why a private transfer of native balance is cheap and discloses no program.

What it publishes

compute_circuit_output builds the message; What a private transaction reveals reads it field by field.

obfuscate_output_ordering sorts the published actions so their order carries nothing. Nullifiers and commitments are sorted separately, so you cannot tell which commitment replaced which nullifier.

emit_dummy_output writes one action per consumed message (its nullifier paired with a dummy commitment) and one per dummy input the prover supplies; the wallet supplies enough dummies to reach seven private actions when there are fewer (Private actions). The dummy commitments and notes come from seeds and ciphertexts the prover supplies, so their randomness is the prover’s responsibility. The circuit only asserts that each dummy note’s ciphertext is at least the requested padding length, when one is requested, and that its encapsulation is as long as an ML-KEM-768 ciphertext. note_ciphertext_is_padded_to_the_requested_length asserts a real note is padded to the requested length.

Padding works only if length is uniform, tested per note kind by every_sealed_note_under_its_floor_has_one_length and every_recovery_note_has_one_length; a note whose size varied with its contents would leak through that size however well it was encrypted. A note larger than the pad size is not cut down, so its length shows.

Confidentiality and addressing are tested together: a_sealed_message_opens_only_to_its_recipient_and_only_as_committed, a_seal_refuses_a_body_addressed_anywhere_but_its_recipient, and a_recovery_note_opens_to_its_recipient_only_under_its_viewing_secret_and_address. Encryption alone is not enough: a body that opened for the right key but the wrong recipient would still be a break.

What the sequencer checks itself

Before verifying the proof against the published journal, settlement checks the parts it can derive independently: the authorized accounts must be exactly the accounts whose signatures and nonces the transaction carries, each disclosed image claim must name the image deployed at that account id now, and each undisclosed claim’s root must be a commitment root the chain has had. A prover that claimed a different image, or claimed an account was authorized when no signature covered it, is refused even though its proof verifies against its own journal. The nullifier and commitment freshness lookups a replay fails also run before proof verification.

How this chapter was checked

Most claims above cite a named test, run as Sources describes, which also says what dev mode leaves unproven. The circuit’s own tests are in lee/state_machine/src/privacy_preserving_transaction/circuit/tests.rs, with the note and seal properties in lee/state_machine/core/src/{sealing.rs,recovery.rs}.