diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md deleted file mode 100644 index 906c71d4..00000000 --- a/.github/copilot-instructions.md +++ /dev/null @@ -1,364 +0,0 @@ -# foc-devnet - AI Coding Instructions - -## Project Overview - -**foc-devnet** is a Rust CLI tool for managing local Filecoin networks with FOC (Filecoin Onchain Contracts) support for warm storage services. It orchestrates Docker containers running Lotus nodes, miners, databases, and deploys smart contracts using Foundry (Forge/Cast). - -**Key Technologies**: Rust, Docker, Filecoin Lotus, FEVM (Filecoin EVM), Foundry, PostgreSQL, ScyllaDB, Solidity - -## Architecture Patterns - -### Step-Based Execution Pattern - -All startup operations follow the `Step` trait pattern (see `src/commands/start/step.rs`): - -```rust -pub trait Step { - fn name(&self) -> &str; - fn pre_execute(&self, context: &mut StepContext) -> Result<(), Box>; - fn execute(&self, context: &mut StepContext) -> Result<(), Box>; - fn post_execute(&self, context: &mut StepContext) -> Result<(), Box>; - fn run(&self, context: &mut StepContext) -> Result<(), Box>; -} -``` - -**Why**: Provides clear separation of concerns, allows verification at each phase, and enables step-level debugging. - -**Execution Flow**: Pre-checks → Main execution → Post-verification - -**Context Sharing**: `StepContext` is a `HashMap` that passes state between steps (e.g., addresses, container IDs). - -### Startup Sequence - -Steps execute in this strict order (see `src/commands/start/mod.rs`): - -1. **Genesis Prerequisites** - Create BLS keys, pre-seal sectors, construct genesis block -2. **Lotus** - Start Filecoin daemon with FEVM enabled -3. **Lotus-Miner** - Start first-generation block producer -4. **FOC Deploy** - Deploy MockUSDFC token and FOC warm storage contracts -5. **Databases** - Start Postgres + Scylla for Curio -6. **Curio** - Start second-generation miner (commented out, WIP) - -**Critical**: Each step depends on previous steps being healthy. DO NOT reorder. - -### Docker Container Architecture - -``` -foc-lotus # Lotus daemon (ports 1234 API, 1235 P2P) -foc-lotus-miner # First-gen miner (port 2345) -foc-builder # Foundry tools (--network host) -postgres / scylla # Databases for Curio (stock images, dynamic ports) -foc-curio # Second-gen miner (WIP) -``` - -**Critical Network Details**: -- `foc-builder` uses `--network host` to access Lotus RPC at `http://localhost:1234/rpc/v1` -- All other containers use bridge networking -- Volume mounts are handled via `docker//volumes_map.toml` (TOML format) - -## Directory Structure & Conventions - -### User Data Directories -All persistent data lives under `~/.foc-devnet/` (see `src/paths.rs`): - -``` -~/.foc-devnet/ -├── artifacts/ -│ ├── bin/ # Built Lotus/Curio binaries -│ └── docker/volumes/ # Container persistent data -│ ├── lotus-data/ # Lotus blockchain data -│ ├── lotus-miner-data/ # Miner data -│ ├── genesis/ # Genesis block config -│ ├── genesis-sectors/ # Pre-sealed sectors -│ ├── lotus-keys/ # BLS signing keys -│ └── foc-contract-addresses.json # Deployed contract addresses -├── logs/ # Container logs -├── repos/ -│ └── filecoin-service/ # FOC contracts repository -├── state/ -│ └── .poison # Poison file (indicates partial startup) -└── config.toml # Configuration file -``` - -### Key Path Functions (src/paths.rs) -- `foc_devnet_home()` - Root directory `~/.foc-devnet/` -- `foc_devnet_docker_volumes()` - Docker volumes directory -- `foc_devnet_lotus_keys()` - BLS key storage -- `contract_addresses_file()` - JSON file with deployed contracts -- `foc_devnet_bin()` - Built binaries directory - -## Smart Contract Deployment - -### FOC Deployment Flow (src/commands/start/foc_deploy.rs) - -**Fund Transfer Chain**: -``` -GLOBAL_FIL_FAUCET (50,000 FIL from genesis, BLS/f3 address) - ↓ Transfer 10,000 FIL -FEVM_FAUCET (f4/delegated address) - ↓ Transfer 5,000 FIL -FOC_DEPLOYER (f4/delegated address that deploys contracts) - ↓ Deploys via Foundry -MockUSDFC + FOC Service Contracts -``` - -**Why f4 Addresses?**: FEVM requires delegated (f4) addresses which have Ethereum compatibility. f3 (BLS) addresses cannot interact with smart contracts. - -**Critical Timing**: After transferring FIL to create f4 addresses, must wait ~4 seconds for address activation on-chain. - -### Contract Deployment Sequence - -1. **MockUSDFC Token** (ERC-20): - - Symbol: USDFC - - Decimals: 18 - - Initial Supply: 1,000,000 tokens - - Source: `contracts/MockUSDFC.sol` - - Uses: `forge create` with `--broadcast` flag - -2. **FOC Service Contracts**: - - Deployed via `warm-storage-deploy-all.sh` script - - Includes: PDPVerifier, ServiceProviderRegistry, FilecoinWarmStorageService, etc. - - All addresses saved to `foc-contract-addresses.json` - -### Known Issues with Contract Deployment - -**Current Problem**: `forge create --broadcast` may not reliably broadcast transactions to Lotus FEVM. - -**Symptoms**: -- Transaction shows as "prepared" but no "Sending transactions" message -- No "Deployed to:" line in output -- Contract address extraction fails - -**Current Workaround**: Using keystore + `cast wallet import` instead of raw `--private-key` flag - -**Alternative Approaches to Consider**: -- Use `forge script` instead of `forge create` -- Use `cast send --create` for contract deployment -- Check Lotus FEVM compatibility with latest Foundry version - -## Embedded Assets Pattern - -Contract files, Dockerfiles, and configs are embedded at compile time (see `src/embedded_assets.rs`): - -```rust -pub const MOCK_USDFC_CONTRACT: &[u8] = include_bytes!("../contracts/MockUSDFC.sol"); -``` - -**Why**: Single binary distribution without requiring external files. - -**When Adding New Assets**: -1. Add file to appropriate directory (e.g., `contracts/`, `docker/`) -2. Add constant to `src/embedded_assets.rs` -3. Extract to temp location before use (contracts need to be on filesystem for Foundry) - -## Common Development Patterns - -### Error Handling -- Use `Box` for flexible error propagation -- User-facing errors use `crossterm::style::Stylize`: `.red()`, `.green()`, `.yellow()`, `.cyan()`, `.bold()` -- Critical errors should be descriptive (include paths, container names, etc.) - -### Lotus API Interactions -Use `Command` to execute Lotus CLI commands inside containers: - -```rust -let output = Command::new("docker") - .args(["exec", "foc-lotus", "/usr/local/bin/lotus-bins/lotus", "wallet", "list"]) - .output()?; -``` - -**Common Lotus Commands**: -- `lotus wallet list` - List all wallets -- `lotus wallet balance ` - Check balance -- `lotus chain list` - Show chain tipsets -- `lotus-miner info` - Miner status - -**JSON-RPC Alternative**: -```bash -curl http://localhost:1234/rpc/v1 -X POST -H "Content-Type: application/json" \ - -d '{"jsonrpc":"2.0","method":"Filecoin.ChainHead","params":[],"id":1}' -``` - -### Docker Utilities (src/docker.rs) -- `container_exists(name)` - Check if container exists -- `container_is_running(name)` - Check if container is running -- `stop_and_remove_container(name)` - Clean up container -- `wait_for_port(port, timeout)` - Wait for service to be ready -- `is_port_available(port)` - Check port availability before starting - -## Configuration System - -### Config File Structure (config.toml) - -```toml -[lotus] -location = "Git" # or "LocalSource" -repo = "https://github.com/filecoin-project/lotus" -branch = "master" - -[curio] -location = "Git" -repo = "https://github.com/filecoin-project/curio" - -[filecoin-services] -location = "LocalSource" -dir = "/path/to/local/filecoin-services" -``` - -**Location Types** (see `src/config.rs`): -- `Git` - Clone from remote repository -- `GitTag` - Specific tag/release -- `LocalSource` - Use local directory (for development) - -**When Modifying Config**: -- Always use `Config::load()` to read current config -- Use `Config::save()` after modifications -- Validate paths for `LocalSource` before saving - -## Regenesis & Reset Patterns - -### Regenesis (Full Reset) -Deletes: BLS keys, genesis sectors, genesis config, blockchain data, contract addresses - -**When to Use**: Complete fresh start, testing genesis modifications - -**Files Deleted**: -- `lotus-keys/key-1`, `lotus-keys/key-2`, `lotus-keys/prefunded-*` -- `genesis-sectors/` -- `genesis/foc-devnet.json` -- `lotus-data/`, `lotus-miner-data/` - -### Reset (Chain Reset Only) -Deletes: Blockchain data, contract addresses (keeps genesis config and keys) - -**When to Use**: Reset chain to block 0 while keeping same accounts - -**Files Deleted**: -- `lotus-data/`, `lotus-miner-data/` -- `foc-contract-addresses.json` - -## Testing & Debugging Commands - -### Build & Run -```bash -cargo build # Dev build -cargo build --release # Optimized build -cargo run -- start # Start cluster -cargo run -- start --regenesis --reset # Full reset + start -``` - -### Container Debugging -```bash -docker ps # List running containers -docker logs foc-lotus # View Lotus logs -docker logs foc-lotus --tail 100 --follow # Tail logs -docker exec foc-lotus /usr/local/bin/lotus-bins/lotus wallet list # Run Lotus commands -docker inspect foc-lotus # Container details -``` - -### Manual Contract Deployment Test -```bash -# Test MockUSDFC deployment manually -docker run --rm --network host \ - -v "$(pwd)/contracts:/tmp" \ - foc-builder bash -c " - forge create /tmp/MockUSDFC.sol:MockUSDFC \ - --rpc-url http://localhost:1234/rpc/v1 \ - --private-key \ - --constructor-args 1000000000000000000000000 \ - --broadcast - " -``` - -## Common Pitfalls & Solutions - -### Port Conflicts -**Problem**: Container fails to start due to port already in use -**Solution**: Check with `lsof -i :1234` or use `foc-devnet stop` to clean up - -### Volume Permission Issues -**Problem**: Container can't write to mounted volumes -**Solution**: Containers run as `foc-user:foc-user` (defined in Dockerfiles). Ensure volumes are writable. - -### Genesis Timing Issues -**Problem**: f4 address not found immediately after creation -**Solution**: FEVM addresses need ~4 seconds activation time. Wait before using. - -### Private Key Format Confusion -**Problem**: Lotus exports keys as hex-encoded JSON, Foundry needs raw hex -**Solution**: Use `hex::decode()` to extract actual key bytes, then re-encode to hex string - -### Forge Broadcast Not Working -**Problem**: `forge create --broadcast` doesn't broadcast to Lotus FEVM -**Investigation**: Check Lotus logs for Ethereum RPC errors, verify FEVM is enabled, test with `cast send` - -## Code Style & Conventions - -### Code Quality Policies -- **File sizes**: No greater than 150 lines -- **Larger files**: Split into multi-file modules when exceeding 150 lines -- **Function sizes**: No greater than 15 lines -- **Magic numbers**: All magic numbers like sleep durations should be constants -- **Magic names**: All magic names like "foc-builder", "foc-deployer" should be constants -- **Command calls**: Refactor all `Command::new(...)` calls into a "shell" module so that nitty gritties and flags are not interspersed throughout the codebase -- **Documentation**: Each function must have a docstring describing its intent -- **Function decomposition**: Break down functions doing multiple things into smaller functions -- **Complex tasks**: Provide examples for functions undertaking complicated tasks - -### Module Documentation -Every module should have a module-level doc comment explaining its purpose: -```rust -//! FOC deployment step. -//! -//! This module handles deploying FOC contracts to Lotus with FEVM. -``` - -### Error Messages -Use descriptive error messages with context: -```rust -return Err(format!( - "Lotus container is not running. FOC deployment requires Lotus to be running with FEVM enabled. \ - Run 'foc-devnet start' to start Lotus first." -).into()); -``` - -### Constants -Define constants at module level for magic values: -```rust -const LOTUS_RPC_PORT: u16 = 1234; -const TRANSACTION_CONFIRMATION_WAIT_SECS: u64 = 15; -const MOCK_USDFC_INITIAL_SUPPLY: &str = "1000000000000000000000000"; -``` - -### Imports Organization -1. Standard library (`std::`) -2. External crates (`serde`, `crossterm`, etc.) -3. Internal crate modules (`crate::paths`, `crate::config`) -4. Parent/current module (`super::`, `self::`) - -## Key Files Reference - -- `src/commands/start/mod.rs` - Startup orchestration and step execution -- `src/commands/start/foc_deploy.rs` - FOC contract deployment logic -- `src/commands/start/step.rs` - Step trait definition -- `src/docker.rs` - Docker utility functions -- `src/paths.rs` - All path resolution functions -- `src/config.rs` - Configuration loading/saving -- `src/embedded_assets.rs` - Embedded file assets -- `docker/` - Dockerfiles and volume mappings -- `contracts/MockUSDFC.sol` - Test ERC-20 token - -## Additional Resources - -- **Filecoin Lotus Docs**: https://lotus.filecoin.io/ -- **FEVM Documentation**: https://docs.filecoin.io/smart-contracts/fundamentals/the-fvm/ -- **Foundry Book**: https://book.getfoundry.sh/ -- **FOC Contracts**: https://github.com/FilOzone/filecoin-services - -## When Making Changes - -1. **Adding New Steps**: Implement the `Step` trait, add to startup sequence in correct order -2. **Modifying Dockerfiles**: Update embedded assets, rebuild with `foc-devnet init --rebuild` -3. **Changing Paths**: Update `src/paths.rs` and ensure backward compatibility -4. **Contract Updates**: Update embedded asset, test deployment manually first -5. **Error Handling**: Always provide context (which container, which file, which command failed) diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 00000000..06ed28d2 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,98 @@ +# Repository instructions + +## Project Overview + +foc-devnet is a Rust CLI that runs local Filecoin networks with FOC (Filecoin +Onchain Cloud) in Docker. It starts Lotus, miners, and databases, and +deploys contracts with Foundry. + +## Architecture Patterns + +### Step-Based Execution Pattern + +Use the [`Step` trait and setup context](src/commands/start/step/mod.rs) for +startup operations. Keep prerequisite checks, execution, and verification in +their respective phases. + +### Startup Sequence + +[`src/commands/start/mod.rs`](src/commands/start/mod.rs) defines both +sequential startup and the parallel step epochs. When adding or moving a step, +update both schedules and respect dependencies between steps. Curio startup +is implemented in [`curio/`](src/commands/start/curio/). + +## Directory Structure & Conventions + +Resolve shared and per-run paths through [`src/paths.rs`](src/paths.rs) +instead of hard-coding the layout. When changing paths, consider existing +installations and run data. + +## Smart Contract Deployment + +The startup modules own [ETH account funding](src/commands/start/eth_acc_funding/), +[MockUSDFC deployment](src/commands/start/usdfc_deploy/), and +[FOC contract deployment](src/commands/start/foc_deploy/). See the +[MockUSDFC Foundry guide](contracts/MockUSDFC/README.md) for manual testing. + +## Embedded Assets Pattern + +[`src/embedded_assets.rs`](src/embedded_assets.rs) embeds Dockerfiles, +volume maps, and the MockUSDFC archive generated by [`build.rs`](build.rs). +When changing packaged files, update the relevant embedding and Cargo +rebuild inputs as needed. +Initialization skips Docker images that already exist; see +[`src/docker/build.rs`](src/docker/build.rs) when testing Dockerfile changes. + +## Common Development Patterns + +### Error Handling +- Use `Box` for flexible error propagation. +- Use `crossterm::style::Stylize` where the surrounding CLI code styles output. +- Include diagnostic context, such as the path, container, or failed command. + +### Docker and Lotus Commands + +Keep subprocess invocations and flags in the appropriate shell helpers rather +than scattering them through orchestration code. See +[`src/docker/shell.rs`](src/docker/shell.rs) for Docker command helpers. + +## Configuration System + +[`src/config.rs`](src/config.rs) defines the config schema and source +locations. Use the existing config loading, saving, and validation paths rather +than hand-writing TOML or parsing source locations again. + +## Testing & Debugging Commands + +See the [quick start](README.md#-quick-start) for CLI usage and +[local checks](ci/README.md#local-checks) for contributor commands. +[`src/cli.rs`](src/cli.rs) defines the supported CLI flags. + +## Documentation + +- Keep `README.md` focused on first use; put advanced guides in [docs/](docs/README.md). +- Document what users need to do, expect, or diagnose. +- In code comments and docstrings, explain non-obvious reasons for decisions; don't restate what the code does. +- Link to the canonical guide instead of duplicating it. Verify commands and config examples. + +## Code Style & Conventions + +### Code Quality Policies +- Define named constants for identifiers, timings, and other magic values. +- Add examples for complex tasks when they clarify usage. + +### Module Documentation +Use a `//!` doc comment to explain why a module exists when its purpose isn't apparent from the code. + +### Imports Organization +1. Standard library (`std::`) +2. External crates (`serde`, `crossterm`, etc.) +3. Internal crate modules (`crate::paths`, `crate::config`) +4. Parent/current module (`super::`, `self::`) + +## Additional Resources + +- **Filecoin Lotus Docs**: https://lotus.filecoin.io/ +- **FEVM Documentation**: https://docs.filecoin.io/smart-contracts/fundamentals/the-fvm/ +- **Foundry documentation**: https://www.getfoundry.sh/ +- **FOC Contracts**: https://github.com/FilOzone/filecoin-services diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 00000000..43c994c2 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1 @@ +@AGENTS.md diff --git a/README.md b/README.md index e05745a6..2df73f4b 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # foc-devnet -**Run a local Filecoin network with FOC (Filecoin Onchain Contracts) in minutes.** +**Run a local Filecoin network with FOC (Filecoin Onchain Cloud) in minutes.** A developer-friendly tool for spinning up complete Filecoin test networks with smart contract support, deterministic key generation, and automated deployment—all running locally in Docker. @@ -8,40 +8,15 @@ A developer-friendly tool for spinning up complete Filecoin test networks with s ## 🚀 Quick Start -Get up and running in three simple steps: - ### Prerequisites -**Non-root user with Docker access**: `foc-devnet` must be run by a non-root user in the `docker` group. - -```bash -echo $(id -u); groups | grep 'docker' -``` +Use [stable Rust via rustup](https://rustup.rs), Docker, Git, and `tar`. +Default setup also needs network access to download repositories and images. +Run as a non-root user who can run `docker info` without `sudo` (on Linux, +typically through the `docker` group). -**Configure host.docker.internal**: Add this entry to `/etc/hosts` so SP URLs work from both host and containers: - -```bash -echo '127.0.0.1 host.docker.internal' | sudo tee -a /etc/hosts -``` - -This is required for SP-to-SP fetch. `foc-devnet start` will check for this and fail with instructions if not configured. - -For GitHub Actions, add this step before running foc-devnet: -```yaml -- run: echo '127.0.0.1 host.docker.internal' | sudo tee -a /etc/hosts -``` - -**Linting (rust + python)**: -```sh -sudo apt install pipx && pipx ensurepath && pipx install black -./scripts/lint.sh # auto-fix mode (default) -FIX=0 ./scripts/lint.sh # check-only mode (used in CI) -``` - -**Pre-commit hook** (optional — runs `lint.sh` before each commit): -```sh -./scripts/install_precommit_hooks.sh -``` +**Check `host.docker.internal`**: It must resolve to loopback on the host. +See [hostname setup](docs/networking.md#setup-requirements) before starting. ### Step 1: Initialize @@ -62,10 +37,10 @@ cargo run -- init \ --curio local:/home/user/code/curio \ --filecoin-services local:/home/user/code/filecoin-services \ --pdp local:/home/user/code/pdp \ - --lotus local:/home/user/code/lotus \ + --lotus local:/home/user/code/lotus ``` -**Re-initializing?** Run `cargo run -- clean` first to remove existing state. Config is preserved by default; use `--all` to reset it too. +**Re-initializing?** Follow the [stop and clean procedure](docs/cli.md#clean). ### Step 2: Build @@ -77,12 +52,11 @@ cargo run -- build curio This will: - Compile Lotus and Curio binaries inside Docker containers - Cache build artifacts for faster subsequent builds -- You can run them in parallel as well for faster builds, if you have a powerful PC. ### Step 3: Start the Network ```bash -cargo run -- start --parallel +cargo run -- start ``` This will: @@ -90,100 +64,36 @@ This will: - Start Lotus daemon with FEVM enabled - Deploy FOC smart contracts (including MockUSDFC) - Start storage provider(s) -- Launch [Portainer UI](https://docs.docksal.io/use-cases/portainer/) for container management +- Launch [Portainer](https://docs.portainer.io/) for container management -Curio providers initialize their storage metadata and register container-visible -paths before launching, so PDP hashspaces include long-term storage on first startup. -Startup retries RPC readiness checks while the daemon initializes. -Existing storage metadata and additional registered paths are preserved. +Run only on a trusted development machine and network. Portainer's published +port is not restricted to loopback, and Portainer has access to the Docker socket. -**If you have troubles**: Use `cargo run -- start`, removing parallelism during start, this may take longer. - -**That's it!** Your local Filecoin network is running. +For experimental parallel startup, use `cargo run -- start --parallel`. ### Step 4: Use the Network -After startup, `USER_1` is fully configured for FOC: USDFC deposited into FilecoinPay and FWSS approved as an operator. Use the network immediately with Synapse, filecoin-pin, or other compatible FOC client software: +After startup, `USER_1` is funded and configured for FOC storage. Check the +cluster with: ```bash -# From a synapse-sdk checkout -NETWORK=devnet node utils/example-storage-e2e.js - -# With filecoin-pin -filecoin-pin add --network devnet -# Equivalent: NETWORK=devnet filecoin-pin add - -# Exercise foc-devnet's full Synapse-driven system scenario -python3 scenarios/test_synapse_e2e.py +cargo run -- status ``` -All connection details (contract addresses, user keys, SP endpoints) are exported to `devnet-info.json`: +Client connection details are exported to +`~/.foc-devnet/state/latest/devnet-info.json`. The file contains raw test private +keys: do not share it or use those keys outside the devnet. -```bash -cat ~/.foc-devnet/state/latest/devnet-info.json -``` - -See [examples/README.md](examples/README.md) for more usage examples. +See [integration examples](examples/README.md) to check balances or exercise +storage with Synapse or filecoin-pin. --- ## ✨ Key Features -### 🪶 Lean Host Requirements -Only needs three things on your machine: -- **tar** archiver -- **rustup/rustc** for building the CLI -- **Docker** for containerized components - -Everything else (Lotus, Curio, dependencies) is built inside Docker. - -### ⚙️ Configurable Repositories -Depends on these repositories, all configurable: -- `filecoin-services` - FOC smart contracts -- `pdp` - PDP contracts, optionally pinned independently from filecoin-services -- `curio` - Next-gen storage provider -- `lotus` - Filecoin daemon - -Each can be: -- Auto-downloaded from GitHub (default) -- Linked to your local git repository for development - -### 🔒 Deterministic Setup -- **Pinned versions**: All components use specific git tags/commits for reproducibility -- **Deterministic keys**: Uses fixed seeds, generating the same keys on every setup -- **Consistent state**: Each run preserves its context in `~/.foc-devnet/run//step_context.json` - -### 🤖 Fully Automated -From building Docker images to deploying contracts—everything is automated: -- Genesis block creation -- Network initialization -- Smart contract deployment -- Storage provider setup - -### 🧩 Modular Architecture -Built with modular steps for easy extension and customization: -- Add custom deployment steps -- Configure multiple PDP service providers -- Control "allowed" SP nodes via `~/.foc-devnet/config.toml` (see [Configuration System](README_ADVANCED.md#configuration-system)) - -### 📜 Programmable -Built for scripting and automation: -- **Contract addresses**: `~/.foc-devnet/run//contract_addresses.json` -- **Step context**: `~/.foc-devnet/run//step_context.json` -- **Latest run symlink**: `~/.foc-devnet/state/latest/` → points to most recent run -- **Custom base directory**: Set `FOC_DEVNET_BASEDIR` env var to override default `~/.foc-devnet` location (see [Environment Variables](README_ADVANCED.md#environment-variables)) -- Write scripts for testing, demos, CI/CD pipelines, etc. - -### 🌐 Isolated Networks -Uses Docker user-defined networks to mimic real-world node separation—just like production deployments. - -### 💰 Built-in Token Contracts -Includes ready-to-use test contracts: -- **MockUSDFC** - ERC-20 test token -- **Multicall3** - Batch contract calls - -### 🖥️ Portainer UI -Bundled with Portainer for browser-based Docker management—no terminal wizardry required. +Use [configuration](docs/configuration.md) to pin or replace dependency sources +and change where devnet data is stored. Try [service provider workflows](docs/service-providers.md) +to test storage with different approval and endorsement settings. --- @@ -191,29 +101,23 @@ Bundled with Portainer for browser-based Docker management—no terminal wizardr | Requirement | Details | |-------------|---------| -| **Rust** | 1.70+ ([rustup.rs](https://rustup.rs)) | +| **Rust** | Stable via [rustup](https://rustup.rs); a native build toolchain is required | | **Docker** | Desktop (macOS) or CE (Linux) | | **tar** | Archive utility (usually pre-installed) | +| **Git** | Required for repository setup | | **Disk Space** | ~20GB for images and blockchain data | -| **Architecture** | Supports both x86 (Intel) and ARM64 (Apple Silicon, AWS Graviton, etc.) architectures. The system automatically selects the appropriate binaries based on your architecture. | +| **Architecture** | x86-64 and ARM64; the devnet CI workflow runs on Linux x86-64 | + +On Debian/Ubuntu, the CLI build uses `build-essential`, `pkg-config`, and +`libssl-dev`. --- ## 🛠️ Need More? -See **[README_ADVANCED.md](README_ADVANCED.md)** for comprehensive documentation on: -- **All commands reference** (init, build, start, stop, clean, status, version) -- **Configuration system** (config.toml structure, parameters, editing) -- **Complete directory structure** (what's stored where and why) -- **Resetting and cleanup** (manual cleanup, disk management) -- **Run ID and Step Context** (isolation mechanism, state sharing) -- **Docker and networking** (container architecture, network topology, Portainer debugging) -- **Repository management** (using local repos, sharing configurations) -- **Command flags** (detailed explanations of all flags and when to use them) -- **Lifecycle overview** (full startup sequence, step implementation) -- **Service Provider examples** (1 SP with 0 authorized, 3 SPs with top 2 authorized, etc.) -- **Troubleshooting guides** (port conflicts, build failures, network issues) -- **Additional user actions** (custom genesis, Lotus API access, contract interaction) +- [Advanced documentation](docs/README.md): CLI, configuration, cleanup, and troubleshooting +- [Local contributor checks](ci/README.md#local-checks) and [CI dependency profiles](ci/README.md) +- [MockUSDFC test token and deployment guide](contracts/README.md) --- diff --git a/README_ADVANCED.md b/README_ADVANCED.md deleted file mode 100644 index b02c5f2b..00000000 --- a/README_ADVANCED.md +++ /dev/null @@ -1,1346 +0,0 @@ -# Advanced Guide: foc-devnet - -This guide covers advanced usage, internal architecture, and operational details of foc-devnet. - ---- - -## Commands Reference - -### `clean` -Removes foc-devnet state. Preserves `config.toml` by default so it can be reused on next `init`. - -```bash -foc-devnet clean [OPTIONS] -``` - -**Options:** -- `--all` - Also remove `config.toml` -- `--images` - Also remove cached foc-* Docker images - -**Examples:** -```bash -foc-devnet clean # Remove state, preserve config.toml -foc-devnet clean --all # Remove everything including config -foc-devnet clean --images # Remove state + Docker images -foc-devnet clean --all --images # Full reset -``` - -### `init` -Initializes foc-devnet by downloading repositories, building Docker images, and preparing the environment. - -Requires a clean home directory. If existing state is present, `init` will refuse and ask you to run `clean` first. If a `config.toml` was preserved across `clean`, it is reused (with any CLI overrides applied on top). - -```bash -foc-devnet init [OPTIONS] -``` - -**Options:** -- `--curio ` - Curio source location -- `--lotus ` - Lotus source location -- `--filecoin-services ` - Filecoin Services source location -- `--pdp ` - PDP source location. If omitted, uses the PDP submodule bundled with Filecoin Services. -- `--proof-params-dir ` - Local proof params directory -- `--rand` - Use random mnemonic instead of deterministic one. Use this for unique test scenarios. - -**Source Format:** -- `latesttag` - Newest git tag in the default repo (resolved once at `init`). -- `latesttag:` - Newest git tag matching a glob selector, e.g. `latesttag:v*` or `latesttag:pdp/v*`. -- `latesttag::` - Newest matching tag from a custom repo, e.g. `latesttag:https://github.com/org/repo.git:v*`. -- `gittag:` - Specific git tag (uses default repo) -- `gittag::` - Tag from custom repo, e.g. `gittag:https://github.com/org/repo.git:v1.0.0` -- `gitcommit:` - Specific commit (uses default repo) -- `gitcommit::` - Commit from custom repo -- `gitbranch:` - Specific branch (uses default repo) -- `gitbranch::` - Branch from custom repo -- `local:` - Local directory - -**Example:** -```bash -foc-devnet init \ - --lotus local:/home/user/lotus \ - --curio gitbranch:pdpv0 -``` - -### `build` -Builds Lotus and Curio binaries in Docker containers. - -> **Note:** This command must be run after `init` to ensure Docker images and environment are prepared. - -```bash -foc-devnet build lotus [PATH] -foc-devnet build curio [PATH] -``` - -**Note:** Binaries are built to `~/.foc-devnet/bin/` which is the expected location for the system. - -**Example:** -```bash -foc-devnet build lotus -foc-devnet build curio /path/to/custom/curio -``` - -### `start` -Starts the local Filecoin network cluster. - -> **Note:** This command should be run after `build` of `lotus` and `curio` to ensure binaries are available. - -```bash -foc-devnet start [OPTIONS] -``` - -**Options:** -- `--parallel` - **⚡ Run steps in parallel for ~40% faster startup (recommended)** - -**Why `--parallel` (Recommended):** -- **⚡ Significant speedup:** Reduces startup time from ~5 min to ~3 min -- **Smart parallelization:** Steps that don't depend on each other run concurrently -- **Production-ready:** Thread-safe implementation with proper synchronization -- **Use case:** Default for most workflows, especially development iteration - -**When NOT to use `--parallel`:** -- Debugging step ordering issues -- Very low-resource machines (< 4GB RAM) -- First-time setup (sequential is easier to follow) - -See [Detailed Start Sequence](#detailed-start-sequence) for information about which steps are parallelized. - -**Recommended for faster startup:** -```bash -foc-devnet start --parallel -``` - -**After successful start:** -- Portainer UI available at http://localhost:5700 (uses first port in configured range) -- Use Portainer to monitor containers, view logs, and debug issues -- All container names include the run ID for easy identification - -### `stop` -Stops all running containers and cleans up Docker networks. - -```bash -foc-devnet stop -``` - -**What it does:** -- Stops containers in reverse order (Curio → Databases → Lotus-Miner → Lotus) -- Removes containers to ensure clean state -- Deletes Docker networks -- Preserves Portainer for persistent access -- Clears run ID - -### `status` -Shows the current status of the foc-devnet system. - -```bash -foc-devnet status -``` - -Displays: -- Current run ID -- Container states -- Network information -- Port allocations - -### `version` -Shows version information. - -```bash -foc-devnet version -``` - ---- - -## Network Architecture & Inter-SP Communication - -### The Challenge - -Running multiple Service Providers (SPs) locally requires them to communicate with each other while remaining accessible from the host (for testing/synapse code). This creates a networking puzzle: - -- **Container-to-container communication:** Docker DNS names (e.g., `foc-curio-1`) work within the docker network but don't resolve from the host -- **Host-to-container communication:** `localhost` works from the host but means different things inside containers -- **The conflict:** Using `localhost:` breaks inter-SP comms because each container sees `localhost` as itself - -### How It Works: `host.docker.internal` - -foc-devnet solves this by using `host.docker.internal` as a unified endpoint that works consistently from both the host and all containers. - -**Setup (mostly automatic):** -1. Verify `/etc/hosts` has: `127.0.0.1 host.docker.internal` - - On macOS with Docker Desktop: automatic - - On Linux: foc-devnet checks for this and provides setup instructions -2. Each Curio container launches with: `--add-host=host.docker.internal:host-gateway` -3. SPs register in the service provider registry as: `http://host.docker.internal:` -4. Curio runs with `CURIO_PULL_ALLOW_INSECURE=1` to allow HTTP/internal connections - -**Why it works:** -- From the host: `host.docker.internal` → `/etc/hosts` → `127.0.0.1` -- From containers: `--add-host` mapping → routes back to the host's IP -- Same hostname everywhere = SPs can call each other + host can access SPs - -### Setup Requirements - -**macOS with Docker Desktop:** -- Works automatically, no setup needed - -**Linux:** -Add this line to `/etc/hosts`: -```bash -echo '127.0.0.1 host.docker.internal' | sudo tee -a /etc/hosts -``` - -**CI/CD (GitHub Actions, etc.):** -Add before running foc-devnet: -```yaml -- run: echo '127.0.0.1 host.docker.internal' | sudo tee -a /etc/hosts -``` - -### Validation - -foc-devnet validates DNS resolution before startup: -```bash -foc-devnet start -# ✓ host.docker.internal resolves to localhost -# Proceeding with startup... -``` - -If resolution fails, you'll get clear error messages with exact fix instructions for your platform. - -### Tradeoffs - -**Benefits:** -- Single endpoint works from everywhere (host + all containers) -- Enables inter-SP communication out of the box -- Minimal setup overhead -- No architectural changes to core components - -**Considerations:** -- Requires `/etc/hosts` modification (one-liner, done once per machine) -- `CURIO_PULL_ALLOW_INSECURE=1` bypasses TLS validation (acceptable for devnet) -- Docker must support `host-gateway` (standard in modern Docker versions) - ---- - -## Configuration System - -### Config File Location - -``` -~/.foc-devnet/config.toml -``` - -### Config Structure - -```toml -# Port range for dynamic allocation -# foc-devnet uses a contiguous range of ports to avoid conflicts with other -# services on your machine. All components (Lotus, Curio SPs, databases, etc.) -# dynamically allocate ports from this range. Using a dedicated range ensures: -# - No conflicts with system services (MySQL, PostgreSQL, etc.) -# - Easy firewall configuration (just open one range) -# - Port availability can be validated before starting -port_range_start = 5700 -port_range_count = 100 - -# Service Provider configuration -approved_pdp_sp_count = 1 # SPs registered and approved in registry -active_pdp_sp_count = 1 # Total SPs actually running - -# Component sources -[lotus] -url = "https://github.com/filecoin-project/lotus.git" -tag = "v1.34.0" - -[curio] -url = "https://github.com/filecoin-project/curio.git" -branch = "pdpv0" - -[filecoin_services] -url = "https://github.com/FilOzone/filecoin-services.git" -tag = "v1.0.0" - -# Optional. When omitted, filecoin-services' service_contracts/lib/pdp -# submodule is used. -[pdp] -url = "https://github.com/FilOzone/pdp.git" -tag = "v3.4.0" - -[multicall3] -url = "https://github.com/mds1/multicall3.git" -branch = "main" - -``` - -### Configuration Parameters - -| Parameter | Type | Default | Description | -|-----------|------|---------|-------------| -| `port_range_start` | u16 | 5700 | Starting port for contiguous port range | -| `port_range_count` | u16 | 100 | Number of ports in the range | -| `approved_pdp_sp_count` | usize | 1 | Number of approved service providers | -| `active_pdp_sp_count` | usize | 1 | Number of running service providers | - -**Constraints:** -- `approved_pdp_sp_count` ≤ `active_pdp_sp_count` ≤ `MAX_PDP_SP_COUNT` (5) - -### How Defaults Work - -Defaults are defined in code (see [`src/config.rs`](src/config.rs) `Config::default()`) and written to `config.toml` during `init`. This means: - -- **First-time setup:** Running `foc-devnet init` creates `config.toml` with current defaults from code -- **Updating defaults:** When a new version of `foc-devnet` includes updated defaults (e.g., newer Lotus version), run `foc-devnet clean --all` then `foc-devnet init` to regenerate `config.toml` with the new defaults -- **Preserving config across re-init:** Running `foc-devnet clean` (without `--all`) preserves your `config.toml`, so a subsequent `init` reuses your existing settings -- **Source of truth:** The code defines what defaults are available; `config.toml` stores your specific configuration - -### Editing Config - -```bash -# Edit manually -vim ~/.foc-devnet/config.toml - -# Or regenerate from defaults -foc-devnet clean --all -foc-devnet init -``` - ---- - -### Environment Variables - -#### `FOC_DEVNET_BASEDIR` - -**Purpose:** Overrides the default `~/.foc-devnet` directory location. - -**Use Cases:** -- **Testing multiple isolated environments:** Run separate instances of foc-devnet with different configurations -- **Custom directory locations:** Store data on a specific disk or partition (e.g., for SSD/HDD optimization) -- **CI/CD pipelines:** Use predictable paths in automated testing environments -- **Shared team environments:** Keep different team members' instances isolated - -**Tilde Expansion:** -The variable supports tilde (`~`) expansion, so you can use paths like `~/my-custom-foc` or `~/projects/foc-test`. - -**Example Usage:** - -```bash -# Use a custom directory with tilde expansion -export FOC_DEVNET_BASEDIR=~/foc-test-env -foc-devnet init -foc-devnet start - -# Use an absolute path -export FOC_DEVNET_BASEDIR=/mnt/ssd/foc-devnet -foc-devnet init - -# Run multiple isolated instances (in different terminals) -# Terminal 1: -export FOC_DEVNET_BASEDIR=~/foc-env-1 -foc-devnet start - -# Terminal 2: -export FOC_DEVNET_BASEDIR=~/foc-env-2 -foc-devnet start -``` - -**Default Behavior:** -If `FOC_DEVNET_BASEDIR` is not set, foc-devnet uses `~/.foc-devnet` as the base directory. - -**Directory Structure:** -When `FOC_DEVNET_BASEDIR` is set, all data directories are created under the specified path instead of `~/.foc-devnet`: -``` -$FOC_DEVNET_BASEDIR/ -├── config.toml -├── bin/ -├── code/ -├── docker/volumes/ -├── keys/ -├── logs/ -├── run/ -├── state/ -└── tmp/ -``` - ---- - -## Directory Structure - -``` -~/.foc-devnet/ -├── config.toml # Main configuration file -├── bin/ # Compiled binaries (lotus, curio) -├── code/ # Cloned repositories, or symlinks -│ ├── lotus/ # Lotus source code -│ ├── curio/ # Curio source code -│ ├── filecoin-services/ # FOC smart contracts -│ └── multicall3/ # Multicall3 contracts -├── docker/ -│ └── volumes/ -│ ├── cache/ # Shared cache (proof params, etc.) -│ │ └── filecoin-proof-parameters/ -│ └── run-specific/ # Run-isolated volumes -│ └── / # Each run has its own volumes -│ ├── lotus-data/ # Lotus blockchain data -│ ├── lotus-miner-data/ -│ ├── curio-1/ # First Curio SP -│ ├── curio-2/ # Second Curio SP (if active) -│ └── ... -├── keys/ # BLS keys (genesis/mnemonic) -│ ├── mnemonic.txt # Seed phrase -│ └── genesis/ # Genesis block keys -├── logs/ # Container logs -├── run/ # Run-specific execution data -│ └── / # e.g., 20260102T1430_ZanyPip/ -│ ├── setup.log # Startup execution log -│ ├── version.txt # Component versions -│ ├── contract_addresses.json # Deployed contracts -│ ├── step_context.json # Step state (addresses, etc.) -│ ├── foc_metadata.json # FOC service metadata -│ └── pdp_sps/ -│ ├── 1.provider_id.json # First SP provider ID -│ ├── 2.provider_id.json # Second SP provider ID -│ └── ... -├── state/ # Global state -│ ├── current_run_id.txt # Current active run -│ └── latest -> ../run// # Symlink to latest run -└── tmp/ # Temporary files -``` - -### Key Files - -**`contract_addresses.json`** - Deployed smart contract addresses: -```json -{ - "MockUSDFC": "0x1234...", - "Multicall3": "0x5678...", - "PDPVerifier": "0x9abc...", - "ServiceProviderRegistry": "0xdef0...", - "FilecoinWarmStorageService": "0x1122..." -} -``` - -**`step_context.json`** - Shared state between steps, useful for figuring out what happened, what commands were run: -```json -{ - "deployer_mockusdfc_eth_address": "0xabcd...", - "deployer_foc_eth_address": "0xef01...", - "mockusdfc_contract_address": "0x1234...", - "foc_lot_api_addr": "/ip4/127.0.0.1/tcp/1234/http", - "pdp_1_provider_id": "f01234" -} -``` - -**`foc_metadata.json`** - FOC service configuration: -```json -{ - "service_name": "FOC DevNet Warm Storage", - "service_description": "Warm storage service...", - "mockusdfc_address": "0x1234...", - "warm_storage_service_address": "0x5678..." -} -``` - ---- - -## Resetting the System - -### Normal Start Behavior - -**What happens on `start`:** -- Stops any running containers from previous runs -- Creates a NEW run with a unique run ID -- Previous run data is **preserved** for historical reference and debugging -- Each run is completely isolated by its run ID - -```bash -foc-devnet start # Creates new run, preserves old ones -``` - -**Why preserve old runs?** -- **Debugging:** Compare logs and state between runs -- **Historical reference:** Track what happened in previous tests -- **No conflicts:** Run IDs ensure complete isolation -- **Disk management:** You control cleanup manually - -### Manual Cleanup - -**Delete specific old run:** -```bash -# Stop cluster first -foc-devnet stop - -# Delete specific run by run ID -rm -rf ~/.foc-devnet/run/20260101T1200_OldRun -rm -rf ~/.foc-devnet/docker/volumes/run-specific/20260101T1200_OldRun -``` - -**Delete all old runs (keep only current):** -```bash -# Stop cluster -foc-devnet stop - -# Find current run ID -CURRENT_RUN=$(cat ~/.foc-devnet/state/current_run_id.txt) - -# Delete all runs except current -cd ~/.foc-devnet/run -ls | grep --invert-match "$CURRENT_RUN" | xargs rm -rf - -cd ~/.foc-devnet/docker/volumes/run-specific -ls | grep --invert-match "$CURRENT_RUN" | xargs rm -rf -``` - -**Complete reset (delete EVERYTHING including config):** -```bash -foc-devnet clean --all --images -``` - ---- - -## Run ID and Step Context - -### Run ID - -**What:** A unique identifier for each cluster execution. - -**Format:** `YYYYMMDDTHHMM_RandomName` - -**Example:** `20260102T1430_ZanyPip` - -**Why needed:** -- **Isolation:** Separate concurrent runs without conflicts -- **Debugging:** Identify logs and data for specific executions -- **Reproducibility:** Track exactly which run produced which results -- **Volume separation:** Each run has its own Docker volumes - -**Generation:** -```rust -// Date: YYYYMMDD (20260102 = January 2, 2026, condensed ISO8601) -// Time: HHMM (1430 = 2:30 PM, no colons for Docker compatibility) -// Name: RandomAdjective + RandomNoun (ZanyPip) -"20260102T1430_ZanyPip" -``` - -**Storage:** -- Current run: `~/.foc-devnet/state/current_run_id.txt` -- Latest symlink: `~/.foc-devnet/state/latest` → `../run//` - -### Step Context (SetupContext) - -**What is a "step"?** A step is a discrete unit of work in the cluster startup process (e.g., starting Lotus daemon, deploying contracts, starting Curio SPs). See [Detailed Start Sequence](#detailed-start-sequence) for a complete list of all steps. - -**What is "step context"?** Thread-safe shared state container that passes data between steps. - - -**Why is "step context" needed?** -- **Dependency resolution:** Later steps need data from earlier steps -- **Decoupling:** Steps don't directly call each other -- **Parallelization:** Thread-safe for concurrent step execution -- **State persistence:** Automatically saved to `step_context.json` - -**Architecture:** -```rust -pub struct SetupContext { - // Thread-safe key-value store for sharing data between steps - // Keys are string literals (see src/commands/start/ for examples) - state: Arc>>, - // Unique identifier for this cluster run (format: YYYYMMDDTHHMM_RandomName) - run_id: String, - // Directory where all run-specific data is stored (~/.foc-devnet/run//) - run_dir: PathBuf, - // Manages dynamic port allocation to avoid conflicts with other services - port_allocator: Arc>, -} -``` - -**Example flow:** - -```rust -// Step 1: ETHAccFundingStep creates deployer address and stores it for later steps -fn execute(&self, context: &SetupContext) -> Result<(), Box> { - // Generate a new Ethereum address for contract deployment - let address = create_eth_address()?; - // Store the address in context so other steps can retrieve it - // Context keys are string literals defined in each step's implementation - context.set("deployer_mockusdfc_eth_address", &address); - Ok(()) -} - -// Step 2: USDFCDeployStep retrieves the address from context and uses it -fn execute(&self, context: &SetupContext) -> Result<(), Box> { - // Retrieve the deployer address that was set by ETHAccFundingStep - // Returns error if key not found (dependency not met) - let deployer = context - .get("deployer_mockusdfc_eth_address") - .ok_or("Deployer not found")?; - // Use the deployer address to deploy the MockUSDFC contract - let contract = deploy_mockusdfc(&deployer)?; - // Store the contract address for subsequent steps that need it - context.set("mockusdfc_contract_address", &contract); - Ok(()) -} - -// Step 3: USDFCFundingStep retrieves the contract address and uses it -fn execute(&self, context: &SetupContext) -> Result<(), Box> { - // Retrieve the contract address set by USDFCDeployStep - let contract = context.get("mockusdfc_contract_address")?; - // Use the contract address to fund test accounts with tokens - fund_accounts(&contract)?; - Ok(()) -} -``` - -**Common context keys:** - -These keys are string literals used throughout the codebase (see step implementations in [`src/commands/start/`](src/commands/start/)). The definitive list is maintained in the code where steps use `context.get()` and `context.set()`. For an example, see [`src/commands/start/usdfc_deploy/prerequisites.rs`](src/commands/start/usdfc_deploy/prerequisites.rs). - -- `deployer_mockusdfc_eth_address` - MockUSDFC deployer address -- `deployer_foc_eth_address` - FOC contracts deployer address -- `mockusdfc_contract_address` - MockUSDFC token contract -- `multicall3_contract_address` - Multicall3 contract -- `foc_lot_api_addr` - Lotus API multiaddr -- `pdp_1_provider_id` - First Curio SP provider ID -- `pdp_2_provider_id` - Second Curio SP provider ID (if active) - ---- - -## Docker and Networking - -### Why Docker? - -**Isolation:** Each component runs in its own container with controlled dependencies. - -**Reproducibility:** Same environment on every machine (Linux, macOS, Windows with WSL2). - -**Lightweight:** Only Docker needed on host; all other dependencies containerized. - -**Build isolation:** Rust, Go, Node.js toolchains stay inside containers. - -### Portainer: Your Debugging Companion - -**What is Portainer?** - -[Portainer](https://docs.docksal.io/use-cases/portainer/) is a lightweight container management UI that gives you visual, browser-based access to all your Docker containers, networks, and volumes. foc-devnet automatically starts Portainer using the first port in your configured range. - -**Access:** http://localhost:5700 (default, or first port from `port_range_start` in config.toml) - -**Why Portainer is essential for debugging:** - -1. **Real-time Container Monitoring:** - - See which containers are running/stopped at a glance - - Monitor CPU/memory usage per container - - Quickly identify crashed or unhealthy containers - -2. **Live Log Streaming:** - - View logs from any container in real-time - - Search and filter log output - - Compare logs across multiple containers simultaneously - - No need to remember `docker logs` commands - -3. **Container Inspection:** - - View environment variables - - Check mounted volumes and their contents - - Inspect network connections - - See container configuration and restart policies - -4. **Interactive Shell Access:** - - Open bash/sh sessions directly in containers - - Execute commands without using `docker exec` - - Useful for inspecting files, running one-off commands - -5. **Network Visualization:** - - See which containers are on which networks - - Understand connectivity between components - - Troubleshoot network isolation issues - -6. **Quick Actions:** - - Restart individual containers without stopping the whole cluster - - Start/stop specific components for testing - - Delete and recreate containers quickly - -**Common debugging workflows with Portainer:** - -```bash -# 1. Check why Lotus isn't responding -# → Open Portainer → Containers → foc--lotus → Logs -# → Look for "API server listening" or error messages - -# 2. Inspect contract deployment failure -# → Containers → foc-builder → Logs -# → Search for "Error" or "failed" - -# 3. Debug Curio SP not registering -# → Containers → foc--curio-1 → Console -# → Run: curio info (to check status) - -# 4. Check database connectivity -# → Containers → foc--postgres-1 → Stats -# → Verify it's running and consuming resources -``` - -**Pro Tips:** -- **Log timestamps:** Portainer shows exact timestamps, helpful for debugging race conditions -- **Multiple tabs:** Open logs from different containers side-by-side for correlation -- **Persistent:** Portainer survives across runs, so you can check old run logs - -### Container Architecture - -| Container | Image | Purpose | Ports | -|-----------|-------|---------|-------| -| `foc--lotus` | foc-lotus | Filecoin daemon (FEVM enabled) | 1234 (API), 1235 (P2P) | -| `foc--lotus-miner` | foc-lotus-miner | First-gen miner (PoRep) | 2345 (API) | -| `foc--postgres-N` | postgres | HarmonyDB for Curio SP N (one per SP) | Dynamic from range | -| `foc--scylla-N` | scylladb/scylla | IndexStore for Curio SP N (one per SP) | Dynamic from range | -| `foc--curio-1` | foc-curio | First Curio SP (PDP) | Dynamic from range | -| `foc--curio-N` | foc-curio | Nth Curio SP (PDP) | Dynamic from range | -| `foc-builder` | foc-builder | Foundry tools (contract deployment) | Host network | -| `foc-portainer` | portainer/portainer-ce | Container management UI | 5700 (first from range) | - -**Note:** Container names include run-id for isolation (e.g., `foc-20260102T1430_ZanyPip-lotus`). - -### Network Topology - -foc-devnet uses **user-defined bridge networks** to separate components: - -**What are user-defined bridge networks?** - -Docker's user-defined bridge networks are virtual networks that provide: -- **Container isolation:** Containers on different networks can't communicate directly -- **Automatic DNS:** Containers can reference each other by name (e.g., `foc-lotus` instead of IP addresses) -- **Network segmentation:** Mimics real-world network separation for testing - -**Important:** All containers are still accessible from the host machine via their exposed ports. The networks only control container-to-container communication and provide convenient DNS resolution. This segregation helps: -- **Test network isolation scenarios:** Simulate how components interact in production -- **Prevent accidental cross-talk:** Ensure services only communicate with intended peers -- **Enable clean DNS:** Use container names instead of hardcoded IPs in configuration - -**Network diagram:** - -```mermaid -graph TB - subgraph host["Host Machine (localhost)"] - portainer["🌐 Portainer
:5700"] - lotus_api["📡 Lotus API
:5701"] - miner_api["⛏️ Miner API
:5702"] - db_api["🗄️ Postgres / Scylla
:5710"] - end - - subgraph lotus_net["foc-<run-id>-lot-net (Lotus Network)"] - lotus["foc-lotus
(Filecoin Daemon)"] - builder["foc-builder
(--net=host)"] - curio_n_lot["foc-curio-n
(on lot-net)"] - end - - subgraph miner_net["foc-<run-id>-lot-m-net (Lotus Miner Network)"] - miner["foc-lotus-miner
(PoRep Miner)"] - end - - subgraph curio_net_n["foc-<run-id>-cur-m-net-n (Curio SP N Network)"] - dbs_n["foc-postgres-n + foc-scylla-n
(Databases)"] - curio_n["foc-curio-n
(PDP Service Provider)"] - end - - %% Container to Host connections - lotus -.->|exposes| lotus_api - miner -.->|exposes| miner_api - dbs_n -.->|exposes| db_api - - %% Network connections - builder -->|uses host network| lotus - curio_n -->|same container| curio_n_lot - miner -->|connects to| lotus - curio_n_lot -->|connects to| lotus - dbs_n <-->|databases| curio_n - - %% Styling - classDef container fill:#fff,stroke:#333,stroke-width:1px - class lotus,builder,curio_n_lot,miner,dbs_n,curio_n container -``` - -**Legend:** -- **Solid lines** → Network connectivity -- **Dotted lines** → Port exposure to host -- **Boxes** → Docker networks (segregation boundaries) -- All services remain accessible from host machine despite network isolation - -**Why multiple networks (segregation purposes):** - -1. **Lotus Network (`foc--lot-net`)**: - - All components that need Lotus API access - - Provides DNS: containers can use `foc--lotus` as hostname - -2. **Lotus Miner Network (`foc--lot-m-net`)**: - - Lotus miner's isolated network - - Miner connects to Lotus daemon by name - -3. **Curio Networks (`foc--cur-m-net-N`)**: - - Each Curio SP gets its own network - - Each Curio SP has its own Postgres and Scylla instances on its network - - Provides DNS: Curio SP N can use `foc--postgres-N` and `foc--scylla-N` as database hosts - -**Builder uses host network** (`--network host`) to access Lotus RPC at `http://localhost:1234/rpc/v1`. - -**Access from host machine:** - -Despite network segregation, you can still access all services from your host: -- Lotus API: `http://localhost:1234/rpc/v1` -- Lotus Miner API: `http://localhost:2345` -- Databases: dynamic ports per SP (see `devnet-info.json`) -- Portainer UI: `http://localhost:5700` -- Curio instances: Dynamic ports (check `docker ps`) - -The networks only affect container-to-container communication, not host-to-container access. - -### Port Management - -**Dynamic allocation:** Ports allocated from configured range (default: 5700-5799). - -**Port Allocator:** Thread-safe sequential port assignment. - -**Port allocation order:** -1. **First port (5700):** Portainer web UI - always uses `port_range_start` -2. **Remaining ports:** Dynamically assigned to Curio instances, databases, and other services as needed - -```bash -# Configure in config.toml -port_range_start = 5700 -port_range_count = 100 -``` - ---- - -## Dependency Repository Management - - - -### Required Dependent Repositories - -- **[lotus](https://github.com/filecoin-project/lotus)** - Filecoin daemon -- **[curio](https://github.com/filecoin-project/curio)** - Storage provider (PDP) -- **[filecoin-services](https://github.com/FilOzone/filecoin-services)** - FOC smart contracts -- **[pdp](https://github.com/FilOzone/pdp)** - PDP contracts; optional independent override mounted over `service_contracts/lib/pdp` -- **[multicall3](https://github.com/mds1/multicall3)** - Multicall3 contract -### Dependent Version Strategy - -Default versions for these repositories are defined in code (see [`src/config.rs`](src/config.rs) `Config::default()`). - -**Version specification methods:** -- **Latest tag** (`latesttag`, `latesttag:`, `latesttag::`): Resolved once at `init` time via `git ls-remote` and pinned as a concrete `GitTag` in `config.toml`. Use a glob selector to scope which tags are considered, e.g. `latesttag:v*` or `latesttag:pdp/v*`. Bare `latesttag` matches all tags. -- **Git tags** (`GitTag`): Used for stable releases. Tags provide version pinning and stability. -- **Git commits** (`GitCommit`): Used for repositories where specific commits are required and there isn't a corresponding tag yet. (Generally tags should be preferred over commits.) -- **Git branches** (`GitBranch`): Used for development or when tracking latest changes. - -**Updating defaults:** See [How Defaults Work](#how-defaults-work) for information on how defaults are defined and the steps to apply updates. - -### Using Local Dependency Repositories - -**For active development:** - -```bash -foc-devnet init \ - --lotus local:/home/user/dev/lotus \ - --curio local:/home/user/dev/curio \ - --filecoin-services local:/home/user/dev/filecoin-services \ - --pdp local:/home/user/dev/pdp -``` - -**Mixed approach:** - -```bash -foc-devnet init \ - --lotus gitbranch:master \ - --curio local:/home/user/dev/curio -``` - -### Sharing Configuration - -**To share your exact setup with others:** - -```bash -# Copy config file -cp shared-config.toml ~/.foc-devnet/config.toml - -# Run init to download and build -# Note: this assumes that both parties are using the same commit of `foc-devnet` -# and that dependency versions in `config.toml` are all tags or commits (rather than branches). -foc-devnet init -``` - ---- - -### Reproducible Builds - -For reproducible builds, specify exact tags or commits in `config.toml`: - -```toml -[lotus] -url = "https://github.com/filecoin-project/lotus.git" -commit = "abc123def456..." - -[curio] -url = "https://github.com/filecoin-project/curio.git" -commit = "789012345678..." -``` - ---- - -## Lifecycle Overview - -The typical workflow follows: `init` → `build` → `start` → `[running]` → `stop` → `start` (regenesis). Each `start` command performs a regenesis, creating a fresh blockchain state. - -### Detailed Start Sequence - -The `start` command orchestrates multiple phases to launch the cluster. See the [Step Implementation Pattern](#step-implementation-pattern) section for how steps are structured. - -#### Before Steps - -**Pre-start cleanup:** - - Stop any existing cluster - - Generate unique run ID (format: `YYYYMMDDTHHMM_RandomName`) - - Create run directories - - Perform regenesis (delete old run volumes) - -**Genesis prerequisites (one-time per start):** - - Generate BLS keys for prefunded accounts - - Create pre-sealed sectors - - Build genesis block configuration - -**Port allocation:** - - Validate port range availability (see [Configuration System](#configuration-system) for port range settings) - - Allocate Portainer port - - Initialize port allocator for dynamic assignment - -**Network creation:** - - Create Lotus network - - Create Lotus Miner network - - Create Curio networks (one per SP) - -#### Steps - -Steps run sequentially by default, or in parallel when using the `--parallel` flag. With `--parallel`, steps are grouped into execution epochs based on dependencies: - -| Epoch | Steps | Parallelized? | Why | -|-------|-------|---------------|-----| -| 1 | Lotus | No | Foundational - everything depends on it | -| 2 | Lotus Miner | No | Needs Lotus running | -| 3 | ETH Account Funding | No | Needs blockchain active | -| 4 | MockUSDFC Deploy + Multicall3 Deploy | **⚡ YES** | Independent contract deployments | -| 5 | FOC Deploy + USDFC Funding + Databases | **⚡ YES** | Parallel contract work + DB startup | -| 6 | Curio SPs | No | Needs databases ready | -| 7 | PDP SP Registration | No | Needs Curio running for ports | -| 8 | User Setup Step | No | User setup step | - -**Time savings:** Epochs 4 and 5 run ~40% faster in parallel mode. - -**Without `--parallel`:** All 8 epochs run sequentially (~5 minutes total). -**With `--parallel`:** Epochs 4-5 run concurrently (~3 minutes total). - -**Lotus Step:** - - Start Lotus daemon container - - Wait for API file - - Verify RPC connectivity - -**Lotus Miner Step:** - - Import pre-sealed sectors - - Initialize miner - - Start mining - -**ETH Account Funding Step:** - - Transfer FIL to create FEVM addresses - - Fund deployer accounts - - Wait for address activation - -**MockUSDFC Deploy Step:** - - Deploy ERC-20 test token - - Save contract address - -**USDFC Funding Step:** - - Transfer tokens to test accounts - - Fund Curio SPs - -**Multicall3 Deploy Step:** - - Deploy Multicall3 contract - - Save contract address - -**FOC Deploy Step:** - - Deploy FOC service contracts - - Deploy PDPVerifier, ServiceProviderRegistry, etc. - - Save all contract addresses - -**Database Step:** - - Start Postgres and Scylla (one pair per Curio SP, on the SP's network) - - Verify Postgres and CQL ports - -**Curio Step:** - - Initialize Curio database schemas - - Start N Curio SP containers - - Configure PDP endpoints - -**PDP SP Registration Step:** - - Register each Curio SP in registry - - Approve authorized SPs - - Save provider IDs - -**User Setup Step:** - - Set up USER_1 for FOC: approve and deposit USDFC into FilecoinPay, approve FWSS as operator - - Export `devnet-info.json` to `~/.foc-devnet/run//devnet-info.json` - - After this step, USER_1 can interact with FOC storage services via synapse-sdk - - USER_2 and USER_3 are funded with USDFC but not configured for FOC - -#### Post Start Steps - - Save step context - - Display summary - - Print access URLs - -#### running -At this point the cluster is active and already has contracts deployed. It is ready for further interaction. - -#### stop -- Stops containers -- Cleans up networks - -#### (re)start -- Regenesis by following the [start steps](#steps) and creating a new blockchain. - -### Step Implementation Pattern - -Every step follows this trait: - -```rust -pub trait Step: Send + Sync { - // Human-readable name for logging and display (e.g., "Lotus", "FOC Deploy") - fn name(&self) -> &str; - // Validation phase: check prerequisites before executing - // (e.g., verify Docker images exist, check port availability) - fn pre_execute(&self, context: &SetupContext) -> Result<(), Box>; - // Main work: perform the actual step (e.g., start container, deploy contract) - fn execute(&self, context: &SetupContext) -> Result<(), Box>; - // Verification phase: confirm step succeeded (e.g., check API is responding, confirm deployment) - fn post_execute(&self, context: &SetupContext) -> Result<(), Box>; - // Orchestrates the full step lifecycle: pre_execute → execute → post_execute - // Returns the duration taken for the step - fn run(&self, context: &SetupContext) -> Result>; -} -``` - ---- - -## Service Provider Examples - -### Example 1: Run 1 SP with 0 Authorized - -**Scenario:** Testing unapproved SP behavior. - -**Configuration:** -```toml -# ~/.foc-devnet/config.toml -approved_pdp_sp_count = 0 -active_pdp_sp_count = 1 -``` - -**What happens:** -- 1 Curio SP starts (PDP_SP_1) -- SP registers in ServiceProviderRegistry -- SP is **not** approved (no authorization) -- SP cannot accept storage deals -- Useful for testing rejection flows - -**Steps:** -```bash -# Edit config -vim ~/.foc-devnet/config.toml -# Set: approved_pdp_sp_count = 0, active_pdp_sp_count = 1 - -# Start cluster -foc-devnet start --parallel - -# Verify -docker ps | grep curio -# Should see: foc--curio-1 - -# Check registration -cat ~/.foc-devnet/run//pdp_sps/1.provider_id.json -# SP exists but not in approved list -``` - -### Example 2: Run 3 SPs with Top 2 Authorized - -**Scenario:** Testing mixed authorization, failover scenarios. - -**Configuration:** -```toml -# ~/.foc-devnet/config.toml -approved_pdp_sp_count = 2 -active_pdp_sp_count = 3 -``` - -**What happens:** -- 3 Curio SPs start (PDP_SP_1, PDP_SP_2, PDP_SP_3) -- PDP_SP_1 and PDP_SP_2 are approved -- PDP_SP_3 registers but is **not** approved -- First 2 SPs can accept deals, third cannot -- Useful for testing authorization policies - -**Steps:** -```bash -# Edit config -vim ~/.foc-devnet/config.toml -# Set: approved_pdp_sp_count = 2, active_pdp_sp_count = 3 - -# Start cluster -foc-devnet start - -# Verify all 3 SPs running -docker ps | grep curio -# Should see: -# foc--curio-1 -# foc--curio-2 -# foc--curio-3 - -# Check provider IDs -cat ~/.foc-devnet/run//pdp_sps/1.provider_id.json -cat ~/.foc-devnet/run//pdp_sps/2.provider_id.json -cat ~/.foc-devnet/run//pdp_sps/3.provider_id.json - -# Query registry (from builder container) -docker exec foc--builder cast call \ - \ - "isApproved(uint256)" \ - -# Returns: true - -docker exec foc--builder cast call \ - \ - "isApproved(uint256)" \ - -# Returns: false -``` - -### Example 3: Maximum SPs (5) - -**Scenario:** Stress testing, load balancing. - -**Configuration:** -```toml -approved_pdp_sp_count = 5 -active_pdp_sp_count = 5 -``` - -**What happens:** -- 5 Curio SPs start (maximum supported) -- All 5 approved -- Distributed across 5 separate networks -- Each SP has own database connection -- Port allocator assigns 5 dynamic ports - -**Steps:** -```bash -# Edit config -vim ~/.foc-devnet/config.toml -# Set: approved_pdp_sp_count = 5, active_pdp_sp_count = 5 - -# Start cluster (may take longer) -foc-devnet start - -# Verify all 5 running -docker ps | grep curio -# Should see: foc--curio-{1,2,3,4,5} - -# Check networks -docker network ls | grep cur-m-net -# Should see: foc--cur-m-net-{1,2,3,4,5} - -# Monitor logs -docker logs -f foc--curio-1 -docker logs -f foc--curio-2 -# ... etc -``` - -### Querying SP Status - -```bash -# List all containers -docker ps --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}" - -# Check specific SP logs -docker logs foc--curio-2 - -# Query provider IDs -cat ~/.foc-devnet/state/latest/pdp_sps/*.provider_id.json - -# Access Postgres (one per SP, see below for more detail) -docker exec -it foc--postgres-1 psql -U curio -d curio - -# Query Lotus for miner info -docker exec foc--lotus lotus state miner-info f01000 - -# Check contract via cast -docker exec foc--builder cast call \ - $(cat ~/.foc-devnet/state/latest/contract_addresses.json | jq -r .ServiceProviderRegistry) \ - "getServiceProvider(uint256)" \ - -``` - -### Querying the Databases - -Each Curio has its own Postgres and Scylla (curio-N → postgres-N / scylla-N). Postgres tables are in the `curio` schema. Credentials: `curio`/`curio`/`curio` (user/pass/db). - -```bash -docker exec foc--postgres-1 psql -U curio -d curio -c "" -docker exec foc--scylla-1 cqlsh -e "" -``` - -Key tables: `curio.harmony_machines`, `curio.harmony_task`, `curio.harmony_task_history`, `curio.parked_pieces`. The Scylla IndexStore holds the piece index and PDP proof cache (`curio.pdp_cache_layer`). - ---- - -## Troubleshooting - -### Port conflicts -```bash -# Check what's using a port -lsof -i :5700 - -# Change port range in config -vim ~/.foc-devnet/config.toml -# Set: port_range_start = 6000 -``` - -### Container won't start -```bash -# Check logs -docker logs foc--lotus - -# Check if image exists -docker images | grep foc-lotus - -# Rebuild if needed -foc-devnet clean -foc-devnet init -``` - -### Build failures -```bash -# Check disk space -df -h - -# Clean Docker -docker system prune -a - -# Rebuild with verbose output -docker build -t foc-lotus docker/lotus/ -``` - -### Network issues -```bash -# List networks -docker network ls | grep foc - -# Inspect network -docker network inspect foc--lot-net - -# Recreate if corrupted -foc-devnet stop -docker network rm foc--lot-net -foc-devnet start -``` - ---- - -## Additional User Actions - -### Custom Genesis Block - -The genesis template is generated during the genesis prerequisites phase of the `start` command and is located at: - -``` -~/.foc-devnet/docker/volumes/run-specific//genesis/ -``` - -To customize the genesis block, you can: -- Modify the genesis generation code in `src/commands/start/lotus/` -- Edit the template files after they're generated (before the Lotus step completes) -- Pass custom genesis parameters through the configuration system - -**Note:** Customizing genesis requires understanding the Filecoin genesis format. See the [Detailed Start Sequence](#detailed-start-sequence) for when genesis prerequisites run. - -```bash -# Modify sector size, block time, etc. -# (Advanced - requires understanding Filecoin genesis format) -``` - -### Monitoring with Portainer -```bash -# Access Portainer UI (uses first port in range) -http://localhost:5700 # Default -# Or: http://localhost: if you changed the config - -# Default login: admin / (set on first access) -``` - -### Accessing Lotus API -```bash -# Get API token -docker exec foc--lotus cat /root/.lotus/token - -# Query via curl -curl -X POST http://localhost:1234/rpc/v1 \ - -H "Content-Type: application/json" \ - -H "Authorization: Bearer " \ - -d '{"jsonrpc":"2.0","method":"Filecoin.ChainHead","params":[],"id":1}' -``` - -### Contract Interaction -```bash -# Using cast (from builder container) -docker exec foc--builder cast send \ - --rpc-url http://localhost:1234/rpc/v1 \ - --private-key \ - \ - "transfer(address,uint256)" \ - \ - 1000000000000000000 - -# Using forge script -docker run --rm --network host \ - -v $(pwd)/scripts:/scripts \ - foc-builder forge script /scripts/MyScript.s.sol \ - --rpc-url http://localhost:1234/rpc/v1 \ - --broadcast -``` - -## Scenario Tests - -Scenario tests are Python scripts that validate devnet state after startup. They share a single running devnet and execute serially in a defined order. The runner lives in `scenarios/` and uses **only Python stdlib** — no `pip install` required. - -### Running scenarios - -```bash -# Run all scenarios -python3 scenarios/run.py - -# Run a single scenario directly -python3 scenarios/test_basic_balances.py - -# Point at a specific devnet run -DEVNET_INFO=~/.foc-devnet/state//devnet-info.json python3 scenarios/run.py -``` - -Reports are written to `~/.foc-devnet/state/latest/scenario_report.md`. - -### CI integration - -Scenarios run automatically in CI after the devnet starts. On nightly runs (or manual dispatch with `reporting` enabled), failures automatically create a GitHub issue with a full report. - -CI resolves compatibility-sensitive dependencies from `ci/dependency-profiles.json`. -Pull requests use the pinned `default` profile, while nightly `stability` runs use -the latest final releases and nightly `frontier` runs pin current development -branch heads to immutable commits. Nightly CI also runs manifest-declared mixed -profiles such as `stability-frontier-curio`, where all dependencies come from -`stability` except the named component, which comes from `frontier`. In -`stability`, PDP is pinned to the git submodule bundled with the selected -filecoin-services stability tag; in `frontier`, PDP is pinned as an independent -repo. Mixed profiles that override filecoin-services keep that PDP pin instead -of implicitly taking the overridden filecoin-services submodule. The resolved -metadata path is exposed to scenarios as `CI_DEPENDENCY_METADATA`; Synapse SDK -and filecoin-pin also receive their exact source, version/ref, and commit -through `SYNAPSE_SDK_*` and `FILECOIN_PIN_*` environment variables. PDP receives -`PDP_SOURCE`, `PDP_REF`, and `PDP_COMMIT` when dependency profiles are resolved. diff --git a/ci/README.md b/ci/README.md index 210a6f6d..51f13023 100644 --- a/ci/README.md +++ b/ci/README.md @@ -1,26 +1,20 @@ # CI Dependency Profiles -`dependency-profiles.json` is the central manifest for CI dependency selection. -Its resolver is located in `scripts/resolve-ci-dependencies.py`. +[`dependency-profiles.json`](dependency-profiles.json) declares the profiles +accepted by the [dependency resolver](../scripts/resolve-ci-dependencies.py). ## Profiles -The manifest declares valid profiles in its top-level `profiles` object: - -- `default`: used by PR CI, a known-working set of client versions. -- `stability`: used by nightly CI to test stable releases. -- `frontier`: used by nightly CI to test branch heads. -- `stability-frontier-lotus`: used by nightly CI to test stable releases - except Lotus, which is resolved from `frontier`. -- `stability-frontier-curio`: used by nightly CI to test stable releases - except Curio, which is resolved from `frontier`. -- `stability-frontier-filecoin-services`: used by nightly CI to test stable - releases except filecoin-services, which is resolved from `frontier`. -- `stability-frontier-pdp`: used by nightly CI to test stable releases except - PDP, which is resolved from `frontier`. - -Each component must define a selection for every component profile referenced by -the top-level profile definitions. Today those component selections are +The manifest's top-level `profiles` object defines which names the resolver +accepts. The [PR workflow](../.github/workflows/ci_pull_request.yml) uses +`default`. The [nightly workflow](../.github/workflows/ci_nightly.yml) has an +explicit matrix for `stability`, `frontier`, and selected +`stability-frontier-*` profiles. Adding a profile to the manifest makes it +resolvable but does not schedule it; add a matrix entry if nightly CI should +run it. + +For each top-level profile, each component must define the selection that +applies to it. The manifest currently uses the component selections `default`, `stability`, and `frontier`. Top-level profile definitions have a `base` component profile and can override @@ -38,9 +32,8 @@ specific components: ``` In that example, Curio resolves from its `frontier` selection while every other -component resolves from `stability`. A profile is valid only if it is explicitly -declared in `profiles`; for example, `stability-frontier-filecoin-pin` does not -exist unless added there. +component resolves from `stability`. Mixed profile names are not generated +automatically. ## Component Fields @@ -135,9 +128,8 @@ Resolve a git submodule gitlink from a tag or tag pattern in another repository. The resolver first resolves `repository` and `tag` with the same rules as `git_tag`, then reads `path` from that tree and records the submodule gitlink SHA -as the selected component commit. PDP uses this to pin the same bundled PDP -gitlink as the selected filecoin-services stability tag, even in mixed profiles -that override filecoin-services itself. +as the selected component commit. PDP's `stability` selection uses this +strategy even in mixed profiles that override filecoin-services itself. ### `npm_version` @@ -211,21 +203,59 @@ Overrides are currently allowed only for npm-installed `synapse-sdk` and `filecoin-pin` selections. They are written to the temporary consumer `package.json`. -Current consumers write npm overrides to the temporary `package.json` used by -their scenario. - ## Current Boundary `resolve-ci-dependencies.py` resolves metadata. It does **not** install components. -Installation currently lives in three places (which consume the resolved -metadata): +The [reusable CI workflow](../.github/workflows/ci_run.yml) passes the +resolved source overrides to `foc-devnet init` for Lotus, Curio, +filecoin-services, and optionally PDP. The +[Synapse runtime](../scenarios/synapse_runtime.py) and +[filecoin-pin scenario](../scenarios/test_multi_copy_upload.py) consume the +metadata when installing their own dependencies. + +### Resolver Commands + +From the repository root, with Python 3, Git, and npm available: + +```sh +metadata="$(mktemp)" +python3 scripts/resolve-ci-dependencies.py resolve \ + --profile stability --output "$metadata" +``` + +To verify a CI checkout, run the command below **after** `foc-devnet init` +has prepared the repositories for the resolved profile. This checks the Git +commits against the metadata and writes the verified commits back to it. + +```sh +python3 scripts/resolve-ci-dependencies.py verify --metadata "$metadata" +``` + +By default, `verify` looks under `~/.foc-devnet/code`; pass `--code-dir` if +the checkouts are elsewhere. The reusable workflow shows how to use +`--github-output` and `--github-env` to pass the resolved settings to CI steps. + +## Local Checks + +Install Rust with `rustfmt` and `clippy`, Python 3, and Black (for example, +with `pipx install black`). The lint script skips checks whose tools are +missing. From the repository root: -- `foc-devnet init`: Lotus, Curio, filecoin-services, and optionally PDP. -- `scenarios/synapse_runtime.py`: released or preview Synapse packages. -- `scenarios/test_multi_copy_upload.py`: filecoin-pin scenario dependency. +```sh +FIX=0 ./scripts/lint.sh # check only, as in PR CI +cargo test --all-targets --all-features +``` + +Run `./scripts/lint.sh` without `FIX=0` to apply formatting fixes. To run the +dependency resolver unit tests on their own: + +```sh +python3 -m unittest discover -s scripts/tests -p 'test_*.py' +``` -This split is intentional, but it is not necessarily the final shape. Resolution -and installation should remain separate phases; however, installation behavior -could become declarative and centralized. +Optionally install the pre-commit hook with +`./scripts/install_precommit_hooks.sh`. It runs the lint script in auto-fix +mode by default, so review and stage any formatting fixes separately. The +installer leaves an existing hook in place unless you pass `-f`. diff --git a/contracts/MockUSDFC/README.md b/contracts/MockUSDFC/README.md index c8d16141..20d05e6b 100644 --- a/contracts/MockUSDFC/README.md +++ b/contracts/MockUSDFC/README.md @@ -1,21 +1,15 @@ # MockUSDFC - Foundry Project -A complete Foundry-based project for deploying and verifying the MockUSDFC token contract. This project is part of the FOC (Filecoin Onchain Contracts) localnet testing infrastructure. - -## Overview - -MockUSDFC is a simple ERC-20 token contract used for testing FOC warm storage services. It includes: - -- **ERC-20 Token**: Standard fungible token with 18 decimals -- **Mint/Burn Functions**: Testing utilities for token supply management -- **Deployment Script**: Automated deployment via Foundry scripts -- **Verification Script**: Comprehensive testing of all contract functions +Use this project to build, test, and manually deploy the +[MockUSDFC test token](../README.md). foc-devnet deploys its own instance during +startup; the manual commands below are not required for a normal startup. ## Prerequisites -- [Foundry](https://book.getfoundry.sh/getting-started/installation) installed -- Running FOC localnet with Lotus FEVM enabled (port 1234) -- Private key for deployment account with sufficient FIL balance +- [Foundry](https://www.getfoundry.sh/introduction/installation), Git, Make, + and Bash for the commands below. +- For deployment and verification only: a running local FEVM RPC endpoint and + a funded test account's hex private key. Never use a production key. ## Quick Start @@ -23,86 +17,95 @@ MockUSDFC is a simple ERC-20 token contract used for testing FOC warm storage se ```bash cd contracts/MockUSDFC -make install +forge install --root "$PWD" --no-git OpenZeppelin/openzeppelin-contracts@v5.0.0 \ + foundry-rs/forge-std@v1.12.0 ``` -This will install OpenZeppelin contracts v5.0.0. +The scripts and tests need `forge-std` as well as OpenZeppelin Contracts. +Use the command above rather than `make install`, which only requests +OpenZeppelin and uses an older Forge option. -### 2. Build Contracts +### 2. Build and Test ```bash make build +make test ``` ### 3. Deploy Contract +For a foc-devnet run, use `info.lotus.host_rpc_url` from `devnet-info.json` +instead of assuming a fixed port. See [Accessing Lotus API](../../docs/integrations.md#accessing-lotus-api). +Set the URL once so deployment and verification target the same endpoint: + ```bash -make deploy PRIVATE_KEY=0x +read -rp 'Local FEVM RPC URL: ' RPC_URL +export RPC_URL +read -rsp 'Local test account private key (0x-prefixed): ' PRIVATE_KEY +printf '\n' +make deploy PRIVATE_KEY="$PRIVATE_KEY" ``` -This will: -- Deploy MockUSDFC with 1,000,000 tokens initial supply -- Display the deployed contract address -- Save deployment details to `broadcast/` directory +`make deploy` uses `--broadcast` and sends a transaction to `RPC_URL`. Once +Foundry reports a successful broadcast, use the logged address or the +deployment record in `broadcast/`. A script log alone does not prove that the +transaction succeeded. ### 4. Verify Contract Functions ```bash -make verify PRIVATE_KEY=0x CONTRACT_ADDRESS=0x +read -rp 'Deployed MockUSDFC address: ' CONTRACT_ADDRESS +make verify PRIVATE_KEY="$PRIVATE_KEY" CONTRACT_ADDRESS="$CONTRACT_ADDRESS" ``` -This will test: -- ✓ Token metadata (name, symbol, decimals) -- ✓ Balance queries -- ✓ Transfer functionality -- ✓ Mint functionality -- ✓ Burn functionality +This simulates the checks against the deployed contract using the RPC state; +it does not broadcast or change live balances. It checks metadata and +exercises mint and burn. The simulated transfer runs only if the signer holds +at least 1,000 tokens. The checks expect the fixed mint recipient (and the +fixed transfer recipient, if exercised) to have no existing token balance. +Prefer a fresh deployment. ### 5. Deploy and Verify in One Step ```bash -make deploy-verify PRIVATE_KEY=0x +make deploy-verify PRIVATE_KEY="$PRIVATE_KEY" ``` -This convenience target will: -1. Deploy the contract -2. Wait 5 seconds for transaction confirmation -3. Automatically verify all functions +This target broadcasts the deployment, extracts the logged address, and waits +five seconds before running the same simulation. Check Foundry's deployment +result if the follow-up check fails. ## Environment Variables -All commands support these optional environment variables: +Deployment and verification accept the following settings: | Variable | Description | Default | |----------|-------------|---------| -| `PRIVATE_KEY` | Deployer's private key (hex format) | **Required** | -| `CONTRACT_ADDRESS` | Address of deployed contract (for verify) | **Required for verify** | -| `RPC_URL` | Filecoin FEVM RPC endpoint | `http://localhost:1234/rpc/v1` | -| `INITIAL_SUPPLY` | Initial token supply (in wei) | `1000000000000000000000000` (1M tokens) | +| `PRIVATE_KEY` | Funded local test account's hex key | Required | +| `CONTRACT_ADDRESS` | Deployed token address | Required for `make verify` | +| `RPC_URL` | Local FEVM RPC endpoint | `http://localhost:1234/rpc/v1` | +| `INITIAL_SUPPLY` | Deployment supply in base units (18 decimals) | `1000000000000000000000000` (1 million tokens) | ### Examples -**Custom RPC URL:** -```bash -make deploy PRIVATE_KEY=0xabc123... RPC_URL=http://custom-rpc:1234/rpc/v1 -``` - **Custom Initial Supply (10M tokens):** ```bash -make deploy PRIVATE_KEY=0xabc123... INITIAL_SUPPLY=10000000000000000000000000 +INITIAL_SUPPLY=10000000000000000000000000 make deploy PRIVATE_KEY="$PRIVATE_KEY" ``` ## Manual Deployment (Without Makefile) -If you prefer to use Foundry commands directly: +To call the scripts directly, use the same key and contract address as above: ### Deploy ```bash forge script script/Deploy.s.sol:DeployMockUSDFC \ - --rpc-url http://localhost:1234/rpc/v1 \ - --private-key 0x \ + --rpc-url "${RPC_URL:-http://localhost:1234/rpc/v1}" \ + --private-key "$PRIVATE_KEY" \ --broadcast \ + --slow \ + --gas-estimate-multiplier 10000 \ -vvv ``` @@ -110,127 +113,12 @@ forge script script/Deploy.s.sol:DeployMockUSDFC \ ```bash forge script script/Verify.s.sol:VerifyMockUSDFC \ - --rpc-url http://localhost:1234/rpc/v1 \ - --private-key 0x \ - --sig "run(address)" 0x \ + --rpc-url "${RPC_URL:-http://localhost:1234/rpc/v1}" \ + --private-key "$PRIVATE_KEY" \ + --sig 'run(address)' "$CONTRACT_ADDRESS" \ -vvv ``` -## Contract Functions - -### Standard ERC-20 Functions - -- `name()` → `"Mock USDC"` -- `symbol()` → `"USDFC"` -- `decimals()` → `18` -- `totalSupply()` → Current total supply -- `balanceOf(address)` → Balance of address -- `transfer(address, uint256)` → Transfer tokens -- `approve(address, uint256)` → Approve spending -- `transferFrom(address, address, uint256)` → Transfer on behalf - -### Testing Functions - -- `mint(address to, uint256 amount)` → Mint new tokens (unrestricted) -- `burn(address from, uint256 amount)` → Burn tokens (unrestricted) - -⚠️ **Note**: Mint and burn functions are intentionally unrestricted for testing purposes. Do not use in production. - -## Integration with foc-localnet - -This Foundry project is designed to simplify the deployment logic in `src/commands/start/usdfc_deploy.rs`. Instead of manually constructing deployment transactions in Rust, the deployment step can now: - -1. **From Host**: Run `make deploy-verify` directly during development -2. **From Rust**: Execute the Makefile targets via `Command::new("make")` -3. **From foc-builder**: Mount this directory and run Foundry scripts - -### Example Rust Integration - -```rust -// In usdfc_deploy.rs -let output = Command::new("make") - .current_dir("/path/to/contracts/MockUSDFC") - .arg("deploy-verify") - .env("PRIVATE_KEY", deployer_private_key) - .env("RPC_URL", "http://localhost:1234/rpc/v1") - .output()?; - -// Parse contract address from output -let contract_address = extract_contract_address(&output.stdout)?; -``` - -## Project Structure - -``` -MockUSDFC/ -├── foundry.toml # Foundry configuration -├── Makefile # Convenient deployment commands -├── README.md # This file -├── src/ -│ └── MockUSDFC.sol # Token contract -├── script/ -│ ├── Deploy.s.sol # Deployment script -│ └── Verify.s.sol # Verification script -├── lib/ # Dependencies (OpenZeppelin) -├── out/ # Compiled artifacts (gitignored) -├── cache/ # Build cache (gitignored) -└── broadcast/ # Deployment logs -``` - -## Troubleshooting - -### "Error: PRIVATE_KEY is required" - -Make sure to provide the private key in hex format: -```bash -make deploy PRIVATE_KEY=0xabc123... -``` - -### "Failed to extract contract address" - -The deployment may have failed. Check the output for errors. Common issues: -- Insufficient FIL balance for gas -- FEVM not enabled on Lotus -- RPC endpoint not accessible - -### "Transaction reverted" - -Wait a few more seconds after deployment before verifying: -```bash -make deploy PRIVATE_KEY=0x... -sleep 10 # Wait longer -make verify PRIVATE_KEY=0x... CONTRACT_ADDRESS=0x... -``` - -### OpenZeppelin Import Errors - -Reinstall dependencies: -```bash -make clean -make install -make build -``` - -## Development - -### Run Tests - -```bash -make test -``` - -### Clean Build Artifacts - -```bash -make clean -``` - -### View All Available Commands - -```bash -make help -``` - ## License -MIT License - See LICENSE file in repository root. +MIT License — see the [repository license](../../LICENSE). diff --git a/contracts/README.md b/contracts/README.md index 48c742a1..a160abcb 100644 --- a/contracts/README.md +++ b/contracts/README.md @@ -1,72 +1,28 @@ # MockUSDFC Token -A simple ERC-20 token for local development and testing with FOC (Filecoin Onchain Contracts). +MockUSDFC is the ERC-20 test token for local FOC (Filecoin Onchain Cloud) development. ## Overview -MockUSDFC is a toy implementation of the USDFC (USD Filecoin) token used in production FOC deployments. It provides the same ERC-20 interface but is designed for local testing only. +**Test use only.** Any caller can mint tokens to any address or burn tokens +from any holder without approval. Do not deploy this contract in production. ## Contract Details -- **Name**: Mock USD Filecoin +- **Name**: Mock USDC - **Symbol**: USDFC - **Decimals**: 18 -- **Initial Supply**: 1,000,000 USDFC (configurable) -- **Features**: - - Standard ERC-20 interface (transfer, approve, transferFrom) - - Mintable by owner - - Simple access control (owner can mint) +- **Interface**: ERC-20 with ERC-2612 permit, plus unrestricted `mint` and `burn` ## Usage in foc-devnet -The MockUSDFC token is automatically deployed during the FOC deployment step when starting the local network: - -```bash -cargo run start -``` - -The deployment sequence: -1. GLOBAL_FIL_FAUCET → FEVM_FAUCET → FOC_DEPLOYER (fund transfers) -2. Deploy MockUSDFC using FOC_DEPLOYER account -3. Deploy FOC contracts with MockUSDFC address +`foc-devnet start` deploys MockUSDFC for the local network as part of startup. ## Manual Deployment -If you need to deploy the token manually: - -```bash -export ETH_RPC_URL="http://localhost:1234/rpc/v1" -export DEPLOYER_ADDRESS="0x..." -export INITIAL_SUPPLY="1000000000000000000000000" # 1 million tokens - -./scripts/deploy-mock-usdfc.sh -``` +See the [MockUSDFC Foundry project](MockUSDFC/README.md) for build, test, and +manual deployment commands using [Foundry](https://www.getfoundry.sh/). ## Contract Source -The contract is located at `contracts/MockUSDFC.sol` and is a minimal ERC-20 implementation for testing purposes. - -**Warning**: This is a TOY contract for local development only. Do NOT use in production. - -## Interacting with the Token - -Once deployed, you can interact with MockUSDFC using standard ERC-20 methods: - -```bash -# Check balance -cast call $TOKEN_ADDRESS "balanceOf(address)(uint256)" $USER_ADDRESS --rpc-url $ETH_RPC_URL - -# Transfer tokens -cast send $TOKEN_ADDRESS "transfer(address,uint256)" $TO_ADDRESS $AMOUNT --rpc-url $ETH_RPC_URL - -# Mint more tokens (owner only) -cast send $TOKEN_ADDRESS "mint(address,uint256)" $TO_ADDRESS $AMOUNT --rpc-url $ETH_RPC_URL -``` - -## For Production - -In production deployments on Calibnet or Mainnet, the real USDFC token addresses are: -- **Calibnet**: `0xb3042734b608a1B16e9e86B374A3f3e389B4cDf0` -- **Mainnet**: `0x80B98d3aa09ffff255c3ba4A241111Ff1262F045` - -These addresses are automatically used by the FOC deployment script when deploying to non-local networks. +[`MockUSDFC/src/MockUSDFC.sol`](MockUSDFC/src/MockUSDFC.sol) diff --git a/docs/README.md b/docs/README.md new file mode 100644 index 00000000..2f0ca30b --- /dev/null +++ b/docs/README.md @@ -0,0 +1,18 @@ +# Advanced documentation + +New to foc-devnet? Start with the [quick start](../README.md#-quick-start). +See the [CLI reference](cli.md) for running the commands from source. + +| I want to… | Guide | +|---|---| +| Look up a command or flag | [CLI reference](cli.md) | +| Change ports, provider counts, dependency sources, or the data directory | [Configuration](configuration.md) | +| Understand what start and stop preserve, find run artifacts, or clean up disk space | [Run lifecycle and cleanup](lifecycle.md) | +| Fix hostname or port conflicts, find logs, or inspect Docker resources | [Networking and troubleshooting](networking.md) | +| Test provider approval and endorsement, or inspect a provider database | [Service provider workflows](service-providers.md) | +| Query Lotus or a deployed contract | [Inspect a running devnet](integrations.md) | +| Run the scenario suite and find its report | [Scenario tests](scenarios.md) | + +For application integration, see the [client examples](../examples/README.md). +For contributor workflows, see [local checks and CI](../ci/README.md) and the +[MockUSDFC contract guide](../contracts/README.md). diff --git a/docs/cli.md b/docs/cli.md new file mode 100644 index 00000000..522d7202 --- /dev/null +++ b/docs/cli.md @@ -0,0 +1,137 @@ +# CLI reference + +Commands and options. For a first run from source, see the [quick start](../README.md#-quick-start). +If the executable is not on your `PATH`, use `cargo run --` in place of +`foc-devnet` from the repository root. + +## Commands Reference + +### `clean` +Removes the contents of the selected [base directory](configuration.md#foc_devnet_basedir), +including builds, keys, cached proof parameters, run data, and logs. It keeps +the directory itself and preserves `config.toml` by default. **Run +[`stop`](#stop) first**: `clean` deletes local state but does not stop +containers or remove Docker networks. + +```bash +foc-devnet clean [OPTIONS] +``` + +**Options:** +- `--all` — Also remove `config.toml`. +- `--images` — Also attempt to remove the shared `foc-lotus`, `foc-lotus-miner`, + `foc-curio`, and `foc-builder` Docker images. Stock images, unrelated images, + and Portainer's container and data volume are not removed. + +Run `stop`, then check `docker ps` for remaining devnet services (Portainer +can remain running). If any are still running, resolve the teardown issue +before deleting their data. To remove local data and foc-devnet images while +keeping the configuration for the next `init`: + +```bash +foc-devnet clean --images +``` + +### `init` +Initializes the base directory, prepares dependency repositories, and builds +Docker images. It does not build the Lotus or Curio binaries. + +Use a fresh base directory or run [`stop`](#stop) followed by [`clean`](#clean) +before reinitializing. If `config.toml` already exists, `init` reuses it and +applies any explicit source overrides. + +```bash +foc-devnet init [OPTIONS] +``` + +**Options:** +- `--curio ` - Curio source location +- `--lotus ` - Lotus source location +- `--filecoin-services ` - Filecoin Services source location +- `--pdp ` — Override the PDP source. If `pdp` is not set in the saved configuration and no override is supplied, use the PDP submodule bundled with Filecoin Services. +- `--proof-params-dir ` — Stage proof parameters from a local directory. +- `--rand` — Generate a random mnemonic instead of the deterministic test mnemonic. +- `--no-docker-build` — Skip artifact staging (including `--proof-params-dir`) and Docker image builds. Use only when the required images are already available. + +**Source Format:** +- `latesttag` — Newest version-sorted Git tag in the configured repo (resolved once at `init`). +- `latesttag:` - Newest git tag matching a glob selector, e.g. `latesttag:v*` or `latesttag:pdp/v*`. +- `latesttag::` - Newest matching tag from a custom repo, e.g. `latesttag:https://github.com/org/repo.git:v*`. +- `gittag:` — Specific tag in the configured repo. +- `gittag::` - Tag from custom repo, e.g. `gittag:https://github.com/org/repo.git:v1.0.0` +- `gitcommit:` — Specific commit in the configured repo. +- `gitcommit::` - Commit from custom repo +- `gitbranch:` — Specific branch in the configured repo. +- `gitbranch::` - Branch from custom repo +- `local:` - Local directory + +Without a custom URL, Git selectors use the configured Git URL, or the built-in +URL if there is no configured Git URL for that component. + +**Example:** +```bash +foc-devnet init --lotus local:/home/user/lotus +``` + +### `build` +Builds Lotus (including `lotus-miner`) or Curio binaries in Docker. Run both +after [`init`](#init); output binaries are placed in `bin/` under the base +directory. + +```bash +foc-devnet build lotus +foc-devnet build curio +``` + +Both subcommands accept an optional positional path but **ignore it**. To use +a local checkout, select it during `init`, for example +`foc-devnet init --curio local:/home/user/curio`. + +### `start` +Starts a fresh local Filecoin network. Run after `init`, `build lotus`, and +`build curio`. Startup first checks [host name resolution](networking.md#setup-requirements), +then attempts to [stop existing devnet services](#stop) on the same Docker daemon. + +```bash +foc-devnet start [--parallel] +``` + +Startup is sequential by default. `--parallel` enables **experimental** +concurrent execution of independent steps; use the default when troubleshooting. +See the [startup sequence](lifecycle.md#lifecycle-overview) and +[run outputs](lifecycle.md#key-files) for what to expect. + +### `stop` +Stops and removes devnet service containers and attempts to remove their Docker +networks. It clears the current run ID from the selected base directory, but +preserves run files and leaves [Portainer](networking.md#portainer-your-debugging-companion) +running. + +```bash +foc-devnet stop +``` + +**Docker-wide devnet scope:** In addition to the recorded run, `stop` sweeps +containers based on foc-devnet-built images and networks matching the devnet +naming scheme on the current Docker daemon. It is not limited to +`FOC_DEVNET_BASEDIR`. Use the same base directory as `start` so `stop` can also +find the recorded run's Postgres and Scylla containers, which use stock images. + +### `status` +Shows the current status of the foc-devnet system. + +```bash +foc-devnet status +``` + +Use it to inspect the recorded run, container states, and published ports. +The builder is not a persistent service, so it need not appear as running. + +### `version` +Shows version information. + +```bash +foc-devnet version [--notty] +``` + +`--notty` forces plain output without tracing prefixes even on a terminal. diff --git a/docs/configuration.md b/docs/configuration.md new file mode 100644 index 00000000..9f4997a4 --- /dev/null +++ b/docs/configuration.md @@ -0,0 +1,174 @@ +# Configuration + +## Configuration System + +### Config File Location + +The configuration file is `~/.foc-devnet/config.toml` by default, or +`$FOC_DEVNET_BASEDIR/config.toml` when the base directory is overridden. + +### Config Structure + +The following is a complete example with the current compiled defaults. +Each component source has one variant table, such as `[lotus.GitTag]`. +Set top-level port and provider counts before the source tables. + +```toml +port_range_start = 5700 +port_range_count = 100 +active_pdp_sp_count = 2 +approved_pdp_sp_count = 2 +endorsed_pdp_sp_count = 1 + +[lotus.GitTag] +url = "https://github.com/filecoin-project/lotus.git" +tag = "v1.39.1" + +[curio.GitTag] +url = "https://github.com/filecoin-project/curio.git" +tag = "v1.29.2" + +[filecoin_services.GitTag] +url = "https://github.com/FilOzone/filecoin-services.git" +tag = "v1.5.0" + +[multicall3.GitTag] +url = "https://github.com/mds1/multicall3.git" +tag = "v3.1.0" +``` + +The source variants are `GitTag` (`url`, `tag`), `GitCommit` (`url`, `commit`), +`GitBranch` (`url`, `branch`), and `LocalSource` (`dir`). PDP is optional. +Without a `pdp` source table, deployment uses Filecoin Services' +`service_contracts/lib/pdp` submodule. For example, add this table to use an +existing local PDP checkout: + +```toml +[pdp.LocalSource] +dir = "/home/user/dev/pdp" +``` + +### Configuration Parameters + +| Parameter | Type | Default | Description | +|-----------|------|---------|-------------| +| `port_range_start` | u16 | 5700 | First host port in the configured range | +| `port_range_count` | u16 | 100 | Number of host ports in the range | +| `active_pdp_sp_count` | usize | 2 | Number of Curio providers to run and register | +| `approved_pdp_sp_count` | usize | 2 | Number of those providers to approve in Warm Storage | +| `endorsed_pdp_sp_count` | usize | 1 | Number of approved providers to endorse | + +Provider counts must satisfy +`0 ≤ endorsed_pdp_sp_count ≤ approved_pdp_sp_count ≤ active_pdp_sp_count ≤ 5`. +If `approved_pdp_sp_count = 0`, set `endorsed_pdp_sp_count = 0` as well. +Use a nonempty [port range](networking.md#port-management) with enough available ports for +the services configured. + +### How Defaults Work + +`init` writes [`Config::default()`](../src/config.rs) when no configuration file +exists. An upgrade does not replace existing settings. To regenerate the +configuration, back it up, run [`foc-devnet stop`](cli.md#stop), and +[check that no devnet services remain](cli.md#clean). Then run: + +```bash +foc-devnet clean --all && foc-devnet init +``` + +This deletes local run data as well as the old configuration. Plain `clean` +preserves `config.toml` for the next `init`. + +### Editing Config + +Edit `config.toml` to change the ports or provider counts for the next `start`. +For source changes, use [`init` source overrides](cli.md#init) when reinitializing. +Keep ports and counts at the top level, before the component tables. + +### Environment Variables + +#### `FOC_DEVNET_BASEDIR` + +Overrides the default `~/.foc-devnet` base directory. Use it to keep different +configurations and their files on separate paths, or to put the data on another +disk. It does **not** isolate Docker resources. Use only one running foc-devnet +per Docker daemon: [start and stop share cleanup scope](cli.md#stop), startup +replaces an existing devnet Portainer, and `clean --images` acts on shared images. + +Use an absolute path for shell and scenario commands. For example, after +stopping any previous devnet from its original base directory: + +```bash +export FOC_DEVNET_BASEDIR="$HOME/foc-test-env" +foc-devnet init +foc-devnet build lotus +foc-devnet build curio +foc-devnet start +``` + +The CLI expands a leading `~`, but not every helper does. The shell examples +in these guides assume `FOC_DEVNET_BASEDIR` is unset or already expanded to an absolute +path. + +## Dependency Repository Management + +Sources are selected through [`init`](cli.md#init) and recorded in +[`config.toml`](#config-structure). + +### Required Dependent Repositories + +- **[lotus](https://github.com/filecoin-project/lotus)** - Filecoin daemon +- **[curio](https://github.com/filecoin-project/curio)** - Storage provider (PDP) +- **[filecoin-services](https://github.com/FilOzone/filecoin-services)** - FOC smart contracts +- **[pdp](https://github.com/FilOzone/pdp)** - PDP contracts; optional independent override mounted over `service_contracts/lib/pdp` +- **[multicall3](https://github.com/mds1/multicall3)** - Multicall3 contract + +### Dependent Version Strategy + +Default versions for these repositories are defined in code (see [`src/config.rs`](../src/config.rs) `Config::default()`). + +Use a tag or commit to pin a checkout; a branch can move. `latesttag` resolves +to a specific tag during `init` and is saved as `GitTag`, so an ordinary re-init +using that config does not automatically select a newer tag. + +**Updating defaults:** See [How Defaults Work](#how-defaults-work) for information on how defaults are defined and the steps to apply updates. + +### Using Local Dependency Repositories + +**For active development:** + +```bash +foc-devnet init \ + --lotus local:/home/user/dev/lotus \ + --curio local:/home/user/dev/curio \ + --filecoin-services local:/home/user/dev/filecoin-services \ + --pdp local:/home/user/dev/pdp +``` + +**Mixed approach:** + +```bash +foc-devnet init \ + --lotus gitbranch:master \ + --curio local:/home/user/dev/curio +``` + +### Sharing Configuration + +Copy a valid config into a clean base directory before `init`. For a shared +setup, use the same foc-devnet version and pin the dependencies. `LocalSource` +paths must exist on the recipient's machine. + +```bash +base="${FOC_DEVNET_BASEDIR:-$HOME/.foc-devnet}" +mkdir -p "$base" +cp -i shared-config.toml "$base/config.toml" +foc-devnet init +``` + +### Reproducible Builds + +Pin each dependency to a specific release tag, as in the +[configuration example](#config-structure), or to an exact commit. For a +commit pin, replace the component's `GitTag` table with a `GitCommit` table +(for example `[lotus.GitCommit]`), keep the `url`, and use `commit` instead of +`tag`. Commit pins avoid relying on tags remaining unchanged. diff --git a/docs/integrations.md b/docs/integrations.md new file mode 100644 index 00000000..3a9e6a8a --- /dev/null +++ b/docs/integrations.md @@ -0,0 +1,29 @@ +# Inspect a running devnet + +For application integration and export validation, see the [client examples](../examples/README.md). + +### Accessing Lotus API +Use the exported URL instead of assuming a host port. The devnet Lotus API +does not require authentication; keep it on a trusted development network. +This example uses `jq` and `curl`: + +```bash +base="${FOC_DEVNET_BASEDIR:-$HOME/.foc-devnet}" +info="$base/state/latest/devnet-info.json" +rpc_url=$(jq -er '.info.lotus.host_rpc_url' "$info") +curl -fsS "$rpc_url" \ + -H 'Content-Type: application/json' \ + -d '{"jsonrpc":"2.0","method":"Filecoin.ChainHead","params":[],"id":1}' +``` + +### Contract Interaction +Use [Foundry's `cast`](https://getfoundry.sh/) on the host with the exported +host RPC URL. For example, read the MockUSDFC supply from a running devnet: + +```bash +base="${FOC_DEVNET_BASEDIR:-$HOME/.foc-devnet}" +info="$base/state/latest/devnet-info.json" +rpc_url=$(jq -er '.info.lotus.host_rpc_url' "$info") +token_addr=$(jq -er '.info.contracts.mockusdfc_addr' "$info") +cast call --rpc-url "$rpc_url" "$token_addr" 'totalSupply()(uint256)' +``` diff --git a/docs/lifecycle.md b/docs/lifecycle.md new file mode 100644 index 00000000..80f81396 --- /dev/null +++ b/docs/lifecycle.md @@ -0,0 +1,130 @@ +# Run lifecycle and cleanup + +## Lifecycle Overview + +The usual workflow is `init` → `build lotus` and `build curio` → `start` → +`stop`. A later `start` creates a fresh run; it does not require a rebuild +unless the binaries have changed or were removed. See +[Normal Start Behavior](#normal-start-behavior). + +## Resetting the System + +### Normal Start Behavior + +Each `start` attempts to stop the existing devnet and creates a new run with a +fresh chain. It preserves older run directories and their run-specific data on +the host. A `stop` followed by `start` does not resume the old chain. + +`state/latest` is updated during startup, **before** there is an export. It is +not a pointer to the last successful or currently running devnet. `stop` leaves +the link in place. If startup fails, the new run may lack `devnet-info.json`. +Even after a successful startup, an export failure is logged as a warning. +Check the selected run and export before using its endpoints. Older exports +under `run//` are useful as records; they do not keep the services live. + +### Manual Cleanup + +Use [`clean`](cli.md#clean) after stopping if none of the local runs need to be kept. +To keep the recorded chain but remove other run data, use Bash and `jq`. +Capture the ID before `stop` clears it. The preview also includes logs from +other CLI commands, including the `stop` command. Do not start another devnet +during cleanup. + +```bash +( + set -e + base=$(cd -- "${FOC_DEVNET_BASEDIR:-$HOME/.foc-devnet}" && pwd -P) + export FOC_DEVNET_BASEDIR="$base" + keep=$(jq -er '.run_id' "$base/state/current_runid.json") + run_id_pattern='^[0-9]{8}T[0-9]{4}_[A-Za-z]+$' + if [[ ! $keep =~ $run_id_pattern || ! -d "$base/run/$keep" || + ! "$base/state/latest" -ef "$base/run/$keep" ]]; then + printf 'Cannot confirm the run to keep; no data removed.\n' >&2 + exit 1 + fi + roots=("$base/run" "$base/docker/volumes/run-specific") + for root in "${roots[@]}"; do + if [[ $(cd -- "$root" && pwd -P) != "$root" ]]; then + printf 'Unexpected run directory: %s; no data removed.\n' "$root" >&2 + exit 1 + fi + done + + foc-devnet stop + running=$(docker ps --format '{{.Names}} {{.Image}}') + db_pattern='^foc-[0-9]{8}T[0-9]{4}_[A-Za-z0-9]+-(postgres|scylla)-[0-9]+$' + while read -r name image; do + case "${image%%:*}" in + foc-lotus|foc-lotus-miner|foc-curio|foc-builder) ;; + *) [[ $name =~ $db_pattern ]] || continue ;; + esac + printf 'Container still running: %s; no data removed.\n' "$name" >&2 + exit 1 + done <<< "$running" + + old_runs=() + for root in "${roots[@]}"; do + for dir in "$root"/*; do + [[ -d $dir && ! -L $dir ]] || continue + id=${dir##*/} + [[ $id =~ $run_id_pattern && $id != "$keep" ]] || continue + old_runs+=("$dir") + done + done + if ((${#old_runs[@]} == 0)); then + printf 'No historical run directories to remove.\n' + exit 0 + fi + printf 'Keep run: %s\nRemove:\n' "$keep" + printf ' %s\n' "${old_runs[@]}" + read -r -p 'Type yes to remove these directories: ' answer + if [[ $answer == yes ]]; then + rm -rf -- "${old_runs[@]}" + fi +) +``` + +## Directory Structure + +``` +/ +├── config.toml +├── bin/ # Compiled binaries +├── code/ # Dependency checkouts or local source symlinks +├── docker/volumes/ +│ ├── cache/ # Shared proof parameters +│ └── run-specific// # Data for one run +│ ├── genesis/ +│ ├── lotus-data/ # Includes the Lotus API token +│ ├── lotus-miner-data/ +│ └── curio/ # One directory per SP, numbered from 1 +│ ├── 1/ +│ └── 2/ +├── keys/ # Test keys and mnemonic; do not share +├── logs/ # Includes build logs under build/ +├── run// +│ ├── setup.log +│ ├── logs/ # Container logs captured at startup finalization +│ ├── post_start_status.log +│ ├── version.txt +│ ├── devnet-info.json # Versioned export for consumers +│ └── pdp_sps/*.provider_id.json +├── state/ +│ ├── current_runid.json # Cleared by stop +│ └── latest # Symlink to latest recorded run directory +└── tmp/ +``` + +`genesis/` contains generated files for inspection. There is no custom-genesis +CLI or configuration option, and startup does not pause for template edits. + +### Key Files + +Use `devnet-info.json` for scripts and SDKs. The export includes a top-level +`version` and an `info` object with the run ID, host RPC URL, contract addresses, +users and their **test private keys**, and provider details. See the +[schema](../examples/devnet-schema.js) and [validation instructions](../examples/README.md). +Do not publish the file or use its keys outside the devnet. + +If present, `step_context.json` can help diagnose startup. Unlike +`devnet-info.json`, its format is internal and can change without notice. diff --git a/docs/networking.md b/docs/networking.md new file mode 100644 index 00000000..f4af8d6f --- /dev/null +++ b/docs/networking.md @@ -0,0 +1,126 @@ +# Networking and troubleshooting + +## Network Architecture & Inter-SP Communication + +### How It Works: `host.docker.internal` + +The service registry advertises provider URLs as +`http://host.docker.internal:` so host-side clients and other +Curio containers can both use them. On the host, this name must resolve to a +loopback address. Curio containers use Docker's `host-gateway` mapping to reach +the published ports. The host-only URL in `devnet-info.json` uses `localhost`. +Provider connections use plain HTTP; use this setup only on a trusted development network. + +### Setup Requirements + +Check name resolution on the host, including on Docker Desktop and in CI. +If `host.docker.internal` does not resolve to loopback, add the following entry +to the host's `/etc/hosts` (update any existing entry instead of duplicating it): + +```text +127.0.0.1 host.docker.internal +``` + +For GitHub Actions, see the [hostname setup step in CI](../.github/workflows/ci_run.yml#L306-L308). + +### Validation + +`foc-devnet start` checks for a loopback address for `host.docker.internal` +before stopping any existing cluster. If it fails, correct the host mapping +before retrying. + +## Docker and Networking + +Docker runs the devnet services and the Lotus and Curio builds. See the +[installation prerequisites](../README.md#prerequisites) for the host requirements. + +### Portainer: Your Debugging Companion + +[Portainer](https://docs.portainer.io/) provides live inspection of Docker +containers, networks, and logs. Open `http://localhost:5700` with the default +configuration, or use the configured `port_range_start` port. Set the admin +password on first access. + +**Trusted networks only.** The devnet publishes Portainer's HTTP port without +a loopback-only bind and mounts the Docker socket. Portainer can manage the +entire Docker daemon, not only the devnet. Restrict access with the host +firewall and do not expose the port publicly or forward it from another network. + +`stop` leaves Portainer running but removes the devnet service containers. +Portainer cannot show Docker logs for removed containers. For prior runs, use +`run//setup.log` and any startup snapshots in `run//logs/`. +For logs produced after startup, capture `docker logs` while the container +still exists. + +### Container Architecture + +| Container | Image | Ports inside the container | +|-----------|-------|----------------------------| +| `foc--lotus` | `foc-lotus` | 1234 (API), 1946 (P2P) | +| `foc--lotus-miner` | `foc-lotus-miner` | 2345 (API) | +| `foc--curio-N` | `foc-curio` | API, UI, and PDP service | +| `foc--postgres-N` | `postgres` | 5432 | +| `foc--scylla-N` | `scylladb/scylla` | 9042 (CQL) | +| `foc--portainer` | `portainer/portainer-ce` | 9000 (HTTP) | + +`N` is the one-based provider index. The `foc-builder` image is used by +short-lived deployment commands; there is no persistent builder to `docker exec` into. + +### Network Topology + +foc-devnet creates user-defined Docker bridge networks with these names: + +- `foc__lot-net` — Lotus, with connections from Lotus Miner and Curio. +- `foc__lot-m-net` — Lotus Miner's separate network. +- `foc__cur-m-net-N` — Curio provider `N` and its Postgres and Scylla containers. + +These networks separate container traffic but do not restrict host access to +published ports. Use [the exported host RPC URL](integrations.md#accessing-lotus-api) for +Lotus and the export's `info.lotus_miner.api_port` and `info.pdp_sps` +entries for the miner, PDP services, and databases. + +### Port Management + +The default host port range is 5700–5799. Portainer uses the first port. +Lotus, Lotus Miner, the Curio instances, and the databases get dynamically +assigned host ports from the rest of the range. Do not assume that a container +port is also its host port. Use `foc-devnet status` or the exported addresses +to locate a running service. + +## Troubleshooting + +### Port conflicts +Check which process is using the conflicting host port, for example +`lsof -i :5700`. If the range needs to change, update `port_range_start` and +`port_range_count` in [the configuration](configuration.md#configuration-system), then start a +new run. If the current cluster is still running, stop it from its original +base directory first. + +### Container won't start +Start with the failed command's output or `setup.log`. Early failures can +happen before `state/latest` is updated or before `post_start_status.log` +and container log snapshots are written. For an existing container, find +its name with `docker ps -a` and inspect it with `docker logs`. Docker +cannot show live logs for a removed container. + +### Build failures +Check available disk space (`df -h`), Docker usage (`docker system df`), and +the CLI build logs under `logs/build/` in the [base directory](lifecycle.md#directory-structure). +If the foc-devnet images need to be rebuilt, use the scoped +[`stop` then `clean --images`](cli.md#clean) procedure, followed by `init`, +`build lotus`, and `build curio`. This removes local run data; save anything +you need first. Use `init` to build images with the host UID/GID settings +foc-devnet expects, rather than building the image with bare `docker build`. + +### Network issues +For host resolution errors, see [Setup Requirements](#setup-requirements). +To inspect the current run's Lotus bridge, use `jq` and Docker: + +```bash +base="${FOC_DEVNET_BASEDIR:-$HOME/.foc-devnet}" +run_id=$(jq -er '.run_id' "$base/state/current_runid.json") && +docker network inspect "foc_${run_id}_lot-net" +``` + +Normal [`stop`](cli.md#stop) attempts to remove the devnet networks. If one remains, +inspect that exact network and its attachments before removing it manually. diff --git a/docs/scenarios.md b/docs/scenarios.md new file mode 100644 index 00000000..0548b182 --- /dev/null +++ b/docs/scenarios.md @@ -0,0 +1,55 @@ +# Scenario tests + +Scenario tests run serially against one running devnet. The Python runner uses +the standard library, but scenarios also invoke Docker and Foundry and run +Node.js clients. Use Python 3.11+, Git, Node.js 24+, npm, and pnpm. The +[prerequisite script](../scripts/setup-scenarios-prerequisites.sh) checks the +JavaScript tools and installs Foundry; the scenarios install client dependencies +and need network access for downloads. +Use the default provider configuration for the full suite: the replication +scenarios need two usable storage providers. + +### Running scenarios + +From the repository root, after starting the devnet and confirming that its +export is present: + +```bash +./scripts/setup-scenarios-prerequisites.sh +python3 scenarios/run.py + +# Or run a single scenario without the suite report +python3 scenarios/test_basic_balances.py +``` + +By default, the suite reads `state/latest/devnet-info.json`. To select an +export explicitly, set both `DEVNET_INFO` (Python checks) and `DEVNET_INFO_PATH` +(Synapse and the [pinned filecoin-pin version](../ci/dependency-profiles.json)) +to the same file. The services for that run must still be running. + +The suite writes `~/.foc-devnet/state/latest/scenario_report.md` by default, +independently of `FOC_DEVNET_BASEDIR`. This example uses `jq` to select the +current run explicitly and write its report alongside its export. Use an +existing directory for `REPORT_FILE`. + +```bash +base="${FOC_DEVNET_BASEDIR:-$HOME/.foc-devnet}" +run_id=$(jq -er '.run_id' "$base/state/current_runid.json") && +info="$base/run/$run_id/devnet-info.json" && +test -f "$info" && +PATH="$HOME/.foc-devnet/artifacts/foundry/bin:$PATH" \ + FOC_DEVNET_BASEDIR="$base" \ + DEVNET_INFO="$info" DEVNET_INFO_PATH="$info" \ + REPORT_FILE="$base/run/$run_id/scenario_report.md" \ + python3 scenarios/run.py +``` + +The prerequisite script installs Foundry under `~/.foc-devnet` regardless of +the selected base directory. Adding that Foundry directory to `PATH`, as in +the example above, makes it available to scenarios using a custom base directory. + +### CI integration + +CI runs scenarios after startup and uploads the report as a workflow artifact. +Nightly or manually enabled reporting can also create or update a GitHub issue. +See [CI Dependency Profiles](../ci/README.md) for dependency selection and pins. diff --git a/docs/service-providers.md b/docs/service-providers.md new file mode 100644 index 00000000..1332da4b --- /dev/null +++ b/docs/service-providers.md @@ -0,0 +1,78 @@ +# Service provider workflows + +Use these recipes with the [provider settings](configuration.md#configuration-parameters) in `config.toml`. + +## Service Provider Examples + +### Example 1: Run 1 SP with 0 Authorized + +To test behavior with a registered but unapproved provider, set these +top-level entries in the existing `config.toml`: + +```toml +active_pdp_sp_count = 1 +approved_pdp_sp_count = 0 +endorsed_pdp_sp_count = 0 +``` + +Run `foc-devnet start` and [inspect the export](#querying-sp-status). The only +provider should have both `is_approved` and `is_endorsed` set to `false`. + +### Example 2: Run 3 SPs with Top 2 Authorized + +To test a mix of approved, endorsed, and unapproved providers, set: + +```toml +active_pdp_sp_count = 3 +approved_pdp_sp_count = 2 +endorsed_pdp_sp_count = 1 +``` + +Run `foc-devnet start` and [inspect the export](#querying-sp-status). Providers +1 and 2 are approved in Warm Storage; only provider 1 is endorsed. Provider 3 +is registered but neither approved nor endorsed. + +### Example 3: Maximum SPs (5) + +To run the maximum number of providers and approve all of them, set: + +```toml +active_pdp_sp_count = 5 +approved_pdp_sp_count = 5 +endorsed_pdp_sp_count = 5 +``` + +Run `foc-devnet start` and [inspect the export](#querying-sp-status). Each +provider has its own Postgres and Scylla containers and its own Curio network. + +### Querying SP Status + +Inspect the approval and endorsement flags recorded at startup, and the +registry proxy address, with `jq`: + +```bash +base="${FOC_DEVNET_BASEDIR:-$HOME/.foc-devnet}" +info="$base/state/latest/devnet-info.json" +jq '.info.pdp_sps | map({provider_id, container_name, pdp_service_url, is_approved, is_endorsed})' "$info" +jq -er '.info.contracts.service_provider_registry_proxy_addr' "$info" +``` + +Approval is in the Warm Storage contract; endorsement is tracked separately. +The export's `provider_id` is the one-based instance index. To look up the +actual on-chain ID for instance `N`, use `pdp_sps/N.provider_id.json` in the +run directory. + +### Querying the Databases + +Each provider has its own Postgres and Scylla containers. Postgres uses `curio` +as the user, password, and database name. To inspect schemas for provider 1 +on a running devnet, use `jq` and Docker: + +```bash +( + base="${FOC_DEVNET_BASEDIR:-$HOME/.foc-devnet}" + run_id=$(jq -er '.run_id' "$base/state/current_runid.json") || exit 1 + docker exec "foc-$run_id-postgres-1" psql -U curio -d curio -c '\dn' + docker exec "foc-$run_id-scylla-1" cqlsh -e 'DESCRIBE KEYSPACES;' +) +``` diff --git a/examples/README.md b/examples/README.md index 81796bc7..07d77ea7 100644 --- a/examples/README.md +++ b/examples/README.md @@ -11,34 +11,45 @@ This directory contains examples demonstrating how to interact with a running FO ## Prerequisites -- Node.js 20+ installed -- A running FOC DevNet instance (`foc-devnet start`) -- npm packages: `viem`, `zod` +- Node.js 24+ and npm +- A running devnet started via the [quick start](../README.md) +- Access to the npm registry to install dependencies ## Usage -1. Start the DevNet: - ```bash - foc-devnet start - ``` - -2. Find the devnet-info.json file: - ```bash - # The file is located in the run directory - cat ~/.foc-devnet/state/latest/devnet-info.json - ``` - -3. Install dependencies and run examples: - ```bash - cd examples - npm install - - # Validate the schema - npm run validate-schema ~/.foc-devnet/state/latest/devnet-info.json - - # Read DevNet info - npm run read-info ~/.foc-devnet/state/latest/devnet-info.json - - # Check balances - npm run check-balances ~/.foc-devnet/state/latest/devnet-info.json - ``` +Run from the repository root: + +```bash +DEVNET_INFO="$HOME/.foc-devnet/state/latest/devnet-info.json" +cd examples +npm install +node validate-schema.js "$DEVNET_INFO" +npm run read-info -- "$DEVNET_INFO" +npm run check-balances -- "$DEVNET_INFO" +``` + +With a custom `FOC_DEVNET_BASEDIR`, use its absolute path in place of +`$HOME/.foc-devnet`. For a specific run, use `/run//devnet-info.json`. +The versioned export contains raw test private keys. Do not share the file or +reuse the keys outside the devnet. + +## Exercise storage + +Use `USER_1` for storage tests. The other test users are funded but are not +configured for Warm Storage. + +Run the repository's Synapse end-to-end scenario from the repository root. +It requires Python 3, Node.js 24+, npm registry access, and two usable storage +providers (the default configuration). + +```bash +python3 scenarios/test_synapse_e2e.py +``` + +With a compatible version of filecoin-pin already installed, add a file with: + +```bash +filecoin-pin add --network devnet path/to/file +``` + +For the full test suite, see [Scenario tests](../docs/scenarios.md). diff --git a/src/commands/start/foc_deploy/mod.rs b/src/commands/start/foc_deploy/mod.rs index 87576184..1ec0e0a1 100644 --- a/src/commands/start/foc_deploy/mod.rs +++ b/src/commands/start/foc_deploy/mod.rs @@ -1,7 +1,6 @@ //! FOC deployment module. //! -//! This module contains all components related to deploying FOC (Filecoin Onchain Contracts) -//! including contract addresses management, deployment logic, and step execution. +//! Deploys Filecoin Onchain Cloud (FOC) contracts for local devnets. pub mod contract_addresses; pub mod deployment; diff --git a/src/config.rs b/src/config.rs index fcb000a0..3101dd6a 100644 --- a/src/config.rs +++ b/src/config.rs @@ -225,7 +225,7 @@ pub struct Config { /// Location specification for the filecoin-services repository. /// /// Defines how to obtain the filecoin-services code, which contains - /// the FOC (Filecoin Onchain Contracts) deployment scripts needed by Curio. + /// the FOC (Filecoin Onchain Cloud) deployment scripts needed by Curio. /// See [`Location`] for available options. pub filecoin_services: Location, @@ -250,7 +250,7 @@ pub struct Config { /// This is the total number of Curio SPs that will be registered and approved /// in the service provider registry. These SPs can accept storage deals. /// Must satisfy: ENDORSED_PDP_SP_COUNT <= APPROVED_PDP_SP_COUNT <= ACTIVE_PDP_SP_COUNT <= MAX_PDP_SP_COUNT - /// Default: 1 + /// Default: 2 pub approved_pdp_sp_count: usize, /// Number of endorsed PDP service providers. @@ -267,16 +267,14 @@ pub struct Config { /// Some may be approved, some may not (for testing unapproved SP scenarios). /// Total miners = 1 (lotus-miner) + ACTIVE_PDP_SP_COUNT (curio SPs) /// Must satisfy: ENDORSED_PDP_SP_COUNT <= APPROVED_PDP_SP_COUNT <= ACTIVE_PDP_SP_COUNT <= MAX_PDP_SP_COUNT - /// Default: 1 + /// Default: 2 pub active_pdp_sp_count: usize, } impl Default for Config { /// Creates a default configuration with sensible defaults. /// - /// The default configuration sets up a minimal cluster with one of each - /// node type and assumes pre-built executables are available in standard - /// system locations (/usr/local/bin/). + /// Starts two active, approved providers, one of which is endorsed. /// /// The defaults should always use `GitCommit` or `GitTag` locations to ensure /// reproducibility. diff --git a/src/external_api/devnet_info.rs b/src/external_api/devnet_info.rs index f3658ecf..cf78ee40 100644 --- a/src/external_api/devnet_info.rs +++ b/src/external_api/devnet_info.rs @@ -55,7 +55,7 @@ pub struct UserInfo { pub evm_addr: String, /// Native Filecoin address (t410f...) pub native_addr: String, - /// Private key in hex format (without 0x prefix) + /// Raw test private key in hex format, with a `0x` prefix. pub private_key_hex: String, }