Repository navigation
feat(discovery): limit discv4 routing-table entries per subnet #16416
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: master
Are you sure you want to change the base?
Changes from all commits
02641de
5e85ec1
a0d63ce
1744bb8
f40a3e2
41e1c11
b0178c6
61c3c23
56bb582
38fc60d
e603dae
4547c30
7b8366b
6d5b8cf
33e2574
337f676
bc270a4
e2843c0
4d35ad0
7173ec9
a9bffc6
502a80e
948edaf
7ddaf92
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -7,5 +7,6 @@ public enum BucketAddResult | |
| { | ||
| Added, | ||
| Refreshed, | ||
| Full | ||
| Full, | ||
| Rejected | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,37 @@ | ||
| // SPDX-FileCopyrightText: 2026 Demerzel Solutions Limited | ||
| // SPDX-License-Identifier: LGPL-3.0-only | ||
|
|
||
| namespace Nethermind.Kademlia; | ||
|
|
||
| /// <summary> | ||
| /// Admission policy for nodes entering the routing table. | ||
| /// </summary> | ||
| /// <remarks> | ||
| /// Lock order is routing-table lock, then limiter lock. <see cref="TryAdmit"/> is called under the routing-table | ||
| /// lock, so an implementation must not call back into the table. The bucket scan receives the bucket's cached array, | ||
| /// which allocates only when the bucket size exceeds the replacement cache size. | ||
| /// </remarks> | ||
| public interface IRoutingTableNodeLimiter<TNode> | ||
| { | ||
| /// <summary>Admits <paramref name="node"/> to the bucket whose active entries are <paramref name="bucketNodes"/>.</summary> | ||
| /// <remarks>Called under the routing-table lock. Must not call back into the table. An exempt verdict releases | ||
| /// any charge the node previously held, so a node that gains an exemption stops consuming its subnet slot.</remarks> | ||
| bool TryAdmit(TNode node, ReadOnlySpan<TNode> bucketNodes); | ||
|
|
||
| /// <summary>Releases the slot held by <paramref name="node"/>, if any. Idempotent.</summary> | ||
| void Release(TNode node); | ||
|
|
||
| /// <summary>Table-wide probe: whether <see cref="TryAdmit"/> would find a table slot. Does not reserve.</summary> | ||
| bool WouldAdmit(TNode node); | ||
|
|
||
| /// <summary> | ||
| /// Bucket-scoped probe: whether <see cref="TryAdmit"/> would admit <paramref name="node"/> to the bucket | ||
| /// whose active entries are <paramref name="bucketNodes"/>. Pure check: never charges, releases, or | ||
| /// mutates limiter state. | ||
| /// </summary> | ||
| /// <remarks> | ||
| /// The default implementation falls back to the table-wide <see cref="WouldAdmit"/> probe. | ||
| /// Called under the routing-table lock. Must not call back into the table. | ||
| /// </remarks> | ||
| bool ProbeAdmit(TNode node, ReadOnlySpan<TNode> bucketNodes) => WouldAdmit(node); | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -30,6 +30,7 @@ private class TreeNode(int k, TKadKey prefix) | |
| private readonly TKadKey _currentNodeHash; | ||
| private readonly IKademliaDistance<TKadKey> _distance; | ||
| private readonly Func<TNode, TNode, TNode>? _mergeOnRefresh; | ||
| private readonly IRoutingTableNodeLimiter<TNode>? _limiter; | ||
| private readonly ILogger _logger; | ||
|
|
||
| private readonly Lock _lock = new(); | ||
|
|
@@ -54,6 +55,7 @@ public KBucketTree( | |
| _distance = distance; | ||
| _currentNodeHash = nodeHashProvider.GetHash(config.CurrentNodeId); | ||
| _mergeOnRefresh = config.MergeOnRefresh; | ||
| _limiter = config.NodeLimiter; | ||
| _root = new TreeNode(config.KSize, distance.Zero); | ||
| _logger = loggerFactory.CreateLogger<KBucketTree<TNode, TKadKey>>(); | ||
| if (_logger.IsEnabled(LogLevel.Trace)) _logger.LogTrace($"Initialized KBucketTree with k={_k}, currentNodeId={_currentNodeHash}"); | ||
|
|
@@ -63,25 +65,19 @@ public BucketAddResult TryAddOrRefresh(in TKadKey nodeHash, TNode node, out TNod | |
| { | ||
| BucketAddResult resp; | ||
| bool fireAdded; | ||
| TNode nodeToStore = node; | ||
| TNode nodeToStore; | ||
| IRoutingTableNodeLimiter<TNode>? limiter = _limiter; | ||
| lock (_lock) | ||
| { | ||
| ThrowIfMergeReentered(); | ||
| KBucket<TNode, TKadKey> bucket = GetBucketForHash(nodeHash); | ||
| if (_mergeOnRefresh is not null && bucket.TryGetStored(nodeHash, out TNode? previous)) | ||
| resp = TryAddOrRefreshLocked(nodeHash, node, out nodeToStore, out toRefresh, out fireAdded); | ||
| if (resp == BucketAddResult.Full) | ||
| { | ||
| _isMergingRefresh = true; | ||
| try | ||
| { | ||
| nodeToStore = _mergeOnRefresh(nodeToStore, previous); | ||
| } | ||
| finally | ||
| { | ||
| _isMergingRefresh = false; | ||
| } | ||
| // 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); | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. [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.
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 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. |
||
| } | ||
|
|
||
| resp = TryAddOrRefreshLocked(nodeHash, nodeToStore, out toRefresh, out fireAdded); | ||
| } | ||
|
|
||
| if (fireAdded) OnNodeAdded?.Invoke(this, nodeToStore); | ||
|
|
@@ -91,6 +87,7 @@ public BucketAddResult TryAddOrRefresh(in TKadKey nodeHash, TNode node, out TNod | |
| private BucketAddResult TryAddOrRefreshLocked( | ||
| in TKadKey nodeHash, | ||
| TNode node, | ||
| out TNode nodeToStore, | ||
| out TNode? toRefresh, | ||
| out bool fireAdded) | ||
| { | ||
|
|
@@ -105,22 +102,88 @@ private BucketAddResult TryAddOrRefreshLocked( | |
| if (current.IsLeaf) | ||
| { | ||
| if (_logger.IsEnabled(LogLevel.Trace)) _logger.LogTrace($"Reached leaf node at depth {depth}"); | ||
| BucketAddResult resp = current.Bucket.TryAddOrRefresh(nodeHash, node, out toRefresh); | ||
| fireAdded = resp == BucketAddResult.Added; | ||
| if (resp is BucketAddResult.Added or BucketAddResult.Refreshed) | ||
| { | ||
| if (_logger.IsEnabled(LogLevel.Trace)) _logger.LogTrace($"Successfully added/refreshed node {node} in bucket at depth {depth}"); | ||
| return resp; | ||
| } | ||
|
|
||
| if (resp == BucketAddResult.Full && ShouldSplit(depth, logDistance)) | ||
| // A new key that would overflow a splittable leaf belongs in a post-split child: | ||
| // split first so the limiter only ever sees the final bucket, which may be empty. | ||
| if (!current.Bucket.ContainsNode(nodeHash) && current.Bucket.Count >= _k && ShouldSplit(depth, logDistance)) | ||
| { | ||
| if (_logger.IsEnabled(LogLevel.Trace)) _logger.LogTrace($"Splitting bucket at depth {depth}"); | ||
| SplitBucket(depth, current); | ||
| continue; | ||
| } | ||
|
|
||
| if (_logger.IsEnabled(LogLevel.Trace)) _logger.LogTrace($"Failed to add node {nodeHash} {node}. Bucket at depth {depth} is full. {_k} {current.Bucket.Count}"); | ||
| // A full unsplittable leaf can only park an absent key in the replacement cache, which | ||
| // holds no charge until promotion. Probe without charging so a transient charge never | ||
| // becomes visible to the limiter-lock-only WouldAdmit consumer between TryAdmit and | ||
| // the Full release. Promotion via TryAdmit charges on a free slot. | ||
| if (_limiter is not null | ||
| && !current.Bucket.ContainsNode(nodeHash) | ||
| && current.Bucket.Count >= _k | ||
| && !ShouldSplit(depth, logDistance)) | ||
| { | ||
| if (!_limiter.ProbeAdmit(node, current.Bucket.GetAllCached())) | ||
| { | ||
| if (_logger.IsEnabled(LogLevel.Trace)) _logger.LogTrace($"Subnet limiter rejected node {node}"); | ||
| nodeToStore = node; | ||
| toRefresh = default; | ||
| fireAdded = false; | ||
| return BucketAddResult.Rejected; | ||
| } | ||
|
|
||
| nodeToStore = node; | ||
| if (_mergeOnRefresh is not null && current.Bucket.TryGetStored(nodeHash, out TNode? previousUncharged)) | ||
| { | ||
| _isMergingRefresh = true; | ||
| try | ||
| { | ||
| nodeToStore = _mergeOnRefresh(node, previousUncharged); | ||
| } | ||
| finally | ||
| { | ||
| _isMergingRefresh = false; | ||
| } | ||
| } | ||
|
|
||
| BucketAddResult unchargedResp = current.Bucket.TryAddOrRefresh(nodeHash, nodeToStore, out toRefresh); | ||
| fireAdded = unchargedResp == BucketAddResult.Added; | ||
| if (_logger.IsEnabled(LogLevel.Trace)) _logger.LogTrace($"Failed to add node {nodeHash} {nodeToStore}. Bucket at depth {depth} is full. {_k} {current.Bucket.Count}"); | ||
| return unchargedResp; | ||
| } | ||
|
|
||
| if (_limiter is not null && !_limiter.TryAdmit(node, current.Bucket.GetAllCached())) | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. [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.
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 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 |
||
| { | ||
| if (_logger.IsEnabled(LogLevel.Trace)) _logger.LogTrace($"Subnet limiter rejected node {node}"); | ||
| nodeToStore = node; | ||
| toRefresh = default; | ||
| fireAdded = false; | ||
| return BucketAddResult.Rejected; | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. [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.
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 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 |
||
| } | ||
|
|
||
| // Merge only after admission: the merge may share mutable state with the | ||
| // stored entry (e.g. Node ENR state), so a rejected endpoint change must | ||
| // not clobber the admitted endpoint that restore still needs. | ||
| nodeToStore = node; | ||
| if (_mergeOnRefresh is not null && current.Bucket.TryGetStored(nodeHash, out TNode? previous)) | ||
| { | ||
| _isMergingRefresh = true; | ||
| try | ||
| { | ||
| nodeToStore = _mergeOnRefresh(node, previous); | ||
| } | ||
| finally | ||
| { | ||
| _isMergingRefresh = false; | ||
| } | ||
| } | ||
|
|
||
| BucketAddResult resp = current.Bucket.TryAddOrRefresh(nodeHash, nodeToStore, out toRefresh); | ||
| fireAdded = resp == BucketAddResult.Added; | ||
| if (resp is BucketAddResult.Added or BucketAddResult.Refreshed) | ||
| { | ||
| if (_logger.IsEnabled(LogLevel.Trace)) _logger.LogTrace($"Successfully added/refreshed node {nodeToStore} in bucket at depth {depth}"); | ||
| return resp; | ||
| } | ||
|
|
||
| if (_logger.IsEnabled(LogLevel.Trace)) _logger.LogTrace($"Failed to add node {nodeHash} {nodeToStore}. Bucket at depth {depth} is full. {_k} {current.Bucket.Count}"); | ||
| return resp; | ||
| } | ||
|
|
||
|
|
@@ -199,7 +262,12 @@ public bool Remove(in TKadKey nodeHash) | |
|
|
||
| KBucket<TNode, TKadKey> bucket = GetBucketForHash(nodeHash); | ||
| removedNode = bucket.GetByHash(nodeHash); | ||
| removed = bucket.RemoveAndReplace(nodeHash); | ||
| removed = bucket.Remove(nodeHash); | ||
| if (removed) | ||
| { | ||
| if (removedNode is not null) _limiter?.Release(removedNode); | ||
| bucket.TryPromote(node => _limiter is null || _limiter.TryAdmit(node, bucket.GetAllCached())); | ||
| } | ||
| } | ||
|
|
||
| if (removed && removedNode is not null) OnNodeRemoved?.Invoke(this, removedNode); | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
[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.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
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