Skip to content

feat(contracts): add node-registry surface to StakingRegistry - #641

Merged
alpergundogdu merged 3 commits into
mainfrom
feat/contracts-node-registry
May 22, 2026
Merged

alpergundogdu merged 3 commits into
mainfrom
feat/contracts-node-registry

Conversation

@alpergundogdu

Copy link
Copy Markdown
Contributor

Summary

Extends StakingRegistry with 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 the BindNodeId(bytes32 nodeId,uint64 nonce) typed-data signature
  • SignatureChecker — EOA + ERC-1271 + ERC-4337 binding-signature verification (ADR 024 — smart accounts work out of the box)

New external surface

Function Purpose
registerNode(nodeId, multiaddrs, regionHint, bindingSig, ed25519Sig) Bind nodeId to msg.sender after verifying both signatures. Requires activeStake >= minStake.
deregisterNode() Flips NodeInfo.active=false, removes from active set, bumps registrationNonce[nodeId]. Does NOT touch stake.
updateMultiaddrs(multiaddrs) Replace registered multiaddrs; governable cooldown rate-limits the path.
getNode(nodeId) / getNodeByAddress(addr) Read NodeInfo.
isActiveNode(nodeId) Full active predicate keyed by NodeId.
getActiveNodeCount() / getActiveNodes(offset, limit) Pagination over the registered-operator set.
getFirstRegisteredAt(addr) Write-once original registration timestamp.
nodeIdOf(addr) Bundled (nodeId, active) read per ADR 003 line 780.
isActive(addr) (refined) Full ADR 003 predicate: registered + active flag + stake >= minStake + not ejected.

ed25519 verifier as a separate audit boundary

IEd25519Verifier is 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 MockEd25519Verifier with a toggle-able accept flag 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.active and remove from the active set when the operator is registered:

  • slash auto-eject (activeStake < minStake / 2) → emits AutoEjected(operator) + NodeAutoEjected(nodeId, remaining)
  • ejectNode (blacklist path) → emits EjectedByBlacklist(operator) + NodeAutoEjected(nodeId, remaining) if registered

Governable parameters (bounded per ADR 009)

Param Default Floor Ceiling
multiaddrUpdateCooldown 0 (disabled per ADR 003 line 684) 0 1 day
maxMultiaddrSize 1024 bytes (ADR 003 line 619) 64 1024

Tests — 54 new unit + 1 fuzz, all passing under FOUNDRY_PROFILE=ci (66/66 across the full suite)

  • Constructor: bounds + zero-address reverts on all 6 constructor args
  • registerNode: happy path; reverts on below-min-stake, zero nodeId, oversize multiaddrs, bad binding signature, rejected ed25519 signature, already-registered, nodeId bound to another operator
  • deregisterNode: flag + nonce + active-set updates; same-nodeId re-register works post-deregister with bumped nonces
  • updateMultiaddrs: replaces + stamps; governable cooldown enforced; reverts when not active
  • Slash auto-eject: also flips NodeInfo.active and drops from active set
  • Blacklist eject: registered → flips both flags; unregistered → flag only
  • Pagination: getActiveNodes offset / limit boundaries

Implementation notes

  • Stack-too-deep in registerNode resolved by extracting _checkRegistrationPreconditions / _checkBindingOneToOne / _verifyBindingSignature / _verifyEd25519OwnershipSignature / _writeNodeInfo helpers. No via_ir enabled — keeping codegen direct.
  • _registeredAddrs is an address[] with a 1-indexed lookup mapping for O(1) swap-pop removal. Tracks NodeInfo.active == true operators (NOT filtered by stake or ejection — consumers combine with isActive for the fully-active predicate).
  • IEd25519Verifier.verify is external returns (bool) (not view) because Solidity disallows overriding a view function with a state-mutating one, and the test mock needs to track call metadata in storage. Real implementations should still be view.

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)
  • Real IEd25519Verifier implementation wrapping a vetted Solidity library

Test plan

  • forge fmt --check clean
  • FOUNDRY_PROFILE=ci forge build --sizes clean
  • FOUNDRY_PROFILE=ci forge test — 66/66 passing
  • CI solidity job green
  • CI ci-success aggregator green

Refs: #452

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Code Review

This pull request implements the 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.

