# PLASM: globally distributed verifiable WebAssembly compute

**PLASM** (`crates/plasm`, licensed **Apache-2.0**) is Phase's reference WebAssembly compute daemon (`plasmd`) and reusable WASM library (also embedded inside `lucidd` on `main` as a strictly local-only, default-disabled `wasm_engine` with an independent CPU pool and Tor fail-closed guards). It empowers researchers, students, and independent builders who only own a single consumer-grade computer to run deterministic, sandboxed WebAssembly (`JobSpec::Wasm`) compute jobs with cryptographic Ed25519 `verify_strict` receipts verifying what ran and what came back. Trusted Circle remote PLASM dispatch remains an open qualification track; local two-Mac WASM receipt parity is verified on `main` (`7e3547a`).

PLASM runs cross-platform on **macOS**, **Windows**, and **Linux** (`x86_64` and `aarch64`), built on the exact same Phase substrate (`phase-identity`, `phase-manifest`, `phase-receipt`, `phase-protocol`, `phase-net`, and `phase-artifact-server`) that powers LUCID and LUMEN.

## Mission: consumer hardware, verifiable scale

High-throughput scientific and engineering workloads normally require cloud GPU/CPU accounts, institutional cluster allocations, or proprietary schedulers. PLASM takes a different approach:

- **One bytecode target everywhere:** Compile Rust, C, C++, or Zig kernels once to WebAssembly (`wasm32-wasip1`) and execute the identical module across macOS Apple Silicon laptops, Windows desktops, and Linux workstations.
- **No central coordinator or accounts:** Peers discover each other via libp2p (Kademlia DHT, mDNS, Circuit Relay v2, DCUtR, AutoNAT, and Identify) over Noise-encrypted QUIC and TCP transports using persistent Ed25519 `NodeIdentity` keys.
- **Cryptographic provenance by default:** Every job submission is a `SignedManifest<JobSpec>`, every output byte is folded into a SHA-256 `CommitmentAccumulator`, and every completed run emits a `SignedReceipt` signed by the executing peer.

## How verifiable WebAssembly execution works

Inside `crates/plasm`, `WasmtimeWorker` implements the workload-agnostic `phase_protocol::Worker` trait for `JobSpecKind::Wasm`:

1. **Signed manifest submission:** A caller packages a `JobSpec::Wasm(WasmJobSpec)` payload (module CID, WASM payload/input, optional `max_duration_ms`, and `max_memory_bytes`) inside a `SignedManifest<JobSpec>` signed with its Ed25519 `NodeIdentity`.
2. **Signature verification and authorization:** `WasmtimeWorker::execute` calls `job.verify()` to confirm signature integrity, then checks `WorkerSecurityConfig::is_authorized_submitter` against the operator's allowlist. A valid signature proves *who* signed the manifest, never that they are authorized to consume host CPU.
3. **Server-side cap clamping:** Manifest-supplied memory and duration caps are untrusted input. `WasmtimeWorker` clamps every job to `min(manifest_limit, operator_ceiling)` before creating a sandbox.
4. **Isolated Wasmtime 36 LTS execution:** `Wasm3Runtime` runs the module inside a fresh **Wasmtime 36 LTS** (`36.0.24`) `Store` backed by a process-wide Cranelift `Engine`, pre-linked WASI preview1 `Linker`, and a bounded 64-entry SHA-256 compiled-module cache.
5. **Commitment and signed receipt:** Captured output is emitted as an `OutputChunk` folded into `CommitmentAccumulator`, and the worker signs a `SignedReceipt<JobResult>` binding `manifest_hash`, output commitment, chunk count, completion status, and execution metrics. Callers verify the Ed25519 signature and replay `CommitmentAccumulator` over the received bytes.

## `plasmd` CLI reference

`crates/plasm` ships the `plasmd` daemon and three companion Phase Boot artifact utilities (`phase-discover`, `phase-verify`, `phase-fetch`).

