Skip to content
Open
Show file tree
Hide file tree
Changes from 6 commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
02641de
feat(kademlia)!: add a routing-table node limiter hook
Jashk120 Nov 26, 2026
5e85ec1
perf(network): look up static and trusted nodes by public key
Jashk120 Nov 26, 2026
a0d63ce
feat(discovery): limit discv4 routing-table entries per subnet
Jashk120 Nov 26, 2026
1744bb8
fix(discovery): keep subnet-limited nodes out of the peer candidate s…
Jashk120 Nov 26, 2026
f40a3e2
test(discovery): cover subnet counts end to end
Jashk120 Nov 26, 2026
41e1c11
Decouple discovery subnet limiter from Network managers via Core seam
Jashk120 Nov 26, 2026
b0178c6
fix(discovery): remove inert fork gate from discv4 subnet limiter
Jashk120 Nov 26, 2026
61c3c23
test(discovery): make subnet cap end-to-end test falsifiable
Jashk120 Nov 26, 2026
56bb582
fix(discovery): run subnet limiter on the bucket the node lands in
Jashk120 Nov 27, 2026
38fc60d
fix(discovery): bypass LAN addresses in discv4 subnet limiter
Jashk120 Nov 27, 2026
e603dae
fix(discovery): cover StaticPeers, bootnode off-switch and limiter docs
Jashk120 Nov 27, 2026
4547c30
chore(discovery): drop redundant usings flagged by code lint
Jashk120 Nov 27, 2026
7b8366b
fix(kademlia): retain subnet-rejected promotion candidates
Jashk120 Nov 29, 2026
6d5b8cf
fix(discovery): drop unused ManagedNodeExemptions overload
Jashk120 Nov 29, 2026
33e2574
fix(discovery): drop subnet-rejected candidates before PeerPool
Jashk120 Nov 29, 2026
337f676
fix(kademlia): keep retained liveness on rejected endpoint change
Jashk120 Nov 29, 2026
bc270a4
fix(kademlia): merge ENR state only after subnet admission
Jashk120 Nov 29, 2026
e2843c0
fix(discovery): charge retained incumbent on refused refresh
Jashk120 Nov 29, 2026
4d35ad0
fix(discovery): exclude rejected seeds from DNS feeder budget
Jashk120 Nov 29, 2026
7173ec9
fix(config): opt xdc_archive out of discovery subnet cap
Jashk120 Nov 29, 2026
a9bffc6
fix(kademlia): probe subnet cap without charging on full leaf
Jashk120 Nov 29, 2026
502a80e
fix(discovery): exempt static peers without DNS lookup
Jashk120 Nov 29, 2026
948edaf
test(discovery): isolate bucket and table subnet guards
Jashk120 Nov 29, 2026
7ddaf92
fix(bootnode): align test fakes with discovery verdict returns
Jashk120 Nov 29, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions src/Nethermind/Nethermind.Init/Modules/DiscoveryModule.cs
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,12 @@ protected override void Load(ContainerBuilder builder)
.AddSingleton<ITrustedNodesManager, ILogManager>((logManager) =>
new TrustedNodesManager(initConfig.TrustedNodesPath.GetApplicationResourcePath(initConfig.DataDir), logManager))

// Backs the discovery subnet limiter's managed exemptions. Slim hosts without this
// registration (e.g. the bootnode) run the limiter without managed exemptions;
// flag-based exemptions (IsStatic/IsTrusted) still apply.
.AddSingleton<IDiscoveryNodeExemptions, IStaticNodesManager, ITrustedNodesManager>((staticNodes, trustedNodes) =>
new ManagedNodeExemptions(staticNodes, trustedNodes))

.Bind<INodeSource, IStaticNodesManager>()
.Bind<INodeSource, ITrustedNodesManager>()

