Skip to content

feat(cli): add decdn node rotate-key + G-NODE-07 journey (#1034) - #1614

Merged
yigitdot merged 7 commits into
mainfrom
feat/1034-node-rotate-key
Aug 11, 2026
Merged

yigitdot merged 7 commits into
mainfrom
feat/1034-node-rotate-key

Conversation

@yigitdot

@yigitdot yigitdot commented Aug 5, 2026 •

Copy link
Copy Markdown
Contributor

Closes #1034.

What

decdn node rotate-key --key <iroh|eth> — the operator key-rotation runbook (adr/appendix-operator-key-rotation.md) as a command, plus the G-NODE-07 journey.

--key iroh — rebind the wire node id

Stage a fresh key → build the terms-free BindNodeId EIP-712 signature and the new key's ed25519 ownership proof → submit bindNodeId → install node.secret only after the receipt carries a matching NodeIdBound log.

The ordering is the design, not a detail. Disk-first would leave a daemon serving under a key no binding names, and that node is unslashable: SlashJudge._checkRegistered(challengedNode, nodeId) resolves the challenged address through nodeIdOf and requires the cited id to equal the bound one, so evidence gathered against the key the node is actually serving under reverts (NodeIdMismatch, or NodeNotRegistered when nothing is bound). The node keeps serving and keeps getting paid while its bond is unreachable. Chain-first risks only the inverse — a plain outage, repaired by --bind-existing.

  • --dry-run produces real signatures over a real key and writes nothing at all — not even data_dir, which staging would have created as a side effect. The preview key is generated in memory only.
  • --bind-existing binds whatever is already at node.secret — the repair lever for a hand-swapped key, and the runbook's rollback path.
  • Refuses a no-op self-rebind rather than burning a binding nonce, and pre-checks NodeIdAlreadyBound before spending gas.

--key eth — migrate the Ethereum address

No rebinding API exists for the address, so this moves the whole identity across the unbonding window. Phase is read from chain state the way decdn node unbond does — deregister → request → waiting → withdraw → reonboard → complete — so a run that lost its receipt converges rather than double-submitting. Reuses bond::execute and register::submit_registration instead of growing a second copy of that sequence. The maturing phase exits non-zero so a polling wrapper cannot read it as done.

Daemon: flag the unslashable state

New crates/node/src/binding_check.rs. One addressToNodeId read at bring-up, a WARN naming the repair, and binding / bound_node_id on admin_v1_health (rendered by decdn node health). Advisory by construction — a daemon that refused to start on a transient RPC failure would be unusable during exactly the window an operator needs it up to fix the binding.

Tests

crates/e2e/tests/g_node_07_rotate_key.rs, three journeys:

  1. Rotation. Slashability swaps atomically (asserted on the raw addressToNodeId / nodeIdToAddress mappings the slashing path reads, not on the liveness-aware isActiveNode); the retired id stops answering and the new one serves; bond, tier, firstBondedAt, and the open channel survive; a delivery paid for before the rotation still settles.
  2. Negative. A key swapped without bindNodeId reports binding=mismatch, resolves to no operator on-chain, and is repaired by --bind-existing. A second --bind-existing is refused rather than silently consuming a nonce.
  3. Eth path. Walks the whole window with advance_time, then asserts the two costs it cannot avoid: a fresh node id, and a reset firstBondedAt.

Two fixes found on the way

  • The e2e fixture deployed a sentinel currentTermsHash, which made any CLI registration journey impossible — terms::ensure_accepted refuses to sign against terms the binary does not hash to. It now deploys the real keccak256(TERMS.md). All 36 journeys still pass, so nothing depended on the sentinel.
  • The CI timeout inventory was already stale by one test, crediting cli_fetch_topup with four running tests when its fourth is #[ignore]d. Corrected to a verified 27 tests / 331m (see the review round below for a further arithmetic fix on top of this); timeout-minutes raised 175 → 200 to keep the ~25m of compile headroom the previous bump targeted.

Review round 2

Two reviews converged on the same root cause from different angles: reonboard (the --key eth re-onboarding phase) minted a fresh node key on every invocation, unconditionally — contradicting the module doc's own resumability claim. An unread registerNode(K1) receipt followed by a retry could mint and install K2 before K1 mines; if K1 then lands first, K2's registration reverts while node.secret already holds it — the exact unslashable mismatch this whole command exists to prevent, reachable through the retry path instead of the happy one. Fixed by reusing the key already on disk when nothing on chain claims it (key_is_reusable, unit-tested); the very first reonboard call still mints fresh, since deregisterNode never clears nodeIdToAddress and the pre-migration key reads as bound to the old address.

Also fixed:

  • A --dry-run preview of a fresh iroh key created data_dir as a side effect of stage_node_key's ensure_data_dir, even though the temp file itself was removed on drop — a real filesystem write from a command advertised to write nothing. Fixed with an in-memory-only NewKey::Preview variant; added the nonexistent-data-dir test.
  • --new-keystore could silently name the SAME address a --key eth migration is leaving. Refused as soon as the phase names a destination address (ensure_distinct_operator).
  • The CI inventory arithmetic itself was off by 3m (13×12+20×4+10×8+5×3 = 331, not 328) — corrected; timeout-minutes stays 200 since the corrected ~166m ceiling still leaves ~34m of headroom, and now links ci: right-size the anvil-e2e timeout budgets (200m bound vs ~6m runs; per-test ceilings smaller than their retry ladders) #1620 for the further work replacing the whole sum-of-ceilings derivation.

Documented rather than changed: BindingStatus::Mismatch doesn't clear to Bound until the daemon restarts, so a mismatch seen right after --bind-existing is a stale sample, not a failed repair. (This round also added a warning about dry-run signatures being submittable by a third party — that was wrong and is retracted in round 3 below.)

Not changed: the ask for finalized/safe-block confirmation depth before committing node.secret on the iroh path. send_for_receipt waits for exactly one inclusion everywhere in this codebase (register, deregister, bond, unbond all share it, no confirmation-depth parameter), and the runbook this PR adds is explicit that one block confirmation is the intended semantics (step 5). Special-casing reorg safety for only this command would be inconsistent with every other on-chain write in the CLI — a cross-cutting concern for all of them, not a fix scoped to key rotation.

Review round 3

A five-agent pass (code review, silent-failure, test coverage, comment accuracy, type design). Every claim was verified against the contracts or the source before being acted on; three agents independently converged on the submitted bug and two on the staged-key hole.

Retraction from round 2. Round 2 added a warning — to the ADR and a code comment — that a leaked --dry-run output lets a third party submit bindNodeId and strand the operator. That is false. _verifyBindingSignature derives the digest from bindingNonce[msg.sender] and validates with isValidSignatureNow(msg.sender, …), and the ed25519 proof puts msg.sender in its preimage — a third-party submitter is msg.sender, so the operator's signatures cannot validate and the transaction reverts InvalidBindingSignature. There is no relayer path. It was introduced by implementing a review suggestion without checking the contract. Both copies are removed and replaced with what is actually true: a dry run discards the key whose id it prints, so that id must not be recorded as the node's next identity.

Critical — a lost receipt could destroy the new secret and reach the unslashable state. send_for_receipt sets InFlight(hash) before awaiting the receipt, so a receipt-fetch failure returns Err with the transaction already broadcast — and the error arm dropped NewKey, whose Drop deletes the staged temp. If the transaction then mined, the chain was bound to a key whose secret existed nowhere, while the daemon served an id bindNodeId had just unbound. Added StagedNodeKey::keep(), parking the secret at node.secret.pending.<node_id> — deliberately not node.secret, so no daemon loads it — whenever outcome.maybe_effected(). A definitively-rejected send still discards it rather than littering key material.

Important:

  • Failed confirm_bound and failed commit returned before write_plan, so --json got empty stdout for exactly the states that most need a receipt — indistinguishable from a config error that sent nothing. Both now report first, and the tx hash is read before the gate so every error can name it.
  • A broken stdout replaced the operation error: piping into head turned "may have been broadcast; re-sending is not idempotent" into "Broken pipe". The receipt now degrades to stderr on both paths.
  • preview_key was derived from dry_run, so a failed real run reported preview_key=false — claiming the printed id named a persisted key at the moment it named one just discarded or parked. Now derived from whether the key was actually persisted.
  • eth submitted omitted approve/declare, both of which bond::execute can land independently — printing approve_tx=0x… next to submitted=false.
  • ensure_distinct_operator never fired on the phases that matter: select_phase returned deregister/request/waiting/withdraw before reading --new-keystore, so a same-address mistake surfaced only after the 14-day window. Now checked on every invocation, with the keystore loaded once per call rather than per branch (scrypt is deliberately expensive — the eth journey went 78s → 12s).
  • The address that transacts was not provably the one confirmed: reonboard re-loaded the keystore after the prompt and transacted from that. It now takes the planned address and refuses a mismatch.
  • confirm_bound now also matches the emitting contract address, not just topic0 and the indexed fields.

Documentation corrections:

  • Two comments described a nodeId → address lookup the slashing path does not perform (see the corrected wording in What above). The PR's premise is unchanged; the explanation was wrong.
  • The documented "carry the original node id across" procedure could not work: --key iroh frees the original on-chain but also archives it and installs the throwaway, so the eth path finds the throwaway on disk and mints a third key. The archive-restore step is now stated in the disclosure, the module doc, and the ADR.
  • --mbps help promised a default that cannot exist (deregisterNode clears the tier, so the fallback is unreachable); --bind-existing rendered literal ** markdown in the terminal.

Tests: confirm_bound — the gate on the irreversible local write — had no coverage at any layer. Six cases added from real encode_log_data receipts (matching log, no log, wrong operator, wrong node id, foreign contract, match among others); the foreign-contract case fails against the pre-hardening filter, so it is discriminating rather than decorative.

Reported but not actioned, with rationale, in this comment: type reshapes, select_phase pure-seam extraction, e2e assertion tightening, and style nits. One out-of-scope item is filed as #1623 rather than bundled.

Verification

cargo fmt --check                                                  ok
cargo clippy --workspace --all-targets --all-features -D warnings  clean
RUSTDOCFLAGS=-D warnings cargo doc --document-private-items        clean (CI form)
cargo nextest run --workspace --no-fail-fast                       2815 passed
cargo nextest run -p decdn-e2e --features anvil-e2e                  36 passed
cargo deny check                                                   ok

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Added decdn node rotate-key workflows for Iroh key rebinding and Ethereum operator-key migration.
    • Added dry-run previews, confirmation safeguards, resumable steps, recovery handling, and structured output.
    • Node health now reports binding status and the currently bound node identity.
    • Nodes detect mismatched or unbound local keys without blocking startup.
    • Added support for repairing locally replaced keys with --bind-existing.
  • Documentation

    • Expanded key-rotation runbooks and updated end-to-end test timeout guidance.
  • Tests

    • Added coverage for rotation, recovery, reachability, and preserved node state.

Wraps `adr/appendix-operator-key-rotation.md` as a command. `--key` picks
the path, because the two are not comparable in cost or effect.

`--key iroh` rebinds the wire node id through `CapacityBond.bindNodeId`:
stage a fresh key, build the terms-free `BindNodeId` EIP-712 signature plus
the new key's ed25519 ownership proof, submit, and install `node.secret`
ONLY after the receipt carries a matching `NodeIdBound` log. That ordering
is the point. Disk-first would leave a daemon serving under a key no binding
names, and such a node is unslashable — `SlashJudge._checkRegistered`
resolves the accused through `nodeIdOf` — so it keeps earning while its bond
is unreachable. Chain-first risks only the inverse, a plain outage that
`--bind-existing` repairs.

`--key eth` moves the whole on-chain identity, since no rebinding API exists
for the address. Phase comes from chain state the way `decdn node unbond`
does — deregister, request, waiting, withdraw, reonboard, complete — so a run
that lost its receipt converges instead of double-submitting. It reuses
`bond::execute` and `register::submit_registration` rather than growing a
second copy of that sequence.

The daemon now flags the unslashable state it cannot otherwise surface: one
`addressToNodeId` read at bring-up, a WARN naming the repair, and
`binding`/`bound_node_id` on `admin_v1_health`. Advisory by construction —
refusing to start on a transient RPC failure would brick the node during the
window an operator needs it up to fix the binding.

Also fixes two things found on the way:

- The e2e chain fixture deployed a sentinel `currentTermsHash`, which made
  every CLI registration journey impossible: `terms::ensure_accepted` refuses
  to sign against terms the binary does not hash to. It now deploys the real
  `keccak256(TERMS.md)`.
- The CI journey timeout inventory was already stale by one test, crediting
  `cli_fetch_topup` with four running tests when its fourth is `#[ignore]`d.
  Corrected to a verified 27 tests / 328m, and the bound raised 175m -> 200m
  to keep the compile headroom the previous bump targeted.

Verified: fmt, `clippy --workspace --all-targets --all-features -D warnings`,
`cargo doc` in CI form, 2801 unit tests, all 36 anvil-e2e tests, cargo-deny.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@coderabbitai

coderabbitai Bot commented Aug 5, 2026 •

Copy link
Copy Markdown

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Free

Run ID: f39385f7-788a-42b8-90af-aafe8ed817b0

📥 Commits

Reviewing files that changed from the base of the PR and between 4832177 and 56e3bec.

📒 Files selected for processing (1)
  • adr/appendix-operator-key-rotation.md
🚧 Files skipped from review as they are similar to previous changes (1)
  • adr/appendix-operator-key-rotation.md

Walkthrough

The PR adds decdn node rotate-key for iroh rebinding and Ethereum identity migration. It adds binding health reporting, contract bindings, E2E journeys, operator runbook updates, and a 200-minute CI timeout.

Changes

Node key rotation and binding health

Layer / File(s) Summary
Binding health reporting
crates/common/src/admin.rs, crates/node/src/binding_check.rs, crates/node/src/runtime/mod.rs, crates/node/src/admin.rs, crates/cli/src/commands/node.rs
The node classifies its on-chain binding and exposes the status and bound node ID through admin health and CLI output.
Rotate-key CLI contract and confirmation
crates/common/src/cli/node.rs, crates/common/src/cli/mod.rs, crates/cli/src/commands/rotate_key/*, crates/cli/src/commands/node.rs
The CLI adds iroh and Ethereum rotation targets, arguments, dispatch, and confirmation handling.
Iroh binding rotation
crates/cli/src/commands/rotate_key/iroh.rs, crates/common/src/identity.rs, crates/incentive/src/capacity_bond.rs, crates/e2e/src/bindings.rs
The iroh workflow signs and submits bindNodeId, validates the NodeIdBound event, and updates node.secret after confirmation.
Ethereum identity migration
crates/cli/src/commands/rotate_key/eth.rs, crates/incentive/src/node_register.rs
The Ethereum workflow handles deregistration, unbonding, withdrawal, waiting, and re-onboarding with a new keystore and node identity.
Rotation fixtures and E2E journeys
crates/e2e/src/chain.rs, crates/e2e/src/client.rs, crates/e2e/src/node.rs, crates/e2e/tests/g_node_07_rotate_key.rs
E2E support resolves the active node identity and validates iroh rebinding, local-key repair, Ethereum migration, and post-rotation behavior.
Operational documentation and test budget
adr/appendix-operator-key-rotation.md, .github/workflows/ci.yml
The runbook documents rotation and rollback procedures. CI includes G-NODE-07 and raises the journey timeout to 200 minutes.

Estimated code review effort: 4 (Complex) | ~60 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Operator
  participant RotateKeyCLI
  participant CapacityBond
  participant NodeDaemon
  Operator->>RotateKeyCLI: Run rotate-key workflow
  RotateKeyCLI->>CapacityBond: Read binding and migration state
  RotateKeyCLI->>CapacityBond: Submit rotation transaction
  CapacityBond-->>RotateKeyCLI: Return receipt and binding event
  RotateKeyCLI->>NodeDaemon: Install key after confirmed iroh binding
  NodeDaemon->>CapacityBond: Check binding during startup
  NodeDaemon-->>Operator: Report binding status through health
Loading

Note

🎁 Summarized by CodeRabbit Free

Your organization is on the Free plan. CodeRabbit will generate a high-level summary and a walkthrough for each pull request. For a comprehensive line-by-line review, please upgrade your subscription to CodeRabbit Pro by visiting https://app.coderabbit.ai/login.

Comment @coderabbitai help to get the list of available commands.

@github-actions

github-actions Bot commented Aug 5, 2026

Copy link
Copy Markdown

Gas snapshot

No gas changes vs base.

@github-actions

github-actions Bot commented Aug 5, 2026 •

Copy link
Copy Markdown

Contracts coverage

Line coverage: 90.07% (2629/2919 lines)
▲ +0.00pp vs base (90.07% → 90.07%)
Run: 31505350084

@github-actions

github-actions Bot commented Aug 5, 2026 •

Copy link
Copy Markdown

Coverage report

Total: 80.17% (was 80.82%, ▼ 0.65%) — 62068/77423 lines

File Coverage Lines Δ
crates/cli/src/commands/key_gen.rs 91.11% 41/45 ● 0.00%
crates/cli/src/commands/node.rs 77.51% 1179/1521 ▲ +1.11%
crates/cli/src/commands/rotate_key/eth.rs 47.09% 356/756 new
crates/cli/src/commands/rotate_key/iroh.rs 62.91% 485/771 new
crates/cli/src/commands/rotate_key/mod.rs 35.14% 13/37 new
crates/common/src/admin.rs 94.78% 127/134 ● 0.00%
crates/common/src/cli/mod.rs 100.00% 3/3 ● 0.00%
crates/common/src/cli/node.rs 100.00% 5/5 ● 0.00%
crates/common/src/identity.rs 88.76% 395/445 ▲ +0.56%
crates/e2e/src/chain.rs 1.52% 21/1381 ▼ 0.09%
crates/e2e/src/client.rs 0.00% 0/441 ● 0.00%
crates/e2e/src/node.rs 24.59% 120/488 ▼ 1.33%
crates/incentive/src/node_register.rs 96.33% 105/109 ▼ 3.67%
crates/node/src/admin.rs 95.55% 1181/1236 ▼ 0.31%
crates/node/src/binding_check.rs 61.43% 43/70 new
crates/node/src/runtime/mod.rs 46.43% 1094/2356 ▼ 0.18%
History
Commit Total Δ vs base
5d34160 79.64% ▼ 0.65%
88a1b54 79.65% ▼ 0.68%
58d1846 79.60% ▼ 0.73%
4832177 80.23% ▼ 0.66%
56e3bec (HEAD) 80.17% ▼ 0.65%

@yigitdot

yigitdot commented Aug 5, 2026

Copy link
Copy Markdown
Contributor Author

Follow-up: the anvil-e2e timeout budgets I touched here are incoherent, not just large

This PR raised anvil-e2e-journeys to timeout-minutes: 200, following the rule the job's own comment states — sum every per-test OVERALL_TIMEOUT, divide by the thread count. That number is wrong, and so is the rule that produced it. Filing this here rather than silently fixing it, since the PR is mergeable as-is: 200m is a backstop that never fires, not a regression.

Checking the actual numbers turned up something worse than over-provisioning. The two budgets contradict each other: the job bound is ~25× the observed run, while the per-test ceilings are smaller than the fixture retry ladders they are supposed to contain. Both follow from the same mistake — every figure in that comment is derived from other figures, and none is anchored to a measurement.

Observed job duration

anvil e2e (journeys) on main, four consecutive runs (2026-08-05): 5m23s, 5m40s, 6m00s, 8m37s. Bound: 200m.

The sibling anvil e2e (settlement) ran 2m02s against timeout-minutes: 60.

Observed test duration

Full suite locally at --test-threads 1: 377s wall clock for all 36 tests. Only two tests exceed 25s:

test measured its ceiling
origin_stream_while_store::…rejects_a_corrupt_outboard… 94.4s 300s
cli_publish::publish_namespace_and_assign_land_on_chain 72.3s 780s
g_node_06_unbond::… 22.7s 780s
g_gov_02_rate_bounds::… 11.1s 1200s
slash_appeal::slash_detection_appeal_and_grant 10.2s 1200s

The rest are ≤ 16s. The 1200s tier runs ~110× faster than its ceiling.

The contradiction

Under CI, ci_scaled doubles the fixture budgets (crates/e2e/src/chain.rs:95, CI_TIMEOUT_MULTIPLIER = 2). A single test that exhausts its setup retry ladders needs:

  • forge build — FORGE_BUILD_TIMEOUT 300s × 2 (CI) × BUILD_ATTEMPTS 3 = 1800s
  • DeployProtocol — DEPLOY_TIMEOUT 60s × 2 (CI) × DEPLOY_ATTEMPTS 4 = 480s

That is ~38m of setup inside a test whose largest ceiling is 20m. The ladders are partly unreachable today: a test that hits them trips its own OVERALL_TIMEOUT first and reports as a generic timeout rather than as the deploy flake it is — and #1384 is exactly that flake. So the ceilings are simultaneously ~100× too large for the happy path and too small for the recovery path they were sized around.

Proposal

  1. Anchor per-test ceilings to measurement, not to each other. Two tiers from observed p100 with a CI margin — roughly 180s for the ≤25s tests, 300s for the two slow ones — replacing today's 300/600/780/1200s spread. Put the rule in the constant's doc so the next journey inherits it.
  2. Make the retry ladders fit inside the ceiling, or shorten them. Better: hoist forge build out of the fixture into a job step that runs once. Fixtures share contracts/out, so only the first test pays a cold build anyway — this removes the 1800s worst case from every test at once.
  3. Derive the job bound from observed job duration. The sum-of-ceilings model assumes every test simultaneously burns its full budget, which cannot happen. timeout-minutes: 30 is ~3.5× the worst observed run and still covers the cold-cache compile the job must include — that compile, not the tests, is what the 8m37s outlier reflects.
  4. Same treatment for anvil-e2e-settlement: 60m against a 2m02s run; ~15m by the same rule.
  5. Optionally, the only two tests above 25s: cli_publish has a hardcoded 60s poll deadline (crates/e2e/tests/cli_publish.rs:318) that dominates its runtime, and the corrupt-outboard test's 94s is spent waiting out a real pull deadline rather than an explicit sleep.

Caveats

  • The runner is a 4-vCPU box at --test-threads 2, so two anvils and two forge deploys contend. Margins have to survive that — which is the argument against cutting per-test ceilings to bare multiples of a local measurement.
  • Cutting a ceiling below the retry ladder it contains re-creates today's problem in the other direction. Items 1 and 2 have to land together.
  • That comment's own history records it going stale four times. Whatever replaces it should state a rule plus a measurement date, not a table of derived arithmetic that rots on the next journey.

@altanoruc

Copy link
Copy Markdown
Contributor

Code review

Strengths

  • The Iroh path builds both signatures from live contract nonces and correctly gates the normal-path node.secret install on an exact NodeIdBound event.
  • The Ethereum waiting phase exits non-zero, while daemon binding-check RPC failures degrade to an explicit unknown health state without blocking startup.
  • The end-to-end tests cover the principal successful Iroh and Ethereum journeys plus manual-key mismatch repair.

Critical

  • Ethereum retry can install a different local key from the one registered on-chain (crates/cli/src/commands/rotate_key/eth.rs:532). Every Reonboard invocation stages and commits a fresh node.secret before calling registerNode at line 570. If registration for key A is broadcast but its receipt is temporarily unreadable, an immediate retry can still observe the new operator as inactive and commit key B. When transaction A lands, the operator is active and bound to A while the daemon holds B; the retry registration then fails preflight or reverts NodeAlreadyRegistered. This creates the exact on-chain/local-key mismatch the command is meant to prevent. Persist and reuse the migration's installed node ID across retries, reconcile addressToNodeId(new_operator) with the local key before generating or reporting Complete, and add a test for a receipt failure between broadcast and mining.

Important

  • Fresh-key dry runs mutate the filesystem (crates/cli/src/commands/rotate_key/iroh.rs:81). NewKey::acquire calls stage_node_key before the --dry-run branch at line 94. Staging creates the data directory when absent and writes then removes a temporary secret, so an absent data directory remains after a command advertised to write nothing. Generate the preview key in memory and only stage it for a real rotation. Add a test using a nonexistent data directory.

  • A single included receipt is treated as irreversible before replacing the key (crates/cli/src/commands/rotate_key/iroh.rs:143). After finding the event in the first successful receipt, line 146 immediately commits the new key. If that block is reorganized out, the chain returns to the old binding while disk retains the new key, producing the unsafe mismatch. Wait for finalized/safe inclusion or a configured confirmation depth, then re-read addressToNodeId(operator) at that block and require it to equal new_node_id before committing the file.

  • --new-keystore may point to the old Ethereum keystore (crates/cli/src/commands/rotate_key/eth.rs:353). The signer is only checked with isActive; there is no new_operator != old_operator check. After withdrawal, passing the original keystore re-bonds and re-registers the same address, resets state, and reports a completed migration even though the Ethereum key did not change. Reject equal addresses before any re-onboarding mutation; when --new-keystore is supplied during an earlier phase, validate it early as well.

Assessment

Ready to merge: No.

The Ethereum retry path can directly create an active on-chain/local-key mismatch, while the Iroh path still violates its no-write and reorg-safety guarantees. These affect the core slashability invariant and should be fixed before merging.

Copy link
Copy Markdown
Contributor

Review

Overview

Implements the operator key-rotation runbook as decdn node rotate-key with two sub-paths (--key iroh rebind via bindNodeId, --key eth full identity migration across the unbonding window), a bring-up binding self-check on the daemon surfaced through admin_v1_health, and the G-NODE-07 e2e journeys. The design is strong: chain-first-then-disk ordering on the iroh path (with the NodeIdBound receipt log as the gate on committing node.secret), phase-from-chain-state on the eth path, and a StagedNodeKey::sign oracle that lets a dry run produce real signatures without persisting anything. The tests assert on the raw addressToNodeId/nodeIdToAddress mappings the slashing path actually reads, which is exactly the right level. Overall this is a high-quality PR; the findings below are one correctness/doc mismatch, one arithmetic slip, and a few smaller notes.

Findings

1. reonboard mints a fresh key on every attempt, contradicting its own resumability comment — crates/cli/src/commands/rotate_key/eth.rs

The module doc says: "Committing the fresh key up front … makes the phase resumable — a failed registerNode retries against the key already on disk instead of minting a third one." But reonboard calls identity::stage_node_key + commit() unconditionally, and stage_node_key always generates a fresh secret. A re-run after a failed registerNode therefore mints and installs another key, and registers that one instead.

Mostly harmless (no registration landed, so any fresh key works), but there is a narrow race the resumability story is supposed to cover: registerNode(K1) broadcast with a lost receipt → operator re-runs → K2 is committed to disk and its registerNode submitted → K1's transaction mines first → K2's registration reverts (operator already active) → disk holds K2 while the chain binds K1. That is the mismatch/unslashable state this very PR teaches the daemon to flag — repairable with --bind-existing, but the code promises it can't happen.

Suggested fix (either is fine):

  • Make the comment honest: the phase is resumable in the sense that no step double-submits, but each attempt that reaches key-staging mints a fresh key.
  • Or actually reuse: before staging, read the key on disk and compare its id against addressToNodeId(old_operator) — if it differs from the old bound id (i.e., a previous reonboard attempt already minted it and it's unbound), reuse it instead of staging.

2. CI timeout inventory arithmetic is off by 3m — .github/workflows/ci.yml

The corrected buckets are 13m×12 + 20m×4 + 10m×8 + 5m×3 = 156 + 80 + 80 + 15 = 331m, not the 328m the comment states (and the PR description repeats as "verified 27 tests / 328m"). Balanced 2-thread ceiling is therefore ~166m, not ~164m. Cross-check from the other direction agrees: the corrected pre-PR sum is 285m (298 − 13), and G-NODE-07 adds 46m → 331m. The 200m bound still leaves ~34m of compile headroom, so nothing functional changes — but this comment is precisely the one that "has gone stale three times now", and it's shipping stale a fourth time. Worth fixing the numbers before merge.

3. Security consideration: dry-run output contains a live, submittable binding signature for a discarded key — rotate_key/iroh.rs

--dry-run (without --bind-existing) prints binding_sig + ed25519_sig over the current on-chain nonces, then drops the staged key. Until the operator's bindingNonce advances, anyone holding that output can submit bindNodeId themselves and rebind the operator to a key whose secret no longer exists — an off-chain griefing lever (node unroutable/unslashable until repaired with --bind-existing, i.e., another nonce burn plus downtime). The exposure requires the operator to leak their own dry-run output (pasting a receipt into a ticket/chat is not far-fetched), but the failure mode is non-obvious enough to deserve a sentence: either in the preview_key caveat (the receipt already flags the discarded key) or in the runbook's --dry-run paragraph, saying the printed signatures remain submittable until the next binding-nonce consumer.

4. Minor: post-migration re-run without --new-keystore gives a misleading error — rotate_key/eth.rs

select_phase can only reach Complete after loading the new keystore, so once the migration has finished, a bare decdn node rotate-key --key eth errors with "the bond is fully withdrawn — pass --new-keystore" — phrased as if a step remains, when the honest answer is "already complete" (the state is indistinguishable from a genuinely pending re-onboard without the keystore, so at most the message could hedge: "…or, if you already re-onboarded, pass it to confirm completion"). Not blocking; the test's step 7 covers the with-flag case.

5. Minor: binding is as-of-startup, and the repair doesn't clear it until restart

Sampled-once is well justified (readiness path), and the DTO doc says so — but after --bind-existing repairs a live daemon, decdn node health keeps reporting binding=mismatch until the restart. The G-NODE-07 negative leg restarts before asserting Bound, so the tests are honest about it; consider one line in the Mismatch WARN or the health field doc telling the operator the status refreshes on restart, so a post-repair mismatch isn't read as a failed repair.

What looks particularly good

  • The confirm_bound gate matching indexed topics (operator + id), not just the event signature — that's the difference between a real gate and a ceremonial one.
  • unpack_multiaddrs rejecting truncation/non-UTF-8 instead of yielding a short list, with the rationale (would re-register a node missing an address) pinned in tests.
  • Waiting-phase non-zero exit with the polling-wrapper rationale, and dry_run carried explicitly so a failed send is distinguishable from a preview.
  • The fixture terms-hash fix (CURRENT_TERMS_HASH = real keccak256(TERMS.md)) — correct call, and the "duplication of the recipe is self-policing" argument holds since a drift fails every CLI registration journey loudly.
  • Conventions: anti-panic policy respected (split_at_checked, saturating_to, no indexing), pure write_*/classify helpers for testability, no compat shims on the HealthResponse DTO change per pre-launch policy, and the ADR appendix updated in ASD-STE100 style.

Verdict

Approve-shaped with fixes requested on #1 (comment or behavior) and #2 (numbers) before merge; #3–#5 are take-or-leave polish.


Generated by Claude Code

Two reviewers converged on the same root cause, from different angles:
reonboard's unconditional fresh-key-per-attempt breaks the resumability the
module doc promises. A registerNode(K1) broadcast with an unread receipt,
followed by a retry before K1 mines, would mint and install K2 and submit
registerNode(K2); if K1 then lands first, K2's registration reverts while
node.secret already holds it — the daemon ends up serving an unbound key,
the exact mismatch this whole command exists to prevent, reachable through
the retry path instead of the happy one.

Fix: reuse the key already on disk when nothing on chain claims it
(key_is_reusable), mint fresh only otherwise. The first-ever reonboard call
still mints fresh, because deregisterNode never clears nodeIdToAddress, so
the pre-migration key reads as "claimed" (by the old address) and falls
through to the same mint path.

Also fixes, in order of what each finding actually was:

- A --dry-run preview of a fresh iroh key created data_dir as a side effect
  of stage_node_key's ensure_data_dir call, even though the temp file itself
  was removed on drop -- a real filesystem write from a command advertised to
  write nothing. Fixed by generating the preview key fully in memory
  (NewKey::Preview) rather than staging it, so a preview against a
  nonexistent data_dir now touches no path on disk.

- --new-keystore could silently name the SAME address a --key eth migration
  is leaving, which would re-bond the old address rather than migrate
  anywhere. Refused as soon as the phase names a destination address.

- The CI journey-timeout inventory comment carried a 331m sum that had been
  transcribed as 328m (13*12+20*4+10*8+5*3=331, not 328), so the derived
  ~164m balanced ceiling was also off. Corrected the arithmetic; timeout-
  minutes stays 200 since even the corrected ~166m ceiling leaves ~34m of
  compile headroom. Referenced #1620, which tracks replacing this whole
  sum-of-ceilings derivation with one anchored to observed job duration.

- Documented two narrower findings rather than changing behavior for them:
  a dry-run's printed bindNodeId signatures stay submittable against the
  live nonces until the binding nonce advances (an off-chain griefing lever
  if the output leaks), and BindingStatus::Mismatch doesn't clear to Bound
  until the daemon restarts, so a mismatch seen right after --bind-existing
  is a stale sample, not a failed repair.

Not fixed: the ask to require finalized/safe-block inclusion before
committing node.secret on the iroh path. send_for_receipt waits for exactly
one inclusion everywhere in this codebase (register, deregister, bond,
unbond all use the same helper with no confirmation-depth parameter), and
the runbook this PR added is explicit that one block confirmation is the
intended semantics (adr/appendix-operator-key-rotation.md, step 5). Adding
bespoke confirmation-depth logic to only this one command would be
inconsistent with every other on-chain write in the CLI; a reorg-safety
policy, if wanted, is a cross-cutting concern for all of them, not this PR.

Verified: fmt, clippy --workspace --all-targets --all-features -D warnings,
2808 unit tests (7 new: key_is_reusable / ensure_distinct_operator /
dry_run_acquire_creates_no_data_dir / preview_key_refuses_to_commit and
their surrounding cases), all 3 G-NODE-07 anvil-e2e journeys.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@yigitdot

yigitdot commented Aug 5, 2026

Copy link
Copy Markdown
Contributor Author

Fixed 88a1b544.

The critical/#1 finding (both reviews)

Confirmed: reonboard staged and committed a fresh key unconditionally, contradicting the module doc's own resumability claim. Fixed by reusing the key on disk when nodeIdToAddress shows nothing claims it, minting fresh only otherwise (key_is_reusable, unit-tested). The first-ever reonboard call still mints fresh — deregisterNode never clears nodeIdToAddress, so the pre-migration key reads as bound to the old address and correctly falls through to a fresh mint.

Dry-run FS mutation

Confirmed — stage_node_key's ensure_data_dir creates the data dir as a side effect even though the temp file is removed on drop. Fixed with an in-memory-only NewKey::Preview variant for --dry-run; added the nonexistent-data-dir test as asked (dry_run_acquire_creates_no_data_dir), plus one pinning that commit() on a preview errors rather than being reachable at all.

--new-keystore same-address

Confirmed, fixed — refused (ensure_distinct_operator) as soon as the phase names a destination address, covering both Reonboard and Complete.

CI arithmetic

Confirmed: 13×12+20×4+10×8+5×3 = 331, not 328. Fixed the sum and the derived ceiling; timeout-minutes stays 200 since the corrected ~166m ceiling still leaves ~34m of headroom. Linked #1620, which tracks replacing the whole sum-of-ceilings approach.

Two documented, not changed

  • Dry-run signature griefing: added to both the ADR --dry-run paragraph and the preview_key doc comment.
  • Mismatch-until-restart: added to BindingStatus::Mismatch's doc.

Not changing: confirmation depth on bindNodeId

send_for_receipt waits for exactly one inclusion everywhere in this codebase — register, deregister, bond, unbond all go through the same helper with no confirmation-depth parameter — and the runbook this PR adds is explicit that one block confirmation is the intended semantics (step 5). Special-casing reorg safety for only this command would be inconsistent with every other on-chain write in the CLI. If a confirmation-depth policy is wanted, it's a cross-cutting change across all of them, not a fix scoped to key rotation — happy to file that separately if there's appetite for it, but didn't want to bury a systemic change inside a review-response commit.

Verified: fmt, clippy --workspace --all-targets --all-features -D warnings, 2808 unit tests (7 new), all 3 G-NODE-07 anvil-e2e journeys.

Five analysis agents reviewed the PR; every claim below was verified against
the contracts or the source before being accepted.

CORRECTION TO MY OWN PRIOR ROUND. In 88a1b54 I added a warning to the ADR
and to a code comment claiming a leaked --dry-run output lets a third party
submit bindNodeId and strand the operator. That is false, and I introduced it
by implementing a review suggestion without checking the contract:
_verifyBindingSignature derives the digest from bindingNonce[msg.sender] and
validates with isValidSignatureNow(msg.sender, ...), and the ed25519 proof
puts msg.sender in its preimage. A third-party submitter IS msg.sender, so
the operator's signatures cannot validate — the transaction reverts
InvalidBindingSignature. There is no relayer path. Both copies of the claim
are removed and replaced with what is actually true: a dry run discards the
key whose id it prints, so that id must not be recorded as the node's next
identity.

Critical:

- A lost receipt could destroy the new secret and reach the unslashable
  state. send_for_receipt sets InFlight(hash) BEFORE awaiting the receipt, so
  a receipt-fetch failure returns Err with the transaction already broadcast;
  the Err arm dropped NewKey, and StagedNodeKey::drop deletes the temp. If the
  transaction then mined, the chain was bound to a key whose secret existed
  nowhere while the daemon served an id bindNodeId had just unbound. Adds
  StagedNodeKey::keep(), which parks the secret at
  node.secret.pending.<node_id> — deliberately not node.secret, so no daemon
  loads it — whenever outcome.maybe_effected(). A definitively-rejected send
  still discards it rather than littering key material.

Important:

- Two paths past the send (failed confirm_bound, failed commit) returned
  before write_plan, so a --json consumer got empty stdout for exactly the
  states that most need a receipt — byte-identical to a config error that
  sent nothing. Both now report before propagating, and the transaction hash
  is read before the gate so every error can name it.
- A broken stdout replaced the operation error: write_plan(...)?
  discarded it, so piping into head turned "may have been broadcast —
  re-sending is not idempotent" into "Broken pipe". The receipt now degrades
  to stderr on both paths and the real error survives.
- preview_key was derived from dry_run, so a failed real run reported
  preview_key=false — asserting the printed new_node_id named a persisted key
  at exactly the moment it named one just discarded or parked. Now derived
  from whether the key was actually persisted.
- eth submitted omitted approve and declare, both of which bond::execute can
  land independently, printing approve_tx=0x... next to submitted=false.
  bond::write_plan, the direct twin, ORs all three of its slots.
- ensure_distinct_operator never fired on the phases that matter:
  select_phase returned deregister/request/waiting/withdraw before reading
  --new-keystore, so a same-address keystore was accepted silently and only
  refused after the 14-day window. Now validated on every invocation. The
  keystore is loaded once per invocation and reused rather than decrypted per
  branch — scrypt is deliberately expensive and this runs on every call across
  the migration (the G-NODE-07 eth journey went 78s -> 12s).
- The address that transacts was not provably the one confirmed: select_phase
  loaded the keystore to derive and disclose an address, then reonboard loaded
  it AGAIN and transacted from that. reonboard now takes the planned address
  and refuses a mismatch.
- confirm_bound also matches the emitting contract address, not just topic0
  and the indexed fields.

Documentation corrections:

- Two comments described a nodeId -> address lookup the slashing path does not
  perform. _checkRegistered(challengedNode, nodeId) resolves the challenged
  ADDRESS through nodeIdOf, so a challenge citing a retired id against a
  still-bound operator reverts NodeIdMismatch; NodeNotRegistered fires only
  when the address has no binding at all. The PR's premise is unchanged —
  evidence against the served, unbound key still cannot be submitted.
- The documented "carry the original node id across" procedure could not
  work: --key iroh frees the original on-chain but also archives it and
  installs the throwaway, so the eth path finds the throwaway on disk and
  mints a third key. The archive-restore step is now stated in the
  disclosure, the module doc, and the ADR.
- --mbps help promised a default that cannot exist (deregisterNode clears the
  tier, so the fallback is unreachable and every real re-onboarding hits the
  required-flag error). Two other places in the PR said so correctly; the
  clap help, which operators actually read, was the odd one out.
- --bind-existing help rendered literal ** markdown in the terminal.
- Documented that both keystores unlock from one password source.

Tests: confirm_bound had no coverage at any layer despite being the gate on
the irreversible local write — six cases added (matching log, no log, wrong
operator, wrong node id, foreign contract, match among other logs), built
from real encode_log_data receipts. The foreign-contract case fails against
the pre-hardening filter. Plus the failed-real-run preview_key regression.

Verified: fmt, clippy --workspace --all-targets --all-features -D warnings,
cargo doc in CI form, 2815 unit tests (7 new), all 3 G-NODE-07 anvil-e2e
journeys.

Reported but not actioned (type reshapes, select_phase pure seam, e2e
assertion tightening, ASD-STE100 nits): see the PR comment.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@yigitdot

yigitdot commented Aug 5, 2026

Copy link
Copy Markdown
Contributor Author

Review round 3 — five-agent pass, fixes in 58d1846a

Ran the comprehensive review toolkit (code review, silent-failure, test coverage, comment accuracy, type design). Verified every claim against the contracts or the source before acting; three agents independently converged on the submitted bug and two on the staged-key hole.

First: a correction to my own previous round

In 88a1b544 I added a warning — to the ADR and a code comment — that a leaked --dry-run output lets a third party submit bindNodeId and strand the operator. That is false, and I introduced it by implementing the round-2 suggestion without checking the contract.

// CapacityBond.sol:838-842
nonce = bindingNonce[msg.sender];
bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(BIND_NODE_TYPEHASH, nodeId, nonce)));
if (!SignatureChecker.isValidSignatureNow(msg.sender, digest, sig)) revert InvalidBindingSignature();