Comment thread contracts/src/StakingRegistry.sol Outdated
Comment on lines +761 to +767
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]);
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

security-high high

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
  1. 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.

Comment on lines +187 to +196
struct NodeInfo {
bytes32 nodeId;
address ethAddress;
bool active;
uint256 registeredAt;
uint256 firstRegisteredAt;
uint256 lastMultiaddrUpdate;
bytes multiaddrs;
string regionHint;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

medium

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
  1. 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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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:

  1. Symmetry. Packing bindingNonce into NodeInfo while registrationNonce stays a standalone mapping would split two conceptually identical things (anti-replay counters) across two storage models. Same reasoning that led us to keep the UnbondingRequest timestamps as uint256 for consistency in an earlier review.
  2. Conceptual separation. NodeInfo holds the node descriptor (multiaddrs, regionHint, timestamps). The binding nonces are authorization state shared with the future bindNodeId rebinding path (PR 3), which operates on an address's nonce independent of node descriptor writes.
  3. 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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Just to add a note, we accept a "~20k one time" cost at any scale.

@alpergundogdu
alpergundogdu force-pushed the feat/contracts-node-registry branch from 9dbb7e9 to 1507a10 Compare May 22, 2026 08:58
@github-actions

github-actions Bot commented May 22, 2026 •

Copy link
Copy Markdown

Gas snapshot

Gas changes vs base
Compiling 63 files with Solc 0.8.28
Solc 0.8.28 finished in 2.91s
Compiler run successful!

Ran 44 tests for test/TestnetFaucet.t.sol:TestnetFaucetTest
[PASS] testFuzz_claim_atOrAboveCooldown(uint256) (runs: 1024, μ: 91484, ~: 91528)
[PASS] testFuzz_claim_belowCooldown(uint256) (runs: 1024, μ: 85158, ~: 85389)
[PASS] test_admin_canGrantAndRevokeRoles() (gas: 56401)
[PASS] test_claim_blocksReentrancy() (gas: 1550228)
[PASS] test_claim_happyPath() (gas: 82821)
[PASS] test_claim_perCallerCooldownIndependence() (gas: 133478)
[PASS] test_claim_revertsBeforeCooldown() (gas: 83092)
[PASS] test_claim_revertsOnInsufficientBalance() (gas: 50715)
[PASS] test_claim_revertsOneSecondBeforeCooldownBoundary() (gas: 82996)
[PASS] test_claim_revertsWhenPaused() (gas: 39998)
[PASS] test_claim_succeedsAfterCooldown() (gas: 90430)
[PASS] test_claim_succeedsAtExactCooldownBoundary() (gas: 87103)
[PASS] test_constructor_allowsZeroCooldown() (gas: 1810378)
[PASS] test_constructor_revertsOnCooldownExceedingMax() (gas: 1015061)
[PASS] test_constructor_revertsOnMainnetChainId() (gas: 988198)
[PASS] test_constructor_revertsOnZeroAdmin() (gas: 985898)
[PASS] test_constructor_revertsOnZeroClaimAmount() (gas: 988045)
[PASS] test_constructor_revertsOnZeroFunding() (gas: 988061)
[PASS] test_constructor_revertsOnZeroGovernance() (gas: 985864)
[PASS] test_constructor_revertsOnZeroPauser() (gas: 985954)
[PASS] test_constructor_revertsOnZeroTokenAddress() (gas: 70468)
[PASS] test_constructor_revertsOnZeroTreasury() (gas: 987830)
[PASS] test_constructor_revertsWhenTreasuryNotApproved() (gas: 1110690)
[PASS] test_constructor_setsStateAndRoles() (gas: 43070)
[PASS] test_nonAdmin_cannotGrantRoles() (gas: 17889)
[PASS] test_pause_blocksClaimUnpauseRestores() (gas: 91691)
[PASS] test_pause_revertsOnNonPauser() (gas: 14607)
[PASS] test_setClaimAmount_revertsOnNonGovernance() (gas: 14702)
[PASS] test_setClaimAmount_revertsOnZero() (gas: 13338)
[PASS] test_setClaimAmount_updatesAndEmits() (gas: 22083)
[PASS] test_setCooldown_acceptsMaxCooldown() (gas: 20228)
[PASS] test_setCooldown_allowsZero() (gas: 94920)
[PASS] test_setCooldown_revertsOnExceedingMax() (gas: 13790)
[PASS] test_setCooldown_revertsOnNonGovernance() (gas: 14705)
[PASS] test_setCooldown_updatesAndEmits() (gas: 22231)
[PASS] test_timeUntilNext_tracksCooldownWindow() (gas: 82615)
[PASS] test_timeUntilNext_zeroBeforeFirstClaim() (gas: 10099)
[PASS] test_unpause_revertsOnNonPauser() (gas: 43483)
[PASS] test_withdraw_revertsOnInsufficientBalance() (gas: 26877)
[PASS] test_withdraw_revertsOnNonGovernance() (gas: 17089)
[PASS] test_withdraw_revertsOnZeroAmount() (gas: 20838)
[PASS] test_withdraw_revertsOnZeroTo() (gas: 18662)
[PASS] test_withdraw_transfersAndEmits() (gas: 44129)
[PASS] test_withdraw_worksWhilePaused() (gas: 68286)
Suite result: ok. 44 passed; 0 failed; 0 skipped; finished in 276.36ms (274.59ms CPU time)

Ran 10 tests for test/Token.t.sol:TokenTest
[PASS] testFuzz_burn_reducesSupplyByExactAmount(uint256) (runs: 1024, μ: 27781, ~: 27700)
[PASS] test_burnFrom_consumesAllowance() (gas: 38534)
[PASS] test_burn_reducesTotalSupplyAndBalance() (gas: 26044)
[PASS] test_constructor_metadata() (gas: 17896)
[PASS] test_constructor_mintsFullSupplyToHolder() (gas: 12954)
[PASS] test_constructor_revertsOnZeroInitialHolder() (gas: 83264)
[PASS] test_constructor_totalSupplyConstantMatches() (gas: 9364)
[PASS] test_noMintFunctionExposed() (gas: 10765)
[PASS] test_noVotesSurfaceExposed() (gas: 11991)
[PASS] test_permit_setsAllowance() (gas: 67380)
Suite result: ok. 10 passed; 0 failed; 0 skipped; finished in 151.92ms (151.39ms CPU time)

Ran 60 tests for test/StakingRegistry.t.sol:StakingRegistryTest
[PASS] testFuzz_slash_threeLegsSumToSlashAmount(uint256) (runs: 1024, μ: 267877, ~: 267920)
[PASS] test_constructor_revertsOnOutOfBoundsMaxMultiaddrSize() (gas: 135651)
[PASS] test_constructor_revertsOnOutOfBoundsMinStake() (gas: 135082)
[PASS] test_constructor_revertsOnOutOfBoundsMultiaddrCooldown() (gas: 73167)
[PASS] test_constructor_revertsOnOutOfBoundsUnbondingPeriod() (gas: 135314)
[PASS] test_constructor_revertsOnZeroAdmin() (gas: 70797)
[PASS] test_constructor_revertsOnZeroToken() (gas: 70713)
[PASS] test_constructor_revertsOnZeroVerifier() (gas: 70770)
[PASS] test_constructor_setsImmutableAndState() (gas: 32980)
[PASS] test_deregisterNode_flipsFlagAndRemovesFromActiveSet() (gas: 358561)
[PASS] test_deregisterNode_revertsWhenNotActive() (gas: 20335)
[PASS] test_ejectNode_flipsBothFlagsWhenRegistered() (gas: 378376)
[PASS] test_ejectNode_revertsWithoutBlacklistRole() (gas: 13021)
[PASS] test_ejectNode_unregisteredOperator_onlySetsFlag() (gas: 117207)
[PASS] test_getActiveNodes_paginationBounds() (gas: 985168)
[PASS] test_isActive_falseWhenAnyStakeInUnbonding() (gas: 425144)
[PASS] test_isActive_requiresStakeAndRegistration() (gas: 426286)
[PASS] test_reRegisterSameNodeId_afterDeregister_works() (gas: 425528)
[PASS] test_recordSettlement_revertsWithoutReporterRole() (gas: 13113)
[PASS] test_recordSettlement_updatesTimestamp() (gas: 39691)
[PASS] test_registerNode_happyPath() (gas: 426051)
[PASS] test_registerNode_revertsBelowMinStake() (gas: 114051)
[PASS] test_registerNode_revertsOnAlreadyRegistered() (gas: 380238)
[PASS] test_registerNode_revertsOnBadBindingSignature() (gas: 124858)
[PASS] test_registerNode_revertsOnNodeIdBoundToOther() (gas: 428422)
[PASS] test_registerNode_revertsOnRejectedEd25519Signature() (gas: 135964)
[PASS] test_registerNode_revertsOnZeroNodeId() (gas: 110265)
[PASS] test_registerNode_revertsWhenEjected() (gas: 138598)
[PASS] test_registerNode_revertsWhenMultiaddrsTooLarge() (gas: 112644)
[PASS] test_registerNode_revertsWhenRegionHintTooLong() (gas: 112471)
[PASS] test_requestUnstake_movesAmountToUnbonding() (gas: 137388)
[PASS] test_requestUnstake_revertsOnInflightRequest() (gas: 140031)
[PASS] test_requestUnstake_revertsOnInsufficientStake() (gas: 89163)
[PASS] test_setMaxMultiaddrSize_withinBounds() (gas: 20363)
[PASS] test_setMinStake_revertsOutOfBounds() (gas: 17669)
[PASS] test_setMinStake_withinBoundsSucceeds() (gas: 20300)
[PASS] test_setUnbondingPeriod_revertsOutOfBounds() (gas: 17636)
[PASS] test_slashAutoEject_bumpsRegistrationNonce() (gas: 541093)
[PASS] test_slash_appliesToActivePlusUnbonding() (gas: 307811)
[PASS] test_slash_autoEjectAlsoFlipsNodeActive() (gas: 585356)
[PASS] test_slash_distributes50_30_20() (gas: 266908)
[PASS] test_slash_drawsFromUnbondingWhenActiveInsufficient() (gas: 312619)
[PASS] test_slash_notifiesSafetyReserve() (gas: 262234)
[PASS] test_slash_revertsOnZeroChallenger() (gas: 93086)
[PASS] test_slash_revertsWhenSafetyReserveNotWired() (gas: 102931)
[PASS] test_slash_revertsWithoutSlashRole() (gas: 92662)
[PASS] test_slash_tier1_is5Percent() (gas: 259268)
[PASS] test_slash_tier2_is15Percent() (gas: 323795)
[PASS] test_slash_tier3Stays50PercentBeyondThird() (gas: 522430)
[PASS] test_slash_tier3_is50Percent() (gas: 389479)
[PASS] test_stake_addsToActiveStake() (gas: 87111)
[PASS] test_stake_clearsEjectedFlagWhenRestakedToMinimum() (gas: 137631)
[PASS] test_stake_revertsOnZeroAmount() (gas: 18288)
[PASS] test_stake_revertsWhenPaused() (gas: 45244)
[PASS] test_unstake_returnsTokensAfterUnbonding() (gas: 135725)
[PASS] test_unstake_revertsBeforeUnbondingComplete() (gas: 128481)
[PASS] test_unstake_revertsWithNoRequest() (gas: 22517)
[PASS] test_updateMultiaddrs_replacesAndStampsTimestamp() (gas: 404234)
[PASS] test_updateMultiaddrs_respectsCooldown() (gas: 426564)
[PASS] test_updateMultiaddrs_revertsWhenNotActive() (gas: 15622)
Suite result: ok. 60 passed; 0 failed; 0 skipped; finished in 449.39ms (462.30ms CPU time)

Ran 3 test suites in 480.71ms (877.67ms CPU time): 114 tests passed, 0 failed, 0 skipped (114 total tests)
━ StakingRegistryTest::testFuzz_slash_threeLegsSumToSlashAmount(uint256) (gas: 267920 → 267920 | 0 0.000%)
━ StakingRegistryTest::test_constructor_revertsOnOutOfBoundsMaxMultiaddrSize() (gas: 135651 → 135651 | 0 0.000%)
━ StakingRegistryTest::test_constructor_revertsOnOutOfBoundsMinStake() (gas: 135082 → 135082 | 0 0.000%)
━ StakingRegistryTest::test_constructor_revertsOnOutOfBoundsMultiaddrCooldown() (gas: 73167 → 73167 | 0 0.000%)
━ StakingRegistryTest::test_constructor_revertsOnOutOfBoundsUnbondingPeriod() (gas: 135314 → 135314 | 0 0.000%)
━ StakingRegistryTest::test_constructor_revertsOnZeroAdmin() (gas: 70797 → 70797 | 0 0.000%)
━ StakingRegistryTest::test_constructor_revertsOnZeroToken() (gas: 70713 → 70713 | 0 0.000%)
━ StakingRegistryTest::test_constructor_revertsOnZeroVerifier() (gas: 70770 → 70770 | 0 0.000%)
━ StakingRegistryTest::test_constructor_setsImmutableAndState() (gas: 32980 → 32980 | 0 0.000%)
━ StakingRegistryTest::test_deregisterNode_flipsFlagAndRemovesFromActiveSet() (gas: 358561 → 358561 | 0 0.000%)
━ StakingRegistryTest::test_deregisterNode_revertsWhenNotActive() (gas: 20335 → 20335 | 0 0.000%)
━ StakingRegistryTest::test_ejectNode_flipsBothFlagsWhenRegistered() (gas: 378376 → 378376 | 0 0.000%)
━ StakingRegistryTest::test_ejectNode_revertsWithoutBlacklistRole() (gas: 13021 → 13021 | 0 0.000%)
━ StakingRegistryTest::test_ejectNode_unregisteredOperator_onlySetsFlag() (gas: 117207 → 117207 | 0 0.000%)
━ StakingRegistryTest::test_getActiveNodes_paginationBounds() (gas: 985168 → 985168 | 0 0.000%)
━ StakingRegistryTest::test_isActive_falseWhenAnyStakeInUnbonding() (gas: 425144 → 425144 | 0 0.000%)
━ StakingRegistryTest::test_isActive_requiresStakeAndRegistration() (gas: 426286 → 426286 | 0 0.000%)
━ StakingRegistryTest::test_reRegisterSameNodeId_afterDeregister_works() (gas: 425528 → 425528 | 0 0.000%)
━ StakingRegistryTest::test_recordSettlement_revertsWithoutReporterRole() (gas: 13113 → 13113 | 0 0.000%)
━ StakingRegistryTest::test_recordSettlement_updatesTimestamp() (gas: 39691 → 39691 | 0 0.000%)
━ StakingRegistryTest::test_registerNode_happyPath() (gas: 426051 → 426051 | 0 0.000%)
━ StakingRegistryTest::test_registerNode_revertsBelowMinStake() (gas: 114051 → 114051 | 0 0.000%)
━ StakingRegistryTest::test_registerNode_revertsOnAlreadyRegistered() (gas: 380238 → 380238 | 0 0.000%)
━ StakingRegistryTest::test_registerNode_revertsOnBadBindingSignature() (gas: 124858 → 124858 | 0 0.000%)
━ StakingRegistryTest::test_registerNode_revertsOnNodeIdBoundToOther() (gas: 428422 → 428422 | 0 0.000%)
━ StakingRegistryTest::test_registerNode_revertsOnRejectedEd25519Signature() (gas: 135964 → 135964 | 0 0.000%)
━ StakingRegistryTest::test_registerNode_revertsOnZeroNodeId() (gas: 110265 → 110265 | 0 0.000%)
━ StakingRegistryTest::test_registerNode_revertsWhenEjected() (gas: 138598 → 138598 | 0 0.000%)
━ StakingRegistryTest::test_registerNode_revertsWhenMultiaddrsTooLarge() (gas: 112644 → 112644 | 0 0.000%)
━ StakingRegistryTest::test_registerNode_revertsWhenRegionHintTooLong() (gas: 112471 → 112471 | 0 0.000%)
━ StakingRegistryTest::test_requestUnstake_movesAmountToUnbonding() (gas: 137388 → 137388 | 0 0.000%)
━ StakingRegistryTest::test_requestUnstake_revertsOnInflightRequest() (gas: 140031 → 140031 | 0 0.000%)
━ StakingRegistryTest::test_requestUnstake_revertsOnInsufficientStake() (gas: 89163 → 89163 | 0 0.000%)
━ StakingRegistryTest::test_setMaxMultiaddrSize_withinBounds() (gas: 20363 → 20363 | 0 0.000%)
━ StakingRegistryTest::test_setMinStake_revertsOutOfBounds() (gas: 17669 → 17669 | 0 0.000%)
━ StakingRegistryTest::test_setMinStake_withinBoundsSucceeds() (gas: 20300 → 20300 | 0 0.000%)
━ StakingRegistryTest::test_setUnbondingPeriod_revertsOutOfBounds() (gas: 17636 → 17636 | 0 0.000%)
━ StakingRegistryTest::test_slashAutoEject_bumpsRegistrationNonce() (gas: 541093 → 541093 | 0 0.000%)
━ StakingRegistryTest::test_slash_appliesToActivePlusUnbonding() (gas: 307811 → 307811 | 0 0.000%)
━ StakingRegistryTest::test_slash_autoEjectAlsoFlipsNodeActive() (gas: 585356 → 585356 | 0 0.000%)
━ StakingRegistryTest::test_slash_distributes50_30_20() (gas: 266908 → 266908 | 0 0.000%)
━ StakingRegistryTest::test_slash_drawsFromUnbondingWhenActiveInsufficient() (gas: 312619 → 312619 | 0 0.000%)
━ StakingRegistryTest::test_slash_notifiesSafetyReserve() (gas: 262234 → 262234 | 0 0.000%)
━ StakingRegistryTest::test_slash_revertsOnZeroChallenger() (gas: 93086 → 93086 | 0 0.000%)
━ StakingRegistryTest::test_slash_revertsWhenSafetyReserveNotWired() (gas: 102931 → 102931 | 0 0.000%)
━ StakingRegistryTest::test_slash_revertsWithoutSlashRole() (gas: 92662 → 92662 | 0 0.000%)
━ StakingRegistryTest::test_slash_tier1_is5Percent() (gas: 259268 → 259268 | 0 0.000%)
━ StakingRegistryTest::test_slash_tier2_is15Percent() (gas: 323795 → 323795 | 0 0.000%)
━ StakingRegistryTest::test_slash_tier3Stays50PercentBeyondThird() (gas: 522430 → 522430 | 0 0.000%)
━ StakingRegistryTest::test_slash_tier3_is50Percent() (gas: 389479 → 389479 | 0 0.000%)
━ StakingRegistryTest::test_stake_addsToActiveStake() (gas: 87111 → 87111 | 0 0.000%)
━ StakingRegistryTest::test_stake_clearsEjectedFlagWhenRestakedToMinimum() (gas: 137631 → 137631 | 0 0.000%)
━ StakingRegistryTest::test_stake_revertsOnZeroAmount() (gas: 18288 → 18288 | 0 0.000%)
━ StakingRegistryTest::test_stake_revertsWhenPaused() (gas: 45244 → 45244 | 0 0.000%)
━ StakingRegistryTest::test_unstake_returnsTokensAfterUnbonding() (gas: 135725 → 135725 | 0 0.000%)
━ StakingRegistryTest::test_unstake_revertsBeforeUnbondingComplete() (gas: 128481 → 128481 | 0 0.000%)
━ StakingRegistryTest::test_unstake_revertsWithNoRequest() (gas: 22517 → 22517 | 0 0.000%)
━ StakingRegistryTest::test_updateMultiaddrs_replacesAndStampsTimestamp() (gas: 404234 → 404234 | 0 0.000%)
━ StakingRegistryTest::test_updateMultiaddrs_respectsCooldown() (gas: 426564 → 426564 | 0 0.000%)
━ StakingRegistryTest::test_updateMultiaddrs_revertsWhenNotActive() (gas: 15622 → 15622 | 0 0.000%)
━ TestnetFaucetTest::testFuzz_claim_atOrAboveCooldown(uint256) (gas: 91528 → 91528 | 0 0.000%)
━ TestnetFaucetTest::testFuzz_claim_belowCooldown(uint256) (gas: 85389 → 85389 | 0 0.000%)
━ TestnetFaucetTest::test_admin_canGrantAndRevokeRoles() (gas: 56401 → 56401 | 0 0.000%)
━ TestnetFaucetTest::test_claim_blocksReentrancy() (gas: 1550228 → 1550228 | 0 0.000%)
━ TestnetFaucetTest::test_claim_happyPath() (gas: 82821 → 82821 | 0 0.000%)
━ TestnetFaucetTest::test_claim_perCallerCooldownIndependence() (gas: 133478 → 133478 | 0 0.000%)
━ TestnetFaucetTest::test_claim_revertsBeforeCooldown() (gas: 83092 → 83092 | 0 0.000%)
━ TestnetFaucetTest::test_claim_revertsOnInsufficientBalance() (gas: 50715 → 50715 | 0 0.000%)
━ TestnetFaucetTest::test_claim_revertsOneSecondBeforeCooldownBoundary() (gas: 82996 → 82996 | 0 0.000%)
━ TestnetFaucetTest::test_claim_revertsWhenPaused() (gas: 39998 → 39998 | 0 0.000%)
━ TestnetFaucetTest::test_claim_succeedsAfterCooldown() (gas: 90430 → 90430 | 0 0.000%)
━ TestnetFaucetTest::test_claim_succeedsAtExactCooldownBoundary() (gas: 87103 → 87103 | 0 0.000%)
━ TestnetFaucetTest::test_constructor_allowsZeroCooldown() (gas: 1810378 → 1810378 | 0 0.000%)
━ TestnetFaucetTest::test_constructor_revertsOnCooldownExceedingMax() (gas: 1015061 → 1015061 | 0 0.000%)
━ TestnetFaucetTest::test_constructor_revertsOnMainnetChainId() (gas: 988198 → 988198 | 0 0.000%)
━ TestnetFaucetTest::test_constructor_revertsOnZeroAdmin() (gas: 985898 → 985898 | 0 0.000%)
━ TestnetFaucetTest::test_constructor_revertsOnZeroClaimAmount() (gas: 988045 → 988045 | 0 0.000%)
━ TestnetFaucetTest::test_constructor_revertsOnZeroFunding() (gas: 988061 → 988061 | 0 0.000%)
━ TestnetFaucetTest::test_constructor_revertsOnZeroGovernance() (gas: 985864 → 985864 | 0 0.000%)
━ TestnetFaucetTest::test_constructor_revertsOnZeroPauser() (gas: 985954 → 985954 | 0 0.000%)
━ TestnetFaucetTest::test_constructor_revertsOnZeroTokenAddress() (gas: 70468 → 70468 | 0 0.000%)
━ TestnetFaucetTest::test_constructor_revertsOnZeroTreasury() (gas: 987830 → 987830 | 0 0.000%)
━ TestnetFaucetTest::test_constructor_revertsWhenTreasuryNotApproved() (gas: 1110690 → 1110690 | 0 0.000%)
━ TestnetFaucetTest::test_constructor_setsStateAndRoles() (gas: 43070 → 43070 | 0 0.000%)
━ TestnetFaucetTest::test_nonAdmin_cannotGrantRoles() (gas: 17889 → 17889 | 0 0.000%)
━ TestnetFaucetTest::test_pause_blocksClaimUnpauseRestores() (gas: 91691 → 91691 | 0 0.000%)
━ TestnetFaucetTest::test_pause_revertsOnNonPauser() (gas: 14607 → 14607 | 0 0.000%)
━ TestnetFaucetTest::test_setClaimAmount_revertsOnNonGovernance() (gas: 14702 → 14702 | 0 0.000%)
━ TestnetFaucetTest::test_setClaimAmount_revertsOnZero() (gas: 13338 → 13338 | 0 0.000%)
━ TestnetFaucetTest::test_setClaimAmount_updatesAndEmits() (gas: 22083 → 22083 | 0 0.000%)
━ TestnetFaucetTest::test_setCooldown_acceptsMaxCooldown() (gas: 20228 → 20228 | 0 0.000%)
━ TestnetFaucetTest::test_setCooldown_allowsZero() (gas: 94920 → 94920 | 0 0.000%)
━ TestnetFaucetTest::test_setCooldown_revertsOnExceedingMax() (gas: 13790 → 13790 | 0 0.000%)
━ TestnetFaucetTest::test_setCooldown_revertsOnNonGovernance() (gas: 14705 → 14705 | 0 0.000%)
━ TestnetFaucetTest::test_setCooldown_updatesAndEmits() (gas: 22231 → 22231 | 0 0.000%)
━ TestnetFaucetTest::test_timeUntilNext_tracksCooldownWindow() (gas: 82615 → 82615 | 0 0.000%)
━ TestnetFaucetTest::test_timeUntilNext_zeroBeforeFirstClaim() (gas: 10099 → 10099 | 0 0.000%)
━ TestnetFaucetTest::test_unpause_revertsOnNonPauser() (gas: 43483 → 43483 | 0 0.000%)
━ TestnetFaucetTest::test_withdraw_revertsOnInsufficientBalance() (gas: 26877 → 26877 | 0 0.000%)
━ TestnetFaucetTest::test_withdraw_revertsOnNonGovernance() (gas: 17089 → 17089 | 0 0.000%)
━ TestnetFaucetTest::test_withdraw_revertsOnZeroAmount() (gas: 20838 → 20838 | 0 0.000%)
━ TestnetFaucetTest::test_withdraw_revertsOnZeroTo() (gas: 18662 → 18662 | 0 0.000%)
━ TestnetFaucetTest::test_withdraw_transfersAndEmits() (gas: 44129 → 44129 | 0 0.000%)
━ TestnetFaucetTest::test_withdraw_worksWhilePaused() (gas: 68286 → 68286 | 0 0.000%)
━ TokenTest::testFuzz_burn_reducesSupplyByExactAmount(uint256) (gas: 27700 → 27700 | 0 0.000%)
━ TokenTest::test_burnFrom_consumesAllowance() (gas: 38534 → 38534 | 0 0.000%)
━ TokenTest::test_burn_reducesTotalSupplyAndBalance() (gas: 26044 → 26044 | 0 0.000%)
━ TokenTest::test_constructor_metadata() (gas: 17896 → 17896 | 0 0.000%)
━ TokenTest::test_constructor_mintsFullSupplyToHolder() (gas: 12954 → 12954 | 0 0.000%)
━ TokenTest::test_constructor_revertsOnZeroInitialHolder() (gas: 83264 → 83264 | 0 0.000%)
━ TokenTest::test_constructor_totalSupplyConstantMatches() (gas: 9364 → 9364 | 0 0.000%)
━ TokenTest::test_noMintFunctionExposed() (gas: 10765 → 10765 | 0 0.000%)
━ TokenTest::test_noVotesSurfaceExposed() (gas: 11991 → 11991 | 0 0.000%)
━ TokenTest::test_permit_setsAllowance() (gas: 67380 → 67380 | 0 0.000%)

--------------------------------------------------------------------------------
Total tests: 114, ↑ 0, ↓ 0, ━ 114
Overall gas change: 0 (0.000%)

Run: 26279611044

@alpergundogdu
alpergundogdu requested a review from Copilot May 22, 2026 08:58
@github-actions

github-actions Bot commented May 22, 2026 •

Copy link
Copy Markdown

Contracts coverage

Line coverage: 88.86% (303/341 lines)
▲ +1.36pp vs base (87.50% → 88.86%)
Run: 26279611044

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]>
@alpergundogdu
alpergundogdu force-pushed the feat/contracts-node-registry branch from 1507a10 to cac318c Compare May 22, 2026 09:04

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Pull request overview

This PR 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) to StakingRegistry, plus governable parameters for multiaddr limits.
  • Introduce IEd25519Verifier and a MockEd25519Verifier for tests.
  • Expand StakingRegistry.t.sol with 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.

Comment thread contracts/src/StakingRegistry.sol Outdated
Comment on lines +718 to +720
/// at or above `minStake` + not ejected.
function isActive(address operator) public view returns (bool) {
return _nodes[operator].active && activeStake[operator] >= minStake && !ejected[operator];
Comment thread contracts/src/StakingRegistry.sol Outdated
Comment on lines +437 to +446
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();
}
Comment on lines +492 to +510
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;
Comment on lines +478 to +490
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;
}
alpergundogdu and others added 2 commits May 22, 2026 10:19
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]>
@alpergundogdu
alpergundogdu merged commit 71ed8b2 into main May 22, 2026
19 checks passed
@alpergundogdu
alpergundogdu deleted the feat/contracts-node-registry branch May 22, 2026 09:29
thiras added a commit that referenced this pull request May 22, 2026
…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]>
thiras added a commit that referenced this pull request May 22, 2026
…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]>
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.

2 participants