Expand Down
3 changes: 2 additions & 1 deletion src/Nethermind/Nethermind.Kademlia/BucketAddResult.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,6 @@ public enum BucketAddResult
{
Added,
Refreshed,
Full
Full,
Rejected

Copy link
Copy Markdown
Contributor

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.

Copy link
Copy Markdown
Author

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

}
26 changes: 26 additions & 0 deletions src/Nethermind/Nethermind.Kademlia/IRoutingTableNodeLimiter.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
// 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);
}
32 changes: 24 additions & 8 deletions src/Nethermind/Nethermind.Kademlia/KBucket.cs
Original file line number Diff line number Diff line change
Expand Up @@ -56,21 +56,32 @@ public BucketAddResult TryAddOrRefresh(in TKadKey hash, TNode item, out TNode? t

internal int CopyAllWithHash((TKadKey Hash, TNode Node)[] destination) => _items.CopyAllWithKey(destination);

public bool RemoveAndReplace(in TKadKey hash)
public bool Remove(in TKadKey hash)
{
if (!_items.Remove(hash)) return false;

if (_replacement.TryPopHead(out TKadKey replacementHash, out TNode? replacement))
{
_items.AddOrRefresh(replacementHash, replacement!);
}
UpdateCachedArray();
return true;
}

if (_cacheItems)
/// <summary>
/// Promotes the most recently cached replacement that <paramref name="canPromote"/> accepts, discarding the
/// candidates it rejects.
/// </summary>
/// <param name="canPromote">Admission predicate for a candidate, or <see langword="null"/> to accept the first.</param>
/// <returns><see langword="true"/> when a replacement was promoted.</returns>
public bool TryPromote(Func<TNode, bool>? canPromote)
{
while (_replacement.TryPopHead(out TKadKey replacementHash, out TNode? replacement))
{
_cachedArray = _items.GetAll();
if (canPromote is not null && !canPromote(replacement!)) continue;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

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.


_items.AddOrRefresh(replacementHash, replacement!);
UpdateCachedArray();
return true;
}

return true;
return false;
}

public void Clear()
Expand All @@ -87,6 +98,11 @@ public void Clear()
internal bool TryGetStored(in TKadKey hash, [MaybeNullWhen(false)] out TNode node)
=> _items.TryGetValue(hash, out node) || _replacement.TryGetValue(hash, out node);

private void UpdateCachedArray()
{
if (_cacheItems) _cachedArray = _items.GetAll();
}

private static bool ShouldUpdateCachedArray(TNode? previous, TNode item)
=> previous is not null &&
(typeof(TNode).IsValueType
Expand Down
25 changes: 24 additions & 1 deletion src/Nethermind/Nethermind.Kademlia/KBucketTree.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand All @@ -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}");
Expand Down Expand Up @@ -81,7 +83,23 @@ public BucketAddResult TryAddOrRefresh(in TKadKey nodeHash, TNode node, out TNod
}
}

IRoutingTableNodeLimiter<TNode>? limiter = _limiter;
if (limiter is not null && !limiter.TryAdmit(nodeToStore, bucket.GetAllCached()))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

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.

{
if (_logger.IsEnabled(LogLevel.Trace)) _logger.LogTrace($"Subnet limiter rejected node {nodeToStore}");
toRefresh = default;
fireAdded = false;
return BucketAddResult.Rejected;
}

resp = TryAddOrRefreshLocked(nodeHash, nodeToStore, out toRefresh, out fireAdded);
if (resp == BucketAddResult.Full)
{
// 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);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

}
}

if (fireAdded) OnNodeAdded?.Invoke(this, nodeToStore);
Expand Down Expand Up @@ -199,7 +217,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);
Expand Down
10 changes: 10 additions & 0 deletions src/Nethermind/Nethermind.Kademlia/KademliaConfig.cs
Original file line number Diff line number Diff line change
Expand Up @@ -69,4 +69,14 @@ public class KademliaConfig<TNode>
/// acquire a lock that callers can hold while entering that routing table (which would invert the lock order).
/// </remarks>
public Func<TNode, TNode, TNode>? MergeOnRefresh { get; set; }