A third-party submitter is msg.sender, so both the nonce and the recovery target are theirs; the operator's signature cannot validate, and the ed25519 proof puts msg.sender in its preimage too. There is no relayer path. Both copies are removed and replaced with what is actually true: a dry run discards the key whose id it prints, so that id must not be recorded as the node's next identity. Apologies for putting a wrong threat model into a primary design artifact.

Critical

A lost receipt could destroy the new secret and reach the unslashable state. send_for_receipt sets InFlight(hash) before awaiting the receipt, so a receipt-fetch failure returns Err with the transaction already broadcast — and the Err arm dropped NewKey, whose Drop deletes the staged temp. If the transaction then mined, the chain was bound to a key whose secret existed nowhere, while the daemon served an id bindNodeId had just unbound. Exactly the fault the module doc claims no ordering can produce.

Added StagedNodeKey::keep(), which parks the secret at node.secret.pending.<node_id> — deliberately not node.secret, so no daemon loads it — whenever outcome.maybe_effected(). A definitively-rejected send still discards it rather than littering key material.

Important

  • Failed confirm_bound and failed commit returned before write_plan, so --json got empty stdout for exactly the states that most need a receipt. Both now report first, and the tx hash is read before the gate so every error can name it.
  • A broken stdout replaced the operation error — piping into head turned "may have been broadcast; re-sending is not idempotent" into "Broken pipe". Receipt now degrades to stderr; the real error survives.
  • preview_key was derived from dry_run, so a failed real run reported preview_key=false — claiming the printed id named a persisted key at the moment it named one just discarded. Now derived from whether the key was persisted.
  • eth submitted omitted approve/declare, printing approve_tx=0x… next to submitted=false.
  • ensure_distinct_operator never fired on the phases that matter — select_phase returned deregister/request/waiting/withdraw before reading --new-keystore, so a same-address mistake surfaced only after the 14-day window. Now checked on every invocation, with the keystore loaded once per call instead of per branch (scrypt; the eth journey went 78s → 12s).
  • The address that transacts wasn't provably the one confirmed: reonboard re-loaded the keystore after the prompt. It now takes the planned address and refuses a mismatch.
  • confirm_bound also matches the emitting contract address.

