Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/heavy-pumas-count.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@cartesi/cli": minor
---

Require cartesi-machine 0.23. Machines stored by 0.22 can't be loaded by 0.23, and the rollups-node and Dave generation the sdk now ships refuses them: rebuild and redeploy every application. `cartesi doctor` applies the same range.
5 changes: 5 additions & 0 deletions .changeset/hungry-books-occur.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@cartesi/cli": minor
---

the contract addresses and ABIs now come from rollups-contracts and dave v3.0.0-beta.1, through wagmi-plugin 1.0.0-alpha.10: every address moves, the devnet ones included, so applications deployed on the previous generation must be rebuilt on cartesi-machine 0.23 and redeployed, and the devnet state the sdk ships moves with them
5 changes: 5 additions & 0 deletions .changeset/quick-games-care.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@cartesi/sdk": minor
---

the runtime image carries the Lua PRT node: `crisium.lua` and the recipe modules it loads, from machine-emulator v0.23.0, at `/opt/cartesi/prt/recipes`, the contract artifacts of dave v3.0.0-beta.1 at `/opt/cartesi/dave`, `cast` for its signatures, `lua-dkjson`, and `/opt/cartesi/prt/store-first-checkpoint.lua`, which stores the checkpoint the player starts epoch 0 from
5 changes: 5 additions & 0 deletions .changeset/soft-snakes-make.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@cartesi/cli": minor
---

export the `[prt]` configuration types from the library: `PrtOptions`, `PrtNode`, `PrtNodeType`, the crisium settings, and `ResolvedPrt` with its node types, which `run({ prt: true })` reads and `RunResult.prtConfig` returns
5 changes: 5 additions & 0 deletions .changeset/sweet-wasps-allow.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@cartesi/cli": minor
---

A `[prt.nodes.<label>]` entry can take `type = "crisium"`: `cartesi run --prt` then runs crisium, the Lua PRT player of the machine-emulator recipes, from the runtime image. As a sentinel (`mode = "sentinel"`, the default) it signs nothing and takes no account, computing the honest claims and reporting what a validator should have done. As a validator (`mode = "validator"`) it claims and disputes with a pool account, a devnet address or `private_key_file`, through a keystore the CLI makes for it, playing `kind = "honest"` (the default) or `"vandal"`, a scripted adversary that posts a made-up claim for epoch 0, loses the dispute and then idles, since only the honest player stores the checkpoints of later epochs. `warning_blocks`, `input_policy` and `dispute_policy` pass through to the player. A crisium node submits no sentry claims, so `sentry = true` is rejected on it.
5 changes: 5 additions & 0 deletions .changeset/swift-memes-wonder.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@cartesi/cli": minor
---

a crisium entry takes `anomaly_handler = "<file>.lua"`: `cartesi run --prt` mounts the file's directory into the node read-only, puts it on `LUA_PATH` after the recipes and passes `--anomaly-handler=<module>`, so the player calls the module's function with each anomaly's kind and message instead of printing it to stderr. The file's name must be a Lua module name. Since its directory is the mount, the module may `require` helpers next to it, and a subdirectory keeps the mount to that directory
28 changes: 28 additions & 0 deletions .github/workflows/cli.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@ on:
pull_request:
paths:
- ".github/workflows/cli.yaml"
- ".github/workflows/sdk.yaml"
- "apps/cli/**"
- "packages/sdk/**"
- "packages/tsconfig/**"
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}-${{ github.event_name }}
Expand All @@ -12,9 +14,17 @@ permissions:
contents: read
packages: write
pull-requests: write
id-token: write
actions: write
jobs:
# the tests run against the images of this PR, so the sdk images build first
sdk:
uses: ./.github/workflows/sdk.yaml
secrets: inherit

build:
runs-on: ubuntu-latest
needs: sdk
env:
TURBO_TOKEN: ${{ secrets.TURBO_TOKEN }}
TURBO_TEAM: ${{ vars.TURBO_TEAM }}
Expand All @@ -28,6 +38,24 @@ jobs:
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1

- name: Login to GitHub Container Registry
uses: docker/login-action@81c6f93d4bc991e510b342a00b419b3bb4efc5c6 # v4.7.0
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}

