Skip to content

feat(cli): add decdn node register for on-chain node registration (#929) - #931

Merged
alpergundogdu merged 2 commits into
mainfrom
claude/node-register-929
Jun 17, 2026
Merged

alpergundogdu merged 2 commits into
mainfrom
claude/node-register-929

Conversation

@alpergundogdu

Copy link
Copy Markdown
Contributor

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 described decdn node register in 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:

  1. Resolves rpc_url / chain_id / capacity_bond_address / eth_keystore / data_dir from flags > the [blockchain]/[identity] TOML config > defaults.
  2. Loads the existing iroh node key (errors if absent — won't mint a fresh identity) and the Ethereum keystore signer (env → file → prompt password sourcing, matching the daemon).
  3. Reads bindingNonce[ethAddress] and registrationNonce[nodeId] from the contract.
  4. Builds the EIP-712 bindingSignature (reusing decdn_incentive::bind_sig) and the ed25519 ownership signature locally.
  5. Packs --multiaddr args into the on-chain (uint16 length, bytes) format.
  6. Submits registerNode(...), awaits the receipt, reports tx hash + status. --dry-run prints the params + signatures without submitting; --json for machine output.

Correctness anchor

The ed25519 ownership digest in the new decdn_incentive::node_register module byte-matches CapacityBond._verifyEd25519OwnershipSignature (keccak256(nodeId‖operator‖chainId‖registrationNonce), 92-byte preimage). A unit test pins it against the committed registerNode vector in contracts/test/CapacityBondRegionE2E.t.sol by 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 reverts BondBelowMinimum/BondBelowCurve if the bond is unposted. The decdn setup wizard and automated updateMultiaddrs stay 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 --check clean; full pre-commit hook suite passed.

🤖 Generated with Claude Code

…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]>
Copilot AI review requested due to automatic review settings June 17, 2026 13:52

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread crates/cli/src/commands/register.rs Outdated
})?;
let node_id = B256::from_slice(node_secret.public().as_bytes());

let signer = load_operator_signer(args, &resolved.keystore)?;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

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
  1. When offloading synchronous file I/O or blocking operations to a threadpool using tokio::task::spawn_blocking in 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.

Comment thread crates/cli/src/commands/register.rs Outdated
Comment on lines +268 to +280
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()))
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

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.

Suggested change
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()))
}

Comment on lines +61 to +76
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)
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Pre-allocate the capacity of the out vector using Vec::with_capacity to avoid multiple reallocations as multiaddrs are packed and appended.

Suggested change
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
  1. Minimize memory allocations in performance-critical code by using in-place filtering or reusable buffers instead of creating multiple intermediate collections.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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_register helpers for the on-chain ownership digest and multiaddr packing, plus vector-pinned tests.
  • Extend CapacityBond ABI bindings with bindingNonce, registrationNonce, and registerNode.
  • Add the decdn node register CLI 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.

Comment on lines +331 to +339
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)")
})?;
Comment thread crates/cli/src/commands/register.rs Outdated
Comment on lines +340 to +345
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));
Comment thread crates/common/src/cli/node.rs Outdated
Comment on lines +492 to +497
/// 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.
Comment on lines +540 to +542
/// Data directory holding `node.secret`. Overrides `identity.data_dir`;
/// defaults to the platform data dir (`~/.local/share/decdn`).
#[arg(long, value_name = "PATH")]
@github-actions

github-actions Bot commented Jun 17, 2026 •

Copy link
Copy Markdown

Coverage report

Total: 85.51% (was 85.75%, ▼ 0.24%) — 37479/43828 lines

File Coverage Lines Δ
crates/cli/src/commands/node.rs 82.73% 1078/1303 ▼ 0.06%
crates/cli/src/commands/register.rs 51.06% 168/329 new
crates/incentive/src/node_register.rs 100.00% 62/62 new
History
Commit Total Δ vs base
17e9ef6 85.52% ▼ 0.23%
04ec0f0 (HEAD) 85.51% ▼ 0.24%

- 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]>
alpergundogdu added a commit that referenced this pull request Jun 17, 2026
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]>
@alpergundogdu

Copy link
Copy Markdown
Contributor Author

Addressed review feedback in 04ec0f0:

  • gemini (high): keystore scrypt decryption now runs in tokio::task::spawn_blocking so it doesn't stall the async executor (matches decdn-node's runtime keystore load); load_operator_signer is async with owned params.
  • gemini (med): pack_multiaddrs pre-allocates its output buffer.
  • Copilot: config-sourced data_dir / eth_keystore paths are now tilde-expanded (not just flag values).
  • Copilot: help text corrected — rpc_url / capacity_bond_address are required (no default), and data_dir defaults to ~/.decdn (was wrongly ~/.local/share/decdn).

@alpergundogdu
alpergundogdu merged commit a084665 into main Jun 17, 2026
22 checks passed
@alpergundogdu
alpergundogdu deleted the claude/node-register-929 branch June 17, 2026 15:16
alpergundogdu added a commit that referenced this pull request Jun 17, 2026
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]>
alpergundogdu added a commit that referenced this pull request Jun 17, 2026
)

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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Implement decdn node register (ADR 019 §2.3 on-chain node registration)

2 participants