Docs

  • Two comments described a nodeId → address lookup the slashing path doesn't perform. _checkRegistered resolves the challenged address through nodeIdOf, so citing a retired id against a still-bound operator reverts NodeIdMismatch, not NodeNotRegistered. The PR's premise is unchanged; the explanation was wrong.
  • The documented "carry the original node id across" procedure could not work — --key iroh frees the original on-chain but also archives it and installs the throwaway, so the eth path finds the throwaway and mints a third key. The archive-restore step is now in the disclosure, module doc, and ADR.
  • --mbps help promised a default that cannot exist; --bind-existing rendered literal ** markdown.

Tests

confirm_bound — the gate on the irreversible local write — had no coverage at any layer. Six cases added from real encode_log_data receipts: matching log, no log, wrong operator, wrong node id, foreign contract, match among others. The foreign-contract case fails against the pre-hardening filter, so it's discriminating rather than decorative.

Reported, not actioned

Type reshapes (BindingReport as a payload enum; Installable/NewKey split so commit() is total; Phase::Reonboard carrying the keystore path); select_phase pure-seam extraction for phase-precedence and maturity-boundary tests; e2e tightening (region/multiaddr carry-forward is a silent-pass, ed25519_sig.len() > 2 accepts "0xdead", probe_node_id(...).is_err() passes on any error); submitted meaning "has a hash" on iroh vs "may have taken effect" on eth; unbonding_period / 86_400 truncating to "0-day window" on short testnets; fixed-size signature arrays; ASD-STE100 nits.