/// <summary>
/// Optional admission policy consulted before a node takes a slot in the routing table. The default,
/// <see langword="null"/>, admits every node.
/// </summary>
/// <remarks>
/// The routing table calls <see cref="IRoutingTableNodeLimiter{TNode}.TryAdmit"/> while holding its own lock, so an
/// implementation must not call back into the table; the lock order is routing-table lock, then limiter lock.
/// </remarks>
public IRoutingTableNodeLimiter<TNode>? NodeLimiter { get; set; }
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
// SPDX-FileCopyrightText: 2026 Demerzel Solutions Limited
// SPDX-License-Identifier: LGPL-3.0-only

using Nethermind.Core.Crypto;

namespace Nethermind.Network;

/// <summary>
/// Live lookup for nodes exempt from discovery subnet limits (managed static/trusted entries).
/// Implemented by the full client; absent in slim hosts such as the bootnode.
/// </summary>
public interface IDiscoveryNodeExemptions
{
/// <summary>Returns <see langword="true"/> when a managed static or trusted node has <paramref name="nodeId"/> as its identity.</summary>
bool IsExempt(PublicKey nodeId);
}
2 changes: 1 addition & 1 deletion src/Nethermind/Nethermind.Network.Core/NodeFilter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ private bool WasSeenRecently(IpSubnetKey key, long now)
/// Allocation-free key for an IP address or a masked subnet prefix, suitable for hash lookups and prefix checks.
/// </summary>
[StructLayout(LayoutKind.Explicit)]
private readonly struct IpSubnetKey : IEquatable<IpSubnetKey>
internal readonly struct IpSubnetKey : IEquatable<IpSubnetKey>
{
// For IPv6: _hi/_lo are the masked 128-bit network prefix (big-endian).
// For IPv4: _hi holds the masked v4 in the low 32 bits (big-endian), _lo is 0.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
Expand Down Expand Up @@ -288,6 +289,73 @@ public async Task StartAsync_ShouldRemoveBootnodeOutsideBoundFamilyAfterFallback
kademlia.DidNotReceive().AddOrRefresh(Arg.Any<Node>());
}

[Test]
public async Task AddNodeToDiscovery_admits_static_and_trusted_nodes_past_a_saturated_subnet()
{
NetworkConfig networkConfig = new()
{
LocalIp = "127.0.0.1",
ExternalIp = "127.0.0.1",
DiscoveryPort = 30303,
P2PPort = 30303
};
DiscoveryConfig discoveryConfig = new() { DiscoveryVersion = DiscoveryVersion.V4 };
IForkInfo forkInfo = Substitute.For<IForkInfo>();
forkInfo.IsForkIdCompatible(Arg.Any<ForkId>()).Returns(true);

ContainerBuilder builder = new();
builder.AddModule(new TestNethermindModule(networkConfig, discoveryConfig));
builder.RegisterInstance(forkInfo).As<IForkInfo>();
await using IContainer root = builder.Build();

NetworkListenerState listenerState = root.Resolve<NetworkListenerState>();
listenerState.SetDiscoveryAddress(IPAddress.Loopback);
listenerState.SetRlpxAddress(IPAddress.Loopback);

await using TestDiscoveryApp app = new(
root,
root.Resolve<IEnode>(),
networkConfig,
discoveryConfig,
root.Resolve<IIPResolver>(),
root.Resolve<IProcessExitSource>(),
LimboLogs.Instance,
listenerState);

app.AddNodeToDiscovery(new Node(TestItem.PublicKeyB, "192.0.2.1", 30303));
app.AddNodeToDiscovery(new Node(TestItem.PublicKeyC, "192.0.2.2", 30303));
app.AddNodeToDiscovery(new Node(TestItem.PublicKeyD, "192.0.2.3", 30303));

Node staticNode = new(TestItem.PublicKeyE, "192.0.2.4", 30303) { IsStatic = true };
Node trustedNode = new(TestItem.PublicKeyF, "192.0.2.5", 30303) { IsTrusted = true };
app.AddNodeToDiscovery(staticNode);
app.AddNodeToDiscovery(trustedNode);

PublicKey[] admitted = [.. app.Table.IterateNodes()
.Where(node => node.Id != root.Resolve<IEnode>().PublicKey)
.Select(static node => node.Id)];
using (Assert.EnterMultipleScope())
{
Assert.That(admitted, Has.Length.EqualTo(4));
Assert.That(admitted, Is.SupersetOf(new[] { staticNode.Id, trustedNode.Id }));
Assert.That(admitted, Does.Not.Contain(TestItem.PublicKeyD));
}
}

