diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 1acfad6..0f15789 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -81,8 +81,10 @@ jobs: logos-devnet --config .github/ci/logos-devnet.toml doctor # The action with a session: it installs logosctl, which runners don't have, and the session - # comes up with a funded wallet. + # comes up with a funded wallet. Off until sessions run again: they wait for a lez_core built + # for LEZ v0.4 in the Logos catalog (see SESSIONS_READY in src/devnet.rs). action-sessions: + if: false runs-on: ubuntu-latest steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 diff --git a/.github/workflows/image.yml b/.github/workflows/image.yml index 8b475e5..7933070 100644 --- a/.github/workflows/image.yml +++ b/.github/workflows/image.yml @@ -13,7 +13,7 @@ on: workflow_dispatch: inputs: lez: - description: LEZ release tag to build, e.g. v0.3.2. Empty builds the CLI's default. + description: LEZ release tag to build, e.g. v0.4.0-rc3. Empty builds the CLI's default. required: false permissions: diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index be30912..7bef514 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -109,8 +109,16 @@ jobs: echo "tag $TAG moved to $tagged after $GITHUB_SHA was checked" >&2 exit 1 fi + # The notes open with the LEZ release this one runs, read from the tagged source. + lez=$(gh api "repos/$GITHUB_REPOSITORY/contents/src/home.rs?ref=$TAG" --jq .content \ + | base64 -d | sed -n 's/^pub const DEFAULT_LEZ: &str = "\(.*\)";$/\1/p') + if [[ ! "$lez" =~ ^v[0-9]+(\.[0-9]+)*(-[A-Za-z0-9.]+)?$ ]]; then + echo "no LEZ tag in src/home.rs at $TAG: '$lez'" >&2 + exit 1 + fi gh release create "$TAG" --repo "$GITHUB_REPOSITORY" --verify-tag \ - --title "$TAG" --generate-notes dist/* + --title "$TAG" --generate-notes dist/* \ + --notes "Runs LEZ $lez. See [which version](https://github.com/$GITHUB_REPOSITORY#which-version) for every release's LEZ." crates-io: needs: github-release diff --git a/Cargo.lock b/Cargo.lock index 02668d0..27860dc 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -58,6 +58,12 @@ version = "1.0.104" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" +[[package]] +name = "base16ct" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c7f02d4ea65f2c1853089ffd8d2787bdbc63de2f0d29dedbcf8ccdfa0ccd4cf" + [[package]] name = "base64" version = "0.23.1" @@ -146,6 +152,12 @@ version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" +[[package]] +name = "const-oid" +version = "0.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8" + [[package]] name = "const-oid" version = "0.10.3" @@ -190,6 +202,18 @@ dependencies = [ "libc", ] +[[package]] +name = "crypto-bigint" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0dc92fb57ca44df6db8059111ab3af99a63d5d0f8375d9972e319a379c6bab76" +dependencies = [ + "generic-array", + "rand_core", + "subtle", + "zeroize", +] + [[package]] name = "crypto-common" version = "0.2.2" @@ -199,6 +223,16 @@ dependencies = [ "hybrid-array", ] +[[package]] +name = "der" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb" +dependencies = [ + "const-oid 0.9.6", + "zeroize", +] + [[package]] name = "deranged" version = "0.5.9" @@ -212,7 +246,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" dependencies = [ "block-buffer", - "const-oid", + "const-oid 0.10.3", "crypto-common", ] @@ -236,6 +270,23 @@ dependencies = [ "litrs", ] +[[package]] +name = "elliptic-curve" +version = "0.13.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b5e6043086bf7973472e0c7dff2142ea0b680d30e18d9cc40f267efbf222bd47" +dependencies = [ + "base16ct", + "crypto-bigint", + "ff", + "generic-array", + "group", + "rand_core", + "sec1", + "subtle", + "zeroize", +] + [[package]] name = "equivalent" version = "1.0.3" @@ -258,6 +309,16 @@ version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" +[[package]] +name = "ff" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0b50bfb653653f9ca9095b427bed08ab8d75a137839d9ad64eb11810d5b6393" +dependencies = [ + "rand_core", + "subtle", +] + [[package]] name = "form_urlencoded" version = "1.2.2" @@ -267,6 +328,17 @@ dependencies = [ "percent-encoding", ] +[[package]] +name = "generic-array" +version = "0.14.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4bb6743198531e02858aeaea5398fcc883e71851fcbcb5a2f773e2fb6cb1edf2" +dependencies = [ + "typenum", + "version_check", + "zeroize", +] + [[package]] name = "getrandom" version = "0.4.3" @@ -278,6 +350,17 @@ dependencies = [ "r-efi", ] +[[package]] +name = "group" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0f9ef7462f7c099f518d754361858f86d8a07af53ba9af0fe635bbccb151a63" +dependencies = [ + "ff", + "rand_core", + "subtle", +] + [[package]] name = "hashbrown" version = "0.17.1" @@ -441,6 +524,16 @@ version = "1.0.19" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" +[[package]] +name = "k256" +version = "0.13.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6e3919bbaa2945715f0bb6d3934a173d1e9a59ac23767fbaaef277265a7411b" +dependencies = [ + "cfg-if", + "elliptic-curve", +] + [[package]] name = "libc" version = "0.2.191" @@ -473,11 +566,12 @@ checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" [[package]] name = "logos-devnet" -version = "0.9.4" +version = "0.10.0" dependencies = [ "anyhow", "bs58", "clap", + "k256", "serde", "serde_json", "sha2", @@ -555,6 +649,12 @@ version = "6.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" + [[package]] name = "rustix" version = "1.1.6" @@ -568,6 +668,19 @@ dependencies = [ "windows-sys", ] +[[package]] +name = "sec1" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3e97a565f76233a6003f9f5c54be1d9c5bdfa3eccfb189469f11ec4901c47dc" +dependencies = [ + "base16ct", + "der", + "generic-array", + "subtle", + "zeroize", +] + [[package]] name = "serde" version = "1.0.229" @@ -649,6 +762,12 @@ version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + [[package]] name = "syn" version = "3.0.10" @@ -925,6 +1044,12 @@ dependencies = [ "synstructure", ] +[[package]] +name = "zeroize" +version = "1.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85ccff8a4805aba1eaa4cd4afcd49f7557dd2cf5fd79ffc37f8959466effc5aa" + [[package]] name = "zerotrie" version = "0.2.5" diff --git a/Cargo.toml b/Cargo.toml index 8e5d997..93b30bd 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "logos-devnet" -version = "0.9.4" +version = "0.10.0" edition = "2024" rust-version = "1.89" description = "A local LEZ chain for Logos development: one command to start it, fund accounts and deploy programs" @@ -20,6 +20,7 @@ path = "src/main.rs" anyhow = "1.0.104" bs58 = "0.5.1" clap = { version = "4.6.7", features = ["derive", "env"] } +k256 = { version = "0.13.4", default-features = false, features = ["arithmetic"] } serde = { version = "1.0.229", features = ["derive"] } serde_json = { version = "1.0.154", features = ["raw_value"] } sha2 = "0.11.1" diff --git a/README.md b/README.md index 7184e1e..3934f20 100644 --- a/README.md +++ b/README.md @@ -4,6 +4,8 @@ A local LEZ chain for Logos development. One command starts a sequencer on your Keep the public testnet for final checks. Messages, service discovery and storage can stay local too: a project that asks for them gets a hub on `127.0.0.1` instead of the Logos fleets. +It runs LEZ v0.4, currently `v0.4.0-rc3`. For LEZ v0.3, use [v0.9.4](https://github.com/drptbl/logos-devnet/releases/tag/v0.9.4), the last release that runs it: `cargo install --locked logos-devnet --version 0.9.4`. [Which version](#which-version) lists every release's LEZ. Sessions wait for a `lez_core` built for v0.4, see [Sessions](#sessions). + ## Install ```bash @@ -13,7 +15,7 @@ cargo install --locked logos-devnet Or take a binary from the [latest release](https://github.com/drptbl/logos-devnet/releases/latest), built for macOS (`aarch64-apple-darwin`, `x86_64-apple-darwin`) and Linux (`x86_64-unknown-linux-musl`, `aarch64-unknown-linux-musl`, static, so any distribution), and check it against its `.sha256`: ```bash -v=v0.9.4 t=aarch64-apple-darwin +v=v0.10.0 t=aarch64-apple-darwin curl -fsSL --remote-name-all https://github.com/drptbl/logos-devnet/releases/download/$v/logos-devnet-$v-$t.tar.gz{,.sha256} shasum -a 256 -c logos-devnet-$v-$t.tar.gz.sha256 \ && tar -xzf logos-devnet-$v-$t.tar.gz \ @@ -24,6 +26,17 @@ Put `~/.local/bin` on your `PATH` if it isn't. `cargo install --locked --git htt It runs on macOS and Linux, and needs Docker (OrbStack, Docker Desktop or Colima). There's no Windows build. With `--native` you need git, a Rust toolchain and LEZ's build dependencies instead: clang, pkg-config and OpenSSL (`brew install pkg-config openssl` on macOS), plus `libpcsclite-dev` on Linux. The first native build takes a few minutes. +## Which version + +Each logos-devnet release runs one LEZ line, and a new LEZ line gets a new minor release: pick the newest release in the row for the LEZ you build on. + +| logos-devnet | LEZ | Default `--lez` | +| --- | --- | --- | +| 0.10.x | v0.4 | `v0.4.0-rc3` | +| 0.1.0 to [0.9.4](https://github.com/drptbl/logos-devnet/releases/tag/v0.9.4) | v0.3 | `v0.3.1` | + +`logos-devnet --version` names the LEZ tag it runs, e.g. `logos-devnet 0.10.0 (LEZ v0.4.0-rc3)`, and each release's notes open with it. + ## Use it ```bash @@ -37,12 +50,12 @@ source ~/.logos-devnet/env # LOGOS_DEVNET_SEQUENCER, LOG | Command | What it does | | --- | --- | -| `up` | Starts the devnet, or resumes it, and makes it match your `logos-devnet.toml`. Takes `--docker` or `--native`, `--lez ` (a v0.3 tag), `--port`, `--block-time`, `--max-txs-per-block`, `--dev-mode` and `--log-filter`, and remembers them. `--rebuild` builds the image or binaries again. | +| `up` | Starts the devnet, or resumes it, and makes it match your `logos-devnet.toml`. Takes `--docker` or `--native`, `--lez ` (a v0.4 tag), `--port`, `--block-time`, `--max-txs-per-block`, `--dev-mode` and `--log-filter`, and remembers them. `--rebuild` builds the image or binaries again. | | `down` | Stops it. The chain is kept. | | `reset` | Deletes the chain and starts a new one, every account group funded at genesis. Takes the same options as `up`. | | `status` | What runs, the chain head, the faucet, programs, account groups, sessions (and which stopped while the chain runs), the messaging hub and local storage. | | `doctor` | Checks the project file, Docker and the image (or git and cargo with `--native`), whether the chain takes the project's settings, the `[programs]` files, the port, the hub's ports, the faucet, the hub's nodes and sessions that stopped while the chain runs, `curl` for programs from a release and, when sessions or the hub need it, `logosctl`, and says how to fix what fails. | -| `fund [amount]` | Sends lepta from the faucet to a public account, 10B by default. | +| `fund [amount] [--key ]` | Sends lepta from the faucet to a public account, 10B by default. An account that was never used is paid by its public key: `--key`, unless it's one of the devnet's own. | | `deploy [--mutable]` | Deploys a program, from its `.bin` (what `cargo risczero build` makes, not the bare ELF), and adds `LOGOS_PROGRAM_` and `LOGOS_PROGRAM__HEX` to the env file. Names are lower-case letters, digits and `-`. With `--mutable`, a new build updates it in place. | | `wallet-config ` | Writes a `wallet_config.json` pointing at the devnet into a new wallet directory. | | `env` | Prints the env file. | @@ -83,6 +96,7 @@ block_time = "1s" max_txs_per_block = 100 dev_mode = true # fake proofs: private calls take a second log_filter = "info,sequencer_core=debug" # the sequencer's RUST_LOG, for `logs` +upstream_accounts = true # also fund LEZ's own genesis accounts on a new chain, for its examples [programs] # name = guest binary, relative to this file counter = "target/riscv32im-risc0-zkvm-elf/docker/counter.bin" @@ -119,7 +133,7 @@ Group names follow the rules for program names, and can't end in `-wallet`. A gr { "amount": 5000000000, "accounts": [ - { "index": 0, "id": "CfcghzvosNM114Akg71vuQyDApHPYpPVC9p4uPFQygye", "hex": "ad54f9c3…" } + { "index": 0, "id": "CfcghzvosNM114Akg71vuQyDApHPYpPVC9p4uPFQygye", "hex": "ad54f9c3…", "key": "57f54786…" } ] } ``` @@ -148,6 +162,8 @@ For a wallet, give it its own directory. `wallet-config` refuses a directory tha ## Sessions +> **Sessions wait for a `lez_core` built for LEZ v0.4.** The Logos catalog's newest, 0.5.1, is built for v0.3 and can't drive a v0.4 chain, so `up` refuses `[sessions]` and `session new` refuses to make one. This section, the [Messaging](#messaging) and [Storage](#storage) ones, and their examples describe how sessions work with [v0.9.4](https://github.com/drptbl/logos-devnet/releases/tag/v0.9.4) on LEZ v0.3. They'll be updated when a v0.4 `lez_core` ships. + A session is a throwaway `logosctl` session wired to the devnet, for an app or an agent that talks to Logos through `logosctl`. You need `logosctl` on your `PATH`. ```bash @@ -169,7 +185,7 @@ Each session runs its own daemon in `~/.logos-devnet/sessions/`, with `lez Sessions follow the chain. `down` stops their daemons. `up` starts them again, loads their modules and opens their wallets, also after a `--port` change. `reset` funds each account again with what it was created with, and makes each wallet forget the old chain: its sync position and the state of its private accounts. Its keys and accounts stay. `session rm` deletes a session and its wallet. -The catalog's `lez_core` 0.5.1 is built on LEZ `v0.3.1`, the default `--lez` tag, so sessions match it. They install that version even once the catalog has a newer one, which may be built for LEZ v0.4. +Sessions install `lez_core` 0.5.1, built on LEZ v0.3, even once the catalog has a newer one: that's what waits for a v0.4 build. ## Messaging @@ -212,7 +228,7 @@ Sessions need nothing passed in: logos-devnet configures their storage before it ## What runs -LEZ's own `sequencer_service` runs, built with two features. `standalone` replaces Bedrock, the L1, with an in-process mock that accepts every block. `prove` runs programs in-process, so you don't need `r0vm`. The default is `v0.3.1`. `--lez` picks another `v0.3` tag, and a chain only runs one tag: `reset --lez ` to switch. LEZ `v0.4` changes the sequencer's config and commands, and isn't supported yet. +LEZ's own `sequencer_service` runs, built with two features. `standalone` replaces Bedrock, the L1, with an in-process mock that accepts every block. `prove` runs programs in-process, so you don't need `r0vm`. The default is `v0.4.0-rc3`: v0.4.0 isn't tagged yet. `--lez` picks another v0.4 tag, and a chain only runs one tag: `reset --lez ` to switch. A new chain is set up with `sequencer_service setup`, as LEZ's own local recipe does, then started from its home. Programs must be built for LEZ v0.4. | | devnet | testnet | | --- | --- | --- | @@ -222,10 +238,18 @@ LEZ's own `sequencer_service` runs, built with two features. `standalone` replac | Block timestamp | your clock | the sequencer's clock | | L1 finality, indexer | none | yes | -Fees are the testnet's. Every call holds `gas_limit × base fee` up front, plus a little for its size, so about 1.6M lepta at a `gas_limit` of 200,000. The faucet makes that irrelevant. +Fees are the testnet's: the wallet measures each call's gas and pays the base fee on it. The faucet makes that irrelevant. + +Genesis funds each account by its public key, which `accounts.json` records for every group account. Paying an account that was never used needs its public key too: `fund --key `, with the key `wallet account new public` printed. The devnet's own accounts, its groups' and the dev wallet's, are paid by theirs. `upstream_accounts = true` under `[devnet]` also keeps LEZ's own genesis accounts funded, whose keys LEZ publishes for its examples and tools. Private calls still prove on your machine, so they take as long as on the testnet: a shielded transfer from a session took 118 s on an Apple M-series laptop. Dev mode skips that. +## Coming from LEZ v0.3 + +logos-devnet runs LEZ v0.4 since v0.10.0. [v0.9.4](https://github.com/drptbl/logos-devnet/releases/tag/v0.9.4) is the last release that runs v0.3, and a project file with `lez = "v0.3.1"` needs it. + +A home that ran v0.3, `~/.logos-devnet` included, keeps its chain until you move it on: `up` stops and says so. `logos-devnet reset` then starts a v0.4 chain there, with the v0.3 dev wallet, account groups and sessions moved aside to `wallet-v0.3/`, `accounts-v0.3/` and `sessions-v0.3/`, untouched. A v0.4 wallet can't read v0.3 storage, so the new chain gets a new faucet and new program ids, and groups are made again. + ## Dev mode `up --dev-mode`, or `dev_mode = true` under `[devnet]`, runs the chain with `RISC0_DEV_MODE=1`: provers make fake proofs and the sequencer accepts them. The same transfer lands in 1 s. @@ -248,6 +272,7 @@ Everything is in `~/.logos-devnet` (or `LOGOS_DEVNET_HOME`): | `native/` | the native runtime's LEZ checkout, build, log and pid file | | `sessions/` | one directory per session: its `logosctl` home, its daemon's `HOME` with its storage, wallet and `session.json` | | `accounts/` | one directory per account group: its wallet and `accounts.json` | +| `*-v0.3/` | a home's LEZ v0.3 dev wallet, groups and sessions, moved aside by the `reset` that took it to v0.4 | | `programs.json` | the binary hash each program was deployed from | | `downloads/` | program binaries the project file names by URL, by SHA-256, and in `packages/` the module packages every daemon installs from, downloaded once and checked against the catalog's SHA-256. Every home uses the one in `~/.logos-devnet`, so a project's own home or a worktree's doesn't download them again. One left in another home from before v0.9.0 can be deleted | | `messaging/` | the hub, for `[messaging]` and `[storage]`: its `logosctl` home, its daemon's `HOME`, message store, ports and node keys in `hub.json` | @@ -279,7 +304,7 @@ With `--json`, a command prints one JSON document and nothing else on stdout. No The repo is a GitHub Action. On a Linux runner it installs `logos-devnet`, starts the devnet from your project file and exports the env into the job: ```yaml -- uses: drptbl/logos-devnet@v0.9.4 +- uses: drptbl/logos-devnet@v0.10.0 with: args: --max-txs-per-block 100 # optional, more options for up - run: cargo test # LOGOS_DEVNET_SEQUENCER, LOGOS_PROGRAM_*, LOGOS_DEVNET_ACCOUNTS_*, RISC0_DEV_MODE are set @@ -294,7 +319,7 @@ Inputs: `version` (default: the release tag you use the action at, or, pinned to `ghcr.io/drptbl/logos-devnet-sequencer:` holds the sequencer and the LEZ `wallet` for `linux/amd64` and `linux/arm64`. `up` pulls it, and builds it locally from [`docker/Dockerfile`](docker/Dockerfile) when no image is published for your tag. To build it yourself: ```bash -docker build --build-arg LEZ_TAG=v0.3.1 -t ghcr.io/drptbl/logos-devnet-sequencer:v0.3.1 - < docker/Dockerfile +docker build --build-arg LEZ_TAG=v0.4.0-rc3 -t ghcr.io/drptbl/logos-devnet-sequencer:v0.4.0-rc3 - < docker/Dockerfile ``` ## License diff --git a/docker/Dockerfile b/docker/Dockerfile index 5cee107..d4b0a2d 100644 --- a/docker/Dockerfile +++ b/docker/Dockerfile @@ -3,11 +3,11 @@ # A standalone LEZ sequencer and the LEZ wallet, built from an upstream tag. Built from stdin, so # it needs no build context: # -# docker build --build-arg LEZ_TAG=v0.3.1 -t ghcr.io/drptbl/logos-devnet-sequencer:v0.3.1 - < docker/Dockerfile +# docker build --build-arg LEZ_TAG=v0.4.0-rc3 -t ghcr.io/drptbl/logos-devnet-sequencer:v0.4.0-rc3 - < docker/Dockerfile # # `standalone` replaces Bedrock with an in-process mock, and `prove` runs guests in-process, so -# the image needs neither a Bedrock node nor r0vm. RISC0_SKIP_BUILD_KERNELS skips the GPU kernels -# `prove` would otherwise compile; the sequencer only executes, it never proves. +# the image needs neither a Bedrock node nor r0vm. The sequencer links the wallet, whose prover +# needs risc0's CPU kernels, so they're built. FROM rust:1-slim-trixie AS build ARG LEZ_TAG @@ -19,20 +19,20 @@ RUN apt-get update && apt-get install -y --no-install-recommends \ && rm -rf /var/lib/apt/lists/* RUN git clone --depth 1 --branch "$LEZ_TAG" https://github.com/logos-blockchain/logos-execution-zone.git /lez WORKDIR /lez -# The tag's rust-toolchain.toml picks the compiler; rustup installs it on first use. Two builds: -# in one, `prove` would reach the wallet too, which then links the kernels skipped here. The -# target cache is locked, so a concurrent build of another tag can't swap binaries before the copy. +# The tag's rust-toolchain.toml picks the compiler; rustup installs it on first use. Two builds, +# so `prove` stays out of the wallet binary. The target cache is locked, so a concurrent build of +# another tag can't swap binaries before the copy. RUN --mount=type=cache,target=/usr/local/cargo/registry \ --mount=type=cache,target=/usr/local/cargo/git \ --mount=type=cache,target=/lez/target,sharing=locked \ - RISC0_SKIP_BUILD_KERNELS=1 cargo build --release --features "$FEATURES" -p sequencer_service \ + cargo build --release --features "$FEATURES" -p sequencer_service \ && cargo build --release -p wallet \ && mkdir -p /out \ && cp target/release/sequencer_service target/release/wallet /out/ \ && strip /out/sequencer_service /out/wallet -# Upstream's debug config for this tag; the CLI patches it rather than shipping its own. +# Upstream's local config for this tag; the CLI patches it rather than shipping its own. RUN mkdir -p /out/share \ - && config="$(find . -path ./target -prune -o -path '*sequencer/service/configs/debug/sequencer_config.json' -print | head -1)" \ + && config="$(find . -path ./target -prune -o -path '*sequencer/service/networks/local.json' -print | head -1)" \ && test -n "$config" \ && cp "$config" /out/share/sequencer_config.json diff --git a/examples/README.md b/examples/README.md index 55f1529..c7a709f 100644 --- a/examples/README.md +++ b/examples/README.md @@ -1,5 +1,7 @@ # Examples +`hello-world`, `sessions`, `messaging` and `storage` run with [logos-devnet v0.9.4](https://github.com/drptbl/logos-devnet/releases/tag/v0.9.4) and LEZ v0.3 for now: sessions wait for a `lez_core` built for LEZ v0.4, and LEZ's tutorial for a v0.4 tag. They'll be updated when those ship. + | Example | | | --- | --- | | [`hello-world`](hello-world) | LEZ's tutorial on a devnet: build a program, deploy it and call it, paid by a funded test account | diff --git a/examples/github-actions/devnet.yml b/examples/github-actions/devnet.yml index 3d7c6d9..60273fa 100644 --- a/examples/github-actions/devnet.yml +++ b/examples/github-actions/devnet.yml @@ -21,7 +21,7 @@ jobs: # Installs logos-devnet, starts the devnet from logos-devnet.toml, and exports its env # (LOGOS_DEVNET_SEQUENCER, LOGOS_PROGRAM_*, LOGOS_DEVNET_ACCOUNTS_*, RISC0_DEV_MODE). - id: devnet - uses: drptbl/logos-devnet@v0.9.4 + uses: drptbl/logos-devnet@v0.10.0 - run: cargo test - name: The devnet's logs if: failure() diff --git a/examples/hello-world/README.md b/examples/hello-world/README.md index 08c6c93..3362d11 100644 --- a/examples/hello-world/README.md +++ b/examples/hello-world/README.md @@ -1,5 +1,7 @@ # Hello world +> **This example follows LEZ's v0.3 tutorial.** logos-devnet runs LEZ v0.4 since v0.10.0. Until LEZ tags a v0.4 release with a working tutorial, run this example with [logos-devnet v0.9.4](https://github.com/drptbl/logos-devnet/releases/tag/v0.9.4). It will be updated then. + LEZ's own program deployment tutorial on a devnet: you build its `hello_world` program, then deploy it and call it, paid by a funded test account. Once everything is built, a run takes about 15 s. `logos-devnet.toml` here gives the example a devnet of its own on a free port, next to a shared one on 3040, with a group of two funded accounts. The first pays for the deploy and the call, and the second gets the greeting. diff --git a/examples/messaging/README.md b/examples/messaging/README.md index c1dc09e..d3ee7cb 100644 --- a/examples/messaging/README.md +++ b/examples/messaging/README.md @@ -1,5 +1,7 @@ # Messaging +> **This example waits for a `lez_core` built for LEZ v0.4.** logos-devnet runs LEZ v0.4 since v0.10.0, and the Logos catalog's `lez_core` 0.5.1 is built for v0.3, so sessions don't run yet. Until a v0.4 one ships, run this example with [logos-devnet v0.9.4](https://github.com/drptbl/logos-devnet/releases/tag/v0.9.4) and LEZ v0.3. It will be updated then. + Two `logosctl` sessions, Alice and Bob, send a message and find each other's service through the devnet's messaging hub. Nothing goes through the public fleet: every node listens on `127.0.0.1`. `logos-devnet.toml` here gives the example a devnet of its own on a free port, the hub, and two sessions with `delivery_module` and `libp2p_module` installed. diff --git a/examples/sessions/README.md b/examples/sessions/README.md index 1bb20ec..a82cd6e 100644 --- a/examples/sessions/README.md +++ b/examples/sessions/README.md @@ -1,5 +1,7 @@ # Sessions +> **This example waits for a `lez_core` built for LEZ v0.4.** logos-devnet runs LEZ v0.4 since v0.10.0, and the Logos catalog's `lez_core` 0.5.1 is built for v0.3, so sessions don't run yet. Until a v0.4 one ships, run this example with [logos-devnet v0.9.4](https://github.com/drptbl/logos-devnet/releases/tag/v0.9.4) and LEZ v0.3. It will be updated then. + Two `logosctl` sessions, Alice and Bob, each with a funded wallet open in `lez_core`, the way an app or an agent talks to Logos. Alice pays Bob, then shields some of her funds into a private account. The devnet runs in dev mode, so the shielded transfer's proof takes a second instead of minutes. `logos-devnet.toml` here gives the example a devnet of its own on a free port, next to a shared one on 3040. `port = 0` takes a free port on the first `up` and keeps it, and `logos-devnet env` shows it. diff --git a/examples/storage/README.md b/examples/storage/README.md index 95fe5a0..2eba01b 100644 --- a/examples/storage/README.md +++ b/examples/storage/README.md @@ -1,5 +1,7 @@ # Storage +> **This example waits for a `lez_core` built for LEZ v0.4.** logos-devnet runs LEZ v0.4 since v0.10.0, and the Logos catalog's `lez_core` 0.5.1 is built for v0.3, so sessions don't run yet. Until a v0.4 one ships, run this example with [logos-devnet v0.9.4](https://github.com/drptbl/logos-devnet/releases/tag/v0.9.4) and LEZ v0.3. It will be updated then. + Two `logosctl` sessions, Alice and Bob, share a file through Logos Storage. Alice uploads it, and Bob downloads it by its CID. Nothing goes through the public storage network: every node listens on `127.0.0.1`. `logos-devnet.toml` here gives the example a devnet of its own on a free port, two sessions, and `[storage]`, which runs a storage node in the hub that both sessions' nodes bootstrap from. Each session's daemon starts its storage node on its own, so there's nothing to create. diff --git a/skills/logos-devnet/SKILL.md b/skills/logos-devnet/SKILL.md index 7051586..50dfa1a 100644 --- a/skills/logos-devnet/SKILL.md +++ b/skills/logos-devnet/SKILL.md @@ -9,7 +9,7 @@ description: logos-devnet runs a local LEZ (Logos Execution Zone) chain. Use whe ## Before you start -- **logos-devnet 0.9.0 or newer**: `logos-devnet --version`. Install it with `cargo install --locked logos-devnet`, or a binary from https://github.com/drptbl/logos-devnet/releases/latest (macOS and Linux). +- **logos-devnet 0.10.0 or newer**: `logos-devnet --version`. Install it with `cargo install --locked logos-devnet`, or a binary from https://github.com/drptbl/logos-devnet/releases/latest (macOS and Linux). - **Docker**: OrbStack, Docker Desktop or Colima, running. `logos-devnet doctor` says when it isn't. - **`logosctl`**, the Logos Core CLI, on `PATH`, only for sessions, `[messaging]` and `[storage]`: a release from https://github.com/logos-co/logos-logoscore-cli/releases. - **LEZ programs** you deploy are built with `cargo risczero build`, which makes the `.bin` the devnet takes. @@ -52,13 +52,14 @@ Pass `--json` to every command: on success stdout holds one JSON document, and n ## Choices - **Home.** Without `home`, every project on the machine shares `~/.logos-devnet` on port 3040, and `up` refuses settings that disagree with what other projects run there. Tests, worktrees and parallel agents get `home = ".logos-devnet"` and `[devnet] port = 0`, a free port of their own. +- **LEZ.** logos-devnet runs LEZ v0.4 (default `v0.4.0-rc3`); programs must be built for it. For LEZ v0.3, use logos-devnet v0.9.4. A home that ran v0.3: `reset` moves its v0.3 wallets aside and starts v0.4. Genesis and payments name accounts by public key, which `accounts.json` records as each account's `key`. `upstream_accounts = true` keeps LEZ's own published genesis accounts funded for its examples. - **Dev mode.** `dev_mode = true` makes private calls prove in about 1 s instead of about 2 min, with fake proofs. A chain keeps its dev mode for life: switching it takes `reset`. Use a chain without dev mode to check that real proofs verify. - **Programs.** A program can be a path, or a release: `{ url = "...", sha256 = "..." }`, downloaded once and deployed only if its SHA-256 matches. Programs deploy immutable, which undisclosed private calls require. While iterating on one, give it `{ path = "...", mutable = true }`: a rebuild then updates it in place with the same id on the next `up`. Its mutability is fixed per chain, so changing it takes `reset`. `.logos-devnet/programs.json` records each deployed program's binary SHA-256 and mutability: compare it with `shasum -a 256 ` to show which build runs. -- **Funding.** Groups that exist when a chain starts are funded at genesis, at once. A group added to a running chain is funded one transfer at a time, about 2.4 s per account. Every call holds about 1.6M lepta of fees up front, so an account that sends needs more than that. `logos-devnet fund Public/ [lepta]` tops one account up. +- **Funding.** Groups that exist when a chain starts are funded at genesis, at once. A group added to a running chain is funded one transfer at a time, about 2.4 s per account. `logos-devnet fund Public/ [lepta]` tops one account up; an account never used takes `--key ` too, unless it's one of the devnet's own. - **Messaging.** An empty `[messaging]` table runs a local hub: a delivery node and a discovery bootstrap on `127.0.0.1`, so messages and service lookups skip the public fleet. Sessions with `delivery_module` or `libp2p_module` loaded (`chat_module` loads the first) get nodes on the hub from `up`; outside a session, create the app's nodes from `LOGOS_DEVNET_DELIVERY_CONFIG` and `LOGOS_DEVNET_DISCOVERY_CONFIG` first in its daemon: the first `createNode` picks the network. `chat_module` still reaches a public key registry. `status --json` shows whether each hub node runs, in `.messaging.delivery_node` and `.messaging.discovery_node`, and `messaging rm` deletes the hub: a project that asks for one gets a new hub, with new addresses, on its next `up`. - **Storage.** Each session runs a storage node of its own, on `127.0.0.1` and in no network. An empty `[storage]` table connects the sessions through a node in the hub, so one session downloads by CID what another uploaded. Sessions need nothing passed in. - **Calling the modules.** To send or receive messages, advertise or look up a service, or upload and download a file from a session, read [modules.md](modules.md): `delivery_module`, `libp2p_module` and `storage_module` take arguments in an order and form their errors don't explain. -- **Sessions** need `logosctl` on `PATH`. `logos-devnet session restart ...` gives each a fresh daemon in seconds, keeping its wallet: use it where a module keeps state while loaded (libp2p_module 1.1.0 advertises one service per load) instead of `logosctl module reload`. They suit apps that talk to Logos through `logosctl` and `lez_core`. Before calling `lez_core` yourself, read [lez_core.md](lez_core.md): it takes ids and amounts in forms its errors don't explain. +- **Sessions** don't run yet: they wait for a `lez_core` built for LEZ v0.4 in the Logos catalog, and `up` refuses `[sessions]` until then (the session notes below, and lez_core.md and modules.md, describe them on logos-devnet v0.9.4 with LEZ v0.3). Sessions need `logosctl` on `PATH`. `logos-devnet session restart ...` gives each a fresh daemon in seconds, keeping its wallet: use it where a module keeps state while loaded (libp2p_module 1.1.0 advertises one service per load) instead of `logosctl module reload`. They suit apps that talk to Logos through `logosctl` and `lez_core`. Before calling `lez_core` yourself, read [lez_core.md](lez_core.md): it takes ids and amounts in forms its errors don't explain. ## Reset @@ -74,7 +75,10 @@ Each refusal changes nothing. `up` prefixes a program's refusal with `program is deployed mutable, asked for immutable` (or the reverse) | Put `mutable` back as deployed, or `reset`. | | `this chain runs in dev mode` / `this chain checks proofs` | Match the chain's dev mode, or `reset --dev-mode` / `reset --dev-mode false`. | | `this chain runs LEZ ` | `reset --lez `. | -| `logos-devnet runs LEZ v0.3 tags` | Use a v0.3 tag, e.g. `--lez v0.3.1`. LEZ v0.4 isn't supported yet. | +| `logos-devnet runs LEZ v0.4 tags` / `is a LEZ v0.3 tag` | Use a v0.4 tag, e.g. `v0.4.0-rc3`, or logos-devnet v0.9.4 for LEZ v0.3. | +| `this home runs LEZ v0.3` | `reset` moves its v0.3 wallets aside and starts v0.4, or use logos-devnet v0.9.4 for it. | +| `sessions don't run yet` | Drop `[sessions]` for now: no `lez_core` for LEZ v0.4 is published. | +| ` has never been used, and LEZ pays such an account only by its public key` | `fund --key `, with the key `wallet account new public` printed. | | `the shared devnet runs with ..., but asks for ...` | Other projects use that devnet. Give this project its own `home` and port. | | `port on 127.0.0.1 is taken` | `up --port `, remembered unless the file sets a fixed `port`. A new project home with `[devnet] port = 0` takes a free one on its first `up`. | | `sessions and the messaging hub need logosctl` | Install the Logos Core CLI, or remove the sessions and `[messaging]`. | diff --git a/skills/logos-devnet/lez_core.md b/skills/logos-devnet/lez_core.md index cb0ae90..076eecc 100644 --- a/skills/logos-devnet/lez_core.md +++ b/skills/logos-devnet/lez_core.md @@ -1,5 +1,7 @@ # lez_core through logosctl +> These calls run in sessions, which wait for a `lez_core` built for LEZ v0.4: they describe sessions on logos-devnet v0.9.4 with LEZ v0.3, and will be updated when one ships. + What `lez_core`, the LEZ module in a `logosctl` session, expects. A session's env (`source <(logos-devnet session env )`) points `logosctl` at its daemon, where the wallet is open. - Account ids are hex. A session's `LOGOS_DEVNET_ACCOUNT_HEX` is its account in that form, a group's `accounts.json` has each account's `hex`, and `logos-devnet account ` prints any id in both forms. diff --git a/skills/logos-devnet/modules.md b/skills/logos-devnet/modules.md index a63a15a..f487631 100644 --- a/skills/logos-devnet/modules.md +++ b/skills/logos-devnet/modules.md @@ -1,5 +1,7 @@ # Messaging, discovery and storage through logosctl +> These calls run in sessions, which wait for a `lez_core` built for LEZ v0.4: they describe sessions on logos-devnet v0.9.4 with LEZ v0.3, and will be updated when one ships. + What `delivery_module`, `libp2p_module` and `storage_module` expect when a session calls them. `source <(logos-devnet session env )` points `logosctl` at a session's daemon; `logos-devnet exec --session -- ` does the same for one command. - Calls answer `{"success": ..., "value": ..., "error": ...}` in the reply's `result`: `logosctl --json call | tail -1 | jq .result`. A call can succeed at the logosctl level and still carry `success: false`. diff --git a/src/account.rs b/src/account.rs index 49a6c82..660d782 100644 --- a/src/account.rs +++ b/src/account.rs @@ -1,7 +1,7 @@ //! Public account ids as the LEZ wallet prints and takes them: 32 bytes in base58, optionally //! prefixed `Public/`. -use anyhow::{Result, bail}; +use anyhow::{Context, Result, bail}; use serde::{Deserialize, Serialize}; /// A public account id, validated as 32 bytes of base58. Stored as bare base58. @@ -40,21 +40,28 @@ impl PublicId { /// From 64 hex characters, the form `lez_core` returns. pub fn from_hex(hex: &str) -> Result { - let bytes = (0..hex.len()) - .step_by(2) - .map(|i| { - hex.get(i..i + 2) - .and_then(|b| u8::from_str_radix(b, 16).ok()) - }) - .collect::>>(); - match bytes { - Some(bytes) if bytes.len() == 32 && hex.len() == 64 => { - Ok(Self(bs58::encode(bytes).into_string())) - } - _ => bail!("{hex} is not an account id (64 hex characters)"), + match hex32(hex) { + Some(bytes) => Ok(Self(bs58::encode(bytes).into_string())), + None => bail!("{hex} is not an account id (64 hex characters)"), } } + /// The public account `key` (64 hex digits, as `public_key_of` gives it) controls: the + /// SHA-256 of LEZ's public account prefix and the key, the same on v0.3 and v0.4. + pub fn of_key(key: &str) -> Result { + use sha2::{Digest, Sha256}; + const PREFIX: &[u8; 32] = b"/LEE/v0.3/AccountId/Public/\x00\x00\x00\x00\x00"; + let Some(key) = hex32(key) else { + bail!("{key} is not a public key (64 hex characters)"); + }; + let id: [u8; 32] = Sha256::new() + .chain_update(PREFIX) + .chain_update(key) + .finalize() + .into(); + Ok(Self(bs58::encode(id).into_string())) + } + /// The bare base58 id. pub fn as_str(&self) -> &str { &self.0 @@ -74,6 +81,31 @@ impl PublicId { } } +/// The public key of `secret` (64 hex digits) as LEZ writes it: the x coordinate of its +/// secp256k1 public key, in hex. What a LEZ v0.4 genesis and `send --to-pk` take. +pub fn public_key_of(secret: &str) -> Result { + use k256::elliptic_curve::sec1::ToEncodedPoint; + let bytes = hex32(secret).context("a private key is 64 hex characters")?; + let secret = k256::SecretKey::from_bytes(&bytes.into()) + .ok() + .context("not a valid private key")?; + let point = secret.public_key().to_encoded_point(false); + let x = point.x().context("the public key has no x coordinate")?; + Ok(x.iter().map(|b| format!("{b:02x}")).collect()) +} + +/// 32 bytes from 64 hex characters. +fn hex32(text: &str) -> Option<[u8; 32]> { + if text.len() != 64 { + return None; + } + let bytes = (0..64) + .step_by(2) + .map(|i| u8::from_str_radix(text.get(i..i + 2)?, 16).ok()) + .collect::>>()?; + bytes.try_into().ok() +} + /// The first `Public/` in wallet output, e.g. from /// `Generated new account with account_id Public/ at path /0`. pub fn first_public_id(output: &str) -> Option { @@ -87,6 +119,25 @@ pub fn first_public_id(output: &str) -> Option { mod tests { use super::*; + #[test] + fn derives_a_public_key_and_its_account_id_as_the_wallet_does() { + // From LEZ v0.3.1's wallet: `account import public --private-key 0101…01`, and + // `account new public`, which prints the key it made. + let secret = "01".repeat(32); + let key = public_key_of(&secret).unwrap(); + assert_eq!( + PublicId::of_key(&key).unwrap().as_str(), + "B1UN3hPgxacgHKBRoThcAmsPajGcUf6YXUhgB36x4DAd" + ); + let made = "4afc5da3b6acabc4892dddb1e49226599326ae3a6a700828e395b5bc9a4b30ba"; + assert_eq!( + PublicId::of_key(made).unwrap().as_str(), + "23cbN9uZbLU1zhcuiZ1qu1eneL8ed8HeHzDEF1br6rEd" + ); + assert!(public_key_of("zz").is_err()); + assert!(PublicId::of_key("abc").is_err()); + } + // A real account id from the LEZ testnet, in base58 and in hex. const SAMPLE_ID: &str = "HpavNGFYxjyhLsy171aXsvv146yUeXmRWiho22uvT43d"; const SAMPLE_HEX: &str = "f9eba477278c918fadafbcb4a6463e947d0fd8de344b5431ee0aa3cd41d7e3a4"; diff --git a/src/chain_config.rs b/src/chain_config.rs index 7469a62..7606406 100644 --- a/src/chain_config.rs +++ b/src/chain_config.rs @@ -1,26 +1,33 @@ -//! The sequencer config a devnet runs on: upstream's own debug config for the pinned LEZ tag, -//! with our chain home, block interval and faucet. Patching upstream's file rather than shipping -//! our own keeps every field a newer tag adds. +//! The sequencer config a devnet runs on: upstream's own local config for the pinned LEZ tag +//! (`networks/local.json`), with our chain home, block interval and faucet. Patching upstream's +//! file rather than shipping our own keeps every field a newer tag adds. use anyhow::{Context, Result, bail}; use serde_json::{Value, json}; -use crate::account::PublicId; - -/// What a devnet changes in upstream's debug config. +/// What a devnet changes in upstream's config. pub struct ChainOptions<'a> { /// Where the sequencer keeps its database and keys, as the sequencer sees the path. pub home: &'a str, /// Block interval, in the sequencer's humantime format (`1s`, `500ms`). pub block_time: &'a str, /// The faucet, funded at genesis. - pub faucet: &'a PublicId, - /// The faucet's genesis balance in lepta. - pub faucet_balance: u64, + pub faucet: &'a Funded, /// The most user transactions a block takes. pub max_txs_per_block: u32, - /// More accounts to fund at genesis, with their balances. - pub genesis_accounts: &'a [(PublicId, u64)], + /// More accounts to fund at genesis. + pub genesis_accounts: &'a [Funded], + /// Keep upstream's own genesis accounts, whose keys are published, funded too: tools such + /// as LEZ's examples fund themselves from them. + pub keep_upstream_accounts: bool, +} + +/// An account funded at genesis, which names it by its public key. +pub struct Funded { + /// Its public key, as 64 hex digits. + pub key: String, + /// Lepta. + pub balance: u64, } /// The bounds `max_txs_per_block` must fall in: upstream's mempool holds 1000 transactions. @@ -37,10 +44,10 @@ pub fn check_max_txs_per_block(max: u32) -> Result<()> { Ok(()) } -/// Returns `debug` with `opts` applied. The faucet is the only funded account: upstream's -/// supply accounts have published keys. -pub fn patch(mut debug: Value, opts: &ChainOptions) -> Result { - let config = debug +/// Returns upstream's config with `opts` applied. Unless the options keep them, the faucet and +/// the given accounts are the only ones funded: upstream's supply accounts have published keys. +pub fn patch(mut upstream: Value, opts: &ChainOptions) -> Result { + let config = upstream .as_object_mut() .context("the upstream sequencer config is not a JSON object")?; config.insert("home".into(), json!(opts.home)); @@ -48,29 +55,35 @@ pub fn patch(mut debug: Value, opts: &ChainOptions) -> Result { check_max_txs_per_block(opts.max_txs_per_block)?; config.insert("max_num_tx_in_block".into(), json!(opts.max_txs_per_block)); // Both would listen on every interface: metrics on 9000 and gossip on a UDP port. A single - // devnet sequencer needs neither. - config.insert("metrics_address".into(), Value::Null); + // devnet sequencer needs neither. The config refuses fields it doesn't know. + config.insert("metrics_listen_address".into(), Value::Null); config.insert("gossip".into(), Value::Null); let genesis = config - .entry("genesis") + .get_mut("genesis") + .and_then(Value::as_object_mut) + .context("the upstream config's `genesis` is not an object")?; + let actions = genesis + .entry("actions") .or_insert_with(|| json!([])) .as_array_mut() - .context("the upstream config's `genesis` is not a list")?; - genesis.retain(|action| action.get("supply_account").is_none()); - genesis.push(json!({ - "supply_account": { "account_id": opts.faucet.as_str(), "balance": opts.faucet_balance } - })); - for (account, balance) in opts.genesis_accounts { - genesis.push(json!({ - "supply_account": { "account_id": account.as_str(), "balance": balance } + .context("the upstream config's `genesis.actions` is not a list")?; + if !opts.keep_upstream_accounts { + actions.retain(|action| { + action.get("supply_account").is_none() && action.get("supply_private_account").is_none() + }); + } + for account in std::iter::once(opts.faucet).chain(opts.genesis_accounts) { + actions.push(json!({ + "supply_account": { + "recipient": { "identified": { "key": account.key } }, + "balance": account.balance + } })); } let block_secs = block_time_secs(opts.block_time)?; - if let Some(timeout) = config - .get("bedrock_config") - .and_then(|b| b["channel_params"]["posting_timeout"].as_u64()) + if let Some(timeout) = genesis["channel_params"]["posting_timeout"].as_u64() && block_secs >= timeout as f64 { bail!( @@ -78,7 +91,7 @@ pub fn patch(mut debug: Value, opts: &ChainOptions) -> Result { opts.block_time ); } - Ok(debug) + Ok(upstream) } /// Seconds in a `1s` / `500ms` / `2m` block time: the forms the sequencer's humantime config @@ -107,78 +120,106 @@ pub fn block_time_secs(text: &str) -> Result { mod tests { use super::*; + /// LEZ v0.4.0-rc3's `networks/local.json`, cut down. fn upstream() -> Value { json!({ "home": ".", + "max_num_tx_in_block": 20, "block_create_timeout": "15s", - "bedrock_config": { "channel_params": { "posting_timeout": 25 } }, - "genesis": [ - { "supply_account": { "account_id": "Stock", "balance": 10 } }, - { "stake_sequencer": { "sequencer_key": "k" } } - ], - "future_field": 7 + "bedrock_config": { "channel_id": "0101", "node_url": "http://localhost:18080" }, + "genesis": { + "channel_params": { "posting_timeout": 25, "exit_delay": 100 }, + "actions": [ + { "supply_account": { "recipient": { "identified": { "key": "aa" } }, "balance": 1 } }, + { "supply_private_account": { "address": "Priv", "balance": 2 } }, + { "stake_sequencer": { "sequencer_key": "k" } } + ] + }, + "gossip": { "listen_addr": "/ip4/0.0.0.0/udp/0/quic-v1", "bootstrap_peers": [] } }) } - const FAUCET: &str = "HpavNGFYxjyhLsy171aXsvv146yUeXmRWiho22uvT43d"; - - const USER: &str = "6YvesSEDWW25kpi8SSki2c8o5m3uACsigvGnNQ6wMruh"; - - fn patched_with(block_time: &str, max_txs_per_block: u32) -> Result { - let faucet = PublicId::parse(FAUCET).unwrap(); - let users = [(PublicId::parse(USER).unwrap(), 7)]; - patch( - upstream(), - &ChainOptions { - home: "/devnet/chain", - block_time, - faucet: &faucet, - faucet_balance: 1_000, - max_txs_per_block, - genesis_accounts: &users, - }, - ) + const FAUCET_KEY: &str = "6aa4c365699b89d963ef85a59868b9612b6001f90750b4970662a62776332e81"; + + fn options<'a>( + faucet: &'a Funded, + users: &'a [Funded], + max_txs_per_block: u32, + keep_upstream_accounts: bool, + ) -> ChainOptions<'a> { + ChainOptions { + home: "/devnet/chain", + block_time: "1s", + faucet, + max_txs_per_block, + genesis_accounts: users, + keep_upstream_accounts, + } } - fn patched(block_time: &str) -> Result { - patched_with(block_time, 20) + fn funded(key: &str, balance: u64) -> Funded { + Funded { + key: key.into(), + balance, + } + } + + fn patched(max_txs_per_block: u32, keep_upstream_accounts: bool) -> Result { + let faucet = funded(FAUCET_KEY, 1_000); + let users = [funded("bb", 7)]; + let opts = options(&faucet, &users, max_txs_per_block, keep_upstream_accounts); + patch(upstream(), &opts) } #[test] - fn sets_home_and_block_time_and_turns_listeners_off() { - let out = patched("1s").unwrap(); + fn runs_alone_and_keeps_the_tags_channel() { + let out = patched(50, false).unwrap(); assert_eq!(out["home"], "/devnet/chain"); assert_eq!(out["block_create_timeout"], "1s"); - assert!(out["metrics_address"].is_null()); + assert_eq!(out["max_num_tx_in_block"], 50); + // v0.4 refuses unknown fields: `metrics_address` would fail the whole config. + assert!(out["metrics_listen_address"].is_null()); + assert!(out.get("metrics_address").is_none()); assert!(out["gossip"].is_null()); - assert_eq!(out["future_field"], 7, "fields we don't know about stay"); + // rc3 needs `exit_delay`, later tags `finality_depth`: the tag's own params stay. + assert_eq!(out["genesis"]["channel_params"]["exit_delay"], 100); } #[test] - fn funds_only_the_faucet_and_the_named_accounts() { - let out = patched("1s").unwrap(); - let genesis = out["genesis"].as_array().unwrap(); + fn genesis_funds_by_public_key() { + let out = patched(20, false).unwrap(); + let funded = |key: &str, balance: u64| json!({ "supply_account": { "recipient": { "identified": { "key": key } }, "balance": balance } }); assert_eq!( - genesis, + out["genesis"]["actions"].as_array().unwrap(), &vec![ json!({ "stake_sequencer": { "sequencer_key": "k" } }), - json!({ "supply_account": { "account_id": FAUCET, "balance": 1000 } }), - json!({ "supply_account": { "account_id": USER, "balance": 7 } }), + funded(FAUCET_KEY, 1000), + funded("bb", 7), ] ); } #[test] - fn sets_and_bounds_the_transactions_per_block() { - assert_eq!(patched_with("1s", 200).unwrap()["max_num_tx_in_block"], 200); - assert!(patched_with("1s", 0).is_err()); - assert!(patched_with("1s", 1001).is_err()); + fn genesis_can_keep_upstreams_published_accounts() { + let out = patched(20, true).unwrap(); + let actions = out["genesis"]["actions"].as_array().unwrap(); + assert_eq!(actions.len(), 5, "{actions:?}"); + assert!(actions[1].get("supply_private_account").is_some()); } #[test] - fn refuses_a_block_time_at_or_over_the_posting_timeout() { - assert!(patched("25s").is_err()); - assert!(patched("500ms").is_ok()); + fn block_time_stays_under_the_posting_timeout() { + let mut upstream = upstream(); + upstream["genesis"]["channel_params"]["posting_timeout"] = json!(1); + let faucet = funded(FAUCET_KEY, 1); + assert!(patch(upstream, &options(&faucet, &[], 20, false)).is_err()); + } + + #[test] + fn sets_and_bounds_the_transactions_per_block() { + assert_eq!(patched(200, false).unwrap()["max_num_tx_in_block"], 200); + assert!(patched(0, false).is_err()); + assert!(patched(1001, false).is_err()); } #[test] diff --git a/src/devnet.rs b/src/devnet.rs index 3dc41fa..04ee37f 100644 --- a/src/devnet.rs +++ b/src/devnet.rs @@ -11,11 +11,11 @@ use std::collections::BTreeMap; use crate::account::{PublicId, first_public_id}; use crate::binary; -use crate::chain_config::{self, ChainOptions}; +use crate::chain_config::{self, ChainOptions, Funded}; use crate::envfile::{self, Env}; use crate::fetch; use crate::groups::{self, Group, GroupInfo}; -use crate::home::{Home, RuntimeKind, Settings, write_json}; +use crate::home::{DEFAULT_LEZ, Home, RuntimeKind, Settings, V0_3_RELEASE, write_json}; use crate::messaging::{Hub, Wants}; use crate::project::{ProgramSource, ProgramSpec, Project}; use crate::report::{ @@ -32,6 +32,17 @@ const FAUCET_BALANCE: u64 = 1_000_000_000_000_000_000; const FAUCET_LABEL: &str = "faucet"; /// What `fund`, sessions and account groups send when no amount is given. pub const DEFAULT_FUND: u64 = 10_000_000_000; +/// Whether sessions run. They wait for a `lez_core` built for LEZ v0.4 in the Logos catalog: the +/// newest, 0.5.1, is built for v0.3 and can't drive a v0.4 chain. Once one ships, pin it in +/// `session::LEZ_CORE_VERSION`, open wallets with its `force_rpc` (it runs a sequencer of its own +/// otherwise), and turn this on. +const SESSIONS_READY: bool = false; + +/// Why sessions don't run yet. +pub(crate) const SESSIONS_WAIT: &str = "sessions don't run yet: they need a lez_core built for LEZ v0.4, \ + and the Logos catalog has only 0.5.1, built for v0.3. Drop [sessions] from the project \ + file for now, or use logos-devnet v0.9.4 with LEZ v0.3"; + /// How `up` waits for a starting sequencer's first block. A long chain replays first, logging /// a different line for each block (186k blocks took 34 min), so `up` waits as long as the log /// shows something new. A sequencer stuck repeating one line counts as quiet. @@ -160,10 +171,14 @@ impl Devnet { } /// Refuses `settings` the chain here can't run on: another LEZ tag or dev mode. Its own - /// record of its dev mode counts, not settings.json's. + /// records of its tag and dev mode count, not settings.json's. fn check_chain_takes(&self, settings: &Settings) -> Result<()> { let chain = Settings { dev_mode: self.home.chain_dev_mode(), + lez: self + .home + .chain_lez() + .unwrap_or_else(|| self.settings.lez.clone()), ..self.settings.clone() }; check_chain_keeps(&chain, settings) @@ -309,10 +324,34 @@ impl Devnet { /// Starts the devnet with `opts` applied, on a new chain when `wipe`. Everything that can /// fail runs before the running sequencer is stopped, the settings saved or the chain - /// deleted, so a bad option leaves the devnet as it was. + /// deleted, so a bad option leaves the devnet as it was. A home that ran LEZ v0.3 is the + /// exception: `reset` moves its wallets aside (see `move_v0_3_aside`) before the steps that + /// need the new ones, and a `reset` run again after a failure doesn't move them twice. fn launch(self, opts: &UpOptions, wipe: bool) -> Result { + // A tag asked for, by flag or project file, is checked before anything else says + // `reset` would apply it. + let asked = opts + .lez + .as_deref() + .or_else(|| self.project.as_ref().and_then(|p| p.devnet.lez.as_deref())); + if let Some(tag) = asked { + crate::home::check_lez(tag)?; + } let running = self.runtime.running(); - let settings = opts.apply(self.with_project_settings(opts, running && !wipe)?); + let mut settings = opts.apply(self.with_project_settings(opts, running && !wipe)?); + let moves_v0_3 = self.home.runs_v0_3(&self.settings.lez); + if moves_v0_3 { + if !wipe { + bail!( + "this home runs LEZ v0.3. `logos-devnet reset` starts it on LEZ v0.4, with \ + its v0.3 wallets, account groups and sessions moved aside, to \ + wallet-v0.3/, accounts-v0.3/ and sessions-v0.3/. {V0_3_RELEASE}" + ); + } + if asked.is_none() { + settings.lez = DEFAULT_LEZ.into(); + } + } crate::home::check_lez(&settings.lez)?; chain_config::block_time_secs(&settings.block_time)?; chain_config::check_max_txs_per_block(settings.max_txs_per_block)?; @@ -350,6 +389,9 @@ impl Devnet { } next.runtime.prepare(opts.rebuild)?; + if moves_v0_3 { + self.move_v0_3_aside()?; + } let faucet = next.dev_faucet()?; if continuing && funds_another_faucet(self.settings.faucet.as_ref(), &faucet) { bail!( @@ -369,8 +411,10 @@ impl Devnet { } next.home.save_settings(&next.settings)?; std::fs::create_dir_all(next.home.chain_dir())?; + next.set_chain_up(&config)?; write_json(&next.home.chain_config(), &config)?; next.home.record_chain_dev_mode(next.settings.dev_mode)?; + next.home.record_chain_lez(&next.settings.lez)?; // Every one is tried, and a failure is reported once the chain runs. let marked = if continuing { Ok(()) @@ -432,6 +476,32 @@ impl Devnet { Ok(wanted) } + /// Moves a LEZ v0.3 home's wallets, account groups and sessions aside (see + /// `Home::move_v0_3_aside`), with each session's daemon stopped first. + fn move_v0_3_aside(&self) -> Result<()> { + // A daemon left running would keep a moved directory open, out of reach. + for session in session::list(&self.home.sessions_dir())? { + let ctl = session.logosctl(); + ctl.stop() + .with_context(|| format!("stopping session {}", session.name))?; + if ctl.answers_within(SESSION_CHECK_TIMEOUT) { + bail!( + "session {}'s daemon still answers after a stop: stop it with `logosctl \ + daemon stop` and its LOGOSCTL_CONFIG_DIR, then `reset` again", + session.name + ); + } + } + let moved = self.home.move_v0_3_aside()?; + if !moved.is_empty() { + eprintln!( + "This home ran LEZ v0.3: its {} are kept as they were, for logos-devnet v0.9.4.", + moved.join(", ") + ); + } + Ok(()) + } + /// Where `program`'s binary is on this machine: its path, or its release, downloaded into /// the home once and checked against its SHA-256. fn program_binary(&self, program: &ProgramSpec) -> Result { @@ -462,6 +532,9 @@ impl Devnet { self.runtime.check_wallet_file(&binary)?; } } + if self.refuses_sessions() { + bail!("{SESSIONS_WAIT}"); + } if self.needs_logosctl() && !logosctl_on_path() { bail!( "sessions and the messaging hub need logosctl, the Logos Core CLI, on your PATH. \ @@ -473,6 +546,15 @@ impl Devnet { self.check_hub_ports() } + /// Whether the project asks for sessions, which don't run yet (see `SESSIONS_READY`). + pub fn refuses_sessions(&self) -> bool { + !SESSIONS_READY + && self + .project + .as_ref() + .is_some_and(|p| !p.sessions.is_empty()) + } + /// Fails when a port the hub keeps is taken while the hub doesn't run, so `up` couldn't /// start it there. pub fn check_hub_ports(&self) -> Result<()> { @@ -647,24 +729,39 @@ impl Devnet { // chunks, saving after each: a batch is one shell argument, and a long one fails. while info.accounts.len() < count { let missing = (count - info.accounts.len()).min(BATCH_CHUNK); - let runs = (0..missing) - .map(|_| { - Ok(vec![ + let secrets = (0..missing) + .map(|_| random_key()) + .collect::>>()?; + let runs: Vec> = secrets + .iter() + .map(|secret| { + vec![ "account".into(), "import".into(), "public".into(), "--private-key".into(), - random_key()?, - ]) + secret.clone(), + ] }) - .collect::>>>()?; - let ids = self - .runtime - .wallet_batch(&wallet, &runs)? + .collect(); + let outputs = self.runtime.wallet_batch(&wallet, &runs)?; + let accounts = secrets .iter() - .map(|out| first_public_id(out).context("the wallet made no account")) + .zip(&outputs) + .map(|(secret, out)| { + let id = first_public_id(out).context("the wallet made no account")?; + let key = crate::account::public_key_of(secret)?; + // A key that names another account would fund the wrong one at genesis. + if PublicId::of_key(&key)? != id { + bail!( + "the wallet made {} from a key that names another", + id.wallet_form() + ); + } + Ok((id, key)) + }) .collect::>>()?; - info = Group::extended(info, ids); + info = Group::extended(info, accounts); group.save_info(&info)?; } group.save_info(&info)?; @@ -685,7 +782,7 @@ impl Devnet { let mut unfunded = Vec::new(); for account in &info.accounts { if !rpc.account_in_use(&account.id)? { - unfunded.push(&account.id); + unfunded.push(account); } } if unfunded.is_empty() { @@ -697,19 +794,28 @@ impl Devnet { unfunded.len(), group.name ); - for id in unfunded { - self.send(id, u128::from(info.amount))?; + for account in unfunded { + self.send( + &account.id, + Some(account.checked_key()?), + u128::from(info.amount), + )?; } } Ok(()) } /// Every account group's accounts with their genesis balance. - fn genesis_accounts(&self) -> Result> { + fn genesis_accounts(&self) -> Result> { let mut accounts = Vec::new(); for group in groups::list(&self.home.groups_dir())? { let info = group.info()?; - accounts.extend(info.accounts.into_iter().map(|a| (a.id, info.amount))); + for account in &info.accounts { + accounts.push(Funded { + key: account.checked_key()?.to_owned(), + balance: info.amount, + }); + } } Ok(accounts) } @@ -744,7 +850,7 @@ impl Devnet { // Funding only needs the dev wallet: a daemon that won't start doesn't cost the // account its funds. let funded = if new_chain { - self.send(&info.account, info.funded).map(drop) + self.send(&info.account, None, info.funded).map(drop) } else { Ok(()) }; @@ -828,19 +934,11 @@ impl Devnet { ) } - /// Sends `amount` lepta from the faucet to `to` and returns its new balance. - fn send(&self, to: &PublicId, amount: u128) -> Result { - let faucet = self.faucet()?; - self.wallet(vec![ - "auth-transfer".into(), - "send".into(), - "--from".into(), - faucet.wallet_form().into(), - "--to".into(), - to.wallet_form().into(), - "--amount".into(), - amount.to_string().into(), - ])?; + /// Sends `amount` lepta from the faucet to `to`, whose public key is `key` when known, and + /// returns its new balance. + fn send(&self, to: &PublicId, key: Option<&str>, amount: u128) -> Result { + let args = transfer_args(self.faucet()?, to, key, amount); + self.wallet(args.into_iter().map(WalletArg::from).collect())?; self.rpc().balance(to) } @@ -853,17 +951,64 @@ impl Devnet { } } + /// The public key of `id` when logos-devnet holds it: a group account's, or one in the dev + /// wallet, such as the faucet. Read where the key lives, so it can't drift from it. + fn known_key(&self, id: &PublicId) -> Result> { + for group in groups::list(&self.home.groups_dir())? { + if let Some(account) = group.info()?.accounts.iter().find(|a| &a.id == id) { + return Ok(Some(account.checked_key()?.to_owned())); + } + } + let storage = self + .home + .wallet_dir() + .join(crate::wallet_storage::STORAGE_FILE); + crate::wallet_storage::public_key(&storage, id) + } + + /// Sets a new chain up from `config`: `setup` writes its channel signing key and funding key + /// file beside a copy of the config, which `up` then keeps up to date. A chain set up before + /// has nothing to do. + fn set_chain_up(&self, config: &Value) -> Result<()> { + if self.home.chain_set_up() { + return Ok(()); + } + // `setup` refuses a home that has a config, e.g. from one that stopped halfway. + remove_if_present(&self.home.chain_config(), |p| std::fs::remove_file(p))?; + let template = self.home.setup_template(); + write_json(&template, config)?; + let set_up = self.runtime.setup_chain(); + remove_if_present(&template, |p| std::fs::remove_file(p))?; + set_up + } + fn chain_config(&self) -> Result { let genesis_accounts = self.genesis_accounts()?; + let faucet = self.faucet()?; + let faucet = Funded { + key: self.known_key(faucet)?.with_context(|| { + format!( + "the dev wallet holds no key for the faucet {}: move {} aside, and `up` \ + makes a new faucet, with new program ids", + faucet.wallet_form(), + self.home.wallet_dir().display() + ) + })?, + balance: FAUCET_BALANCE, + }; chain_config::patch( self.runtime.upstream_config()?, &ChainOptions { home: &self.runtime.chain_home(), block_time: &self.settings.block_time, - faucet: self.faucet()?, - faucet_balance: FAUCET_BALANCE, + faucet: &faucet, max_txs_per_block: self.settings.max_txs_per_block, genesis_accounts: &genesis_accounts, + keep_upstream_accounts: self + .project + .as_ref() + .and_then(|p| p.devnet.upstream_accounts) + .unwrap_or(false), }, ) } @@ -1023,12 +1168,34 @@ impl Devnet { }) } - pub fn fund(&self, account: &str, amount: u128) -> Result { + /// Sends `amount` lepta from the faucet to `account`. LEZ v0.4 pays an account it has + /// never seen only by its public key, `key`. + pub fn fund(&self, account: &str, amount: u128, key: Option<&str>) -> Result { let to = PublicId::parse(account)?; + if let Some(key) = key + && PublicId::of_key(key)? != to + { + bail!( + "that public key names another account than {}", + to.wallet_form() + ); + } // Fails before any work when there is no faucet yet. self.faucet()?; self.require_running()?; - let balance = self.send(&to, amount)?; + let key = match key { + Some(key) => Some(key.to_owned()), + None => self.known_key(&to)?, + }; + if key.is_none() && !self.rpc().account_in_use(&to)? { + bail!( + "{} has never been used, and LEZ pays such an account only by its public \ + key: pass it with `--key `, as `wallet account new public` printed it or \ + `wallet account get --keys` prints it", + to.wallet_form() + ); + } + let balance = self.send(&to, key.as_deref(), amount)?; Ok(Balance { account: to.wallet_form(), balance: Some(balance), @@ -1085,6 +1252,9 @@ impl Devnet { if session.exists() { bail!("session {name} exists. `logos-devnet session rm {name}` first"); } + if !SESSIONS_READY { + bail!("{SESSIONS_WAIT}"); + } let modules = session::modules_with(extra)?; // Fails before any work when there is no faucet yet. self.faucet()?; @@ -1198,7 +1368,7 @@ impl Devnet { funded: amount, }; session.save_info(&info)?; - self.send(&info.account, amount)?; + self.send(&info.account, None, amount)?; // The session is made and funded either way: the next `up` joins it again. if let Err(e) = self.join_hub(&ctl) { eprintln!("session {}: {e:#}", session.name); @@ -1438,10 +1608,11 @@ impl Devnet { let id = self.account_id(account)?; let rpc = self.rpc(); let state = rpc.account(&id)?; - let shards: BTreeMap> = state["data"]["shards"] + // Each program's bytes. + let states: BTreeMap> = state["data"]["actor_states"] .as_object() - .map(|shards| { - shards + .map(|states| { + states .iter() .map(|(program, bytes)| { let bytes = bytes.as_array().into_iter().flatten(); @@ -1451,11 +1622,11 @@ impl Devnet { .collect() }) .unwrap_or_default(); - let data = shards + let data = states .iter() .map(|(p, bytes)| (p.clone(), bytes.len())) .collect(); - let data_hex = shards + let data_hex = states .iter() .map(|(p, bytes)| { ( @@ -1813,23 +1984,33 @@ fn remove_if_present(path: &Path, remove: fn(&Path) -> std::io::Result<()>) -> R } } -/// A wallet config in the shape `lez_core` 0.5.1 writes. It reads `sequencer.sequencer_addr`; -/// the top-level `sequencer_addr` and `sequencers` are set too, so a build that reads those -/// finds the devnet as well. +/// The LEZ wallet's config, pointing at `sequencer`. It sets no `gas_limit`: the wallet +/// measures each transaction's gas within its default budget (2M at rc3), which leaves room for +/// a 96 KiB program segment. fn wallet_config(sequencer: &str) -> Value { json!({ - "gas_limit": 200_000, - "multi_sequencer_client_config": { "calibration_limit": 3, "distribution_limit": 1 }, "seq_block_poll_max_amount": 100, "seq_poll_max_retries": 10, "seq_poll_timeout": WALLET_POLL_TIMEOUT, "seq_tx_poll_max_blocks": 15, - "sequencer": { "sequencer_addr": sequencer }, - "sequencer_addr": sequencer, - "sequencers": [{ "sequencer_addr": sequencer }] + "sequencer": { "sequencer_addr": sequencer } }) } +/// The wallet's arguments that send `amount` lepta from `from` to `to`. LEZ takes an account +/// it has never seen only when the payment names its public key (`key`), and then refuses `--to` +/// beside it. +fn transfer_args(from: &PublicId, to: &PublicId, key: Option<&str>, amount: u128) -> Vec { + let mut args: Vec = vec!["auth-transfer".into(), "send".into(), "--from".into()]; + args.push(from.wallet_form()); + match key { + Some(key) => args.extend(["--to-pk".into(), key.to_owned()]), + None => args.extend(["--to".into(), to.wallet_form()]), + } + args.extend(["--amount".into(), amount.to_string()]); + args +} + /// The account `wallet account list` shows with `[label]`. fn labelled(list: &str, label: &str) -> Option { let tag = format!("[{label}]"); @@ -2449,19 +2630,53 @@ mod tests { } #[test] - fn wallet_configs_point_every_address_field_at_the_devnet() { + fn wallet_configs_point_at_the_devnet() { let config = wallet_config("http://127.0.0.1:3040"); assert_eq!( config["sequencer"]["sequencer_addr"], "http://127.0.0.1:3040" ); - assert_eq!(config["sequencer_addr"], "http://127.0.0.1:3040"); - assert_eq!( - config["sequencers"][0]["sequencer_addr"], - "http://127.0.0.1:3040" - ); - assert_eq!(config["gas_limit"], 200_000); assert_eq!(config["seq_poll_timeout"], "2s"); + // The wallet measures each transaction's gas within its own default budget. + assert!(config.get("gas_limit").is_none()); + } + + #[test] + fn pays_an_account_by_its_key_when_known() { + let faucet = PublicId::parse(ID).unwrap(); + let to = PublicId::parse("6YvesSEDWW25kpi8SSki2c8o5m3uACsigvGnNQ6wMruh").unwrap(); + let to_id = format!("Public/{}", to.as_str()); + // LEZ admits an account it has never seen only when the payment names its key. + let by_key = transfer_args(&faucet, &to, Some("ab"), 5); + assert!( + by_key.windows(2).any(|w| w == ["--to-pk", "ab"]), + "{by_key:?}" + ); + assert!( + !by_key.contains(&"--to".to_owned()), + "--to and --to-pk conflict" + ); + assert!(transfer_args(&faucet, &to, None, 5).contains(&to_id)); + } + + #[test] + fn refuses_sessions_until_a_lez_core_for_v0_4_ships() { + let dir = tempfile::tempdir().unwrap(); + let devnet = devnet_with_file(dir.path(), "home = \"home\"\n[sessions.alice]\n"); + assert!(devnet.refuses_sessions()); + let err = devnet.check_needs(|| true).unwrap_err(); + assert!(err.to_string().contains("lez_core"), "{err}"); + let err = devnet.session_new("bob", &[], 1).unwrap_err(); + assert!(err.to_string().contains("lez_core"), "{err}"); + } + + #[test] + fn funds_by_key_only_the_account_the_key_names() { + let dir = tempfile::tempdir().unwrap(); + let devnet = devnet_in(&dir.path().join("home")); + let key = crate::account::public_key_of(&"01".repeat(32)).unwrap(); + let err = devnet.fund(ID, 5, Some(&key)).unwrap_err(); + assert!(err.to_string().contains("names another account"), "{err}"); } #[test] @@ -2573,7 +2788,7 @@ mod tests { fn up_reports_what_it_deployed_and_updated() { let id = PublicId::parse(ID).unwrap(); let mut status = Status { - lez: "v0.3.1".into(), + lez: "v0.4.0-rc3".into(), runtime: "docker".into(), sequencer: report::Sequencer { url: "http://127.0.0.1:3040".into(), @@ -2657,6 +2872,43 @@ mod tests { assert!(devnet.check_chain_takes(&dev).is_ok()); } + #[test] + fn a_v0_3_home_moves_on_only_by_reset() { + let dir = tempfile::tempdir().unwrap(); + let home = Home::locate(Some(dir.path().into())).unwrap(); + let v0_3 = Settings { + lez: "v0.3.1".into(), + ..Settings::default() + }; + home.save_settings(&v0_3).unwrap(); + for lez in [None, Some("v0.4.0-rc3".to_owned())] { + let opts = UpOptions { + lez, + ..UpOptions::default() + }; + let err = Devnet::open(home.clone(), None) + .unwrap() + .up(&opts) + .unwrap_err() + .to_string(); + assert!(err.contains("reset") && err.contains("v0.9.4"), "{err}"); + } + assert_eq!(home.load_settings().unwrap(), v0_3, "nothing changed"); + } + + #[test] + fn a_chain_keeps_its_own_lez_tag_without_settings() { + // A chain whose settings.json was lost reads as the default tag: its own record must + // stop another tag's config being written over it. + let dir = tempfile::tempdir().unwrap(); + let home = Home::locate(Some(dir.path().to_path_buf())).unwrap(); + std::fs::create_dir_all(home.chain_dir()).unwrap(); + home.record_chain_lez("v0.4.7").unwrap(); + let devnet = Devnet::open(home, None).unwrap(); + let err = devnet.check_chain_takes(&Settings::default()).unwrap_err(); + assert!(err.to_string().contains("runs LEZ v0.4.7"), "{err}"); + } + #[test] fn says_why_a_program_needs_reset() { let elf = Path::new("out/counter.bin"); @@ -2879,7 +3131,10 @@ mod tests { let written = devnet.write_project_wallet_config(&target).unwrap(); let config: Value = serde_json::from_str(&std::fs::read_to_string(&written.path).unwrap()).unwrap(); - assert_eq!(config["sequencer_addr"], "http://127.0.0.1:3040"); + assert_eq!( + config["sequencer"]["sequencer_addr"], + "http://127.0.0.1:3040" + ); assert!(devnet.write_project_wallet_config(&target).is_err()); } @@ -2887,7 +3142,7 @@ mod tests { fn fund_and_deploy_refuse_before_up() { let dir = tempfile::tempdir().unwrap(); let devnet = devnet_in(dir.path()); - let err = devnet.fund(ID, 1).unwrap_err(); + let err = devnet.fund(ID, 1, None).unwrap_err(); assert!(err.to_string().contains("logos-devnet up"), "{err}"); let elf = dir.path().join("program.bin"); std::fs::write(&elf, [0u8; 8]).unwrap(); @@ -2900,18 +3155,24 @@ mod tests { } #[test] - fn up_refuses_a_lez_tag_outside_v0_3_before_saving_anything() { + fn up_refuses_a_lez_tag_outside_v0_4_before_saving_anything() { let dir = tempfile::tempdir().unwrap(); let home = Home::locate(Some(dir.path().into())).unwrap(); - let opts = UpOptions { - lez: Some("v0.4.0-rc3".into()), - ..UpOptions::default() + let up = |lez: &str| { + let opts = UpOptions { + lez: Some(lez.into()), + ..UpOptions::default() + }; + Devnet::open(home.clone(), None) + .unwrap() + .up(&opts) + .unwrap_err() + .to_string() }; - let err = Devnet::open(home.clone(), None) - .unwrap() - .up(&opts) - .unwrap_err(); - assert!(err.to_string().contains("--lez v0.3.1"), "{err}"); + let err = up("v0.5.0"); + assert!(err.contains(&format!("--lez {DEFAULT_LEZ}")), "{err}"); + let err = up("v0.3.1"); + assert!(err.contains("v0.9.4"), "{err}"); assert!(!home.settings_file().exists(), "nothing saved"); } @@ -2920,15 +3181,16 @@ mod tests { let dir = tempfile::tempdir().unwrap(); let home = Home::locate(Some(dir.path().into())).unwrap(); std::fs::create_dir_all(home.chain_dir().join("rocksdb-0101")).unwrap(); + home.record_chain_lez(DEFAULT_LEZ).unwrap(); let opts = UpOptions { - lez: Some("v0.3.9".into()), + lez: Some("v0.4.9".into()), ..UpOptions::default() }; let err = Devnet::open(home.clone(), None) .unwrap() .up(&opts) .unwrap_err(); - assert!(err.to_string().contains("reset --lez v0.3.9"), "{err}"); + assert!(err.to_string().contains("reset --lez v0.4.9"), "{err}"); assert!(!home.settings_file().exists(), "nothing saved"); } diff --git a/src/doctor.rs b/src/doctor.rs index ff23099..ccfd662 100644 --- a/src/doctor.rs +++ b/src/doctor.rs @@ -195,6 +195,15 @@ pub fn run(devnet: &Devnet, project_error: Option<&anyhow::Error>) -> Doctor { } } + if devnet.refuses_sessions() { + checks.push(Check { + name: "sessions".into(), + ok: false, + detail: crate::devnet::SESSIONS_WAIT.into(), + fix: None, + }); + } + if devnet.wants_hub() { checks.push(match devnet.check_hub_ports() { Ok(()) => pass("hub ports", "free, or held by the running hub"), diff --git a/src/groups.rs b/src/groups.rs index e7e2895..ea5de77 100644 --- a/src/groups.rs +++ b/src/groups.rs @@ -65,6 +65,23 @@ pub struct GroupAccount { pub id: PublicId, /// Hex, the form `lez_core` takes. pub hex: String, + /// Its public key, in hex: what genesis funds, and `send --to-pk` pays. + pub key: String, +} + +impl GroupAccount { + /// Its public key, once checked to name this account: genesis and payments by key would + /// otherwise fund another. + pub fn checked_key(&self) -> Result<&str> { + if PublicId::of_key(&self.key)? != self.id { + anyhow::bail!( + "{} has a public key in accounts.json that names another account: delete its \ + group, and `up` makes it again", + self.id.wallet_form() + ); + } + Ok(&self.key) + } } #[derive(Debug, Clone)] @@ -125,15 +142,21 @@ impl Group { write_json(&self.manifest(), &serde_json::to_value(info)?) } - /// `info` with `ids` appended, numbered after the accounts it has. - pub fn extended(mut info: GroupInfo, ids: Vec) -> GroupInfo { + /// `info` with `accounts` (each id with its public key) appended, numbered after the + /// accounts it has. + pub fn extended(mut info: GroupInfo, accounts: Vec<(PublicId, String)>) -> GroupInfo { let start = info.accounts.len(); - info.accounts - .extend(ids.into_iter().enumerate().map(|(i, id)| GroupAccount { - index: start + i, - hex: id.hex(), - id, - })); + info.accounts.extend( + accounts + .into_iter() + .enumerate() + .map(|(i, (id, key))| GroupAccount { + index: start + i, + hex: id.hex(), + id, + key, + }), + ); info } } @@ -159,10 +182,27 @@ mod tests { const A: &str = "HpavNGFYxjyhLsy171aXsvv146yUeXmRWiho22uvT43d"; const B: &str = "6YvesSEDWW25kpi8SSki2c8o5m3uACsigvGnNQ6wMruh"; + #[test] + fn trusts_a_recorded_key_only_when_it_names_its_account() { + let secret = "01".repeat(32); + let key = crate::account::public_key_of(&secret).unwrap(); + let id = PublicId::of_key(&key).unwrap(); + let info = Group::extended(GroupInfo::default(), vec![(id, key.clone())]); + assert_eq!(info.accounts[0].checked_key().unwrap(), key); + let wrong = Group::extended( + GroupInfo::default(), + vec![(PublicId::parse(A).unwrap(), key)], + ); + assert!(wrong.accounts[0].checked_key().is_err()); + } + #[test] fn numbers_new_accounts_after_the_existing_ones() { - let one = Group::extended(GroupInfo::default(), vec![PublicId::parse(A).unwrap()]); - let two = Group::extended(one, vec![PublicId::parse(B).unwrap()]); + let one = Group::extended( + GroupInfo::default(), + vec![(PublicId::parse(A).unwrap(), "aa".to_owned())], + ); + let two = Group::extended(one, vec![(PublicId::parse(B).unwrap(), "bb".to_owned())]); assert_eq!(two.accounts[0].index, 0); assert_eq!(two.accounts[1].index, 1); assert_eq!(two.accounts[1].id.as_str(), B); @@ -179,7 +219,7 @@ mod tests { amount: 5, ..GroupInfo::default() }, - vec![PublicId::parse(A).unwrap()], + vec![(PublicId::parse(A).unwrap(), "aa".to_owned())], ); group.save_info(&info).unwrap(); assert_eq!(group.info().unwrap(), info); diff --git a/src/home.rs b/src/home.rs index 753b6ac..bfb5948 100644 --- a/src/home.rs +++ b/src/home.rs @@ -25,34 +25,47 @@ use serde_json::Value; use crate::account::PublicId; -/// The LEZ release `lez_core` 0.5.1 is built on, which the public testnet runs. Bump with the -/// testnet; the image workflow builds this tag when it changes. -pub const DEFAULT_LEZ: &str = "v0.3.1"; +/// The LEZ release the devnet runs unless asked for another v0.4 tag. Bump with LEZ's releases; +/// the image workflow builds this tag when it changes. +pub const DEFAULT_LEZ: &str = "v0.4.0-rc3"; const IMAGE_REPO: &str = "ghcr.io/drptbl/logos-devnet-sequencer"; const DEFAULT_PORT: u16 = 3040; const DEFAULT_BLOCK_TIME: &str = "1s"; -/// Upstream's debug config allows 20 transactions per block. +/// Upstream's local config allows 20 transactions per block. pub const DEFAULT_MAX_TXS_PER_BLOCK: u32 = 20; /// The sequencer's log filter (`RUST_LOG`): its own progress, without its actor framework's. pub const DEFAULT_LOG_FILTER: &str = "info,kameo=warn"; -/// A LEZ tag logos-devnet runs: one of the v0.3 line, e.g. `v0.3.1`. LEZ v0.4 changes the -/// sequencer's config and commands, the wallet's format and how accounts are funded. +/// A LEZ tag logos-devnet runs: one of the v0.4 line, e.g. `v0.4.0-rc3`. pub fn check_lez(tag: &str) -> Result<()> { - let patch = tag.strip_prefix("v0.3.").unwrap_or_default(); - let numbered = patch - .split(['-', '.']) - .next() - .is_some_and(|n| !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit())); - if !numbered { + if is_v0_3(tag) { + anyhow::bail!("{tag} is a LEZ v0.3 tag. {V0_3_RELEASE}"); + } + if !numbered(tag, "v0.4.") { anyhow::bail!( - "logos-devnet runs LEZ v0.3 tags, and {tag} isn't one: use `--lez {DEFAULT_LEZ}` or \ - another v0.3 tag. LEZ v0.4 changes the sequencer and wallet, and isn't supported yet" + "logos-devnet runs LEZ v0.4 tags, and {tag} isn't one: use `--lez {DEFAULT_LEZ}`" ); } Ok(()) } +/// Where LEZ v0.3 lives on. +pub const V0_3_RELEASE: &str = "logos-devnet runs LEZ v0.4 since v0.10.0, and v0.9.4 is the last \ + release that runs v0.3: `cargo install --locked logos-devnet --version 0.9.4`, or \ + https://github.com/drptbl/logos-devnet/releases/tag/v0.9.4"; + +/// Whether `tag` is a LEZ v0.3 tag, which homes from before v0.10.0 ran. +pub fn is_v0_3(tag: &str) -> bool { + numbered(tag, "v0.3.") +} + +/// Whether `tag` is `prefix` and a patch number, with any suffix, e.g. `v0.4.` and `0-rc3`. +fn numbered(tag: &str, prefix: &str) -> bool { + tag.strip_prefix(prefix) + .and_then(|patch| patch.split(['-', '.']).next()) + .is_some_and(|n| !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit())) +} + /// A log filter the sequencer takes: `RUST_LOG` syntax, e.g. `debug` or /// `info,sequencer_core=debug`. pub fn check_log_filter(filter: &str) -> Result<()> { @@ -208,6 +221,15 @@ impl Home { pub fn chain_config(&self) -> PathBuf { self.chain_dir().join("sequencer_config.json") } + /// The config a new LEZ v0.4 chain is set up from; `setup` copies it to `chain_config`. + pub fn setup_template(&self) -> PathBuf { + self.chain_dir().join("setup-template.json") + } + /// Whether a LEZ v0.4 chain here has been set up. `setup` writes its channel signing key, + /// then this file, then the config, which `up` writes again anyway. + pub fn chain_set_up(&self) -> bool { + self.chain_dir().join("bedrock_funding_public_key").exists() + } /// The chain's own record of its dev mode, which `reset` deletes with it. fn chain_dev_mode_file(&self) -> PathBuf { self.chain_dir().join("dev-mode") @@ -225,6 +247,21 @@ impl Home { let value = crate::envfile::dev_mode_value(dev_mode); std::fs::write(&file, value).with_context(|| format!("writing {}", file.display())) } + + /// The LEZ tag the chain here runs, kept with the chain like its dev mode: a lost or edited + /// settings file would read as the default tag, and v0.3 and v0.4 can't run each other's + /// chain. Chains from before v0.10.0 have none. + pub fn chain_lez(&self) -> Option { + std::fs::read_to_string(self.chain_dir().join("lez")) + .ok() + .map(|tag| tag.trim().to_owned()) + .filter(|tag| !tag.is_empty()) + } + + pub fn record_chain_lez(&self, tag: &str) -> Result<()> { + let file = self.chain_dir().join("lez"); + std::fs::write(&file, tag).with_context(|| format!("writing {}", file.display())) + } pub fn wallet_dir(&self) -> PathBuf { self.root.join("wallet") } @@ -237,6 +274,52 @@ impl Home { pub fn sessions_dir(&self) -> PathBuf { self.root.join("sessions") } + + /// Whether the chain here ran LEZ v0.3: its own record says so, or it has none and either + /// the settings (`settings_lez`) say so or it was never set up the way v0.4 chains are. + pub fn runs_v0_3(&self, settings_lez: &str) -> bool { + match self.chain_lez() { + Some(tag) => is_v0_3(&tag), + None => is_v0_3(settings_lez) || (self.has_chain() && !self.chain_set_up()), + } + } + + /// Moves a LEZ v0.3 home's wallets aside, to `-v0.3/`, so a v0.4 chain starts its own: + /// a v0.4 wallet can't read v0.3 storage. Nothing is deleted or overwritten, and a home moved + /// once isn't moved again, so a `reset` that fails later can run again. Returns the + /// directories moved. + pub fn move_v0_3_aside(&self) -> Result> { + let done = self.root.join("moved-v0.3"); + if done.exists() { + return Ok(Vec::new()); + } + let dirs = ["wallet", "accounts", "sessions"] + .map(|dir| (self.root.join(dir), self.root.join(format!("{dir}-v0.3")))); + for (from, to) in &dirs { + if from.exists() && to.exists() { + anyhow::bail!( + "{} and {} both exist: move one of them elsewhere, then `reset` again", + from.display(), + to.display() + ); + } + } + let mut moved = Vec::new(); + for (from, to) in &dirs { + if from.exists() { + std::fs::rename(from, to) + .with_context(|| format!("moving {} to {}", from.display(), to.display()))?; + moved.push( + to.file_name() + .unwrap_or_default() + .to_string_lossy() + .into_owned(), + ); + } + } + std::fs::write(&done, "").with_context(|| format!("writing {}", done.display()))?; + Ok(moved) + } pub fn groups_dir(&self) -> PathBuf { self.root.join("accounts") } @@ -365,24 +448,80 @@ mod tests { use super::*; #[test] - fn runs_only_lez_v0_3_tags() { - for tag in ["v0.3.1", "v0.3.2", "v0.3.10", "v0.3.2-rc1"] { + fn runs_lez_v0_4_tags_and_points_v0_3_at_its_last_release() { + for tag in ["v0.4.0-rc3", "v0.4.0", "v0.4.12"] { assert!(check_lez(tag).is_ok(), "{tag}"); } - for tag in [ - "v0.4.0-rc3", - "v0.4.0", - "v0.3", - "v0.3.", - "v0.3.x", - "0.3.1", - "main", - ] { + for tag in ["v0.3.1", "v0.3.2-rc1"] { + let err = check_lez(tag).unwrap_err().to_string(); + assert!(err.contains("v0.9.4"), "{err}"); + } + for tag in ["v0.5.0", "v0.4", "v0.4.", "v0.4.x", "0.4.0", "main"] { assert!(check_lez(tag).is_err(), "{tag}"); } assert!(check_lez(DEFAULT_LEZ).is_ok()); } + #[test] + fn a_v0_4_chain_is_set_up_once_setup_wrote_its_funding_key() { + let dir = tempfile::tempdir().unwrap(); + let home = Home::locate(Some(dir.path().to_path_buf())).unwrap(); + std::fs::create_dir_all(home.chain_dir()).unwrap(); + // `setup` writes the channel key first: stopped there, it must run again. + std::fs::write(home.chain_dir().join("channel_signing_key"), "k").unwrap(); + assert!(!home.chain_set_up()); + std::fs::write(home.chain_dir().join("bedrock_funding_public_key"), "f").unwrap(); + assert!(home.chain_set_up()); + } + + #[test] + fn moves_a_v0_3_homes_wallets_aside_once() { + let dir = tempfile::tempdir().unwrap(); + let home = Home::locate(Some(dir.path().to_path_buf())).unwrap(); + for d in ["wallet", "accounts", "sessions"] { + std::fs::create_dir_all(home.root().join(d)).unwrap(); + std::fs::write(home.root().join(d).join("data"), "v0.3").unwrap(); + } + assert_eq!( + home.move_v0_3_aside().unwrap(), + ["wallet-v0.3", "accounts-v0.3", "sessions-v0.3"] + ); + let kept = home.root().join("accounts-v0.3/data"); + assert_eq!(std::fs::read_to_string(&kept).unwrap(), "v0.3"); + // A `reset` that failed after the move runs again: v0.4's own groups stay where they are. + std::fs::create_dir_all(home.groups_dir()).unwrap(); + assert!(home.move_v0_3_aside().unwrap().is_empty()); + assert!(home.groups_dir().exists()); + assert_eq!(std::fs::read_to_string(kept).unwrap(), "v0.3"); + } + + #[test] + fn refuses_to_move_over_an_earlier_move() { + let dir = tempfile::tempdir().unwrap(); + let home = Home::locate(Some(dir.path().to_path_buf())).unwrap(); + for d in ["wallet", "wallet-v0.3"] { + std::fs::create_dir_all(home.root().join(d)).unwrap(); + } + let err = home.move_v0_3_aside().unwrap_err().to_string(); + assert!(err.contains("both exist"), "{err}"); + assert!(home.wallet_dir().exists()); + } + + #[test] + fn tells_a_v0_3_chain_from_a_v0_4_one() { + let dir = tempfile::tempdir().unwrap(); + let home = Home::locate(Some(dir.path().to_path_buf())).unwrap(); + assert!(!home.runs_v0_3(DEFAULT_LEZ)); + assert!(home.runs_v0_3("v0.3.1"), "the settings say so"); + // A chain with neither a record nor v0.4's setup, its settings lost. + std::fs::create_dir_all(home.chain_dir().join("rocksdb-0101")).unwrap(); + assert!(home.runs_v0_3(DEFAULT_LEZ)); + std::fs::write(home.chain_dir().join("bedrock_funding_public_key"), "f").unwrap(); + assert!(!home.runs_v0_3(DEFAULT_LEZ)); + home.record_chain_lez("v0.3.1").unwrap(); + assert!(home.runs_v0_3(DEFAULT_LEZ), "its own record wins"); + } + #[test] fn refuses_an_empty_log_filter() { assert!(check_log_filter("debug").is_ok()); @@ -533,7 +672,7 @@ mod tests { fn names_the_image_by_lez_tag() { assert_eq!( Settings::default().image(), - "ghcr.io/drptbl/logos-devnet-sequencer:v0.3.1" + "ghcr.io/drptbl/logos-devnet-sequencer:v0.4.0-rc3" ); assert_eq!(Settings::default().sequencer_url(), "http://127.0.0.1:3040"); } diff --git a/src/main.rs b/src/main.rs index 79217e2..4cf8926 100644 --- a/src/main.rs +++ b/src/main.rs @@ -3,7 +3,7 @@ use std::path::PathBuf; use anyhow::Result; -use clap::{Parser, Subcommand}; +use clap::{CommandFactory, FromArgMatches, Parser, Subcommand}; mod account; mod binary; @@ -24,7 +24,7 @@ mod storage; mod wallet_storage; use devnet::{DEFAULT_FUND, Devnet, UpOptions}; -use home::Home; +use home::{DEFAULT_LEZ, Home}; use project::Project; use report::emit; @@ -69,6 +69,10 @@ enum Command { /// Lepta to send. #[arg(default_value_t = u128::from(DEFAULT_FUND))] amount: u128, + /// The account's public key, in hex: LEZ v0.4 pays an account it has never seen only + /// by its key. + #[arg(long)] + key: Option, }, /// Deploy a program binary, and add `LOGOS_PROGRAM_` to the env file. Deploy { @@ -202,7 +206,12 @@ impl Command { } fn main() -> Result<()> { - let cli = Cli::parse(); + // The LEZ release it runs comes with the version, so which logos-devnet goes with which LEZ + // is one command away. + let version: &'static str = + Box::leak(format!("{} (LEZ {})", env!("CARGO_PKG_VERSION"), DEFAULT_LEZ).into_boxed_str()); + let matches = Cli::command().version(version).get_matches(); + let cli = Cli::from_arg_matches(&matches).unwrap_or_else(|e| e.exit()); let json = cli.json; let project_file = match cli.config { Some(path) => Some(path), @@ -242,7 +251,11 @@ fn main() -> Result<()> { } Ok(()) } - Command::Fund { account, amount } => emit(&devnet.fund(&account, amount)?, json), + Command::Fund { + account, + amount, + key, + } => emit(&devnet.fund(&account, amount, key.as_deref())?, json), Command::Deploy { name, elf, mutable } => emit(&devnet.deploy(&name, &elf, mutable)?, json), Command::Accounts(command) => match command { AccountsCommand::New { diff --git a/src/project.rs b/src/project.rs index 706eb0d..4b164b1 100644 --- a/src/project.rs +++ b/src/project.rs @@ -7,6 +7,7 @@ //! [devnet] # optional: the same settings as `up`'s flags //! block_time = "1s" //! max_txs_per_block = 100 +//! upstream_accounts = true # also fund LEZ's own genesis accounts on a new chain //! //! [programs] # name = guest binary, relative to this file //! counter = "target/riscv32im-risc0-zkvm-elf/docker/counter.bin" @@ -114,6 +115,10 @@ pub struct DevnetSection { pub max_txs_per_block: Option, pub dev_mode: Option, pub log_filter: Option, + /// Keep LEZ's own genesis accounts, whose keys are published, funded too on a new chain: + /// LEZ's examples and tools fund themselves from them. Not a setting `up` keeps: only a + /// new chain's genesis reads it. + pub upstream_accounts: Option, } impl DevnetSection { @@ -326,6 +331,15 @@ mod tests { assert!(project_in(dir.path(), "[messaging]\nport = 1\n").is_err()); } + #[test] + fn can_keep_upstreams_genesis_accounts() { + let dir = tempfile::tempdir().unwrap(); + let project = project_in(dir.path(), "[devnet]\nupstream_accounts = true\n").unwrap(); + assert_eq!(project.devnet.upstream_accounts, Some(true)); + let project = project_in(dir.path(), "").unwrap(); + assert_eq!(project.devnet.upstream_accounts, None); + } + #[test] fn reads_every_section_and_resolves_paths_against_the_file() { let dir = tempfile::tempdir().unwrap(); diff --git a/src/report.rs b/src/report.rs index 6609653..80992bc 100644 --- a/src/report.rs +++ b/src/report.rs @@ -404,7 +404,7 @@ mod tests { #[test] fn status_fields_are_stable() { let status = Status { - lez: "v0.3.1".into(), + lez: "v0.4.0-rc3".into(), runtime: "docker".into(), sequencer: Sequencer { url: "http://127.0.0.1:3040".into(), @@ -476,7 +476,7 @@ mod tests { #[test] fn a_runtime_that_didnt_answer_leaves_the_sequencer_unknown() { let status = Status { - lez: "v0.3.1".into(), + lez: "v0.4.0-rc3".into(), runtime: "docker".into(), sequencer: Sequencer { url: "http://127.0.0.1:3040".into(), diff --git a/src/rpc.rs b/src/rpc.rs index 1524b77..67ef1ef 100644 --- a/src/rpc.rs +++ b/src/rpc.rs @@ -71,7 +71,8 @@ impl Rpc { .with_context(|| format!("getTransaction returned {value}")) } - /// An account's state: its `nonce` and its `data` shards, by program id. + /// An account's state: its `nonce` and its `data.actor_states` by program id, or null for an + /// account never used. pub fn account(&self, account: &PublicId) -> Result { self.call("getAccount", json!([account.as_str()])) } @@ -87,11 +88,13 @@ fn result_of(reply: Value, method: &str) -> Result { .with_context(|| format!("{method} returned no result: {reply}")) } +/// Whether `getAccount`'s answer is an account in use: it sent something, or a program keeps +/// data in it, its balance included. It answers null for an account never used. pub(crate) fn in_use(account: &Value) -> bool { let nonce = account["nonce"].as_u64().unwrap_or(0); - let has_data = account["data"]["shards"] + let has_data = account["data"]["actor_states"] .as_object() - .is_some_and(|shards| !shards.is_empty()); + .is_some_and(|data| !data.is_empty()); nonce > 0 || has_data } @@ -137,10 +140,12 @@ mod tests { #[test] fn tells_a_deployed_header_from_a_fresh_account() { - // As the sequencer answered getAccount for a header and an unused account. - let header = json!({ "nonce": 1, "data": { "shards": { "JAQ5": [29, 100] } } }); - let fresh = json!({ "nonce": 0, "data": { "shards": {} } }); - assert!(in_use(&header)); + // As the sequencer answers getAccount for a header, a funded account and unused ones. + let header = json!({ "nonce": 1, "data": { "actor_states": { "JAQ5": [29, 100] } } }); + let funded = json!({ "nonce": 0, "data": { "actor_states": { "P": [1] } } }); + let fresh = json!({ "nonce": 0, "data": { "actor_states": {} } }); + assert!(in_use(&header) && in_use(&funded)); assert!(!in_use(&fresh)); + assert!(!in_use(&Value::Null), "an account never used"); } } diff --git a/src/runtime/docker.rs b/src/runtime/docker.rs index 32d9436..c6b6f41 100644 --- a/src/runtime/docker.rs +++ b/src/runtime/docker.rs @@ -212,6 +212,26 @@ impl Runtime for Docker { stdout_of(self.compose().args(["up", "--detach", "sequencer"])).map(drop) } + fn setup_chain(&self) -> Result<()> { + self.write_compose_file()?; + let template = format!("{CHAIN_MOUNT}/{}", file_name(&self.home.setup_template())); + stdout_of( + self.compose() + .args([ + "run", + "--rm", + "--no-deps", + "-T", + "--interactive=false", + "sequencer", + ]) + .arg("sequencer_service") + .args(super::setup_args(CHAIN_MOUNT, &template)), + ) + .map(drop) + .context("setting the chain up") + } + /// Takes the project down whatever state its containers are in (running, paused, /// restarting). Only an unreachable Docker counts as nothing to stop. fn stop(&self) -> Result<()> { @@ -282,6 +302,13 @@ impl Runtime for Docker { } } +/// The last part of `path`. +fn file_name(path: &Path) -> String { + path.file_name() + .map(|name| name.to_string_lossy().into_owned()) + .unwrap_or_default() +} + /// `logos-devnet` for the default home, and a name derived from the path for any other, so /// two homes never share containers. fn compose_project(home: &Home) -> String { @@ -370,17 +397,20 @@ struct ComposeInputs<'a> { /// The compose file. The RPC is published on loopback only: it has no caller auth. fn compose_spec(i: &ComposeInputs) -> Value { + let command = json!([ + "sequencer_service", + "start", + CHAIN_MOUNT, + "--rpc-listen-address", + format!("0.0.0.0:{CONTAINER_PORT}") + ]); json!({ "name": i.project, "services": { "sequencer": { "image": i.image, "user": i.user, - "command": [ - "sequencer_service", - format!("{CHAIN_MOUNT}/sequencer_config.json"), - "--port", CONTAINER_PORT.to_string() - ], + "command": command, "ports": [format!("127.0.0.1:{}:{CONTAINER_PORT}", i.port)], // The long form takes any path, `:` included. "volumes": [{ @@ -399,7 +429,9 @@ fn compose_spec(i: &ComposeInputs) -> Value { "user": i.user, "profiles": ["tools"], "entrypoint": ["wallet"], - "environment": { "LEE_WALLET_HOME_DIR": WALLET_MOUNT } + // The wallet asks for a password on the terminal unless this is set, and an + // empty one keeps its storage unencrypted. + "environment": { "LEE_WALLET_HOME_DIR": WALLET_MOUNT, "LEE_WALLET_PASSWORD": "" } } } }) @@ -412,7 +444,7 @@ mod tests { fn inputs() -> ComposeInputs<'static> { ComposeInputs { project: "logos-devnet", - image: "ghcr.io/drptbl/logos-devnet-sequencer:v0.3.1", + image: "ghcr.io/drptbl/logos-devnet-sequencer:v0.4.0-rc3", port: 3040, user: "501:20", chain_dir: "/Users/me/My Devnet/chain", @@ -421,6 +453,26 @@ mod tests { } } + #[test] + fn the_sequencer_starts_from_its_home() { + let spec = compose_spec(&inputs()); + assert_eq!( + spec["services"]["sequencer"]["command"], + json!([ + "sequencer_service", + "start", + "/devnet/chain", + "--rpc-listen-address", + "0.0.0.0:3040" + ]) + ); + // The wallet asks for a password on the terminal unless this is set; empty is none. + assert_eq!( + spec["services"]["wallet"]["environment"]["LEE_WALLET_PASSWORD"], + "" + ); + } + #[test] fn the_sequencer_skips_proof_checks_only_in_dev_mode() { let spec = compose_spec(&inputs()); @@ -513,7 +565,6 @@ mod tests { "target": "/devnet/chain" }]) ); - assert_eq!(seq["command"][1], "/devnet/chain/sequencer_config.json"); let wallet = &spec["services"]["wallet"]; assert_eq!(wallet["user"], "501:20"); assert_eq!( diff --git a/src/runtime/mod.rs b/src/runtime/mod.rs index 507f33c..c48169e 100644 --- a/src/runtime/mod.rs +++ b/src/runtime/mod.rs @@ -66,6 +66,9 @@ pub trait Runtime { /// Starts the sequencer on the config in the chain directory. Returns once it is launched, /// not once it serves. fn start(&self) -> Result<()>; + /// Sets a new chain's home up from the config at `Home::setup_template` (see `setup_args`): + /// its config, channel signing key and funding key file. + fn setup_chain(&self) -> Result<()>; /// Stops the sequencer if it runs. fn stop(&self) -> Result<()>; /// Whether the sequencer runs. False when the runtime can't be asked (Docker is down). @@ -94,6 +97,26 @@ pub trait Runtime { fn last_log_line(&self) -> Option; } +/// The Bedrock funding public key `setup` takes: the one LEZ's own local recipes use. A standalone +/// sequencer has no Bedrock node, so nothing ever pays with it. +pub const FUNDING_KEY: &str = "2e03b2eff5a45478e7e79668d2a146cf2c5c7925bce927f2b1c67f2ab4fc0d26"; + +/// `sequencer_service`'s arguments that set a chain `home` up from `template`, with the +/// template's genesis, so the first `start` creates the channel. +pub(crate) fn setup_args(home: &str, template: &str) -> Vec { + [ + "setup", + home, + "--config", + template, + "--funding-public-key", + FUNDING_KEY, + "--create-channel", + ] + .map(str::to_owned) + .to_vec() +} + /// A sequencer log line without the time it starts with, `[2026-11-15T18:45:51Z INFO ...`, so /// a line repeated later reads the same. pub(crate) fn log_line_text(line: &str) -> String { @@ -360,6 +383,22 @@ fn combined(output: &Output) -> String { mod tests { use super::*; + #[test] + fn sets_a_v0_4_chain_up_from_a_template() { + assert_eq!( + setup_args("/devnet/chain", "/devnet/chain/setup-template.json"), + [ + "setup", + "/devnet/chain", + "--config", + "/devnet/chain/setup-template.json", + "--funding-public-key", + FUNDING_KEY, + "--create-channel", + ] + ); + } + #[test] fn a_log_line_without_its_time() { let at = |t: &str| { diff --git a/src/runtime/native.rs b/src/runtime/native.rs index 84bf5e8..73ed45e 100644 --- a/src/runtime/native.rs +++ b/src/runtime/native.rs @@ -114,20 +114,15 @@ impl Runtime for Native { .args(["build", "--release", "-p", package]); cmd }; - // Two builds: in one, `prove` would reach the wallet too, which then links the prover - // kernels that RISC0_SKIP_BUILD_KERNELS leaves out. - run_building( - cargo("sequencer_service") - .env("RISC0_SKIP_BUILD_KERNELS", "1") - .args(["--features", SEQUENCER_FEATURES]), - )?; + // Two builds, so `prove` stays out of the wallet binary. The sequencer links the wallet, + // whose prover needs risc0's CPU kernels, so they're built. + run_building(cargo("sequencer_service").args(["--features", SEQUENCER_FEATURES]))?; run_building(&mut cargo("wallet")) } fn upstream_config(&self) -> Result { - let path = find_debug_config(&self.src()).context( - "the LEZ checkout has no sequencer/service/configs/debug/sequencer_config.json", - )?; + let path = find_upstream_config(&self.src()) + .context("the LEZ checkout has no sequencer/service/networks/local.json")?; let text = std::fs::read_to_string(&path)?; serde_json::from_str(&text).with_context(|| format!("{} is not JSON", path.display())) } @@ -153,10 +148,12 @@ impl Runtime for Native { .create(true) .append(true) .open(self.log_file())?; - let child = Command::new(self.bin("sequencer_service")) - .arg(self.home.chain_config()) - .args(["--listen-address", "127.0.0.1", "--port"]) - .arg(self.settings.port.to_string()) + let mut cmd = Command::new(self.bin("sequencer_service")); + cmd.arg("start") + .arg(self.home.chain_dir()) + .arg("--rpc-listen-address") + .arg(format!("127.0.0.1:{}", self.settings.port)); + let child = without_sequencer_vars(&mut cmd) .current_dir(self.home.chain_dir()) .envs(sequencer_env( self.settings.dev_mode, @@ -173,6 +170,17 @@ impl Runtime for Native { Ok(()) } + fn setup_chain(&self) -> Result<()> { + let args = super::setup_args( + &self.home.chain_dir().to_string_lossy(), + &self.home.setup_template().to_string_lossy(), + ); + let mut cmd = Command::new(self.bin("sequencer_service")); + stdout_of(without_sequencer_vars(&mut cmd).args(args)) + .map(drop) + .context("setting the chain up") + } + fn stop(&self) -> Result<()> { let Some(pid) = self.live_pid() else { let _ = std::fs::remove_file(self.pid_file()); @@ -202,6 +210,7 @@ impl Runtime for Native { all_output_of( Command::new(self.bin("wallet")) .env("LEE_WALLET_HOME_DIR", home) + .env("LEE_WALLET_PASSWORD", "") .args(args), ) .map(|out| redact_recovery_phrase(&out)) @@ -213,6 +222,7 @@ impl Runtime for Native { let out = all_output_of( Command::new("sh") .env("LEE_WALLET_HOME_DIR", home) + .env("LEE_WALLET_PASSWORD", "") .arg("-c") .arg(script), ) @@ -234,6 +244,17 @@ impl Runtime for Native { } } +/// `cmd` without the `SEQUENCER_*` variables this process has: the sequencer reads each of its +/// flags from one, and a stray one would change the devnet. +fn without_sequencer_vars(cmd: &mut Command) -> &mut Command { + for (var, _) in std::env::vars_os() { + if var.to_string_lossy().starts_with("SEQUENCER_") { + cmd.env_remove(var); + } + } + cmd +} + /// Whether a process's command line (as `ps -o command=` prints it) runs `bin`: it starts /// with that path, then ends or goes on to the arguments. fn runs(command: &str, bin: &Path) -> bool { @@ -242,12 +263,13 @@ fn runs(command: &str, bin: &Path) -> bool { .is_some_and(|rest| rest.is_empty() || rest.starts_with(' ')) } -/// Upstream's debug sequencer config, wherever this tag keeps it. -fn find_debug_config(dir: &Path) -> Option { +/// Upstream's local sequencer config, `sequencer/service/networks/local.json`, wherever in the +/// checkout this tag keeps it. +fn find_upstream_config(dir: &Path) -> Option { let mut stack = vec![(dir.to_path_buf(), 0)]; while let Some((dir, depth)) = stack.pop() { - let file = dir.join("sequencer_config.json"); - if dir.ends_with("sequencer/service/configs/debug") && file.exists() { + let file = dir.join("local.json"); + if dir.ends_with("sequencer/service/networks") && file.exists() { return Some(file); } if depth >= 6 { @@ -269,19 +291,19 @@ mod tests { #[test] fn recognises_only_the_sequencer_binary_itself() { - let bin = Path::new("/h/native/v0.3.1/target/release/sequencer_service"); + let bin = Path::new("/h/native/v0.4.0-rc3/target/release/sequencer_service"); assert!(runs( - "/h/native/v0.3.1/target/release/sequencer_service /h/chain/c.json --port 3040", + "/h/native/v0.4.0-rc3/target/release/sequencer_service /h/chain/c.json --port 3040", bin )); assert!(runs( - "/h/native/v0.3.1/target/release/sequencer_service", + "/h/native/v0.4.0-rc3/target/release/sequencer_service", bin )); for other in [ - "lldb /h/native/v0.3.1/target/release/sequencer_service", - "vim /h/native/v0.3.1/target/release/sequencer_service.rs", - "/h/native/v0.3.1/target/release/sequencer_service_old --port 1", + "lldb /h/native/v0.4.0-rc3/target/release/sequencer_service", + "vim /h/native/v0.4.0-rc3/target/release/sequencer_service.rs", + "/h/native/v0.4.0-rc3/target/release/sequencer_service_old --port 1", ] { assert!(!runs(other, bin), "{other}"); } @@ -302,23 +324,24 @@ mod tests { } #[test] - fn finds_the_debug_config_in_either_layout() { - for layout in ["lez/sequencer/service", "sequencer/service"] { - let dir = tempfile::tempdir().unwrap(); - let debug = dir.path().join(layout).join("configs/debug"); - std::fs::create_dir_all(&debug).unwrap(); - std::fs::write(debug.join("sequencer_config.json"), "{}").unwrap(); - let found = find_debug_config(dir.path()).unwrap(); - assert_eq!(found, debug.join("sequencer_config.json"), "{layout}"); - } + fn finds_the_local_config() { + let dir = tempfile::tempdir().unwrap(); + let networks = dir.path().join("lez/sequencer/service/networks"); + std::fs::create_dir_all(&networks).unwrap(); + std::fs::write(networks.join("testnet.json"), "{}").unwrap(); + std::fs::write(networks.join("local.json"), "{}").unwrap(); + assert_eq!( + find_upstream_config(dir.path()).unwrap(), + networks.join("local.json") + ); } #[test] fn ignores_build_output() { let dir = tempfile::tempdir().unwrap(); - let debug = dir.path().join("target/sequencer/service/configs/debug"); - std::fs::create_dir_all(&debug).unwrap(); - std::fs::write(debug.join("sequencer_config.json"), "{}").unwrap(); - assert!(find_debug_config(dir.path()).is_none()); + let networks = dir.path().join("target/sequencer/service/networks"); + std::fs::create_dir_all(&networks).unwrap(); + std::fs::write(networks.join("local.json"), "{}").unwrap(); + assert!(find_upstream_config(dir.path()).is_none()); } } diff --git a/src/session.rs b/src/session.rs index d32eee1..9491036 100644 --- a/src/session.rs +++ b/src/session.rs @@ -25,8 +25,9 @@ use crate::runtime::{stdout_of, stdout_within}; use crate::wallet_storage; const LEZ_CORE: &str = "lez_core"; -/// The `lez_core` built on LEZ v0.3, the line logos-devnet runs. A later one may be built on -/// LEZ v0.4, whose fees, transactions and built-in programs a v0.3 chain doesn't take. +/// The `lez_core` sessions install. 0.5.1 is built on LEZ v0.3, which logos-devnet no longer +/// runs, so sessions wait (see `devnet::SESSIONS_READY`): this becomes the first `lez_core` +/// built on LEZ v0.4 that the Logos catalog publishes. const LEZ_CORE_VERSION: &str = "0.5.1"; /// How long `stop` waits for a daemon to exit. const STOP_TIMEOUT: Duration = Duration::from_secs(30); diff --git a/src/wallet_storage.rs b/src/wallet_storage.rs index 7f26424..961dfe0 100644 --- a/src/wallet_storage.rs +++ b/src/wallet_storage.rs @@ -40,7 +40,7 @@ type RawObject = BTreeMap; /// The LEZ wallet's state of a fresh account: what every account holds on a new chain. fn fresh_account() -> Result { Ok(RawValue::from_string( - r#"{"nonce":0,"data":{"shards":{}}}"#.into(), + r#"{"nonce":0,"data":{"actor_states":{}}}"#.into(), )?) } @@ -68,10 +68,23 @@ fn edit_member( /// not a guess. fn forget_chain(text: &str) -> Result { let mut storage: RawObject = serde_json::from_str(text)?; + if storage.contains_key("ciphertext") { + anyhow::bail!( + "the wallet's storage is encrypted with a password, so its state from the old chain \ + can't be cleared: make the wallet again without one" + ); + } storage.insert( "last_synced_block".into(), RawValue::from_string("0".into())?, ); + // The block its sync started from, too. + if storage.contains_key("synced_from_block") { + storage.insert( + "synced_from_block".into(), + RawValue::from_string("0".into())?, + ); + } edit_member(&mut storage, "key_chain", |key_chain| { edit_object(key_chain, |key_chain| { edit_member(key_chain, "accounts", |accounts| { @@ -135,7 +148,47 @@ pub fn forget_chain_in(storage: &Path) -> Result<()> { ) })?; replace_file(storage, forgotten.as_bytes()) - .with_context(|| format!("replacing {}", storage.display())) + .with_context(|| format!("replacing {}", storage.display()))?; + // The wallet caches the nullifiers it saw spent next to the storage: the old chain's. + let nullifiers = storage.with_extension("nullifiers"); + match std::fs::remove_file(&nullifiers) { + Err(e) if e.kind() != std::io::ErrorKind::NotFound => { + Err(e).with_context(|| format!("deleting {}", nullifiers.display())) + } + _ => Ok(()), + } +} + +/// The public key, in hex, of the public account `id` in the wallet whose storage is at +/// `storage`: as written for an account the wallet made, or derived from an imported one's +/// private key. Only a key that names `id` counts. `None` when the wallet holds no such account. +pub fn public_key(storage: &Path, id: &crate::account::PublicId) -> Result> { + use crate::account::{PublicId, public_key_of}; + let text = match std::fs::read_to_string(storage) { + Ok(text) => text, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None), + Err(e) => return Err(e).with_context(|| format!("reading {}", storage.display())), + }; + let wallet: serde_json::Value = serde_json::from_str(&text) + .with_context(|| format!("{} is not a LEZ wallet storage", storage.display()))?; + let accounts = wallet["key_chain"]["accounts"] + .as_array() + .into_iter() + .flatten(); + for account in accounts { + let key = if account["Public"]["account_id"] == id.as_str() { + account["Public"]["data"]["pk"].as_str().map(str::to_owned) + } else if account["ImportedPublic"]["account_id"] == id.as_str() { + account["ImportedPublic"]["pub_sign_key"] + .as_str() + .map(public_key_of) + .transpose()? + } else { + continue; + }; + return Ok(key.filter(|key| PublicId::of_key(key).is_ok_and(|of| &of == id))); + } + Ok(None) } /// Replaces `path` with `contents` in one step, keeping its permissions: it never holds half of @@ -172,17 +225,17 @@ pub(crate) mod tests { use super::*; use serde_json::Value; - /// A session's `storage.json` after a chain ran, as the LEZ wallet writes it: synced to - /// block 42, a private account and a shared one holding notes, and an account imported from - /// genesis data whose nonce only fits a u128. + /// A wallet's `storage.json` after a chain ran, in the layout LEZ v0.4.0-rc3's wallet + /// writes: synced to block 42 from block 40, a private account and a shared one holding + /// notes, and an account imported from genesis data whose nonce only fits a u128. pub(crate) const SYNCED_STORAGE: &str = r#"{ "key_chain": { "accounts": [ { "Public": { "account_id": "P", "chain_index": "/0", "data": { "k": [1, 2] } } }, { "Private": { "account_id": "Q", "chain_index": "/0", "data": { "value": [ { "keys": 2 }, [ - [ { "Regular": "111" }, { "nonce": 7, "data": { "shards": { "T": [1, 2] } } } ], - [ { "Regular": "222" }, { "nonce": 3, "data": { "shards": {} } } ] + [ "Regular", { "nonce": 7, "data": { "actor_states": { "T": [1, 2] } } } ], + [ "Regular", { "nonce": 3, "data": { "actor_states": {} } } ] ] ], "ccc": [0], "cci": 0 } } }, { "ImportedPrivate": { "account": { "nonce": 340282366920938463463374607431768211455 } } } @@ -191,10 +244,11 @@ pub(crate) mod tests { "shared_private_accounts": { "S": { "group_label": "g", "identifier": "1", "pda_seed": null, "authority_program_id": null, - "account": { "nonce": 5, "data": { "shards": { "T": [9] } } } } + "account": { "nonce": 5, "data": { "actor_states": { "T": [9] } } } } } }, "last_synced_block": 42, + "synced_from_block": 40, "labels": { "main": { "Public": "P" } } }"#; @@ -207,11 +261,12 @@ pub(crate) mod tests { "{text}" ); let storage: Value = serde_json::from_str(&text).unwrap(); - let fresh = serde_json::json!({ "nonce": 0, "data": { "shards": {} } }); + let fresh = serde_json::json!({ "nonce": 0, "data": { "actor_states": {} } }); assert_eq!(storage["last_synced_block"], 0); + assert_eq!(storage["synced_from_block"], 0); let private = &storage["key_chain"]["accounts"][1]["Private"]["data"]["value"]; assert_eq!(private[0], serde_json::json!({ "keys": 2 }), "keys stay"); - assert_eq!(private[1][0][0], serde_json::json!({ "Regular": "111" })); + assert_eq!(private[1][0][0], "Regular"); assert_eq!(private[1][0][1], fresh); assert_eq!(private[1][1][1], fresh); let shared = &storage["key_chain"]["shared_private_accounts"]["S"]; @@ -220,11 +275,64 @@ pub(crate) mod tests { // Everything else is as it was. let mut expected: Value = serde_json::from_str(SYNCED_STORAGE).unwrap(); expected["last_synced_block"] = 0.into(); + expected["synced_from_block"] = 0.into(); expected["key_chain"]["accounts"][1] = storage["key_chain"]["accounts"][1].clone(); expected["key_chain"]["shared_private_accounts"]["S"]["account"] = fresh; assert_eq!(storage, expected); } + #[test] + fn drops_the_spent_nullifiers_the_wallet_cached() { + let dir = tempfile::tempdir().unwrap(); + let storage = dir.path().join(STORAGE_FILE); + std::fs::write(&storage, SYNCED_STORAGE).unwrap(); + let nullifiers = dir.path().join("storage.nullifiers"); + std::fs::write(&nullifiers, "old chain").unwrap(); + forget_chain_in(&storage).unwrap(); + assert!(!nullifiers.exists()); + } + + #[test] + fn reads_an_accounts_public_key_from_the_wallet() { + let dir = tempfile::tempdir().unwrap(); + let storage = dir.path().join(STORAGE_FILE); + // As LEZ's wallet writes them: a generated account keeps its key as `pk`, an imported + // one its private key as `pub_sign_key`. + let made = "4afc5da3b6acabc4892dddb1e49226599326ae3a6a700828e395b5bc9a4b30ba"; + let text = format!( + r#"{{"key_chain":{{"accounts":[ + {{"Public":{{"account_id":"23cbN9uZbLU1zhcuiZ1qu1eneL8ed8HeHzDEF1br6rEd","chain_index":[0],"data":{{"sk":"x","pk":"{made}"}}}}}}, + {{"ImportedPublic":{{"account_id":"B1UN3hPgxacgHKBRoThcAmsPajGcUf6YXUhgB36x4DAd","pub_sign_key":"{}"}}}} + ]}},"last_synced_block":1}}"#, + "01".repeat(32) + ); + std::fs::write(&storage, text).unwrap(); + let key = |id: &str| public_key(&storage, &crate::account::PublicId::parse(id).unwrap()); + assert_eq!( + key("23cbN9uZbLU1zhcuiZ1qu1eneL8ed8HeHzDEF1br6rEd") + .unwrap() + .as_deref(), + Some(made) + ); + let imported = key("B1UN3hPgxacgHKBRoThcAmsPajGcUf6YXUhgB36x4DAd").unwrap(); + assert_eq!( + imported, + Some(crate::account::public_key_of(&"01".repeat(32)).unwrap()) + ); + assert_eq!( + key("HpavNGFYxjyhLsy171aXsvv146yUeXmRWiho22uvT43d").unwrap(), + None + ); + } + + #[test] + fn refuses_an_encrypted_storage() { + // A wallet with a password keeps its state inside the ciphertext, out of reach. + let sealed = r#"{"version":1,"kdf":{},"nonce":"aa","ciphertext":"bb"}"#; + let err = forget_chain(sealed).unwrap_err(); + assert!(format!("{err:#}").contains("password"), "{err:#}"); + } + #[test] fn forgetting_a_chain_adds_nothing_and_refuses_a_layout_it_doesnt_know() { let bare = r#"{"key_chain":{"accounts":[]},"last_synced_block":9}"#; diff --git a/tests/cli.rs b/tests/cli.rs index d90beeb..d1922f9 100644 --- a/tests/cli.rs +++ b/tests/cli.rs @@ -19,3 +19,23 @@ fn up_says_docker_is_unreachable_instead_of_building() { assert!(stderr.contains("no Docker daemon answers"), "{stderr}"); assert!(!stderr.contains("Building"), "{stderr}"); } + +#[test] +fn the_version_names_the_lez_release_it_runs() { + let out = Command::new(env!("CARGO_BIN_EXE_logos-devnet")) + .arg("--version") + .output() + .unwrap(); + let stdout = String::from_utf8_lossy(&out.stdout); + let home = + std::fs::read_to_string(concat!(env!("CARGO_MANIFEST_DIR"), "/src/home.rs")).unwrap(); + let lez = home + .lines() + .find_map(|l| l.strip_prefix("pub const DEFAULT_LEZ: &str = \"")) + .and_then(|l| l.strip_suffix("\";")) + .unwrap(); + assert_eq!( + stdout.trim(), + format!("logos-devnet {} (LEZ {lez})", env!("CARGO_PKG_VERSION")) + ); +}