Out of scope, filed as #1623: NodeCommand::Reload's doc still lists two reloadable fields when the set is four — predates this PR, now contradicted by it.

Verified: fmt, clippy --workspace --all-targets --all-features -D warnings, cargo doc in CI form, 2815 unit tests (7 new), all 3 G-NODE-07 anvil-e2e journeys.

@yigitdot
yigitdot requested a review from thiras August 5, 2026 20:15
yigitdot and others added 3 commits August 10, 2026 20:09
Four agents reviewed round 3 — the commit that was itself a response to
round 2. Every high-severity claim was verified against the source before
being accepted; three agents converged independently on the first two.

CRITICAL, and a hole in round 3's own fix. Round 3 added key-parking for the
two post-send paths where the bind's fate is UNCERTAIN, and left the one path
where it is PROVEN as the only one that still destroyed the key. Reaching
`new_key.commit()` means `confirm_bound` already matched a NodeIdBound log
for this exact operator and id, so the chain names this key — and
`StagedNodeKey::commit(self)` dropped the stage on a failed install, letting
Drop delete the temp. Worst corner: `install_staged`'s restore-also-failed
branch leaves node.secret MISSING, and --bind-existing refuses when no key is
on disk, so recovery needed a manual .bak restore plus a second bindNodeId and
another binding nonce. Now `commit` takes &mut self, the caller retains the
key, and both post-send failures park it — recovery is a mv.

