Skip to content

feat(node,cli): load eth_keystore into a live PrivateKeySigner (#406) - #442

Merged
alpergundogdu merged 5 commits into
mainfrom
claude/analyze-prs-issues-WP2BQ
May 7, 2026
Merged

alpergundogdu merged 5 commits into
mainfrom
claude/analyze-prs-issues-WP2BQ

Conversation

@alpergundogdu

Copy link
Copy Markdown
Contributor

Summary

Closes #406. Carved out of #327's runtime-integration scope. Anything that signs (EIP-712 vouchers per #319, on-chain txs per #327) needs a usable alloy::signers::local::PrivateKeySigner regardless of whether on-chain RPC is wired up — this PR delivers that.

Two halves:

  1. decdn key-gen now generates the Ethereum keystore alongside the Ed25519 node key (its doc-comment already advertised it). Password sources, in precedence order: DECDN_KEYSTORE_PASSWORD env, --password-file, interactive prompt with double-entry confirm. Pre-flight rejects when either file exists without --force.
  2. Runtime keystore loader in crates/common/src/eth_identity.rs returns a live PrivateKeySigner. The runtime resolves the password, decrypts on a spawn_blocking thread (scrypt KDF is CPU-bound), pins chain id 421614 (Arbitrum Sepolia), and threads Arc<PrivateKeySigner> through AdminState::new so future consumers clone from a single source.

Implementation notes

  • Module placement. New crates/common/src/eth_identity.rs mirrors crates/common/src/identity.rs's shape. Both decdn-cli (key-gen) and decdn-node (runtime) need this code, and decdn-common is the only crate both depend on.
  • Permission parity with node.secret. The keystore is encrypted at rest, but a leaked ciphertext + weak password is enough for an offline KDF attack. So the same 0o600 file / 0o700 data_dir model applies. identity::validate_data_dir and create_data_dir_secure were bumped to pub(crate) for reuse rather than duplicating the helpers.
  • Atomic write. Alloy's encrypt_keystore writes in-place under a name we control; we pass a unique temp name, chmod 0o600, then rename to keystore.json. Failure paths clean up the temp file.
  • Rand version bridge. Workspace rand is 0.10; alloy-signer-local 2.0 wants Rng + CryptoRng from rand 0.8 (via rand_core 0.6). The new module sources fresh secret bytes via rand::rng() (workspace) and feeds alloy's KDF/IV via alloy::signers::k256::elliptic_curve::rand_core::OsRng. Both are CSPRNGs over OS entropy.
  • signer-keystore alloy feature. Verified the meta-crate exposes signer-keystore = ["signer-local", "alloy-signer-local?/keystore"]; added to the workspace tuple.
  • spawn_blocking for runtime decrypt. scrypt at default params runs in hundreds of ms, easily seconds with hardened params — has to run off the tokio worker pool.
  • keystore_password_file is CLI/env-only. Deliberately not surfaced in TOML — passwords (or paths to passwords) don't belong in checked-in config files even by reference. The new field on ResolvedBlockchain is populated only from BlockchainArgs.
  • AdminState::new arity reaches 8. Tagged #[allow(clippy::too_many_arguments)] with a note. A builder refactor is deferred to a follow-up.
  • PrivateKeySigner Debug impl. Alloy's stock impl prints the address only, never the secret scalar — confirmed by manual inspection.

Out of scope (per #406)

Test plan

  • cargo fmt --all -- --check clean
  • cargo clippy --workspace --all-targets -- -D warnings clean
  • cargo test --workspace -- --test-threads=1 clean (the parallel-run flake on persistent_sighup_observes_both_signals is pre-existing — process-global SIGHUP races between the two tests in crates/node/tests/sighup_signal.rs regardless of this PR)
  • RUSTDOCFLAGS="-D warnings" cargo doc --workspace --no-deps --document-private-items clean
  • Manual smoke test: DECDN_KEYSTORE_PASSWORD=hunter2 cargo run --bin decdn -- key-gen --output-dir /tmp/decdn-test produces node.secret (32 bytes, 0o600), keystore.json (~436 bytes valid v3 JSON, 0o600), data_dir 0o700, and prints the EIP-55 address
  • cargo deny check — not run locally (binary unavailable in dev env); will run in CI

New tests

  • 18 unit tests in crates/common/src/eth_identity.rs:
    • round-trip address recovery, wrong-password rejection (without echoing the password in the error), missing/malformed/non-v3 keystore rejection, secure-perms enforcement, group/symlink rejection, password source precedence, trailing-\n / CRLF stripping, no-TTY prompt fallback, EIP-712 sign-and-recover with an inline sol! { TinyVoucher }
  • 4 integration tests in crates/cli/tests/key_gen_e2e.rs:
    • both files written with correct modes, --force produces a fresh keystore, error when keystore exists without --force, error when node.secret exists without --force (pre-flight short-circuits before any password prompt)

🤖 Generated with Claude Code


Generated by Claude Code

claude added 2 commits May 6, 2026 17:22
Carved out of #327's runtime-integration scope. Anything that signs
(EIP-712 vouchers per #319, on-chain txs per #327) needs a usable
`alloy::signers::local::PrivateKeySigner` regardless of whether on-chain
RPC is wired up.

Changes:

- `crates/common/src/eth_identity.rs` (new): `keystore_path`,
  `generate_and_persist`, `load_signer`, and a `PasswordSource`-driven
  `read_password` that resolves env > `--keystore-password-file` >
  interactive TTY prompt. Atomic write via temp-name + chmod 0o600 +
  rename. Reuses `identity::validate_data_dir` /
  `create_data_dir_secure` (bumped to `pub(crate)`) so node.secret and
  keystore.json share permission semantics.
- `decdn key-gen` now generates the Ethereum keystore alongside the
  Ed25519 node key (its doc-comment already advertised it). Sources the
  password from env / `--password-file` / interactive double-confirm
  prompt before any disk write so an aborted prompt leaves nothing on
  disk. Pre-flight check rejects when either file exists without
  `--force`. New `crates/cli/tests/key_gen_e2e.rs` covers the four
  golden paths.
- Runtime (`crates/node/src/runtime/mod.rs`): `load_eth_signer` reads
  the password, decrypts on a `spawn_blocking` thread (scrypt KDF is
  CPU-bound, ~hundreds of ms), pins the signer to chain id 421614
  (Arbitrum Sepolia), and threads `Arc<PrivateKeySigner>` through
  `AdminState::new` so future signing consumers can clone from a single
  source. Failure surfaces fast — before the cache and endpoint are
  built — so a missing/wrong-password keystore aborts startup with a
  clear message.
- `BlockchainArgs.keystore_password_file` (CLI/env-only; not in TOML —
  passwords/paths-to-passwords don't belong in checked-in config) and
  `ResolvedBlockchain.keystore_password_file` plumb the source path
  through resolution.
- Workspace `alloy` features gain `signer-keystore`; new workspace dep
  `rpassword = "7"` for the interactive prompt path.
- `AdminState::new` arity reaches 8 (`#[allow(clippy::too_many_arguments)]`
  with a note); a builder refactor is deferred to a follow-up.

Tests added:
- 18 unit tests in `eth_identity.rs` (round-trip, wrong-password,
  missing/malformed/non-v3, secure perms, group/symlink rejection,
  password env-vs-file precedence, trailing-newline / CRLF stripping,
  TTY fallback, EIP-712 sign-and-recover with an inline `sol!` voucher).
- 4 integration tests in `crates/cli/tests/key_gen_e2e.rs`.

Out of scope (per #406): on-chain RPC and contract calls (stays in
#327), hardware wallet / remote signer support.

🤖 Generated with [Claude Code](https://claude.com/claude-code)
`cargo fmt` would have collapsed the multi-line tuple form into a
single line; my post-fmt edit re-introduced the longer form, which
CI's rustfmt --check flagged.

https://claude.ai/code/session_01FBBEqDGhNYSUZuGWDGiWAD

@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 Ethereum keystore support, allowing for the generation, persistence, and loading of Web3 Secret Storage v3 files. It introduces a new eth_identity module in crates/common for keystore management, updates the key_gen CLI command to include keystore generation, and integrates a PrivateKeySigner into the node's AdminState. The implementation includes robust password sourcing from environment variables, files, or interactive prompts, and ensures that CPU-intensive decryption is handled on blocking threads. I have no feedback to provide.

@alpergundogdu

Copy link
Copy Markdown
Contributor Author

Review summary

Reviewed against adr/appendix-operator-key-rotation.md (the canonical key-rotation runbook) and adr/appendix-poc-production-seams.md (Seam 1: KeyStore).

Strengths

  • Atomic write via temp + chmod + rename; failure paths clean up the temp file.
  • Permission parity with node.secret (0o600 / 0o700) reuses identity::* helpers rather than duplicating them.
  • Pre-flight check before read_password so an aborted prompt leaves nothing on disk.
  • 18 unit tests + 4 integration tests cover wrong password (no echo), symlink rejection, group bits, malformed/non-v3 JSON, password source precedence, CRLF stripping, no-TTY fallthrough, and EIP-712 sign/recover.
  • Doc-comments justify their existence (RNG bridge, atomic-write rationale, KDF blocking).

To address in this PR

  1. Relocate eth_identity.rs to crates/incentive. Per appendix-poc-production-seams.md §Seam 1, KeyStore lives in incentive and covers both iroh + Ethereum keys. The common-placement justification (CLI doesn't depend on incentive) flips when you observe that any client binary will sign vouchers (ADR 003 §EIP-712 Voucher) — clients and nodes share the keystore surface. Add decdn-incentive to cli/Cargo.toml. Free functions for now; the KeyStore trait per §Seam 1 lands with Implement EIP-712 payment voucher creation and verification #319 (its shape needs to absorb voucher signing).
  2. Extract identity::ensure_data_dir(&Path) -> Result<()> — collapses the duplicated validate-or-create pattern between eth_identity::generate_and_persist and identity::load_or_generate, and keeps validate_data_dir / create_data_dir_secure as pub(crate) (no incidental API surface added by the move).
  3. Dedupe KEYSTORE_PASSWORD_ENV. Currently declared in both cli/src/commands/key_gen.rs:5 and node/src/runtime/mod.rs:489. Promote to a single pub const in eth_identity.rs.
  4. ARBITRUM_SEPOLIA_CHAIN_ID = 421_614 is hardcoded in 4 places (runtime, two test throwaway_signer helpers, the EIP-712 loopback test). Promote to a pub const in eth_identity.rs (one source of truth) and consider threading through ResolvedBlockchain next to rpc_url — chain-id-keyed config is already a seam pattern (§Seam 8).
  5. EIP-712 loopback test should sign the canonical BindNodeId schema (per ADR 003 §EIP-712 NodeId-to-Ethereum Binding), not the ad-hoc TinyVoucher. Inline sol! { struct BindNodeId { bytes32 nodeId; uint64 nonce; } }. Catches schema-divergence regressions cheaply; importing from incentive::voucher would be circular but the inline sol! pattern is already established.

Follow-up issues

  • --force semantics conflict with the operator key-rotation runbook. appendix-operator-key-rotation.md §1 step 9 requires archiving the old iroh keystore for MAX_EVIDENCE_AGE_US; current code does fs::remove_file. The runbook's §1 (iroh-only) and §2.x (Ethereum-only) procedures both require single-key regeneration, but current --force is all-or-nothing. Suggest splitting into --force=keystore / --force=node-key / --force=all, or moving the file aside (.bak.<ts>) instead of removing. Worth a separate issue + design discussion before changing behavior.
  • Builder for AdminState::new (now 8 args). Already flagged in the PR description.
  • Password zeroing. password: &str flows through several String allocations without zeroize. Defense-in-depth; could use secrecy::SecretString later.
  • Atomic-write window: brief gap where alloy writes the temp file with default perms (~0o644) before the chmod 0o600. Mitigated by data_dir = 0o700; worth a one-line comment acknowledging.

 review)

Per `appendix-poc-production-seams.md` §Seam 1, the keystore surface
lives in `crates/incentive` — both nodes (slash signing, on-chain
settlement) and clients (voucher signing per ADR 003 §EIP-712 Voucher
Signature) share it, so `incentive` is the natural home rather than
`common`. The original `common` placement was justified only by the
CLI dep graph; that flips when `incentive` is acknowledged as a shared
participant concern, and the seams ADR is already explicit on this.

Changes:

- Move `crates/common/src/eth_identity.rs` →
  `crates/incentive/src/eth_identity.rs`. Free functions for now; the
  `KeyStore` trait per §Seam 1 (`load_node_key` + `load_eth_key` +
  `sign_voucher`) lands with #319 — its shape needs to absorb voucher
  signing, which isn't in scope here.
- Add `decdn-incentive` to `cli/Cargo.toml`'s `[dependencies]` so
  `key-gen` can reach the shared module. Drop `rpassword` from
  `decdn-common` (only `eth_identity` used it); add `decdn-common`,
  `rand`, `rpassword`, and `tempfile` (dev) to `decdn-incentive`.
- Add `decdn_common::identity::ensure_data_dir(&Path)` as the public
  validate-or-create helper so `node.secret` and `keystore.json` go
  through one path. `validate_data_dir` / `create_data_dir_secure`
  stay `pub(crate)` — no incidental API surface added.
- Promote `KEYSTORE_PASSWORD_ENV` and `ARBITRUM_SEPOLIA_CHAIN_ID` to
  `pub const` in `eth_identity` (single source of truth). Previously
  duplicated across `cli/commands/key_gen.rs`, `node/runtime/mod.rs`,
  and the test `throwaway_signer` helpers in `cli/tests/admin_peers.rs`
  and `node/admin.rs`.
- Replace the ad-hoc `TinyVoucher` in the EIP-712 loopback test with
  the canonical `BindNodeId(bytes32 nodeId,uint64 nonce)` schema from
  ADR 003 §EIP-712 NodeId-to-Ethereum Binding. Add
  `bind_node_id_type_hash_matches_adr_003` locking the type hash
  against schema drift (mirrors `voucher_type_hash_matches_adr_003`).

`cargo fmt --all -- --check`, `cargo clippy --workspace --all-targets
-- -D warnings`, and `cargo test --workspace -- --test-threads=1` are
all clean. eth_identity test count: 18 → 19 with the new schema-lock.
#406 review)

Addresses the deferred items from the review of #442:

1. Force semantics now archive instead of destroy. The runbook
   (appendix-operator-key-rotation.md §1 step 9, §5) requires keeping
   the prior key for archival and rollback; previous code did
   fs::remove_file. New decdn_common::identity::move_aside renames the
   existing file to <name>.bak.<unix_ts> and bails if the bak path
   already exists. Used by both cli/key_gen.rs (node.secret) and
   eth_identity::generate_and_persist (keystore.json).

   Flag-split (--force-keystore / --force-node-key) deferred — the
   runbook procedures are offline anyway, so in-place single-key
   rotation is UX nice-to-have rather than runbook-required.

2. Password zeroing via zeroize::Zeroizing<String>. read_password,
   read_password_file, prompt_password now return Zeroizing<String>
   so password bytes are scrubbed on drop. Callers compose via deref
   coercion — no API change at the &str boundary.

3. Atomic-write window comment. eth_identity::generate_and_persist
   now documents the brief gap between alloy's encrypt_keystore
   (~0o644) and the chmod 0o600. Mitigated by data_dir = 0o700.

New tests:
- eth_identity::tests::force_archives_old_keystore_to_bak (verifies
  the bak file holds the byte-for-byte prior keystore)
- key_gen_e2e::force_archives_both_prior_keys (verifies both
  node.secret.bak.<ts> and keystore.json.bak.<ts> exist)

Test counts: eth_identity 19 → 20, key_gen_e2e 4 → 5. cargo fmt /
clippy --workspace --all-targets -- -D warnings / test --workspace
-- --test-threads=1 all clean.

Deferred to separate issues:
- --force-keystore / --force-node-key flag split
- Builder for AdminState::new (deferred in original PR description)
Local clippy passed under Rust 1.94.1; CI runs 1.95.0 which added
the lint. Mechanical rewrite — same semantics.
@alpergundogdu
alpergundogdu merged commit f502fe4 into main May 7, 2026
18 of 20 checks passed
@alpergundogdu
alpergundogdu deleted the claude/analyze-prs-issues-WP2BQ branch May 7, 2026 12:53
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.

Load eth_keystore into a live PrivateKeySigner

2 participants