Repository navigation
feat(cli): add decdn node register for on-chain node registration (#929) - #931
Conversation
…929) Implements ADR 019 § Step 2.3: the operator-facing command that binds the local iroh identity on-chain via `CapacityBond.registerNode`. It loads the node key and Ethereum keystore, reads the operator's `bindingNonce` and `registrationNonce`, builds the EIP-712 `bindingSignature` and the ed25519 ownership signature locally, packs the multiaddrs, and submits the transaction (or prints everything under `--dry-run`). This is the only `node` subcommand that talks to the chain rather than the admin RPC. The ed25519 ownership digest in `decdn_incentive::node_register` byte-matches `CapacityBond._verifyEd25519OwnershipSignature`; a unit test pins it against the committed registerNode vector in CapacityBondRegionE2E.t.sol, so a drift in the packed preimage fails loudly rather than at on-chain revert time. Phase 2.1/2.2 (`approve`/`bond`/`declareMbps`) remain an operator precondition (the contract reverts if the bond is unposted). - incentive: extend the CapacityBond `sol!` bindings with `registerNode` + `bindingNonce`/`registrationNonce`; add `node_register` (digest + multiaddr packing) with vector-pinned tests. - cli: new `node register` command + args; promote alloy to a normal dep (already in the binary tree via incentive, so no new bloat). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
There was a problem hiding this comment.
Code Review
This pull request implements the decdn node register subcommand for on-chain node registration (ADR 019 § Step 2.3). It adds the necessary CLI commands, argument parsing, and off-chain signature generation logic. The review feedback highlights a critical issue where synchronous blocking operations (keystore decryption and user prompts) are executed directly within an async function, potentially blocking the Tokio executor thread; it suggests offloading this to tokio::task::spawn_blocking and refactoring the signer loader to accept owned parameters. Additionally, it recommends optimizing pack_multiaddrs by pre-allocating the output vector's capacity.
Important
The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.
| })?; | ||
| let node_id = B256::from_slice(node_secret.public().as_bytes()); | ||
|
|
||
| let signer = load_operator_signer(args, &resolved.keystore)?; |
There was a problem hiding this comment.
The load_operator_signer function performs synchronous, blocking operations—specifically reading from standard input (which blocks indefinitely waiting for user input) and decrypting the Ethereum keystore using a CPU-heavy Key Derivation Function (KDF) like scrypt or argon2 (which blocks for hundreds of milliseconds). Calling this directly inside an async fn blocks the Tokio executor thread, preventing other tasks from making progress. Wrap this call in tokio::task::spawn_blocking to offload it to a dedicated threadpool and await the join handle to ensure correct ordering and prevent task dropping during shutdown.
let keystore = resolved.keystore.clone();
let password_file = resolved_password_file(args);
let signer = tokio::task::spawn_blocking(move || {
load_operator_signer(password_file, keystore)
})
.await
.context("failed to load operator signer")??;References
- When offloading synchronous file I/O or blocking operations to a threadpool using
tokio::task::spawn_blockingin Rust, await the join handle instead of using fire-and-forget if you need to guarantee operation ordering or ensure that pending tasks are not dropped during runtime shutdown.
| fn load_operator_signer( | ||
| args: &cli::RegisterArgs, | ||
| keystore: &Path, | ||
| ) -> anyhow::Result<PrivateKeySigner> { | ||
| let mut sources = vec![PasswordSource::Env(eth_identity::KEYSTORE_PASSWORD_ENV)]; | ||
| if let Some(path) = resolved_password_file(args) { | ||
| sources.push(PasswordSource::File(path)); | ||
| } | ||
| sources.push(PasswordSource::Prompt { confirm: false }); | ||
| let password = eth_identity::read_password(&sources, "eth keystore password")?; | ||
| eth_identity::load_signer(keystore, &password) | ||
| .with_context(|| format!("failed to load keystore at {}", keystore.display())) | ||
| } |
There was a problem hiding this comment.
Refactor load_operator_signer to accept owned parameters (Option<PathBuf> and PathBuf) instead of references to RegisterArgs and Path. This allows the function to be easily moved into a tokio::task::spawn_blocking closure.
| fn load_operator_signer( | |
| args: &cli::RegisterArgs, | |
| keystore: &Path, | |
| ) -> anyhow::Result<PrivateKeySigner> { | |
| let mut sources = vec![PasswordSource::Env(eth_identity::KEYSTORE_PASSWORD_ENV)]; | |
| if let Some(path) = resolved_password_file(args) { | |
| sources.push(PasswordSource::File(path)); | |
| } | |
| sources.push(PasswordSource::Prompt { confirm: false }); | |
| let password = eth_identity::read_password(&sources, "eth keystore password")?; | |
| eth_identity::load_signer(keystore, &password) | |
| .with_context(|| format!("failed to load keystore at {}", keystore.display())) | |
| } | |
| fn load_operator_signer( | |
| password_file: Option<PathBuf>, | |
| keystore: PathBuf, | |
| ) -> anyhow::Result<PrivateKeySigner> { | |
| let mut sources = vec![PasswordSource::Env(eth_identity::KEYSTORE_PASSWORD_ENV)]; | |
| if let Some(path) = password_file { | |
| sources.push(PasswordSource::File(path)); | |
| } | |
| sources.push(PasswordSource::Prompt { confirm: false }); | |
| let password = eth_identity::read_password(&sources, "eth keystore password")?; | |
| eth_identity::load_signer(&keystore, &password) | |
| .with_context(|| format!("failed to load keystore at {}", keystore.display())) | |
| } |
| pub fn pack_multiaddrs(addrs: &[String]) -> anyhow::Result<Vec<u8>> { | ||
| let mut out = Vec::new(); | ||
| for addr in addrs { | ||
| let bytes = addr.as_bytes(); | ||
| let len = u16::try_from(bytes.len()).map_err(|_| { | ||
| anyhow::anyhow!( | ||
| "multiaddr is {} bytes, exceeds the uint16 length prefix max of {}: {addr}", | ||
| bytes.len(), | ||
| u16::MAX, | ||
| ) | ||
| })?; | ||
| out.extend_from_slice(&len.to_be_bytes()); | ||
| out.extend_from_slice(bytes); | ||
| } | ||
| Ok(out) | ||
| } |
There was a problem hiding this comment.
Pre-allocate the capacity of the out vector using Vec::with_capacity to avoid multiple reallocations as multiaddrs are packed and appended.
| pub fn pack_multiaddrs(addrs: &[String]) -> anyhow::Result<Vec<u8>> { | |
| let mut out = Vec::new(); | |
| for addr in addrs { | |
| let bytes = addr.as_bytes(); | |
| let len = u16::try_from(bytes.len()).map_err(|_| { | |
| anyhow::anyhow!( | |
| "multiaddr is {} bytes, exceeds the uint16 length prefix max of {}: {addr}", | |
| bytes.len(), | |
| u16::MAX, | |
| ) | |
| })?; | |
| out.extend_from_slice(&len.to_be_bytes()); | |
| out.extend_from_slice(bytes); | |
| } | |
| Ok(out) | |
| } | |
| pub fn pack_multiaddrs(addrs: &[String]) -> anyhow::Result<Vec<u8>> { | |
| let total_len: usize = addrs.iter().map(|s| s.len() + 2).sum(); | |
| let mut out = Vec::with_capacity(total_len); | |
| for addr in addrs { | |
| let bytes = addr.as_bytes(); | |
| let len = u16::try_from(bytes.len()).map_err(|_| { | |
| anyhow::anyhow!( | |
| "multiaddr is {} bytes, exceeds the uint16 length prefix max of {}: {addr}", | |
| bytes.len(), | |
| u16::MAX, | |
| ) | |
| })?; | |
| out.extend_from_slice(&len.to_be_bytes()); | |
| out.extend_from_slice(bytes); | |
| } | |
| Ok(out) | |
| } |
References
- Minimize memory allocations in performance-critical code by using in-place filtering or reusable buffers instead of creating multiple intermediate collections.
There was a problem hiding this comment.
Pull request overview
This PR adds an operator-facing CLI flow to register a node on-chain (ADR 019 §2.3), wiring decdn node register to construct the required EIP-712 binding signature + ed25519 ownership signature and submit CapacityBond.registerNode.
Changes:
- Add
decdn_incentive::node_registerhelpers for the on-chain ownership digest and multiaddr packing, plus vector-pinned tests. - Extend
CapacityBondABI bindings withbindingNonce,registrationNonce, andregisterNode. - Add the
decdn node registerCLI subcommand and implement the on-chain registration transaction path.
Reviewed changes
Copilot reviewed 9 out of 9 changed files in this pull request and generated 4 comments.
Show a summary per file
| File | Description |
|---|---|
| crates/incentive/src/node_register.rs | New helper module for ownership digest + multiaddr packing with unit tests pinned to contract vectors. |
| crates/incentive/src/lib.rs | Exposes the new node_register module. |
| crates/incentive/src/capacity_bond.rs | Extends ABI bindings to include nonce getters and registerNode. |
| crates/common/src/cli/node.rs | Adds CLI surface (NodeCommand::Register, RegisterArgs) and help text for the new command. |
| crates/common/src/cli/mod.rs | Re-exports RegisterArgs. |
| crates/cli/src/commands/register.rs | Implements decdn node register end-to-end (config resolution, signing, tx submission, output). |
| crates/cli/src/commands/node.rs | Dispatches NodeCommand::Register to the new implementation. |
| crates/cli/src/commands/mod.rs | Registers the new commands::register module. |
| crates/cli/Cargo.toml | Promotes alloy to a normal dependency for the CLI registration command. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| let data_dir = args | ||
| .data_dir | ||
| .clone() | ||
| .map(|p| expand_tilde(&p)) | ||
| .or_else(|| file.identity.as_ref().and_then(|i| i.data_dir.clone())) | ||
| .or_else(cli::default_data_dir) | ||
| .ok_or_else(|| { | ||
| anyhow::anyhow!("data_dir not set and no default available (pass --data-dir)") | ||
| })?; |
| let keystore = args | ||
| .keystore | ||
| .clone() | ||
| .map(|p| expand_tilde(&p)) | ||
| .or_else(|| bc.and_then(|b| b.eth_keystore.clone())) | ||
| .unwrap_or_else(|| eth_identity::keystore_path(&data_dir)); |
| /// Unlike the other `node` subcommands this performs an on-chain | ||
| /// transaction, so it needs the blockchain coordinates (`rpc_url`, | ||
| /// `chain_id`, `capacity_bond_address`) and the operator's keys rather than | ||
| /// an admin URL. Each is taken from a flag when present, otherwise from the | ||
| /// `[blockchain]` / `[identity]` tables of the TOML config (same file the | ||
| /// daemon reads), otherwise the built-in default. |
| /// Data directory holding `node.secret`. Overrides `identity.data_dir`; | ||
| /// defaults to the platform data dir (`~/.local/share/decdn`). | ||
| #[arg(long, value_name = "PATH")] |
Coverage reportTotal: 85.51% (was 85.75%, ▼ 0.24%) — 37479/43828 lines
History
|
- Offload the scrypt keystore decryption to `spawn_blocking` so it doesn't stall the async executor (matches the daemon runtime's keystore load). `load_operator_signer` now takes owned params and is async. - Tilde-expand config-sourced `data_dir` / `eth_keystore` paths, not just flag values — `data_dir = "~/.decdn"` in TOML now resolves. - Pre-allocate `pack_multiaddrs`' output buffer. - Fix `RegisterArgs` help: `rpc_url` / `capacity_bond_address` are required (no default); correct the `data_dir` default to `~/.decdn`. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Implements ADR 019 § Step 2.1–2.2: the operator command that stakes to a capacity tier before registration. The operator passes only `--mbps`; the TOKEN amount is read from the on-chain `bondRequired` curve. Idempotent by construction: it reads `bondRequired(mbps)`, `activeBond`, `minBond`, `declaredMbps`, the band, and the ERC-20 allowance, computes `target = max(minBond, bondRequired(mbps))`, and approves + bonds only the shortfall (`target − activeBond`), then `declareMbps` unless already at the tier. Bonding the shortfall rather than a flat amount means a re-run after a partial failure converges instead of double-bonding. The tier is validated against the on-chain `[minCapacityMbps, maxCapacityMbps]` band up front so an out-of-band `--mbps` is rejected before any bond is stranded behind a `declareMbps` revert. `--dry-run` prints the plan; `--json` for machine output. - incentive: extend the CapacityBond `sol!` bindings with token/activeBond/ minBond/declaredMbps/bondRequired/min+maxCapacityMbps views and bond/ declareMbps writes. Reuse `decdn_incentive::Erc20` for allowance/approve/ balanceOf. - cli: extract the shared chain plumbing (config-coordinate resolution, keystore-signer loading, provider build, address/hex helpers) into `commands::chain_ctx`, flatten a shared `ChainArgs` flag group into both `RegisterArgs` and `BondArgs`, and refactor `register` onto it. Review fixes (#934): a real no-op run now reports `submitted=false dry_run=false` rather than masquerading as a dry-run preview; the shared `chain_ctx` carries the register-branch fixes (scrypt keystore load offloaded to `spawn_blocking`; config-sourced `data_dir`/`eth_keystore` paths tilde-expanded). Stacked on #929 (PR #931); operator flow is `decdn node bond --mbps N` then `decdn node register …`. The `decdn setup` wizard is tracked in #933. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Addressed review feedback in
|
Implements ADR 019 § Step 2.1–2.2: the operator command that stakes to a capacity tier before registration. The operator passes only `--mbps`; the TOKEN amount is read from the on-chain `bondRequired` curve. Idempotent by construction: it reads `bondRequired(mbps)`, `activeBond`, `minBond`, `declaredMbps`, the band, and the ERC-20 allowance, computes `target = max(minBond, bondRequired(mbps))`, and approves + bonds only the shortfall (`target − activeBond`), then `declareMbps` unless already at the tier. Bonding the shortfall rather than a flat amount means a re-run after a partial failure converges instead of double-bonding. The tier is validated against the on-chain `[minCapacityMbps, maxCapacityMbps]` band up front so an out-of-band `--mbps` is rejected before any bond is stranded behind a `declareMbps` revert. `--dry-run` prints the plan; `--json` for machine output. - incentive: extend the CapacityBond `sol!` bindings with token/activeBond/ minBond/declaredMbps/bondRequired/min+maxCapacityMbps views and bond/ declareMbps writes. Reuse `decdn_incentive::Erc20` for allowance/approve/ balanceOf. - cli: extract the shared chain plumbing (config-coordinate resolution, keystore-signer loading, provider build, address/hex helpers) into `commands::chain_ctx`, flatten a shared `ChainArgs` flag group into both `RegisterArgs` and `BondArgs`, and refactor `register` onto it. Review fixes (#934): a real no-op run now reports `submitted=false dry_run=false` rather than masquerading as a dry-run preview; the shared `chain_ctx` carries the register-branch fixes (scrypt keystore load offloaded to `spawn_blocking`; config-sourced `data_dir`/`eth_keystore` paths tilde-expanded). Stacked on #929 (PR #931); operator flow is `decdn node bond --mbps N` then `decdn node register …`. The `decdn setup` wizard is tracked in #933. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
) Implements ADR 019 § Step 2.1–2.2: the operator command that stakes to a capacity tier before registration. The operator passes only `--mbps`; the TOKEN amount is read from the on-chain `bondRequired` curve. Idempotent by construction: it reads `bondRequired(mbps)`, `activeBond`, `minBond`, `declaredMbps`, the band, and the ERC-20 allowance, computes `target = max(minBond, bondRequired(mbps))`, and approves + bonds only the shortfall (`target − activeBond`), then `declareMbps` unless already at the tier. Bonding the shortfall rather than a flat amount means a re-run after a partial failure converges instead of double-bonding. The tier is validated against the on-chain `[minCapacityMbps, maxCapacityMbps]` band up front so an out-of-band `--mbps` is rejected before any bond is stranded behind a `declareMbps` revert. `--dry-run` prints the plan; `--json` for machine output. - incentive: extend the CapacityBond `sol!` bindings with token/activeBond/ minBond/declaredMbps/bondRequired/min+maxCapacityMbps views and bond/ declareMbps writes. Reuse `decdn_incentive::Erc20` for allowance/approve/ balanceOf. - cli: extract the shared chain plumbing (config-coordinate resolution, keystore-signer loading, provider build, address/hex helpers) into `commands::chain_ctx`, flatten a shared `ChainArgs` flag group into both `RegisterArgs` and `BondArgs`, and refactor `register` onto it. Review fixes (#934): a real no-op run now reports `submitted=false dry_run=false` rather than masquerading as a dry-run preview; the shared `chain_ctx` carries the register-branch fixes (scrypt keystore load offloaded to `spawn_blocking`; config-sourced `data_dir`/`eth_keystore` paths tilde-expanded). Stacked on #929 (PR #931); operator flow is `decdn node bond --mbps N` then `decdn node register …`. The `decdn setup` wizard is tracked in #933. Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
Closes #929.
Implements ADR 019 § Step 2.3: the operator-facing CLI command that binds the local iroh identity on-chain via
CapacityBond.registerNode. Until now ADR 019 describeddecdn node registerin present tense but it did not exist — operators had to hand-build the EIP-712 + ed25519 signatures and submit the transaction manually.What it does
decdn node register --region DE --multiaddr /ip4/.../udp/4433/quic-v1:rpc_url/chain_id/capacity_bond_address/eth_keystore/data_dirfrom flags > the[blockchain]/[identity]TOML config > defaults.bindingNonce[ethAddress]andregistrationNonce[nodeId]from the contract.bindingSignature(reusingdecdn_incentive::bind_sig) and the ed25519 ownership signature locally.--multiaddrargs into the on-chain(uint16 length, bytes)format.registerNode(...), awaits the receipt, reports tx hash + status.--dry-runprints the params + signatures without submitting;--jsonfor machine output.Correctness anchor
The ed25519 ownership digest in the new
decdn_incentive::node_registermodule byte-matchesCapacityBond._verifyEd25519OwnershipSignature(keccak256(nodeId‖operator‖chainId‖registrationNonce), 92-byte preimage). A unit test pins it against the committed registerNode vector incontracts/test/CapacityBondRegionE2E.t.solby verifying the published ed25519 signature against the locally-computed digest — a real differential check against the authoritative on-chain encoding, so a preimage drift fails at test time rather than at on-chain revert time.Scope
Only Step 2.3 (
registerNode). Phase 2.1/2.2 (approve/bond/declareMbps) remain an operator precondition — the contract revertsBondBelowMinimum/BondBelowCurveif the bond is unposted. Thedecdn setupwizard and automatedupdateMultiaddrsstay deferred per ADR 019 § Deferred & Open.Tests
cargo nextest run -p decdn-incentive -p decdn-cli— green (incl. the vector-pinned digest test + config-precedence + output-shape tests).cargo clippy/cargo fmt --checkclean; full pre-commit hook suite passed.🤖 Generated with Claude Code