Same principle applied one level down: `keep()` used to destroy the temp when
its own rename failed. It now sets committed first and leaves the material in
place, naming the surviving path — it is only ever called when the key may
already be bound, so an awkwardly-named file beats a lost identity. `commit`
keeps the opposite policy on purpose (a failed install means never bound), and
a test now pins that the two do not get 'unified'.

Important:

- MaybeBroadcast rendered as submitted=false / bind_tx=skipped on the exact
  path that parks a key, so a --json wrapper read 'nothing happened' and would
  re-run, double-submitting over the same binding nonce. submitted is now
  tri-state (true/unknown/false) with bind_tx=unknown and a maybe_broadcast
  field. This is the bug round 3 fixed on the eth side, left on the iroh side.
- The parked key was stderr-only English. parked_key is now a field in both
  renderings, and the three different reasons for its absence are no longer
  conflated — describe_key_fate consults the key rather than the Option.
- confirm_bound's error hard-coded 'has been preserved separately', which is
  false under --bind-existing (nothing to preserve) and when parking failed
  (stderr simultaneously said discarded). The claim moved to the caller.
- The success path swallowed a failed stdout write and exited 0, losing
  bind_tx and archived_key. report()'s degradation is for paths that already
  carry an error; success now fails. Same for eth's Ok arm.
