Repository navigation
Conversation
Admit, release and probe table entries through IRoutingTableNodeLimiter, charged under the tree lock with a Rejected verdict that refreshes and evicts nothing. Full-bucket inserts land uncharged in the replacement cache; promotion re-checks admission and drops rejected candidates. Remove KBucket.RemoveAndReplace (migrate to Remove + TryPromote(null)).
Count 10 per table and 2 per bucket per public /24 (IPv6 /64, exact keys for private addresses), keyed through IpSubnetKey math. Identity exemptions never charge; foreign-fork nodes are never admitted. Null limiter when recent-ip filtering is off, so discv5 is unchanged.
Upstream moved discovery types to Nethermind.Network.Core and cut Discovery's reference to Nethermind.Network, breaking the limiter's IStaticNodesManager/ITrustedNodesManager dependency. Add IDiscoveryNodeExemptions to Core, implemented by the full client as ManagedNodeExemptions and registered in Init's DiscoveryModule. The limiter, modules and NodeSource now depend only on the optional seam; slim hosts without the registration run without managed exemptions (flag-based exemptions still apply).
20c1245 to
41e1c11
Compare
marcindsobczak
left a comment
There was a problem hiding this comment.
Checked at 41e1c1186c: Debug build of Nethermind.Network.Discovery.Test.
- Whole assembly: 729/730 passed, 1 skipped.
- Four mutants, each run on the whole assembly:
- routing-table gate removed: 9 tests fail, but the module-wiring test still passes (first inline comment);
- no
ReleaseonFull: 1 fails; - promotion without re-admission: 3 fail;
- no old-key decrement on an address change: 1 fails.
- Temporary probe tests (not committed):
- through the real discv4 module wiring: a foreign-fork ENR learned after bonding, also over a full ENRRequest/ENRResponse round trip, and same-address peers in a default-size table;
- on
KBucketTree: a split-triggering insert.
- Traced every discv4 caller of
TryAddOrRefreshandRemove, andNodeHealthTracker, the only consumer ofBucketAddResult. ARejectedresult never leads toRemove, and I found no charge leak onFull, split, promotion or removal. FilterDiscoveryNodesByRecentIphad no consumer at the base, as the description says. xdc and xdc-testnet keep it off.
Verdict: changes needed — the fork rejection does not hold for nodes whose ENR arrives after bonding, and the end-to-end test passes without the routing-table gate.
🤖 AI agent (Claude Code / Opus 5.5) acting on behalf of @marcindsobczak.
| using (Assert.EnterMultipleScope()) | ||
| { | ||
| Assert.That(tableTargets, Has.Length.EqualTo(TargetCount)); | ||
| Assert.That(tableTargets.Any(node => node.Id == rejected), Is.False); |
There was a problem hiding this comment.
[possible issue] Medium — this end-to-end test passes with the routing-table gate removed. I deleted KBucketTree.cs:87-93, so TryAdmit is never called and nothing is Rejected. Nine other tests fail, but this one passes. Three of its checks cannot fail:
- L74 searches
tableTargets, which only holds targets (L67), andrejectedis not a target. WithtableNodes.Any(...)here, the test passes at this head and fails with the gate removed (Expected: False, But was: True). - L75-77:
BucketSize = 2(L172) already caps every bucket at two entries. - L83 reads 18 candidates, but
rejectedis bonded last (L63) and published 19th, so L90 never sees it.
L73 also holds without a limiter. Suggest checking tableNodes at L74 and using a bucket size above TargetBucketLimit. For the stream, bond one more node from a fresh subnet after rejected and read 19 candidates.
🤖 AI agent (Claude Code / Opus 5.5) acting on behalf of @marcindsobczak.
There was a problem hiding this comment.
test now asserts against the whole table, bucket size 16 with a split-forcing layout,
| // Foreign-fork nodes are never admitted and never charged: the fork check runs before any | ||
| // count, so one node from another chain cannot hide a subnet. Rejection mutates nothing, so a | ||
| // refused address change keeps the old endpoint and charge. | ||
| if (IsForeignFork(node)) return false; |
There was a problem hiding this comment.
[possible issue] Medium — on the live path a foreign-fork node is admitted and charged before its ENR is known, so this check only refuses its later refreshes. Every bond admits the node from the pong, a Node built from the message with no ENR (KademliaAdapter.cs:626-633, :679-689), and the ENR is fetched only afterwards (:494-504 for inbound pings, :255-261 for outgoing ones). The ENR refresh is then Rejected, and rejection keeps the incumbent. MergeOnRefresh runs before the limiter (KBucketTree.cs:73-84), so the stored entry also takes the foreign ENR, and every later refresh is rejected too.
Tested through the real module wiring: a ping advertising an ENR sequence, answered by a pong and an ENRResponse with a foreign fork id. Afterwards the node is in the table, its stored ENR is the foreign one, and GetKNeighbour (what FINDNODE replies use) still returns it. FINDNODE replies had no fork filter at the base either (Kademlia.cs:217-227). Should a fork mismatch on a refresh remove the entry, or should behaviour change 2 be narrowed?
🤖 AI agent (Claude Code / Opus 5.5) acting on behalf of @marcindsobczak.
There was a problem hiding this comment.
narrowing the PR and removing the fork gate from PR.
| // A refresh of the identity in place neither consumes nor re-checks a slot. | ||
| if (_held.TryGetValue(node.Id, out NodeFilter.IpSubnetKey existingKey) && existingKey.Equals(key)) return true; | ||
|
|
||
| if (CountInBucket(bucketNodes, key, node.Id) >= BucketLimit) return false; |
There was a problem hiding this comment.
[possible issue] Low — while the table holds at most k entries, it is a single bucket. Only a full bucket splits (KBucketTree.cs:134-139), and k defaults to 16. So this check caps a key at 2 for the whole table, not 10, and with only same-address peers the table never reaches k, so it never splits.
Peers bonded through the real module wiring with the default discovery config:
- from
127.0.0.1(different ports): 2 of 6 admitted, and 2 of 12; - from
10.0.0.1-6: 6 of 6.
Behaviour change 3 says a same-host devnet loses entries above ten nodes; it starts at the third. A devnet bootnode, whose table answers everyone's FINDNODE, is capped the same way, and the bootnode tool builds its NetworkConfig without this flag (tools/Bootnode/Nethermind.Bootnode/DiscoveryContainer.cs:53-63), so it cannot turn the cap off. Suggest the LAN bypass the description mentions for geth (no cap for loopback and private keys), or at least a corrected behaviour-change note.
🤖 AI agent (Claude Code / Opus 5.5) acting on behalf of @marcindsobczak.
There was a problem hiding this comment.
Fixed in 38fc60d (LAN bypass) and e603dae (bootnode switch, docs).
LAN addresses now bypass the limiter entirely — geth table.go:addIP AddrIsLAN parity, via the existing IsLoopbackOrPrivateOrLinkLocal helper: IPv4 loopback 127/8, RFC1918 (10/8, 172.16/12, 192.168/16), link-local 169.254/16, CGNAT 100.64/10; IPv6 ::1, ULA fc00::/7, link-local fe80::/10. Both of your probes now admit in full — 15 loopback nodes on distinct ports and 10 private 10/8 nodes all enter the table (LAN keys are null, so they never charge a slot, and two public nodes still fit alongside them in a bucket), while TEST-NET-1 stays capped in the same test: Lan_addresses_bypass_table_and_bucket_limits_while_testnets_stay_capped.
For the bootnode: tools/Bootnode gains --filter-discovery-nodes-by-recent-ip (default on, e603dae), wired into the NetworkConfig it builds, so a public-IP testnet bootnode can turn the cap off without a code change; the full client keeps Network.FilterDiscoveryNodesByRecentIp.
| } | ||
|
|
||
| IRoutingTableNodeLimiter<TNode>? limiter = _limiter; | ||
| if (limiter is not null && !limiter.TryAdmit(nodeToStore, bucket.GetAllCached())) |
There was a problem hiding this comment.
[possible issue] Low — TryAdmit gets the leaf from before any split, but a full, splittable leaf is split later in TryAddOrRefreshLocked (:134-139). So a node can be refused even though the child it lands in holds none of its subnet.
Probe: CreateTree(k: 2, beta: 32) with SecondBit/100 and SecondBit | 1/101 (one subnet), then HighBit/102 (same subnet). Without a limiter it is Added (2 buckets); with SubnetLimiter(2, 10) it is Rejected. Same_subnet_node_in_a_different_bucket_is_admitted_up_to_the_table_cap triggers the split with node 200 from another subnet, so it misses this.
The effect lasts only until a node from another subnet splits the bucket. Fix: run the limiter on the leaf the node actually lands in, e.g. from the leaf branch of TryAddOrRefreshLocked once no split is pending.
🤖 AI agent (Claude Code / Opus 5.5) acting on behalf of @marcindsobczak.
There was a problem hiding this comment.
Fixed in 56bb582.
The limiter no longer pre-checks against the pre-split leaf. In TryAddOrRefreshLocked's leaf branch, a full splittable leaf now splits first for a new key, the loop re-descends, and the limiter runs at the leaf the node actually lands in — which may hold none of its subnet. Your exact probe is Added now, asserted in Same_subnet_node_landing_in_empty_child_after_split_is_admitted (it was Rejected at the previous head).
Trade-off, noted in the commit message: a candidate the limiter will refuse can now split a full splittable leaf before being refused, where the old pre-check rejected before any tree mutation. The split is the same one an admitted node triggers, preserves all entries, and is bounded by depth and beta — no growth an attacker could not already force with admitted nodes from rotating subnets.
| { | ||
| /// <inheritdoc/> | ||
| public bool IsExempt(PublicKey nodeId) | ||
| => staticNodesManager.ContainsNode(nodeId) || trustedNodesManager.ContainsNode(nodeId); |
There was a problem hiding this comment.
[possible issue] Low — Network.StaticPeers entries are not covered here. NodesLoader only sets IsStatic on them (NodesLoader.cs:52-56), and they never enter StaticNodesManager. Discovery messages build fresh Nodes without the flag (KademliaAdapter.cs:679-689), and MergeOnRefresh merges only ENR state.
So a configured static peer that entered the table with its flag (e.g. via ProtocolsManager.AddNodeToDiscovery(session.Node)) is exempt only until its first discovery refresh. After that it is charged if its subnet has room, or every refresh is Rejected if not. PrivilegedIpProvider handles this source on its own (PrivilegedIpProvider.cs:45-54).
Suggest parsing the INetworkConfig.StaticPeers ids once here, the same way, with a test that refreshes such a peer from a plain Node.
🤖 AI agent (Claude Code / Opus 5.5) acting on behalf of @marcindsobczak.
There was a problem hiding this comment.
Fixed in e603dae.
ManagedNodeExemptions now parses INetworkConfig.StaticPeers once, in its constructor, the same way NodesLoader.LoadConfigPeers does — NetworkNode.ParseNodes, enode entries only — and matches by node id. A routing-table entry built from discovery (flags unset, MergeOnRefresh touching ENR state only) therefore stays exempt across refreshes by identity, covering the ProtocolsManager.AddNodeToDiscovery path you traced.
The requested test is ManagedNodeExemptions_keep_config_static_peer_exempt_without_flag: with the subnet's table cap already saturated by ordinary nodes, a plain Node (no IsStatic) refresh of the configured enode admits via the exemption, consumes no slot, and an ordinary node from the same subnet is still refused. Wired in DiscoveryModule with INetworkConfig/ILogManager.
| { | ||
| KademliaConfig<Node> config = CreateKademliaConfig(ctx.Resolve<IDiscoveryConfig>()); | ||
| INetworkConfig networkConfig = ctx.Resolve<INetworkConfig>(); | ||
| config.NodeLimiter = networkConfig.FilterDiscoveryNodesByRecentIp |
There was a problem hiding this comment.
[suggestion] Low — this key now switches the subnet cap, but its description still reads "Reject discovery nodes whose IP key was seen recently (time-windowed), using the peer IP filter." (INetworkConfig.cs:156). That text feeds the config docs, so an operator who needs the cap off (for example on a same-host devnet) will not find it there.
Suggest describing the new behaviour: 2 per bucket, 10 per table, the candidate filter, and exact keys for private and loopback addresses. FilterDiscoveryNodesBySameSubnet (:159) still says same-subnet IPs "share a single entry"; it needs the same update.
🤖 AI agent (Claude Code / Opus 5.5) acting on behalf of @marcindsobczak.
There was a problem hiding this comment.
Fixed in 38fc60d and e603dae.
FilterDiscoveryNodesByRecentIp now reads: "Limit discovery table entries per subnet key (2/bucket, 10/table, LAN bypassed)." FilterDiscoveryNodesBySameSubnet now reads: "When limiting discovery nodes, bucket public IPs by subnet (IPv4 /24, IPv6 /64); LAN addresses bypass the limit (2/bucket, 10/table)." The KademliaModule registration comment states the same plus the candidate filter, so an operator who needs the cap off finds the switch in the docs; the bootnode tool exposes it as --filter-discovery-nodes-by-recent-ip.
The fork check cannot fire at admission: a discv4 bond admits the node from the pong, which carries no ENR, and the fork id only arrives after the entry is incumbent -- the check could merely freeze later refreshes. Narrow the limiter to geth parity: fork-agnostic, like geth's table; foreign-fork nodes count against the caps like any other node. Removes the ILogManager plumbing that only served the fork probe.
The test passed with the routing-table gate deleted: the rejected-node assertion searched a pre-filtered list it could never be in, BucketSize of 2 physically capped buckets below the limiter's bucket limit, and the candidate read stopped before the rejected node was ever published. Assert against the whole table, set the bucket size above the limit with a split-forcing peer layout, and read every candidate published by the bonded nodes. Fails red with the gate commented out.
The limiter pre-check in TryAddOrRefresh consulted the leaf returned by GetBucketForHash, which is the leaf before any split: a new key that overflows a full, splittable leaf was counted against a bucket it would never land in, so a node could be rejected even though the post-split child holds none of its subnet. Split full splittable leaves before the add for new keys and admit at the final leaf, so the limiter only ever sees the bucket the node actually enters. Trade-off: a candidate the limiter will reject can now split a full splittable leaf before being refused, where the old pre-check rejected before any tree mutation. The split is the same one an admitted node triggers, preserves all entries, and is bounded by depth and beta, so it adds no growth an attacker could not already force with admitted nodes from rotating subnets. Same_subnet_node_landing_in_empty_child_after_split_is_admitted fails on the previous code (Rejected instead of Added).
The limiter keyed loopback and private addresses exactly, so a same-host devnet admitted only two nodes per address: the bucket cap of 2 bound on the single unsplit bucket before the table cap of 10 could ever apply, and with only same-address peers the table never reached k to split. Match geth table.go:addIP AddrIsLAN parity: loopback, private (incl. CGNAT 100.64.0.0/10), link-local and IPv6 ULA addresses bypass the caps entirely, and a public->LAN move releases the stale charge so only active public entries count. Lan_addresses_bypass_table_and_bucket_limits_while_testnets_stay_capped fails on the previous code (the third loopback node is rejected).
svlachakis
left a comment
There was a problem hiding this comment.
- High -
DiscoveryNodeLimiter.cs:4and the other added imports flagged by code lint produce sixIDE0005warnings and fail the check. Remove the imports listed in the log.
ManagedNodeExemptions matches config StaticPeers by id so discovery refreshes without IsStatic stay exempt; back-compat shim kept. Bootnode gains FilterDiscoveryNodesByRecentIp option wired to NetworkConfig. KademliaModule comment states 2/bucket, 10/table, candidate filter and LAN bypass.
IDE0005 leftovers from the fork-gate removal, covered by ImplicitUsings or parent-namespace scope.
Fixed. Removed the unused imports |
| while (_replacement.TryPopHead(out TKadKey replacementHash, out TNode? replacement)) | ||
| { | ||
| _cachedArray = _items.GetAll(); | ||
| if (canPromote is not null && !canPromote(replacement!)) continue; |
There was a problem hiding this comment.
Rejected candidates are dropped from the cache here. I'd keep them, one removal can drain the whole replacement cache when their subnet sits at the cap
There was a problem hiding this comment.
Fixed in 7b8366b. TryPromote now iterates _replacement.GetAllWithKey() head-first (same ordering as the old TryPopHead loop) and removes only the candidate that passes re-admission; rejected candidates stay cached, so a subnet at cap no longer drains the replacement cache. UpdateCachedArray still runs on promote.
|
|
||
| /// <summary>Back-compat shim; config-file peers simply contribute no ids.</summary> | ||
| [System.Obsolete("Use the (IStaticNodesManager, ITrustedNodesManager, INetworkConfig, ILogManager) overload.")] | ||
| public ManagedNodeExemptions( |
There was a problem hiding this comment.
This overload has no callers and the type is new, I'd drop it
| { | ||
| if (node.IdHash.Equals(_currentNodeHash) || HasIncompatibleForkId(node)) return true; | ||
|
|
||
| if (kademliaConfig.NodeLimiter?.WouldAdmit(node) is false) |
There was a problem hiding this comment.
[P2] A peer rejected by the bucket cap still reaches PeerPool. With two ordinary peers from a public /24 in an unsplit bucket, the third peer's bonding pong reaches KBucketTree and is rejected. KademliaAdapter.HandlePing still publishes the signed-PING candidate after the bond. NodeSource.WouldAdmit checks the table count of two against ten, so the rejected endpoint is yielded to PeerPool. Propagate the routing admission verdict to candidate publication so a bucket-rejected endpoint is dropped.
There was a problem hiding this comment.
Fixed in 33e2574. INodeHealthTracker.OnIncomingMessageFrom now returns the BucketAddResult, and KademliaAdapter.ShouldPublishCandidate (KademliaAdapter.cs:518) drops the candidate when the verdict is Rejected
| Refreshed, | ||
| Full | ||
| Full, | ||
| Rejected |
There was a problem hiding this comment.
[P2] A rejected endpoint change can cancel the liveness check for the endpoint the table retains. While a probe to incumbent A is pending, the same identity can complete a separate discv4 bond at B. NodeHealthTracker.OnIncomingMessageFrom clears the pending refresh by identity before the new Rejected result leaves A in the table, then clears the failure count too. If A times out, RefreshAsync skips removal because B already cleared the marker. Lookups keep returning A and its subnet charge remains occupied. Clear liveness state only when the update is accepted or the message proves liveness at the retained endpoint.
There was a problem hiding this comment.
Fixed in 337f676. NodeHealthTracker.OnIncomingMessageFrom (NodeHealthTracker.cs:128-135) clears _isRefreshing and _peerFailures only when addResult != Rejected — a refused endpoint change at B leaves the pending refresh and failure count for retained A intact, so A's timeout still evicts it and frees the slot and charge
| continue; | ||
| } | ||
|
|
||
| if (_limiter is not null && !_limiter.TryAdmit(node, current.Bucket.GetAllCached())) |
There was a problem hiding this comment.
[P3] A DNS-fed endpoint change can replace the restart address even when subnet admission refuses it. If the DNS feeder supplies a newer verified ENR advertising only B for an incumbent at A, MergeOnRefresh installs that ENR in A's shared state before TryAdmit rejects B. The table retains A, but DiscoveryPersistenceManager writes the ENR for B under the same node ID. Restore then only tries B and loses A as a seed even if A still answers. Preserve the admitted UDP endpoint for restore when the saved ENR only advertises the refused endpoint.
There was a problem hiding this comment.
Fixed in bc270a4. MergeOnRefresh now runs only after admission: both the charged path and the probe path check the limiter first, and a refused endpoint change returns Rejected
| // A refresh of the identity in place neither consumes nor re-checks a slot. | ||
| if (_held.TryGetValue(node.Id, out NodeFilter.IpSubnetKey existingKey) && existingKey.Equals(key)) return true; | ||
|
|
||
| if (CountInBucket(bucketNodes, key, node.Id) >= BucketLimit) return false; |
There was a problem hiding this comment.
[P3] The table can admit an eleventh ordinary entry after a trusted exemption is revoked. Start with nine charged peers from one subnet and a tenth peer exempt only through the trusted manager, in a bucket already holding two charged peers from that subnet. After admin_removeTrustedPeer, a same-endpoint discovery refresh fails the bucket check and leaves that active peer uncharged. An insertion in a different bucket with room then sees nine charges and raises actual ordinary occupancy from ten to eleven. Account for the retained incumbent when processing the same-endpoint refresh so further admissions see the full subnet.
There was a problem hiding this comment.
Fixed in e2843c0. Both refusal paths (bucket full, table full) now call ChargeRetainedIncumbent before returning false (DiscoveryNodeLimiter.cs:92-104), so a refused refresh of a revoked-but-retained incumbent books its subnet and later insertions elsewhere see the full count.
| if (_logger.IsEnabled(LogLevel.Trace)) _logger.LogTrace($"Subnet limiter rejected node {node}"); | ||
| toRefresh = default; | ||
| fireAdded = false; | ||
| return BucketAddResult.Rejected; |
There was a problem hiding this comment.
[P2] Subnet refusals can exhaust the discv4 DNS feeder before it adds any seed. With two ordinary peers from one public /24 already in the unsplit root, the next 50 compatible, reachable DNS records from that subnet can all return Rejected. NodeHealthTracker discards the result and NodeSourceToDiscV4Feeder increments addedNodes after each void call, so it stops before a later eligible record from a different subnet. Propagate the subnet refusal to the feeder so rejected entries do not spend its seed budget.
There was a problem hiding this comment.
Fixed in 4d35ad0. IDiscoveryApp.AddNodeToDiscovery now returns whether the node was admitted, and the feeder skips addedNodes++ on false (NodeSourceToDiscV4Feeder.cs:50-55); CompositeDiscoveryApp broadcasts then ORs over its app snapshot
| { | ||
| KademliaConfig<Node> config = CreateKademliaConfig(ctx.Resolve<IDiscoveryConfig>()); | ||
| INetworkConfig networkConfig = ctx.Resolve<INetworkConfig>(); | ||
| config.NodeLimiter = networkConfig.FilterDiscoveryNodesByRecentIp |
There was a problem hiding this comment.
[P3] The xdc_archive profile activates the new limiter on XDC mainnet while xdc explicitly opts out. The runner loads the selected JSON profile independently. Both profiles use chainspec/xdc.json and the same XdcDiscoveryApp, but xdc_archive leaves FilterDiscoveryNodesByRecentIp at its default of true. With stock settings, an upgraded archive node can therefore refuse the third ordinary peer from a public subnet in a bucket. Carry the XDC mainnet opt-out into xdc_archive.json.
There was a problem hiding this comment.
Fixed in 7173ec9. xdc_archive.json sets "FilterDiscoveryNodesByRecentIp": false; all three XDC profiles (xdc.json, xdc-testnet.json, xdc_archive.json) now opt out identically.
| // The node landed in the replacement cache, not the table: release the | ||
| // charge so only active entries count. Full implies the key was absent | ||
| // from the active set, so this cannot release a live slot. | ||
| limiter?.Release(nodeToStore); |
There was a problem hiding this comment.
[P3] A replacement-cache insertion can make NodeSource drop an eligible candidate even though active subnet occupancy stays at nine. In a full unsplittable leaf, TryAdmit publishes the tenth charge and unlocks the limiter before the bucket returns Full and the tree releases the charge. The candidate consumer takes only the limiter lock, so an already queued, uncharged candidate can be filtered in that interval. Its identity remains reserved in RecentNodeFilter after the drop. Check eligibility without charging an absent key in a full unsplittable leaf, and charge it when promoted.
There was a problem hiding this comment.
Fixed in a9bffc6. A full unsplittable leaf now uses ProbeAdmit (DiscoveryNodeLimiter.cs:151-159) — a pure check under the limiter lock with no mutation and no charge — and parks the candidate uncharged; the charge happens only when promotion admits it. The consumer's WouldAdmit window can no longer observe a phantom tenth charge.
| _trustedNodesManager = trustedNodesManager; | ||
| ILogger logger = logManager.GetClassLogger<ManagedNodeExemptions>(); | ||
| // Mirror NodesLoader: only enode entries from config become static peers. | ||
| _configStaticIds = NetworkNode.ParseNodes(networkConfig.StaticPeers, logger) |
There was a problem hiding this comment.
[P3] A transient DNS failure can omit a configured static identity from discovery exemptions for the lifetime of the process. The singleton builds its ID set through ParseNodes, which drops a hostname enode when Enode's DNS lookup fails. If DNS recovers before NodesLoader enumerates StaticPeers, that later parse loads the peer as static, but discovery messages still create unflagged nodes and the frozen exemption set misses the ID. Those refreshes can be charged or refused. Derive the exemption ID from validated enode syntax independently of DNS resolution.
There was a problem hiding this comment.
Fixed in 502a80e. ParseConfigStaticIds now works in two passes: pass 1 mirrors NetworkNode.ParseNodes with per-entry error handling (a hostname entry that fails DNS is logged and skipped, exactly like NodesLoader); pass 2 parses each enode's ID with syntax-only validation — same checks as the Enode constructor minus the DNS lookup (scheme, port, path, fragment, ?discport, PublicKey), so a DNS outage at startup can no longer freeze a static identity out of the exemption set.
| } | ||
|
|
||
| HashSet<PublicKey> used = [.. fillers, .. targets]; | ||
| PublicKey rejected = byPrefix[5].Skip(fillerTakes[5]).First(key => !used.Contains(key)); |
There was a problem hiding this comment.
[P3] The integration test's eleventh peer exercises the bucket guard, leaving the table admission guard untested by this case. Prefixes 4 and 5 land in leaf 10, which has nine fillers, two prefix-4 targets and at most one self entry. With 11 or 12 entries against capacity 16, the leaf never splits before the prefix-5 insertion. The prefix model reaches bucket rejection with the table guard omitted. Use a peer in prefix 6 or 7 to test the table limit and exercise a bucket-only rejection while the table count is below ten.
There was a problem hiding this comment.
Fixed in 948edaf. The e2e now isolates both guards through the real container limiter: the bucket-rejected node (@192.0.2.240) is asserted while the table sits at 8<10 and limiter.WouldAdmit(...) is true — only the bucket guard could refuse; the table-rejected node (prefix-6 @192.0.2.250) is asserted with limiter.TryAdmit(..., empty bucket) false — only the table guard could refuse; an accepted control from a fresh subnet (@198.51.100.1) follows.
| ILogger logger = logManager.GetClassLogger<ManagedNodeExemptions>(); | ||
| // Mirror NodesLoader: only enode entries from config become static peers. | ||
| _configStaticIds = NetworkNode.ParseNodes(networkConfig.StaticPeers, logger) | ||
| .Where(static n => n.IsEnode) |
There was a problem hiding this comment.
[P3] The new production Where/Select/ToHashSet chain violates the explicit rule in .agents/rules/coding-style.md to use a simple loop when one works. Build the set with a foreach over the parsed nodes and add NodeId for each enode.
There was a problem hiding this comment.
Fixed in 502a80e— the set is built with a plain foreach + Add;
svlachakis
left a comment
There was a problem hiding this comment.
The unused-using failure from my last review is fixed. The limiter now checks the destination bucket and exempts LAN addresses. The DNS feeder still counts subnet rejections against its seed budget. Please carry the admission result back to the feeder and add a case where a refused seed is followed by an admissible one. Existing thread
Both Points addressed in 4d35ad0: the admission result is carried back to the feeder (AddNodeToDiscovery → bool, rejected seeds skip the budget count), and NodeSourceToDiscV4FeederTests.Test_ShouldNotCountRejectedSeedAgainstLimit is exactly the requested case — first seed refused by the subnet cap, then a seed from a different subnet admitted within the same budget. The feeder test for the refused-then-admitted sequence also fails if rejected seeds are counted again. |
svlachakis
left a comment
There was a problem hiding this comment.
The feeder now skips refused seeds on discv4-only nodes. CompositeDiscoveryApp.cs:215 still combines both admission results. A discv5 admission can count against the discv4 feeder budget. Use the discv4 result for that budget and cover the mixed-version case. Previous thread
Supersedes #15915 (lease-based design).
Changes
Limits how many discv4 routing-table entries a single IP subnet may hold: 2 per bucket, 10 per table (geth v1.16.5
table.gobucketIPLimit/tableIPLimit), IPv6 /64.IRoutingTableNodeLimiter<TNode>inNethermind.Kademlia, attached viaKademliaConfig<TNode>.NodeLimiter(null default, so discv5 and non-discv4 consumers keep today's behaviour). OnlyKBucketTreecharges, inside its existing lock — a full splittable leaf splits first for a new key, so the limiter always evaluates the bucket the node actually lands in; onlyNodeSourceprobes, read-only viaWouldAdmit. One counter, two readers, and a rejected table candidate cannot reach the peer-candidate stream. Lock order is routing-table lock → limiter lock; the limiter never calls back into the table.DiscoveryNodeLimiterimplements it. Subnet keys reuseNodeFilter.IpSubnetKey(made internal;InternalsVisibleToalready exists): /24 for public IPv4, /64 for IPv6. LAN addresses (IPv4 loopback, RFC1918 incl. CGNAT, link-local; IPv6 loopback, ULA, link-local) bypass the limiter entirely, gethtable.go:addIPAddrIsLANparity;FilterDiscoveryNodesBySameSubnet=falsekeys every public address exactly.IsStatic/IsTrusted, the static/trusted managers via a newContainsNode(PublicKey)(O(1) override onNodesManager,foreachdefault body for external implementations), and configNetwork.StaticPeersids parsed once inManagedNodeExemptions(enode entries only, mirroringNodesLoader), so a discovery-built entry without the flag stays exempt across refreshes. The managers are consulted live per admission, so a node that gains an exemption stops consuming its slot, and one that loses it recharges on its next refresh when there is room.BucketAddResult.Rejected: a rejected refresh only declines to update the entry. No admission path evicts a live incumbent; a refused endpoint change keeps the previous endpoint and charge, and the limiter mutates no state before every check passes (a refused new key may still have split a full bucket — seeSplit before admissionbelow).Fullinsert releases the fresh charge, and promotion re-runs admission (refused candidates are discarded).Breaking
The admission verdict is now returned instead of discarded, which changes three signatures (all in-repo implementors migrated):
IDiscoveryApp.AddNodeToDiscovery(Node)now returnsbool(true= admitted and counted against feeder budgets,false= refused or skipped).IKademlia<TNode>.AddOrRefresh(TNode)now returnsBucketAddResult.INodeHealthTracker<TNode>.OnIncomingMessageFrom(TNode)now returnsBucketAddResult.KBucket.RemoveAndReplacewas removed. UseRemove(hash)followed byTryPromote(null).BucketAddResult.Rejected, the limiter interface and the config property are additive.Why these choices
2 per bucket / 10 per table, not 1 per /24. Requested in review: with a limit of 1, one node from another chain could hide a whole subnet. The constants are geth's, verbatim, and add no new settings. 1 per /24 would also drop honest co-located nodes (hosting ranges contribute one peer each) and reshape existing tables on upgrade. Cost of 2/10: a bucket scan (≤ k entries) per new insert, and a weaker Sybil bound; a Sybil identity counts under any cap, and only the constant raises its cost. Reverting to 1 per /24 is a two-
constchange.LAN bypass, not exact-keyed private capping. geth's
table.go:addIPnever chargesAddrIsLANaddresses, so its caps bind public ranges only. We mirror that with the existingIsLoopbackOrPrivateOrLinkLocalhelper (loopback, RFC1918, link-local, CGNAT, IPv6 ULA/loopback/link-local). Private ranges are not internet-routable, so a subnet bound there has no Sybil value, while capping them broke same-host devnets and private testnets — the exact-keyed variant capped a 127.0.0.1 devnet at its third node. Cost: a large private deployment fills the table uncounted, as it does in geth today. Public-IP testnets sharing few subnets can switch the cap off:Network.FilterDiscoveryNodesByRecentIpfor the client, a new--filter-discovery-nodes-by-recent-ipflag for the bootnode tool.Split before admission, then gate at the landing leaf. An earlier pre-check ran on the pre-split leaf and refused nodes whose post-split landing bucket held none of their subnet. A full splittable leaf now splits first for a new key and the limiter runs at the leaf the node lands in. Cost: a candidate the limiter will refuse can split a full splittable leaf first — the same split an admitted node triggers, preserves all entries, and is bounded by depth and beta, so no growth beyond what admitted nodes from rotating subnets already force.
Fork-agnostic, like geth's table. An earlier iteration rejected foreign-fork ENRs before charging, but a discv4 bond admits from the pong, which carries no ENR: the fork id only arrives after the entry is incumbent, so the gate could never stop an admission — it only froze later refreshes. geth's table has no fork gate; foreign-fork nodes count against the caps like any other node and stay bounded by the same 2/10.
Active-only charging, not geth's charge-at-entry for replacement-cache entries. This repo's replacement cache refuses new entries when full instead of evicting (
DoubleEndedLru.AddOrRefreshreturnsFullat capacity), so geth's release-on-evict has no event to hook here. Doing it faithfully needs a cached-vs-refused result flag, a release inClear()on split (up to 16 cached entries per split), previous-value threading for address changes, and a second cache scan or an accepted asymmetry. That is roughly 40–60 production and 80–120 test lines, for a bound that only tightens inert standby entries. Cost: a bucket's cache can hold several same-/24 nodes. They are bounded, never answer lookups, cannot promote while the subnet is saturated, and the table cap holds regardless. Promotion re-checking is also stricter than geth, whose promotion installs a random replacement with no IP re-check. If maintainers want geth's exact model, the fallback is to charge cache entries against the table limit only and release inClear()(~25 lines).No persisted-node exemption and no persistence-format change. The exemption would only avoid a one-time reshaping on upgrade, and it brings a third RLP field on
NetworkNode, aFallbackEnrmember, a downgrade path, and a fallback-ENR fix with its restart test: about 250 lines and 3–4 commits, in the area that collected three review findings in #15915. Upstream'sCreatePersistedNodealready always writes the verified ENR, so no code path discards one. Cost: a table exceeding the caps is shaped once, on the first capped run.Read-only probe in
NodeSource, not a gating decorator. #15915 usedAdmissionGatedKademliaAdapterplusPeerCandidateReservations. That needs the adapter, a staticConditionalWeakTablekeyed by config instance (a container overridingKademliaConfig<Node>would silently get a different store, and the release would go to the wrong one), release wiring and tests, about 80 lines. The one leak-free alternative, a publish-time predicate, would move discv4 admission policy into the genericKademliaAdapter. Cost, the one known give-up: a candidate dropped by the probe after being published once keeps itsRecentNodeFilterdedupe entry (about k × max-distance ≈ 4096 ids before it re-publishes). This dedupe retention is pre-existing candidate-pipeline behaviour, and it is rare at cap 10.Rejection never evicts. A
RejectAndEvictverdict would re-introduce a removal path on the refresh code, which is exactly the machinery behind #15915's incumbent-eviction bug (rejected pong → pending-refresh flag never clears →routingTable.Remove), for a case only an operator can trigger. A revoked exemption keeps its slot, recharges when room appears, and leaves only through the existing ping-failure path. Cost: after an operator revokes a static/trusted entry in a full subnet, the table briefly holds one node above cap, and new entries for that key stay blocked meanwhile.Resolver-free keying, not
CreateNodeFilterKey(ip, currentIp)as inRlpxHost. Its same-subnet-as-self refinement needs the current IP to share the remote's /24, and no public address can share a /24 with a local IP (RFC1918, loopback and link-local blocks do not straddle /24s, and LAN remotes are bypassed outright). The resolver could never change an outcome, and consulting it only added resolution-state drift and an untestable branch. Cost: none found. The modes the review asked to preserve (/64, exact-IP) areDefaultKey's own behaviour; LAN addresses are bypassed instead of exact-keyed (LAN paragraph above).Behaviour changes
NetworkConfig.FilterDiscoveryNodesByRecentIphad no consumer before; this PR is its first. Default on. Chains that opted out (xdc, xdc-testnet) keep today's behaviour via their existing configs, andxdc_archive.jsonnow sets it tofalsetoo, so the cap does not bind xdc_archive. The bootnode tool gains--filter-discovery-nodes-by-recent-ip(default on).AddrIsLANparity), so same-host devnets and private-network testnets keep today's behaviour.Tests
DiscoveryNodeLimiterTests(limits at 2 and 10 exactly, /24 and /64 keying, LAN bypass vs capped TEST-NET-1, refresh and address-change semantics, release idempotence, every exemption incl. config static peers without the flag, revoked-exemption recharge);KBucketTreeTests(rejected refresh keeps the incumbent, promotion re-checked, split does not double-count,Fullreleases, same-subnet node landing in an empty post-split child is admitted);KademliaModuleTestswith the real module wiring (N nodes in one /24: exactly two per bucket and ten per table, the refused node absent from the whole table, a fresh-subnet node bonded after it still reaching the candidate stream, FINDNODE still answered);NodeSourceTests(cap-gated candidates); end-to-end static/trusted bypass inDiscoveryAppTests.Discovery 737/737 (+1 pre-existing IPv6 env-skip), Xdc 881/881, Bootnode 118/118; full solution builds with
EnforceCodeStyleInBuild, 0 warnings.