| Command | Purpose |
|---|---|
| `plasmd init [--path <FILE>]` | Write a default JSON configuration file (`~/.config/plasm/config.json`) containing `listen_addrs`, `peer_addrs`, and `bootstrap_peers`. |
| `plasmd start [--config <FILE>] [--listen <MULTIADDR>...] [--peer <MULTIADDR>...]` | Load or generate the persistent Ed25519 `NodeIdentity`, bind libp2p listeners, bootstrap Kademlia DHT, advertise node capabilities, and dial configured peers. |
| `plasmd run [--quiet] <WASM_FILE> [ARGS...]` | Execute a local `.wasm` module inside the Wasmtime sandbox for local testing (`--quiet` outputs only module stdout). |
| `plasmd execute-job <WASM_FILE> [ARGS...]` | Hash `<WASM_FILE>` with SHA-256, construct a `JobRequest`, run it through `ExecutionHandler`, and print structured JSON with `job_id`, `exit_code`, `stdout`, `stderr`, and the signed `receipt`. |
| `plasmd compute <WASM_FILE> [--artifacts <DIR>] [--identity <FILE>]` | Execute one explicitly selected local WASM module (only its exact CID is approved; bounded stdin with 5s EOF limit; zero remote artifact fetches) and write JSON with the verified Ed25519 `verify_strict` receipt and exact ordered output chunks. |
| `plasmd serve [--artifacts <DIR>] [--channel <NAME>] [--arch <ARCH>] [--port <PORT>] [--bind <ADDR>] [--no-dht] [--no-mdns]` | Start the content-addressed HTTP artifact provider server (`phase-artifact-server`) with optional DHT and mDNS advertisement. |
| `plasmd provider status [--json] [--addr <URL>]` | Query `/status` on a running artifact provider (default `http://127.0.0.1:8080`) for health, uptime, and transfer metrics. |
| `plasmd provider list [--addr <URL>]` | Query `/manifest.json` on a running artifact provider and list all available hashed artifacts by channel and architecture. |
| `plasmd version` | Print the `plasmd` version string. |

### Quick start from source

Requires Rust `1.89+` (workspace edition `2021`):

```bash
git clone https://github.com/msitarzewski/phase.git
cd phase
cargo build --release -p plasm --locked
```

Initialize configuration and start a local node:

```bash
./target/release/plasmd init
./target/release/plasmd start --listen /ip4/0.0.0.0/tcp/8000
```

Connect to a peer on a documentation test address:

```bash
./target/release/plasmd start \
  --listen /ip4/0.0.0.0/tcp/8000 \
  --peer /ip4/198.51.100.10/tcp/8000/p2p/<PEER_ID>
```

Run a WebAssembly module locally and inspect its signed JSON receipt:

```bash
./target/release/plasmd run ./workload.wasm
./target/release/plasmd execute-job ./workload.wasm
```

Serve content-addressed artifacts for peers on port `8080` and inspect provider health:

```bash
./target/release/plasmd serve --port 8080 --bind 127.0.0.1
./target/release/plasmd provider status --addr http://127.0.0.1:8080 --json
./target/release/plasmd provider list --addr http://127.0.0.1:8080
```

## Research, student, and builder use cases

Because WebAssembly modules are self-contained, portable, and deterministic, PLASM fits embarrassingly parallel and verification-sensitive CPU workloads well:

- **Parameter sweeps and grid searches:** Partition hyperparameter grids or physical simulation sweeps into independent WASM tasks, fan them out across a lab or student study circle, and verify every returned result with its Ed25519 receipt.
- **Monte Carlo simulations:** Run fixed-seed stochastic models across volunteer or home computers; deterministic WASI execution ensures identical seeds produce bit-for-bit verifiable trajectories.
- **Dataset indexing and transformation:** Parse, normalize, or index content-addressed text, CSV, or binary shards without installing Python/C++ toolchains on every helper machine.
- **Bioinformatics and scientific kernels:** Compile sequence alignment, spectral analysis, or numerical solvers from Rust, C/C++, or Zig to `wasm32-wasip1` and run them unmodified across macOS, Windows, and Linux peers.
- **Reproducible build and verification checks:** Independently re-execute deterministic test vectors, proof checks, or hash validations on separate peers to cross-check results.

## Trust model and sandboxing boundaries

PLASM is engineered to fail closed on both operator safety and result verification:

- **Default-deny execution (`WorkerSecurityConfig`):** `WasmtimeWorker::new` defaults to an empty `authorized_submitters` allowlist (`allow_unauthenticated = false`). Uninvited peers cannot execute arbitrary WebAssembly on your machine.
- **Bounded CPU, memory, and wall-clock limits:** Every execution runs in an isolated Wasmtime `Store` with fuel metering (`consume_fuel(true)`, scaled to the job timeout), a strict linear-memory limit (`StoreLimits::memory_size`, default `128 MiB`, clamped by operator policy), and a hard wall-clock ceiling (default `300s` in `WasmtimeWorker`, clamped by operator policy).
- **Zero host filesystem or network escape:** The WASI preview1 context (`WasiCtxBuilder::new().inherit_stdio().build_p1()`) exposes no host directories (`preopened_dir` is not configured) and no network sockets. A guest module cannot read host files, write to disk, or open outbound connections.
- **Honest privacy and verification limits:** A verified `SignedReceipt` proves *which Ed25519 peer* signed the exact SHA-256 commitment over the returned output for a specific `SignedManifest` hash. It does **not** encrypt job inputs from the executing worker—do not submit confidential data to peers you do not trust. For untrusted circles, pair deterministic modules with redundant re-execution across multiple peers to detect dishonest outputs.

For the shared Phase crate architecture and wire-level receipt specifications, see [Workspace architecture, crates and Plasm](architecture-and-crates.md), [Cryptography, receipts and verification](cryptography-and-receipts.md), and [Phase network protocols](protocols.md).