- confirm_bound computed the ABI-drift-vs-absence distinction and discarded
  it, then told the operator the two were indistinguishable. They imply
  opposite recoveries (install the parked key vs delete it), so it now
  partitions and reports which, including the decode error.
- The eth planned-operator guard's message shipped with collapsed indentation
  from a heredoc that ate its line continuations — which was itself evidence
  the branch had never been executed. Extracted as a pure
  ensure_planned_operator and tested, including a guard on the whitespace.

Tests (the whole parking mechanism was unverified — zero callers outside
production code):
- StagedNodeKey::keep: parks and survives Drop, the bytes reload to the
  recorded public key, node.secret is untouched, and a failed rename leaves
  the temp with its path named. Plus the abandoned-stage and failed-commit
  policies, so the three outcomes stay distinct.
- park-vs-discard across all six SendOutcome variants, and both non-staged
  NewKey arms.
- submitted for each of the seven transaction slots, and the negative case
  that a minted node id alone is not a submission.
- e2e: a same-address --new-keystore is refused on the FIRST invocation, with
  is_registered still true afterwards — pinning 'refused before
  deregisterNode', which nothing asserted.

Docs: the .pending. artifact now has a rollback row in the runbook; the ADR's
named revert is EOA-qualified (a permissive ERC-1271 submitter clears the
binding check and reverts InvalidEd25519Signature instead); 'before deregister'
dropped as over-constraining (bindNodeId has no active/bond precondition); the
dry-run paragraph carves out --bind-existing; and key_persisted is renamed
key_installed, since a parked key IS persisted and still is not the identity.

