Repository navigation
feat(contracts): add node-registry surface to StakingRegistry - #641
Conversation
There was a problem hiding this comment.
Code Review
This pull request implements the node registry system in StakingRegistry.sol, enabling operators to bind iroh NodeIds to Ethereum addresses through EIP-712 and ed25519 signature verification. Key additions include registerNode, deregisterNode, and updateMultiaddrs functions, along with paginated views for active nodes. Feedback identifies a security vulnerability where the registrationNonce is not incremented during auto-ejection, which could allow for signature replays upon re-registration. Additionally, a storage optimization was suggested to pack the bindingNonce into the NodeInfo struct to reduce gas costs.
| function _ejectNodeIfActive(address operator) internal { | ||
| NodeInfo storage info = _nodes[operator]; | ||
| if (!info.active) return; | ||
| info.active = false; | ||
| _removeFromRegisteredSet(operator); | ||
| emit NodeAutoEjected(info.nodeId, activeStake[operator]); | ||
| } |
There was a problem hiding this comment.
The _ejectNodeIfActive helper, which handles both slash-induced auto-ejection and blacklist ejection, fails to increment the registrationNonce for the node. This is inconsistent with the deregisterNode implementation (line 503) and allows an operator to potentially reuse an old ed25519 signature if they attempt to re-register the same nodeId after being ejected. To maintain the security invariant that every registration requires a fresh proof of ownership (as specified in ADR 003), the nonce should be bumped whenever a node is removed from the active set.
function _ejectNodeIfActive(address operator) internal {
NodeInfo storage info = _nodes[operator];
if (!info.active) return;
bytes32 nodeId = info.nodeId;
info.active = false;
registrationNonce[nodeId] += 1;
_removeFromRegisteredSet(operator);
emit NodeAutoEjected(nodeId, activeStake[operator]);
}
References
- In Architecture Decision Records (ADRs), explicitly document security assumptions and design constraints that justify current implementation choices (e.g., omitting per-record signatures due to a no-relay model). These constraints should be kept in the canonical documentation to ensure they are visible during future protocol changes, preventing the silent invalidation of the security model.
| struct NodeInfo { | ||
| bytes32 nodeId; | ||
| address ethAddress; | ||
| bool active; | ||
| uint256 registeredAt; | ||
| uint256 firstRegisteredAt; | ||
| uint256 lastMultiaddrUpdate; | ||
| bytes multiaddrs; | ||
| string regionHint; | ||
| } |
There was a problem hiding this comment.
The bindingNonce mapping (line 211) can be moved into the NodeInfo struct to optimize storage. Since ethAddress (20 bytes) and active (1 byte) only occupy 21 bytes of their 32-byte storage slot, adding bindingNonce (uint64, 8 bytes) to the struct would allow it to pack into the same slot. This would save one storage slot per operator, reducing gas costs for registration and updates.
References
- Optimize storage in Solidity structs by reordering fields to pack types smaller than 32 bytes (e.g., address and bool) into single slots and placing dynamic-type fields (like bytes or string) at the end of the struct to minimize the number of storage slots used.
There was a problem hiding this comment.
Declining this one, with reasoning — bindingNonce and registrationNonce are sibling replay nonces (one keyed by address, one by nodeId), and they're part of the binding-state mapping family alongside nodeIdToAddress / addressToNodeId. Keeping all four as top-level mappings is deliberate:
- Symmetry. Packing
bindingNonceintoNodeInfowhileregistrationNoncestays a standalone mapping would split two conceptually identical things (anti-replay counters) across two storage models. Same reasoning that led us to keep theUnbondingRequesttimestamps asuint256for consistency in an earlier review. - Conceptual separation.
NodeInfoholds the node descriptor (multiaddrs, regionHint, timestamps). The binding nonces are authorization state shared with the futurebindNodeIdrebinding path (PR 3), which operates on an address's nonce independent of node descriptor writes. - Interface cost. The public
bindingNonce(address)auto-getter would have to become a hand-written view to preserve the surface, adding back some of what packing saves.
The gas saving is ~1 cold SSTORE per operator's first registration (~20k, one-time), negligible at the tens-of-nodes PoC scale. Happy to revisit if we ever expect a large operator set where the per-operator slot matters — flagging as the maintainer's call.
There was a problem hiding this comment.
Just to add a note, we accept a "~20k one time" cost at any scale.
9dbb7e9 to
1507a10
Compare
Gas snapshotGas changes vs baseRun: 26279611044 |
Contracts coverageLine coverage: 88.86% (303/341 lines) |
Extends StakingRegistry with the iroh-NodeId binding + multiaddrs
registry from ADR 003 § Node Registry. Stake mechanics and slash math
are unchanged; this layers identity + active-set pagination on top of
the merged stake-and-slash core.
OZ v5 additions: EIP712 (BindNodeId typed-data domain) + SignatureChecker
(EOA + ERC-1271 + ERC-4337 binding signatures, ADR 024).
New surface:
- registerNode / deregisterNode / updateMultiaddrs
- getNode / getNodeByAddress / isActiveNode / getActiveNodeCount /
getActiveNodes (pagination) / getFirstRegisteredAt / nodeIdOf
- refined isActive(addr): registered + active + stake>=min + !ejected
- IEd25519Verifier abstraction (real impl is its own audit boundary;
tests use MockEd25519Verifier)
- governable multiaddrUpdateCooldown [0,1d] + maxMultiaddrSize [64,1024]
Auto-eject (slash + blacklist) propagates to NodeInfo.active +
registrationNonce bump + active-set removal (gemini security review:
every active-set exit invalidates stale ed25519 registration sigs).
Rebased onto main's contract CI overhaul (#644). Integrated #644's
slash() hardening into the node-registry version: block-scoped
stake-reduction locals, slither-disable divide-before-multiply on the
bps share calcs, checks-effects-interactions (all eject effects commit
before external transfers; emits defer to after), forge-lint
block-timestamp disable on the updateMultiaddrs cooldown comparison.
.gas-snapshot baseline regenerated for the new surface.
Local verification (forge v1.7.1, matching CI pin): forge fmt --check,
forge build --deny warnings, forge test (111/111), npm run lint
(solhint 0 errors), gas snapshot regenerated.
Out of scope (follow-up): bindNodeId (rebinding), reclaimNodeId
(squat recovery), real IEd25519Verifier implementation.
Refs: #452
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
1507a10 to
cac318c
Compare
There was a problem hiding this comment.
Pull request overview
This PR extends the Solidity StakingRegistry contract with the ADR-003 node-registry surface (iroh NodeId ↔ EVM address binding, multiaddrs storage/update with cooldown, pagination over registered operators), using EIP-712 + SignatureChecker for Ethereum-key consent and an injected IEd25519Verifier for NodeId ownership proof. It also adds a test mock verifier and expands the Foundry test suite to cover the new behavior.
Changes:
- Add node registry storage, events, errors, and external methods (
registerNode,deregisterNode,updateMultiaddrs, node/pagination views) toStakingRegistry, plus governable parameters for multiaddr limits. - Introduce
IEd25519Verifierand aMockEd25519Verifierfor tests. - Expand
StakingRegistry.t.solwith constructor-arg coverage and node-registry unit tests; update gas snapshot.
Reviewed changes
Copilot reviewed 5 out of 5 changed files in this pull request and generated 4 comments.
Show a summary per file
| File | Description |
|---|---|
| contracts/src/StakingRegistry.sol | Implements node registry (EIP-712 binding + ed25519 verification), active-set tracking/pagination, and new governance parameters; integrates node deactivation into eject paths. |
| contracts/src/interfaces/IEd25519Verifier.sol | Adds verifier interface used as an injectable audit boundary for ed25519 signature checks. |
| contracts/test/mocks/MockEd25519Verifier.sol | Test-only ed25519 verifier stub that records last-call inputs and can be toggled to accept/reject. |
| contracts/test/StakingRegistry.t.sol | Adds comprehensive unit tests for node registration flows, multiaddr cooldown, pagination, and updated constructor wiring. |
| contracts/.gas-snapshot | Updates gas baselines to reflect new contract surface and tests. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| /// at or above `minStake` + not ejected. | ||
| function isActive(address operator) public view returns (bool) { | ||
| return _nodes[operator].active && activeStake[operator] >= minStake && !ejected[operator]; |
| function _checkRegistrationPreconditions(bytes32 nodeId, uint256 multiaddrsLength) internal view { | ||
| if (nodeId == bytes32(0)) revert ZeroNodeId(); | ||
| if (multiaddrsLength > maxMultiaddrSize) { | ||
| revert MultiaddrsTooLarge({ size: multiaddrsLength, ceiling: maxMultiaddrSize }); | ||
| } | ||
| if (activeStake[msg.sender] < minStake) { | ||
| revert StakeBelowMinimum({ stake: activeStake[msg.sender], required: minStake }); | ||
| } | ||
| if (_nodes[msg.sender].active) revert NodeAlreadyRegistered(); | ||
| } |
| info.multiaddrs = multiaddrs; | ||
| info.regionHint = regionHint; | ||
| } | ||
|
|
||
| /// @notice Mark `msg.sender`'s registered node as inactive and remove | ||
| /// from the active set. Does NOT move stake — operators | ||
| /// exit stake separately via `requestUnstake` / `unstake`. | ||
| /// @dev Increments `registrationNonce[nodeId]` so any pre-deregistration | ||
| /// ed25519 signature cannot be replayed after a re-registration. | ||
| /// Stake remains slashable while it sits in the unbonding flow; | ||
| /// the `MAX_EVIDENCE_AGE_US < unbondingPeriod` invariant | ||
| /// (ADR 014 § Unbonding interaction) prevents slash-then-run. | ||
| function deregisterNode() external nonReentrant whenNotPaused { | ||
| NodeInfo storage info = _nodes[msg.sender]; | ||
| if (!info.active) revert NodeNotActive(); | ||
|
|
||
| bytes32 nodeId = info.nodeId; | ||
| info.active = false; | ||
| registrationNonce[nodeId] += 1; |
| function _writeNodeInfo(bytes32 nodeId, bytes calldata multiaddrs, string calldata regionHint) internal { | ||
| NodeInfo storage info = _nodes[msg.sender]; | ||
| info.nodeId = nodeId; | ||
| info.ethAddress = msg.sender; | ||
| info.active = true; | ||
| info.registeredAt = block.timestamp; | ||
| // `firstRegisteredAt == 0` is a write-once sentinel (zero means | ||
| // "never registered"), not a value-bearing comparison — the strict | ||
| // equality is exactly the intended semantics per ADR 003 line 680. | ||
| // slither-disable-next-line incorrect-equality | ||
| if (info.firstRegisteredAt == 0) { | ||
| info.firstRegisteredAt = block.timestamp; | ||
| } |
Four findings from Copilot, all applied: 1. isActive now requires no in-flight unbonding (unbondingOf.amount == 0) — ADR 003 line 785 lists "stake fully or partially in unbonding" as inactive, even when remaining activeStake >= minStake. 2. registerNode rejects ejected callers (new OperatorEjected error). Prevents a blacklist/auto-ejected operator that still holds stake >= minStake from re-entering _registeredAddrs / getActiveNodes while ejected == true. Reinstatement (re-stake to >= minStake) is required first. 3. regionHint is length-bounded (MAX_REGION_HINT_BYTES = 16, new RegionHintTooLong error) — anti-state-bloat bound; ADR 003 specifies a 2-byte ISO 3166-1 alpha-2 code (self-reported/unverified). 4. deregisterNode vs ADR 003 reconciled. Implementation flips the active flag without auto-unbonding (deactivation and stake exit are separate; stake stays bonded + slashable; re-register needs no re-funding). ADR 003 line 678 updated to match — the slash-then-run protection keys off requestUnstake, not deregistration, so it holds. Tests +3, 114/114 passing under FOUNDRY_PROFILE=ci. Gas snapshot regenerated. Refs: #452 Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
The Copilot-requested `unbondingOf[operator].amount == 0` clause in isActive tripped slither's incorrect-equality (Medium) detector — same false-positive class as the firstRegisteredAt == 0 write-once sentinel. It's a presence check (no in-flight unbonding request), not a manipulable balance equality. Scoped slither-disable with rationale. Refs: #452 Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…he seed Covers the deferreds from PR 646 + PR 647's own description that became unblocked by #641 landing the StakingRegistry contract: - `crates/incentive/src/staking_registry.rs`: alloy `sol!` bindings for StakingRegistry. View functions consumed at runtime (`isActive`, `isActiveNode`, `nodeIdOf`, `getActiveNodes`, `getActiveNodeCount`) plus the six events that mutate the active set (`NodeRegistered`, `NodeDeregistered`, `NodeAutoEjected`, `EjectedByBlacklist`, `Reinstated`, `UnbondingRequested`). Write functions and governance events are intentionally out of scope — the node runtime never sends transactions to this contract. - `crates/node/src/dht/chain_staker_set.rs`: `ChainStakerSet`. Paginated `getActiveNodes(offset, 100)` at startup, then `isActive(operator)` per entry to filter `_registeredAddrs` down to the strict active predicate. Spawns a background watcher task that follows the six membership events and emits `StakerChange` via a `broadcast::Sender`. Watcher restarts its event filters with exponential backoff (1s → 60s cap) on RPC failure. Multicall3 batching at bootstrap and a re-bootstrap-on-extended- outage path are flagged as follow-ups. - `crates/node/src/dht/staker_set.rs`: `StakerSet` trait gains `subscribe_changes() -> broadcast::Receiver<StakerChange>` and `StakerChange { Active(NodeId) | Inactive(NodeId) }`. `ConfigStakerSet` holds a silent `broadcast::Sender` so receivers stay open forever without firing — call sites can be impl-agnostic instead of branching. Same pattern in the `AllStaked` test stub. - `crates/node/src/dht/publish.rs`: `RepublishScheduler::seed_cold_start(iter)` batch-schedules every input hash with an independent `uniform(0, 40 min)` draw per ADR 022 §Bootstrap. Consumed by the runtime at startup over `CacheEngine::access_times_snapshot` (which already exists; the PR-647 deferred bullet claiming we needed a new accessor was incorrect — verified at `crates/cache/src/engine.rs:1244`). - `crates/node/src/runtime/mod.rs`: builds the alloy `RootProvider<Http<reqwest::Client>>` from `cfg.blockchain.rpc_url`, parses `cfg.blockchain.staking_registry_address`, and replaces the `ConfigStakerSet::empty()` placeholder + warn with `ChainStakerSet::bootstrap(...).await`. Bootstrap RPC failure is fatal — per ADR 022 §Bootstrap the DHT cannot function without a populated staker set. Cold-start seed happens between scheduler construction and the `run_republish` spawn so any blob already on disk gets a jittered first-publish entry without waiting for `subscribe_inserts`. Tests: 5 new unit tests (`apply_change` active/inactive idempotent on `ChainStakerSet`, `ConfigStakerSet::subscribe_changes` stays-open-never-fires, `RepublishScheduler::seed_cold_start` distribution + empty-input no-op). The existing 1094 tests still pass — 1099 total. An anvil-backed integration test (deploy `StakingRegistry`, register two operators, assert bootstrap populates, deregister one, assert the watcher emits `Inactive`) would be the highest-value addition; it requires contract-deployment scaffolding the workspace doesn't yet have and is flagged as a follow-up. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…efresh (PR 4/5 of #320) (#647) * feat(node): DHT bootstrap, republish scheduler, bucket refresh (ADR 022) PR 4 of 4 for #320 (Kademlia content discovery). Wires the requester-side outbound primitives plus the long-running maintenance tasks that keep the network healthy. What's in: - `crates/node/src/dht/client.rs` — outbound `find_node`, `store`, `find_value` primitives. Wraps connect → open_bi → frame → decode with a hard 8s timeout and exposes `extract_app_error_code` so callers can match on ADR 013 application error codes (e.g. retry on `RATE_LIMITED`, give up on `MALFORMED_MESSAGE`). - `crates/node/src/dht/bootstrap.rs` — ADR 022 §Bootstrap two-step: (1) seed the routing table directly from `StakerSet::active_nodes()` so inbound DHT traffic can route immediately, (2) fan out `FindNode(self.node_id)` to up to 8 seeds in parallel and ingest every `closer_node` they return. Best-effort — bootstrap failure doesn't abort startup; the seed step alone leaves the table populated. - `crates/node/src/dht/publish.rs` — `RepublishScheduler` with a `BinaryHeap<(due_us, hash)>` keyed by jittered due time. Steady- state: uniform(30, 50) min per ADR 022 §STORE Flow step 3. Cold- start: uniform(0, 40) min per §Bootstrap. The `run_republish` task consumes `CacheEngine::subscribe_inserts` from PR 3 and fans out `Store` to the K+3 = 23 closest peers per due hash. Broadcast `Lagged` logs a warning and continues; the next cycle (or a node restart) will recover. - `crates/node/src/dht/bucket_refresh.rs` — `run_bucket_refresh` task picks the bucket with the oldest last-refresh timestamp per tick (default 1 hour), generates a random `NodeId` whose XOR distance falls in that bucket, and runs `FindNode(random)` against the bucket's freshest peer to repopulate. ADR 022 §Routing Table. - `crates/node/src/dht/origin.rs` — `OriginDirectory` trait + file- config-driven `ConfigOriginDirectory`. The chain-backed `ChainOriginDirectory` reads `PublisherRegistry.namespaceOf` → `OriginAssignment.getOrigins` → `StakingRegistry.nodeIdOf` per ADR 022 §FIND_VALUE Flow; that impl lives in the on-chain origin-directory follow-up. - Runtime wiring: bootstrap runs once at startup with the resolved staker set; the three long-running tasks (republish, bucket refresh, record-store GC) join the existing `JoinSet` shutdown pipeline. Three new loopback integration tests at `crates/node/tests/dht_bootstrap.rs`: - `client_find_node_roundtrip_via_dht_client_module` proves the new client primitives produce the same wire shape as the existing `dht_loopback.rs` hand-written exchange path. - `bootstrap_seeds_routing_and_runs_self_lookup` exercises the full bootstrap orchestration: client C → seed = server S → bootstrap → asserts C's table contains S AND S's table contains C (the latter from C's `FindNode` against S authenticating the connection). - `client_store_lands_record_at_server` exercises the republish scheduler's leaf operation in isolation: a staked publisher's `store` lands a record in the server's `RecordStore`. What's deferred: - Iterative requester-side `FindValue` lookup (α=3 parallel queries with the three ADR-022 §Lookup integrity filters: XOR-distance, active-staker, negative-probe-cache; provider-set randomisation). Splits into a follow-up PR (PR 5 of #320) — the iterative algorithm is non-trivial and pairs more naturally with the prefetch path (ADR 022 §Popularity Signals) than with the maintenance tasks here. `client::find_value` is already in place to support it. - Cold-start cache-iteration: walking every blob in the cache at boot to schedule republish with the uniform(0, 40) min window. `CacheEngine` lacks a public hash-iteration accessor; filed as a follow-up. Steady-state operation via `subscribe_inserts` is unaffected. - alloy `sol!` placeholder bindings for `PublisherRegistry`, `OriginAssignment`, and `StakingRegistry.{nodeIdOf, getActiveNodes}` views. The trait abstractions (`StakerSet`, `OriginDirectory`) isolate the consuming code from the chain dependency, so the bindings can land with the chain-backed impls in one follow-up. 1018 workspace tests pass. Refs #320. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * fix(node): apply PR #647 review (eager publish, K+3 fanout, stop-on-evict, error chain) Five-bot review on PR #647 found four correctness issues, two important hygiene issues, and one CI failure. All addressed. CI: - PR title renamed: "DHT bootstrap..." → "dht bootstrap..." (the semantic-PR check requires a lowercase subject after `feat(node):`). Critical correctness: - **Eager publish on cache insert.** ADR 022 §STORE Flow steps 2-3 say "send Store NOW, then schedule next at T + uniform(30, 50) min". The previous code scheduled with the steady-state window from the start, so a freshly-cached blob wasn't discoverable for up to 50 minutes. `run_republish` now calls `publish_hash` directly on every insert event before scheduling the next jitter draw. Regression test: `run_republish_publishes_immediately_on_cache_insert`. - **K+3 = 23 fanout actually fans to 23.** `RoutingTable::closest` caps at `K_BUCKET_SIZE = 20` for wire-response safety. The republish path was hitting that cap silently — only publishing to K=20, not K+3=23. Added `RoutingTable::closest_unbounded(target, n)` with no wire-cap clamp, and switched the republish call to use it. ADR 022 §STORE Flow line 128 specifies the three overflow targets as the load-bearing defense against an attacker suppressing receivers. Regression test: `closest_unbounded_returns_more_than_k_when_requested`. - **Stop republishing on cache eviction.** ADR 022 line 122: "A node stops re-publishing when it evicts the blob." Previously the scheduler kept publishing forever once `subscribe_inserts` fired — including DMCA / operator-evict cases. `run_republish` now consumes the `CacheEngine` handle and checks `cache.is_evicted` + `cache.has(hash)` before each republish; evicted hashes get `scheduler.unschedule` and drop out of the rotation. - **Preserve typed iroh errors through the client chain.** The previous `.map_err(|e| anyhow::anyhow!("...: {e}"))` form string-formatted iroh's `ConnectionError` / `ReadError` and discarded the typed source. `extract_app_error_code` walks the error chain looking for those types to pull out ADR 013 application error codes — it was unreliable as a result. Switched to `.context()` which preserves the typed cause chain via `anyhow::Context`. The helper is now meaningful. Important hygiene: - **Bucket refresh: all non-empty buckets per tick.** ADR 022 §Routing Table specifies "1 hour" as the refresh interval **per bucket**. The previous "one bucket per tick" implementation gave a populated bucket up to `KEYSPACE_BITS × interval ≈ 10.5 days` between refreshes. `run_bucket_refresh` now snapshots every non-empty bucket per tick and fans out the `FindNode` RPCs in parallel. Realistic scale (≤30 populated buckets even in a 500-node network) is comfortably under the routing-table peers' default per-IP rate limit (100 req/s). - **Randomise bootstrap fanout.** The `StakerSet` trait contract at `staker_set.rs:30` says callers MUST randomise before any selection step an attacker could influence. The bootstrap code took the first 8 entries from the trait's iteration order. Now shuffles via `SliceRandom::shuffle` before `.take(8)`. Particularly important once a chain-backed `StakerSet` ships and returns entries in on-chain insertion order (which is attacker-influenceable). - **Dedupe `bucket_of`.** Made `routing::bucket_index` `pub(crate)` and dropped the copy in `bucket_refresh.rs`. The own-code comment even acknowledged this was a duplicate. 1021 workspace tests pass (3 new regression guards). Clippy + fmt clean. Refs #320, addresses PR #647 multi-bot review. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * feat(node): chain-backed StakerSet, subscribe_changes, cold-start cache seed Covers the deferreds from PR 646 + PR 647's own description that became unblocked by #641 landing the StakingRegistry contract: - `crates/incentive/src/staking_registry.rs`: alloy `sol!` bindings for StakingRegistry. View functions consumed at runtime (`isActive`, `isActiveNode`, `nodeIdOf`, `getActiveNodes`, `getActiveNodeCount`) plus the six events that mutate the active set (`NodeRegistered`, `NodeDeregistered`, `NodeAutoEjected`, `EjectedByBlacklist`, `Reinstated`, `UnbondingRequested`). Write functions and governance events are intentionally out of scope — the node runtime never sends transactions to this contract. - `crates/node/src/dht/chain_staker_set.rs`: `ChainStakerSet`. Paginated `getActiveNodes(offset, 100)` at startup, then `isActive(operator)` per entry to filter `_registeredAddrs` down to the strict active predicate. Spawns a background watcher task that follows the six membership events and emits `StakerChange` via a `broadcast::Sender`. Watcher restarts its event filters with exponential backoff (1s → 60s cap) on RPC failure. Multicall3 batching at bootstrap and a re-bootstrap-on-extended- outage path are flagged as follow-ups. - `crates/node/src/dht/staker_set.rs`: `StakerSet` trait gains `subscribe_changes() -> broadcast::Receiver<StakerChange>` and `StakerChange { Active(NodeId) | Inactive(NodeId) }`. `ConfigStakerSet` holds a silent `broadcast::Sender` so receivers stay open forever without firing — call sites can be impl-agnostic instead of branching. Same pattern in the `AllStaked` test stub. - `crates/node/src/dht/publish.rs`: `RepublishScheduler::seed_cold_start(iter)` batch-schedules every input hash with an independent `uniform(0, 40 min)` draw per ADR 022 §Bootstrap. Consumed by the runtime at startup over `CacheEngine::access_times_snapshot` (which already exists; the PR-647 deferred bullet claiming we needed a new accessor was incorrect — verified at `crates/cache/src/engine.rs:1244`). - `crates/node/src/runtime/mod.rs`: builds the alloy `RootProvider<Http<reqwest::Client>>` from `cfg.blockchain.rpc_url`, parses `cfg.blockchain.staking_registry_address`, and replaces the `ConfigStakerSet::empty()` placeholder + warn with `ChainStakerSet::bootstrap(...).await`. Bootstrap RPC failure is fatal — per ADR 022 §Bootstrap the DHT cannot function without a populated staker set. Cold-start seed happens between scheduler construction and the `run_republish` spawn so any blob already on disk gets a jittered first-publish entry without waiting for `subscribe_inserts`. Tests: 5 new unit tests (`apply_change` active/inactive idempotent on `ChainStakerSet`, `ConfigStakerSet::subscribe_changes` stays-open-never-fires, `RepublishScheduler::seed_cold_start` distribution + empty-input no-op). The existing 1094 tests still pass — 1099 total. An anvil-backed integration test (deploy `StakingRegistry`, register two operators, assert bootstrap populates, deregister one, assert the watcher emits `Inactive`) would be the highest-value addition; it requires contract-deployment scaffolding the workspace doesn't yet have and is flagged as a follow-up. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * fix(node): address PR #647 multi-agent review Findings consolidated from 5 review agents (code-reviewer, pr-test-analyzer, comment-analyzer, silent-failure-hunter, type-design-analyzer): - Drop `EjectedByBlacklist` event subscription. `StakingRegistry.ejectNode` emits both `EjectedByBlacklist(operator)` AND `NodeAutoEjected(nodeId)` in the same call (contract lines 662-672); subscribing to both produced one wasted `nodeIdOf` RPC per blacklist ejection. The `NodeAutoEjected` arm covers the membership change with the canonical nodeId. Operators with no nodeId binding are never in our active set, so dropping `EjectedByBlacklist` loses no information. - Rewrite the Failure-model docstring to match what `watcher_loop` actually does today (log + exponential-backoff filter restart, no resync). The previous version promised a `getActiveNodes` resync after `WATCHER_RESYNC_THRESHOLD` that the code did not implement (constant was `#[allow(dead_code)]`). Drop the dead constant. - Remove the fabricated ADR 019 § Step 3.3 quote. ADR 019 names four events (`NodeRegistered`, `NodeMultiaddrUpdated`, `NodeDeregistered`, `NodeAutoEjected`); our subscription is the correct active-set predicate (no `MultiaddrUpdated` because it doesn't move membership; plus `Reinstated` and `UnbondingRequested` because they do). Ground the comment in the contract's own write paths instead. - Log `warn!` on `RwLock` poison recovery in `read_active` and `apply_change` — matches the in-repo precedent at `cache/src/engine.rs:510-516`. A poisoned lock means *something panicked while holding the write lock*; silent recovery hid that signal completely. - Improve the `nodeIdOf` RPC-failure warn message to spell out that dropping the event leaves the cached set diverged from chain state until a follow-up event arrives. Same observability point as the poison-recovery log. - Fix bootstrap pagination off-by-one: break on `page.is_empty()` instead of `page_len < PAGE_SIZE`. At exactly 100/200/… registered operators the previous condition issued one wasted trailing RPC returning an empty page. - Switch `seed_cold_start` test from peeking at the private `s.heap` to a behavioural `drain_due` check at deadline — survives a future swap to a different scheduling primitive. - Trim stale issue / PR-number references in doc comments (#283, "PR 5", "PR 647", "deferred Multicall3", ADR-line citations). Trim WHAT-narrating bullets in the `staking_registry.rs` module doc; keep the two non-obvious gotchas (`getActiveNodes` not filtered, `nodeIdOf.active` is the full predicate). - Trim WHAT-narrating runtime comments around `ChainStakerSet` bootstrap + cold-start seed; keep only the load-bearing WHY (fatal-on-failure rationale, subscribe-before-seed ordering). - Document the `RecvError::Lagged` contract on `StakerSet::subscribe_changes` so consumers know to handle it. Type-design suggestions (rename `StakerChange::Active/Inactive` → `Joined/Left`, rename `_watcher` field, swap broadcast::Receiver for `Stream` in the trait) are deliberately deferred — they're public-API churn for stylistic gains, not load-bearing. Anvil-backed integration test for the full chain → Rust contract remains the highest-value follow-up (operator→NodeId binding via `nodeIdOf`, watcher reconnect on RPC failure). Tests: 1099/1099 pass. clippy clean. fmt clean. cargo doc clean. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * fix(node): clean up doc rot + dead code from DHT PR4 review Addresses Alper's review on #647: drop the unused `MAX_RESPONSE_BYTES` constant + its placeholder `let _ =` (a doc-described `read_to_end` bound that never existed); remove the `PathBuf` cargo-cult import and the misleading `let _ = cache_dir;` "kept-alive guard" in the republish-on-insert test; rewrite the `bucket_refresh` module doc to match the all-buckets-per-tick behavior the constant doc and code already describe; rewrite `schedule_steady`'s self-contradictory doc to describe the push-duplicate-then-dedupe-on-drain behavior that actually exists; drop the unused `_cache` parameter from `publish_hash` (the cache-still-holds check lives in the caller). No behavior change. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> --------- Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
Summary
Extends
StakingRegistrywith the iroh-NodeId binding + multiaddrs registry from ADR 003 § Node Registry. Stake mechanics and slash math are unchanged; this PR layers identity on top of the merged stake-and-slash core.OZ v5 additions to the composition
EIP712— domain separator("StakingRegistry", "1")for theBindNodeId(bytes32 nodeId,uint64 nonce)typed-data signatureSignatureChecker— EOA + ERC-1271 + ERC-4337 binding-signature verification (ADR 024 — smart accounts work out of the box)New external surface
registerNode(nodeId, multiaddrs, regionHint, bindingSig, ed25519Sig)msg.senderafter verifying both signatures. RequiresactiveStake >= minStake.deregisterNode()NodeInfo.active=false, removes from active set, bumpsregistrationNonce[nodeId]. Does NOT touch stake.updateMultiaddrs(multiaddrs)getNode(nodeId)/getNodeByAddress(addr)isActiveNode(nodeId)getActiveNodeCount()/getActiveNodes(offset, limit)getFirstRegisteredAt(addr)nodeIdOf(addr)(nodeId, active)read per ADR 003 line 780.isActive(addr)(refined)>= minStake+ not ejected.ed25519 verifier as a separate audit boundary
IEd25519Verifieris a 1-function interface (verify(publicKey, messageHash, signature) returns (bool)). The real Solidity implementation wrapping a vetted ed25519 library lands as its own PR — keeping that audit surface isolated, and making the verifier swappable if RIP-7212 ever ships on Arbitrum and a precompile becomes available.Tests use
MockEd25519Verifierwith a toggle-ableacceptflag and records of the last(publicKey, messageHash, signature)so assertions can verify StakingRegistry passes the right arguments.Auto-eject integration
Both eject paths now flip
NodeInfo.activeand remove from the active set when the operator is registered:slashauto-eject (activeStake < minStake / 2) → emitsAutoEjected(operator)+NodeAutoEjected(nodeId, remaining)ejectNode(blacklist path) → emitsEjectedByBlacklist(operator)+NodeAutoEjected(nodeId, remaining)if registeredGovernable parameters (bounded per ADR 009)
multiaddrUpdateCooldownmaxMultiaddrSizeTests — 54 new unit + 1 fuzz, all passing under
FOUNDRY_PROFILE=ci(66/66 across the full suite)registerNode: happy path; reverts on below-min-stake, zero nodeId, oversize multiaddrs, bad binding signature, rejected ed25519 signature, already-registered, nodeId bound to another operatorderegisterNode: flag + nonce + active-set updates; same-nodeId re-register works post-deregister with bumped noncesupdateMultiaddrs: replaces + stamps; governable cooldown enforced; reverts when not activeNodeInfo.activeand drops from active setgetActiveNodesoffset / limit boundariesImplementation notes
registerNoderesolved by extracting_checkRegistrationPreconditions/_checkBindingOneToOne/_verifyBindingSignature/_verifyEd25519OwnershipSignature/_writeNodeInfohelpers. Novia_irenabled — keeping codegen direct._registeredAddrsis anaddress[]with a 1-indexed lookup mapping for O(1) swap-pop removal. TracksNodeInfo.active == trueoperators (NOT filtered by stake or ejection — consumers combine withisActivefor the fully-active predicate).IEd25519Verifier.verifyisexternal returns (bool)(notview) because Solidity disallows overriding aviewfunction with a state-mutating one, and the test mock needs to track call metadata in storage. Real implementations should still beview.Out of scope (follow-up PR)
bindNodeId(rebinding for key rotation per ADR 003 lines 763, 801)reclaimNodeId(squat recovery per ADR 003 lines 640, 727)IEd25519Verifierimplementation wrapping a vetted Solidity libraryTest plan
forge fmt --checkcleanFOUNDRY_PROFILE=ci forge build --sizescleanFOUNDRY_PROFILE=ci forge test— 66/66 passingsolidityjob greenci-successaggregator greenRefs: #452