# the CLI composes cartesi/<image>:<tag> from Docker Hub, so the PR
# images come in under the devel tag the local build uses too
- name: Pull the sdk images of this PR as devel
env:
PR_TAG: pr-${{ github.event.number }}
run: |
for image in sdk rollups-runtime rollups-database; do
docker pull "ghcr.io/cartesi/${image}:${PR_TAG}"
docker tag "ghcr.io/cartesi/${image}:${PR_TAG}" "cartesi/${image}:devel"
done

- uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0

- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
Expand Down
11 changes: 6 additions & 5 deletions .github/workflows/sdk.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,8 @@ on:
required: true
DOCKERHUB_TOKEN:
required: true
pull_request:
paths:
- ".github/workflows/sdk.yaml"
- "packages/sdk/**"
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}-${{ github.event_name }}
group: ${{ github.workflow }}-sdk-${{ github.ref }}-${{ github.event_name }}
cancel-in-progress: true
permissions:
contents: read
Expand Down Expand Up @@ -83,6 +79,11 @@ jobs:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}

# rollups-node has no release for emulator 0.23 yet: the runtime image
# installs the debs of PR 831's build (see the script)
- name: Fetch the rollups-node debs
run: packages/sdk/scripts/fetch-rollups-node.sh

- name: Build and push
uses: docker/bake-action@018cb6412ab401ebaa809aa5f85966b74628600f # v7.4.0
if: ${{ !startsWith(github.ref, 'refs/tags/sdk@') }}
Expand Down
2 changes: 1 addition & 1 deletion apps/cli/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
"viem": "^2.57.3"
},
"devDependencies": {
"@cartesi/wagmi-plugin": "1.0.0-alpha.9",
"@cartesi/wagmi-plugin": "1.0.0-alpha.10",
"@commander-js/extra-typings": "^15.0.0",
"@inquirer/confirm": "^6.3.3",
"@inquirer/core": "^12.0.4",
Expand Down
227 changes: 220 additions & 7 deletions apps/cli/src/compose/prt-node.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
import path from "node:path";
import type { Address } from "viem";
import { anvil } from "viem/chains";
import type { ResolvedPrtNode } from "../prt.js";
import type { ComposeFile, Service } from "../types/compose.js";
import { fileSecret, secretInitService } from "./secrets.js";
import { escapeComposeValue } from "./common.js";
import { fileSecret, RUNTIME_USER, secretInitService } from "./secrets.js";

/**
* The compose services of the PRT nodes the CLI runs: one sling node per
* [prt.nodes.<label>] entry with `type = "sling"`. They are composed after
* the deploy, since each one needs the application's address.
* The compose services of the PRT nodes the CLI runs: a sling node per
* [prt.nodes.<label>] entry with `type = "sling"`, a crisium player per entry
* with `type = "crisium"`. They are composed after the deploy, since each one
* needs the application's address.
*/

export type PrtNodeServiceOptions = {
Expand All @@ -22,9 +25,9 @@ export type PrtNodeServiceOptions = {
export const prtNodeServiceName = (label: string) => `prt-node-${label}`;

/**
* The service that installs an entry's key file. Named outside the nodes'
* `prt-node-` space, since a label may hold a `-`, so no label can produce
* the installer's name of another node.
* The service that installs an entry's key file, or prepares a crisium node's
* data. Named outside the nodes' `prt-node-` space, since a label may hold a
* `-`, so no label can produce the installer's name of another node.
*/
const prtNodeInitServiceName = (label: string) =>
`secret-init-${prtNodeServiceName(label)}`;
Expand All @@ -45,6 +48,55 @@ const DATA_DIR = "/var/lib/cartesi-rollups-node/snapshots";
/** Where the node reads the built machine, the same files the rollups-node deploys. */
const TEMPLATE_DIR = "/var/lib/cartesi-rollups-node/template";

/** The chain as the containers reach it; anvil serves WebSocket on the same port. */
const RPC_URL = "http://anvil:8545";
const WS_URL = "ws://anvil:8545";

/**
* The crisium player and its recipes in the runtime image, and the dave
* contract artifacts it reads (`packages/sdk/Dockerfile`).
*/
const RECIPES_DIR = "/opt/cartesi/prt/recipes";
const DAVE_DIR = "/opt/cartesi/dave";
const CRISIUM = `${RECIPES_DIR}/crisium.lua`;
/**
* Where an entry's anomaly handler is mounted, read-only: the directory of the
* file it names, whole, so the module may `require` helpers next to it. Only
* the node service mounts it; the init service runs no player.
*/
const HANDLER_DIR = "/opt/cartesi/prt/handler";
/**
* The recipes require each other by module name, so lua finds them here. The
* handler's directory comes after them, so no file of it shadows a recipe.
*/
const luaPath = (handler?: string): string =>
`${[RECIPES_DIR, ...(handler === undefined ? [] : [HANDLER_DIR])]
.map((dir) => `${dir}/?.lua`)
.join(";")};;`;
const LUA_PATH = luaPath();

/**
* A crisium node's volume, its data directory: its state and checkpoints, and
* for a validator the keystore cast signs with. The init service fills it, as
* root, and hands it to the runtime user.
*/
const prtNodeDataVolume = (label: string) =>
`prt_node_${label.replaceAll("-", "_")}_data`;
const STATE_DIR = `${DATA_DIR}/state`;
const CHECKPOINTS_DIR = `${DATA_DIR}/checkpoints`;
const KEYSTORE_DIR = `${DATA_DIR}/keystore`;
const PASSWORD_FILE = `${DATA_DIR}/password`;

/**
* The init's helper in the runtime image: stores the checkpoint a crisium node
* starts epoch 0 from, the template with an empty output history, laid out as
* the player's own checkpoints are. It lives next to the recipes it calls,
* since the checkpoint format moves with them.
*/
const INIT_SCRIPT = "/opt/cartesi/prt/store-first-checkpoint.lua";
/** A devnet account's key, for the init service that imports it; public. */
const INIT_KEY_VARIABLE = "PRT_NODE_PRIVATE_KEY";

/** The key of an entry on a devnet account, which resolution always sets. */
const privateKeyOf = (node: ResolvedPrtNode): string => {
if (node.privateKey === undefined) {
Expand Down Expand Up @@ -117,12 +169,173 @@ const sling = (
};
};

/** The player's command line: what the CLI knows, then the entry's settings. */
const crisiumArgs = (
options: PrtNodeServiceOptions,
node: ResolvedPrtNode,
): string[] => {
const { application, blockTime } = options;
const { label } = node;
const settings = node.crisium ?? { mode: "sentinel" };
const validator = settings.mode === "validator";
return [
"lua5.4",
CRISIUM,
`--rpc=${RPC_URL}`,
`--ws=${WS_URL}`,
`--application=${application}`,
`--label=${label}`,
`--poll-interval=${Math.max(1, blockTime)}`,
`--dave=${DAVE_DIR}`,
`--state=${STATE_DIR}`,
`--checkpoints=${CHECKPOINTS_DIR}`,
`--mode=${settings.mode}`,
...(validator
? [
`--kind=${settings.kind ?? "honest"}`,
`--keystore=${KEYSTORE_DIR}/${prtNodeServiceName(label)}`,
`--password-file=${PASSWORD_FILE}`,
]
: []),
...(settings.warningBlocks !== undefined
? [`--warning-blocks=${settings.warningBlocks}`]
: []),
...(settings.inputPolicy !== undefined
? [`--input-policy=${settings.inputPolicy}`]
: []),
...(settings.disputePolicy !== undefined
? [`--dispute-policy=${settings.disputePolicy}`]
: []),
// the file's base name is a module name, so it is safe as an argument
...(settings.anomalyHandler !== undefined
? [
`--anomaly-handler=${path.basename(settings.anomalyHandler, ".lua")}`,
]
: []),
];
};

/** The bind mount of an entry's anomaly handler: its directory, read-only. */
const handlerMount = (handler: string) => ({
type: "bind" as const,
source: escapeComposeValue(path.dirname(handler)),
target: HANDLER_DIR,
read_only: true,
bind: { create_host_path: false },
});

/**
* The service that fills a crisium node's volume before each run: the
* checkpoint of epoch 0 from the template, and for a validator a keystore made
* from its key, with a password drawn here, both for the runtime user only. Its
* command names the application, so a redeploy recreates it and starts the
* volume clean, while a restart keeps the state. Unlike the key file installer
* it needs the chain, for the geometry.
*/
const crisiumInitService = (
options: PrtNodeServiceOptions,
node: ResolvedPrtNode,
secret: ReturnType<typeof fileSecret> | undefined,
): Service => {
const { application, imageTag = "latest" } = options;
const { label } = node;
const service = prtNodeServiceName(label);
const validator = node.crisium?.mode === "validator";
const key =
secret === undefined
? `"$${INIT_KEY_VARIABLE}"`
: `"$(head -n 1 ${secret.source.target} | tr -d '[:space:]')"`;
const command = [
"find /dst -mindepth 1 -delete",
`install -d -o ${RUNTIME_USER} -g ${RUNTIME_USER} /dst/state /dst/checkpoints`,
`lua5.4 ${INIT_SCRIPT} ${RPC_URL} ${application} ${TEMPLATE_DIR}/image ${DAVE_DIR} /dst/checkpoints/epoch-0`,
...(validator
? [
"install -d -m 0700 /dst/keystore",
"od -An -N16 -tx1 /dev/urandom | tr -d ' \\n' > /dst/password",
`cast wallet import ${service} --keystore-dir /dst/keystore --private-key ${key} --unsafe-password "$(cat /dst/password)" > /dev/null`,
]
: []),
`chown -R ${RUNTIME_USER}:${RUNTIME_USER} /dst`,
...(validator
? [`chmod 0400 /dst/keystore/${service} /dst/password`]
: []),
].join("\n");

return {
image: `cartesi/rollups-runtime:${imageTag}`,
user: "root",
restart: "no",
depends_on: { anvil: { condition: "service_healthy" } },
entrypoint: ["sh", "-ec"],
command: [escapeComposeValue(command)],
environment: {
LUA_PATH,
...(validator &&
secret === undefined && {
// a devnet account's key is public, so it can go in the environment
[INIT_KEY_VARIABLE]: privateKeyOf(node),
}),
},
volumes: [
...(secret ? [secret.source] : []),
`./.cartesi:${TEMPLATE_DIR}:ro`,
`${prtNodeDataVolume(label)}:/dst`,
],
};
};

const crisium = (
options: PrtNodeServiceOptions,
node: ResolvedPrtNode,
): ComposeFile => {
const { imageTag = "latest" } = options;
const { label } = node;
const secret =
node.source.kind === "key-file"
? fileSecret(prtNodeServiceName(label), node.source.path)
: undefined;
const handler = node.crisium?.anomalyHandler;

const service: Service = {
image: `cartesi/rollups-runtime:${imageTag}`,
// lua as PID 1 would ignore the stop signal
init: true,
depends_on: {
anvil: { condition: "service_healthy" },
[prtNodeInitServiceName(label)]: {
condition: "service_completed_successfully",
},
},
command: crisiumArgs(options, node),
environment: { LUA_PATH: luaPath(handler) },
volumes: [
`${prtNodeDataVolume(label)}:${DATA_DIR}`,
...(handler === undefined ? [] : [handlerMount(handler)]),
],
};

return {
services: {
[prtNodeServiceName(label)]: service,
[prtNodeInitServiceName(label)]: crisiumInitService(
options,
node,
secret,
),
},
volumes: { [prtNodeDataVolume(label)]: {} },
};
};

/** The compose files of the PRT nodes the CLI runs, one per type it knows. */
export default (options: PrtNodeServiceOptions): ComposeFile[] =>
options.nodes.flatMap((node) => {
switch (node.type) {
case "sling":
return [sling(options, node)];
case "crisium":
return [crisium(options, node)];
default:
return [];
}
Expand Down
4 changes: 3 additions & 1 deletion apps/cli/src/config/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ export const MAX_NVRAMS = 8; // guest exposes nvrams as /dev/uio0 to /dev/uio7

export const DEFAULT_FORMAT = "ext2";
export const DEFAULT_RAM = "128Mi";
export const DEFAULT_SDK_VERSION = "0.12.0-alpha.45";
// the devel tag of the local sdk build (bun run build --filter @cartesi/sdk) while the
// rollups-node of PR 831 has no release: restored to the released version with the wip commit
export const DEFAULT_SDK_VERSION = "devel";
export const DEFAULT_SDK_IMAGE = "cartesi/sdk";
export const PREFERRED_PORT = 6751;
Loading
Loading