Verified: fmt, clippy --workspace --all-targets --all-features -D warnings,
2825 unit tests (10 new), all 3 G-NODE-07 anvil-e2e journeys.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…merge

Main moved `TERMS.md` from the repo root into `crates/cli/` (the new
package-embeds check: an `include_str!` reaching the workspace root builds
in-tree and then fails for every `cargo install` user, because a published
`.crate` contains only its own package directory).

The merge was textually clean, so nothing flagged that this fixture's
`include_str!("../../../TERMS.md")` no longer resolved — it surfaced only on
the post-merge build. Repointed at `../../cli/TERMS.md`, which is legitimate
here solely because `decdn-e2e` is `publish = false` and the check exempts
unpublished crates; the doc now says so, since the old rationale ("repo-root
TERMS.md") no longer describes where the file lives.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@yigitdot

Copy link
Copy Markdown
Contributor Author

Review round 4 — four-agent pass on round 3, fixes in 44bc5568; branch also merged with main

Ran the toolkit against 58d1846a specifically (the round-3 commit, which was itself a response to round 2 and had never been reviewed). Verified every high-severity claim against the source first; three agents converged independently on the first two findings.

Critical — a hole in round 3's own fix

Round 3 added key-parking for the two post-send paths where the bind's fate is uncertain, and left the one path where it is proven as the only one that still destroyed the key.

Reaching new_key.commit() means confirm_bound already matched a NodeIdBound log for this exact operator and id — the chain names this key. StagedNodeKey::commit(self) consumed the stage, so a failed install dropped it and Drop deleted the temp. Worst corner: install_staged's restore-also-failed branch leaves node.secret missing, and --bind-existing refuses when no key is on disk — so recovery needed a manual .bak restore plus a second bindNodeId and another binding nonce.

commit now takes &mut self, the caller retains the key, and both post-send failures park it. Recovery becomes a mv. Same principle one level down: keep() no longer destroys the temp when its own rename fails — it is only ever called when the key may already be bound, so an awkwardly-named surviving file beats a lost identity. commit keeps the opposite policy deliberately, and a test now pins that the two don't get "unified".

Important

  • MaybeBroadcast rendered as submitted=false / bind_tx=skipped — on the exact path that parks a key. A --json wrapper read "nothing happened" and would re-run, double-submitting over the same nonce. Now tri-state (true/unknown/false) with bind_tx=unknown and a maybe_broadcast field. This is the bug round 3 fixed on the eth side, left standing on the iroh side.
  • The parked key was stderr-only English — now parked_key in both renderings, and the three different reasons for its absence are no longer conflated.
  • confirm_bound claimed "has been preserved separately" — false under --bind-existing, and false when parking failed (where stderr simultaneously said discarded). The claim moved to the caller, which is the only place that knows.
  • The success path swallowed a failed stdout write and exited 0, losing bind_tx and archived_key. report()'s degradation is for paths that already carry an error; success now fails.
  • ABI drift was computed and discarded. After round 3 added the emitter-address filter, a log matching this registry and topic0 that still fails to decode is drift — and drift vs absence imply opposite recoveries (install the parked key vs delete it). Now partitioned and reported, including the decode error.
  • The eth planned-operator message shipped with collapsed indentation from a heredoc that ate its line continuations. The test analyst's inference is the useful part: that defect proved the branch had never been executed. Extracted as a pure ensure_planned_operator, tested, with a guard on the whitespace itself.

Tests — the parking mechanism had zero coverage

keep() had no callers outside production code. Added: parks and survives Drop; the bytes reload to the recorded public key; node.secret untouched; a failed rename leaves the temp and names it; plus the abandoned-stage and failed-commit policies so all three outcomes stay distinct. Also park-vs-discard across all six SendOutcome variants, submitted for each of the seven tx slots (and the negative: a minted node id is not a submission), and an e2e assertion that a same-address --new-keystore is refused on the first invocation with is_registered still true — pinning "refused before deregisterNode", which nothing asserted.

Docs

.pending. now has a rollback row in the runbook. The ADR's named revert is EOA-qualified (a permissive ERC-1271 submitter clears the binding check and reverts InvalidEd25519Signature instead). "before deregister" dropped as over-constraining. The dry-run paragraph carves out --bind-existing. key_persisted → key_installed, since a parked key is persisted and still isn't the identity.

The comment pass also confirmed round 3's retraction landed correctly: the slashing-mechanism correction is accurate at both sites, and the carry-over procedure traces cleanly end-to-end.

Branch merged with main

The branch was 30 commits behind and CI's green was computed against a 3-day-old base. Merged origin/main (29e01b27) and re-ran everything. The merge was textually clean but not semantically: main moved TERMS.md from the repo root into crates/cli/ for its new package-embeds check, which broke this PR's e2e fixture include_str!. Caught on the post-merge build and fixed in 48321774 — worth flagging as the concrete argument for merging before merge rather than after.

Verified on the merged tree: fmt, clippy --workspace --all-targets --all-features -D warnings, cargo doc in CI form, 2898 unit tests (10 new), all 36 anvil-e2e journeys, cargo deny.

Reported, not actioned

report()'s persisted per-call-site pinning (all four values independently verified correct; needs a seam), select_phase pure-seam extraction, the double identical password prompt, --new-keystore decrypted on --dry-run, eth's stage_and_install_fresh_key dropping the archive path (pre-existing), and the type reshapes deferred since round 3.

One conflict, in adr/appendix-operator-key-rotation.md steps 7-10 of the
EOA -> EOA migration. #1650 rewrote the payment model from pairwise channels
to a shared pool and swept this file's vocabulary; this branch had rewritten
step 8 in review round 4.

Resolved per-line rather than per-hunk, since the two sides touched disjoint
steps:
- step 7  -> main (rewritten for pools; this branch never edited it)
- step 8  -> ours (the 'from the old address' fix that dropped an
             over-constraining 'before deregister', plus the three-step
             archive-restore procedure — main left step 8 untouched)
- steps 9, 10 -> main (channels -> pools)

Deliberately NOT swept: the channel vocabulary in this branch's Rust doc
comments. #1650 is ADR-only (no crates/, no contracts/) — PaymentChannel.sol
still exists and PaymentPool.sol does not — so those comments describe what
the code actually does today. Rewriting them to pool vocabulary would make
them false, which is the failure mode the earlier review rounds were about.
The metric names decdn_channels_open and decdn_channel_deposit_usdc are
likewise unchanged, matching main's own choice to keep them.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@yigitdot
yigitdot merged commit 09c3b44 into main Aug 11, 2026
27 checks passed
@yigitdot
yigitdot deleted the feat/1034-node-rotate-key branch August 11, 2026 15:15
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.

cli+e2e G-NODE-07: decdn node rotate-key

2 participants