private sealed class TestDiscoveryApp(
ILifetimeScope rootScope,
IEnode enode,
INetworkConfig networkConfig,
IDiscoveryConfig discoveryConfig,
IIPResolver ipResolver,
IProcessExitSource processExitSource,
ILogManager logManager,
NetworkListenerState listenerState)
: DiscoveryApp(rootScope, enode, networkConfig, discoveryConfig, ipResolver, processExitSource, logManager, listenerState)
{
public IKademlia<PublicKey, Node> Table => Kademlia;
}

private static NodeRecord CreateAsymmetricDualStackRecord() =>
TestEnrBuilder.BuildSigned(
TestItem.PrivateKeyA,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ public class NodeSourceTests
private DiscoveryConfig _discoveryConfig = null!;
private KademliaConfig<Node> _kademliaConfig = null!;
private IForkInfo _forkInfo = null!;
private IRoutingTableNodeLimiter<Node> _nodeLimiter = null!;
private Channel<Node> _peerCandidates = null!;

[SetUp]
Expand All @@ -55,6 +56,9 @@ public void Setup()
_forkInfo = Substitute.For<IForkInfo>();
_forkInfo.IsForkIdCompatible(Arg.Any<ForkId>())
.Returns(static call => call.Arg<ForkId>().ForkHash == CompatibleForkHash);
_nodeLimiter = Substitute.For<IRoutingTableNodeLimiter<Node>>();
_nodeLimiter.WouldAdmit(Arg.Any<Node>()).Returns(true);
_kademliaConfig.NodeLimiter = _nodeLimiter;
_nodeSource = new NodeSource(
_kademliaDiscovery,
_adapter,
Expand Down Expand Up @@ -148,6 +152,27 @@ public async Task DiscoverNodes_should_keep_node_when_fork_check_fails(Cancellat
Assert.That(enumerator.Current.Id, Is.EqualTo(node.Id));
}

[Test]
[CancelAfter(10000)]
public async Task DiscoverNodes_should_drop_a_candidate_the_table_would_reject(CancellationToken token)
{
Node atCap = new(TestItem.PublicKeyA, "192.168.1.1", 30303);
Node belowCap = new(TestItem.PublicKeyB, "192.168.1.2", 30303);
_nodeLimiter.WouldAdmit(Arg.Is<Node>(node => node.Id == atCap.Id)).Returns(false);
_nodeLimiter.WouldAdmit(Arg.Is<Node>(node => node.Id == belowCap.Id)).Returns(true);

await using IAsyncEnumerator<Node> enumerator = _nodeSource.DiscoverNodes(token).GetAsyncEnumerator(token);
ValueTask<bool> moveNext = enumerator.MoveNextAsync();
await _kademliaDiscovery.Started.Task.WaitAsync(token);
RaisePeerCandidate(atCap);
RaisePeerCandidate(belowCap);

#pragma warning disable NUnit2045 // The assertions sequence an asynchronous state transition or wait prerequisite with dependent state checks; preserve fail-fast ordering.
Assert.That(await moveNext.AsTask(), Is.True);
#pragma warning restore NUnit2045
Assert.That(enumerator.Current.Id, Is.EqualTo(belowCap.Id));
}

[Test]
[CancelAfter(10000)]
public async Task DiscoverNodes_should_stop_random_walk_when_enumeration_is_disposed(CancellationToken token)
Expand Down
Loading
Loading