From d73d4c6d24cddac09922929ac8669cd614660bca Mon Sep 17 00:00:00 2001 From: Ruben Buniatyan <337518+rubo@users.noreply.github.com> Date: Thu, 26 Nov 2026 21:43:12 +0100 Subject: [PATCH 01/22] refactor(network): move the transport-free RLPx host policy out of RlpxHost The socket transport that follows needs the same dial, filter, session tracking and listener behaviour as RlpxHost. These move unchanged into internal types both hosts can use: - RlpxDialPolicy: the recent-IP filter with privileged IPs, and dialing a node's endpoint, then the other address family its verified ENR advertises - RlpxSessionTracker: the session events, the activity observer, marking a session disconnected a second after its connection closes, and at shutdown - RlpxListener: the fallback bind and the dual-mode listener socket - RlpxErrorHandler: the logging and disconnect policy for an error in the communication with a peer, from ZeroNettyP2PHandler.ExceptionCaught --- .../Discv4/Kademlia/KademliaAdapterTests.cs | 2 +- .../RlpxHostIntegrationTests.cs | 18 +- .../ProtocolHandlers/ZeroNettyP2PHandler.cs | 35 +-- .../P2P/RlpxErrorHandler.cs | 65 +++++ .../Nethermind.Network/Rlpx/RlpxDialPolicy.cs | 136 +++++++++ .../Nethermind.Network/Rlpx/RlpxHost.cs | 263 ++---------------- .../Nethermind.Network/Rlpx/RlpxListener.cs | 63 +++++ .../Rlpx/RlpxSessionTracker.cs | 140 ++++++++++ 8 files changed, 442 insertions(+), 280 deletions(-) create mode 100644 src/Nethermind/Nethermind.Network/P2P/RlpxErrorHandler.cs create mode 100644 src/Nethermind/Nethermind.Network/Rlpx/RlpxDialPolicy.cs create mode 100644 src/Nethermind/Nethermind.Network/Rlpx/RlpxListener.cs create mode 100644 src/Nethermind/Nethermind.Network/Rlpx/RlpxSessionTracker.cs diff --git a/src/Nethermind/Nethermind.Network.Discovery.Test/Discv4/Kademlia/KademliaAdapterTests.cs b/src/Nethermind/Nethermind.Network.Discovery.Test/Discv4/Kademlia/KademliaAdapterTests.cs index a54a67ec1c9e..2bd07076c1c1 100644 --- a/src/Nethermind/Nethermind.Network.Discovery.Test/Discv4/Kademlia/KademliaAdapterTests.cs +++ b/src/Nethermind/Nethermind.Network.Discovery.Test/Discv4/Kademlia/KademliaAdapterTests.cs @@ -1410,7 +1410,7 @@ public async Task OnIncomingMsg_ping_should_keep_verified_enr_when_bonded_endpoi if (Socket.OSSupportsIPv6) { - Assert.That(RlpxHost.TryCreateAlternateDialNode(peerNode, true, out Node? alternate), Is.True); + Assert.That(RlpxDialPolicy.TryCreateAlternateDialNode(peerNode, true, out Node? alternate), Is.True); using (Assert.EnterMultipleScope()) { Assert.That(alternate!.Address, Is.EqualTo(new IPEndPoint(ipv6Address, 30305))); diff --git a/src/Nethermind/Nethermind.Network.Test/RlpxHostIntegrationTests.cs b/src/Nethermind/Nethermind.Network.Test/RlpxHostIntegrationTests.cs index b38b3566476e..cc469859cc38 100644 --- a/src/Nethermind/Nethermind.Network.Test/RlpxHostIntegrationTests.cs +++ b/src/Nethermind/Nethermind.Network.Test/RlpxHostIntegrationTests.cs @@ -664,7 +664,7 @@ public async Task ConnectAsync_FallsBackToVerifiedIpv6EndpointWithoutPublishingF IPEndPoint originalAddress = node.Address; int originalDiscoveryPort = node.DiscoveryPort; #pragma warning disable NUnit2045 // The call establishes an output or mutable state needed by later assertions; keep the success prerequisite fail-fast. - Assert.That(RlpxHost.TryCreateAlternateDialNode(node, allowNonRoutable: true, out Node? alternate), Is.True); + Assert.That(RlpxDialPolicy.TryCreateAlternateDialNode(node, allowNonRoutable: true, out Node? alternate), Is.True); #pragma warning restore NUnit2045 Assert.That(alternate!.Address, Is.EqualTo(new IPEndPoint(IPAddress.IPv6Loopback, listeningPort))); @@ -971,7 +971,7 @@ public void Dial_address_policy_rejects_invalid_and_public_to_private_transition string address, bool allowNonRoutable, bool expected) => - Assert.That(RlpxHost.IsDialAddressAcceptable(IPAddress.Parse(address), allowNonRoutable), Is.EqualTo(expected)); + Assert.That(RlpxDialPolicy.IsDialAddressAcceptable(IPAddress.Parse(address), allowNonRoutable), Is.EqualTo(expected)); [Test] public void Alternate_dial_requires_current_verified_record() @@ -983,7 +983,7 @@ public void Alternate_dial_requires_current_verified_record() unverified.IsStatic = true; unverified.IsTrusted = true; unverified.IsBootnode = true; - Assert.That(RlpxHost.TryCreateAlternateDialNode(unverified, allowNonRoutable: false, out _), Is.False, + Assert.That(RlpxDialPolicy.TryCreateAlternateDialNode(unverified, allowNonRoutable: false, out _), Is.False, "peer role flags must not authenticate an ENR"); Node stale = CreateDualStackNode( @@ -992,7 +992,7 @@ public void Alternate_dial_requires_current_verified_record() verified: true, sequence: 1); stale.ObserveEnrSequence(2); - Assert.That(RlpxHost.TryCreateAlternateDialNode(stale, allowNonRoutable: false, out _), Is.False); + Assert.That(RlpxDialPolicy.TryCreateAlternateDialNode(stale, allowNonRoutable: false, out _), Is.False); } [TestCase("10.0.0.1", "::1", false)] @@ -1015,7 +1015,7 @@ public void Alternate_dial_only_allows_loopback_from_loopback(string primaryAddr #pragma warning restore NUnit2045 Assert.That(node!.SetVerifiedEnr(record), Is.True); - Assert.That(RlpxHost.TryCreateAlternateDialNode(node, allowNonRoutable: true, out _), Is.EqualTo(expected)); + Assert.That(RlpxDialPolicy.TryCreateAlternateDialNode(node, allowNonRoutable: true, out _), Is.EqualTo(expected)); } [Test] @@ -1025,20 +1025,20 @@ public void Alternate_dial_obeys_withdrawal_family_validation_and_routability() IPAddress.Parse("8.8.8.8"), 30303, IPAddress.Parse("fc00::1"), 30304, verified: true); - Assert.That(RlpxHost.TryCreateAlternateDialNode(publicToPrivate, allowNonRoutable: false, out _), Is.False); + Assert.That(RlpxDialPolicy.TryCreateAlternateDialNode(publicToPrivate, allowNonRoutable: false, out _), Is.False); Node privateToPrivate = CreateDualStackNode( IPAddress.Parse("10.0.0.1"), 30303, IPAddress.Parse("fc00::1"), 30304, verified: true); - Assert.That(RlpxHost.TryCreateAlternateDialNode(privateToPrivate, allowNonRoutable: true, out _), Is.True); + Assert.That(RlpxDialPolicy.TryCreateAlternateDialNode(privateToPrivate, allowNonRoutable: true, out _), Is.True); NodeRecord mappedRecord = CreateDualStackRecord( IPAddress.Parse("8.8.8.8"), 30303, IPAddress.Parse("::ffff:8.8.4.4"), 30304, sequence: 0); Node mapped = CreateNode(mappedRecord, verified: true); - Assert.That(RlpxHost.TryCreateAlternateDialNode(mapped, allowNonRoutable: false, out _), Is.False); + Assert.That(RlpxDialPolicy.TryCreateAlternateDialNode(mapped, allowNonRoutable: false, out _), Is.False); NodeRecord withdrawal = CreateDualStackRecord( IPAddress.Parse("8.8.8.8"), 30303, @@ -1047,7 +1047,7 @@ public void Alternate_dial_obeys_withdrawal_family_validation_and_routability() #pragma warning disable NUnit2045 // The call establishes an output or mutable state needed by later assertions; keep the success prerequisite fail-fast. Assert.That(publicToPrivate.SetVerifiedEnr(withdrawal), Is.True); #pragma warning restore NUnit2045 - Assert.That(RlpxHost.TryCreateAlternateDialNode(publicToPrivate, allowNonRoutable: false, out _), Is.False); + Assert.That(RlpxDialPolicy.TryCreateAlternateDialNode(publicToPrivate, allowNonRoutable: false, out _), Is.False); } private static Node CreateDualStackNode(int ipv4Port, int ipv6Port) diff --git a/src/Nethermind/Nethermind.Network/P2P/ProtocolHandlers/ZeroNettyP2PHandler.cs b/src/Nethermind/Nethermind.Network/P2P/ProtocolHandlers/ZeroNettyP2PHandler.cs index 3a8e6a742216..968750be2699 100644 --- a/src/Nethermind/Nethermind.Network/P2P/ProtocolHandlers/ZeroNettyP2PHandler.cs +++ b/src/Nethermind/Nethermind.Network/P2P/ProtocolHandlers/ZeroNettyP2PHandler.cs @@ -4,11 +4,8 @@ using System; using System.Buffers; using System.Diagnostics; -using System.Net.Sockets; -using System.Runtime.CompilerServices; using DotNetty.Buffers; using DotNetty.Common.Utilities; -using DotNetty.Handlers.Timeout; using DotNetty.Transport.Channels; using Nethermind.Core.Exceptions; using Nethermind.Logging; @@ -172,42 +169,12 @@ private void ReleaseOutputPacket() public override void ExceptionCaught(IChannelHandlerContext context, Exception exception) { - if (exception is SocketException or RlpReaderException or ReadTimeoutException) - { - if (_logger.IsTrace) TraceCommunicationError(exception); - } - else - { - if (_logger.IsDebug) _logger.Debug($"Error in communication with {GetClientId(_session):hide}: {exception:hide}"); - } - - if (exception is IInternalNethermindException) - { - // Do nothing as we don't want to drop peer for internal issue. - } - else if (_session?.Node?.IsStatic != true && _session?.Node?.IsTrusted != true) - { - DisconnectReason reason = exception switch - { - SocketException { SocketErrorCode: SocketError.ConnectionReset } => DisconnectReason.ConnectionReset, - RlpLimitException => DisconnectReason.MessageLimitsBreached, - _ => DisconnectReason.Exception, - }; - _session.InitiateDisconnect(reason, $"Error in communication with {GetClientId(_session)} ({exception.GetType().Name}): {exception.Message}"); - } - else + if (!RlpxErrorHandler.TryHandle(_session, exception, _logger)) { base.ExceptionCaught(context, exception); } - - [MethodImpl(MethodImplOptions.NoInlining)] - void TraceCommunicationError(Exception communicationException) => - _logger.Trace($"Error in communication with {GetClientId(_session):hide} ({communicationException.GetType().Name}): {communicationException:hide}"); } - private static string GetClientId(ISession? session) => - session?.Node?.ToString(Node.Format.Console) ?? $"unknown {session?.RemoteHost}"; - public void EnableSnappy() => SnappyEnabled = true; private sealed class SnappyOutputWriter : IBufferWriter diff --git a/src/Nethermind/Nethermind.Network/P2P/RlpxErrorHandler.cs b/src/Nethermind/Nethermind.Network/P2P/RlpxErrorHandler.cs new file mode 100644 index 000000000000..ec7488eaf2bc --- /dev/null +++ b/src/Nethermind/Nethermind.Network/P2P/RlpxErrorHandler.cs @@ -0,0 +1,65 @@ +// SPDX-FileCopyrightText: 2026 Demerzel Solutions Limited +// SPDX-License-Identifier: LGPL-3.0-only + +using System; +using System.Net.Sockets; +using System.Runtime.CompilerServices; +using DotNetty.Handlers.Timeout; +using Nethermind.Core.Exceptions; +using Nethermind.Logging; +using Nethermind.Serialization.FluentRlp; +using Nethermind.Stats.Model; + +namespace Nethermind.Network.P2P; + +/// +/// Handles an error in the communication with a peer, as every RLPx transport does. +/// +internal static class RlpxErrorHandler +{ + /// Logs the error and disconnects the peer, unless the error is internal or the peer is static or trusted. + /// The peer's session. + /// The error. + /// The transport's logger. + /// + /// for a static or trusted peer, which is not disconnected: the transport passes the error on. + /// + public static bool TryHandle(ISession session, Exception exception, ILogger logger) + { + if (exception is SocketException or RlpReaderException or ReadTimeoutException) + { + if (logger.IsTrace) TraceCommunicationError(session, exception, logger); + } + else + { + if (logger.IsDebug) logger.Debug($"Error in communication with {GetClientId(session):hide}: {exception:hide}"); + } + + if (exception is IInternalNethermindException) + { + // Do nothing as we don't want to drop peer for internal issue. + return true; + } + + if (session?.Node?.IsStatic != true && session?.Node?.IsTrusted != true) + { + DisconnectReason reason = exception switch + { + SocketException { SocketErrorCode: SocketError.ConnectionReset } => DisconnectReason.ConnectionReset, + RlpLimitException => DisconnectReason.MessageLimitsBreached, + _ => DisconnectReason.Exception, + }; + session.InitiateDisconnect(reason, $"Error in communication with {GetClientId(session)} ({exception.GetType().Name}): {exception.Message}"); + return true; + } + + return false; + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static void TraceCommunicationError(ISession session, Exception exception, ILogger logger) => + logger.Trace($"Error in communication with {GetClientId(session):hide} ({exception.GetType().Name}): {exception:hide}"); + + private static string GetClientId(ISession? session) => + session?.Node?.ToString(Node.Format.Console) ?? $"unknown {session?.RemoteHost}"; +} diff --git a/src/Nethermind/Nethermind.Network/Rlpx/RlpxDialPolicy.cs b/src/Nethermind/Nethermind.Network/Rlpx/RlpxDialPolicy.cs new file mode 100644 index 000000000000..423b405683b6 --- /dev/null +++ b/src/Nethermind/Nethermind.Network/Rlpx/RlpxDialPolicy.cs @@ -0,0 +1,136 @@ +// SPDX-FileCopyrightText: 2026 Demerzel Solutions Limited +// SPDX-License-Identifier: LGPL-3.0-only + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Sockets; +using System.Runtime.CompilerServices; +using System.Threading; +using System.Threading.Tasks; +using Nethermind.Logging; +using Nethermind.Network.Enr; +using Nethermind.Stats.Model; + +namespace Nethermind.Network.Rlpx; + +/// +/// Decides which peers an RLPx host contacts or accepts, and on which endpoints it dials them. +/// +/// Shared by the RLPx hosts, so that each one owns only its transport. +internal sealed class RlpxDialPolicy(NodeFilter nodeFilter, IPrivilegedIpProvider privilegedIpProvider, ILogger logger) +{ + /// Privileged addresses (static and trusted nodes) bypass the recent-IP filter so they can always connect. + public bool ShouldContact(IPAddress ip, bool exactOnly = false) + => privilegedIpProvider.IsPrivileged(ip) || nodeFilter.TryAccept(ip, exactOnly); + + /// + /// Tells whether to accept an inbound connection, rejecting IPs already seen within the filter window. + /// + /// + /// Primary outgoing endpoints are recorded by before ; + /// fallback endpoints are checked without mutation and recorded only after connecting. + /// + public bool AcceptsInbound(IPAddress ip) => privilegedIpProvider.IsPrivileged(ip) || nodeFilter.TryAccept(ip); + + /// Refreshes the filter entry of a peer that sent or received a message. + public void OnSessionActivity(Node remoteNode) => nodeFilter.Touch(remoteNode.Address.Address, remoteNode.IsStatic || remoteNode.IsBootnode); + + /// Dials a node on its endpoint, then on the other address family its verified ENR advertises. + /// The node to dial. + /// Dials one endpoint and tells whether the connection was established. + /// Cancels the dial, including the fallback. + public async Task ConnectAsync(Node node, Func> tryConnect, CancellationToken cancellationToken) + { + if (logger.IsTrace) logger.Trace($"|NetworkTrace| {node.ToString("s"):hide} initiating OUT connection"); + + bool allowNonRoutable = node.Address.Address.IsLoopbackOrPrivateOrLinkLocal; + bool primaryAccepted = IsDialAddressAcceptable(node.Address.Address, allowNonRoutable); + if (!primaryAccepted) + { + if (logger.IsTrace) TraceRejectedDialEndpoint(node, node.Address); + } + else if (await tryConnect(node, cancellationToken)) + { + return true; + } + + if (!TryCreateAlternateDialNode(node, allowNonRoutable, out Node? alternate)) + { + return false; + } + + bool exactOnly = alternate.IsStatic || alternate.IsBootnode; + bool privileged = privilegedIpProvider.IsPrivileged(alternate.Address.Address); + if (!privileged && !nodeFilter.WouldAccept(alternate.Address.Address, exactOnly)) + { + if (logger.IsTrace) TraceFilteredDialEndpoint(alternate); + return false; + } + + cancellationToken.ThrowIfCancellationRequested(); + if (logger.IsDebug) + { + string reason = primaryAccepted ? "Failed to connect" : "Rejected dial endpoint"; + logger.Debug($"{reason} for {node.ToString("s"):hide} on {node.Address:hide}, retrying on {alternate.Address:hide}"); + } + + bool connected = await tryConnect(alternate, cancellationToken); + if (connected && !privileged) + { + nodeFilter.Touch(alternate.Address.Address, exactOnly); + } + + return connected; + } + + internal static bool TryCreateAlternateDialNode(Node node, bool allowNonRoutable, [NotNullWhen(true)] out Node? alternate) + { + NodeRecord? record = node.Enr; + AddressFamily alternateFamily = node.Address.AddressFamily switch + { + AddressFamily.InterNetwork => AddressFamily.InterNetworkV6, + AddressFamily.InterNetworkV6 => AddressFamily.InterNetwork, + _ => AddressFamily.Unknown + }; + bool familySupported = alternateFamily switch + { + AddressFamily.InterNetwork => Socket.OSSupportsIPv4, + AddressFamily.InterNetworkV6 => Socket.OSSupportsIPv6, + _ => false + }; + if (!familySupported || record is null || !node.IsVerifiedEnr(record) || + record.EnrSequence < node.HighestObservedEnrSequence || + !Node.TryFromEnr(record, alternateFamily, out alternate) || + alternate.Id != node.Id || alternate.Address.Equals(node.Address) || + (IPAddress.IsLoopback(alternate.Address.Address) && !IPAddress.IsLoopback(node.Address.Address)) || + !IsDialAddressAcceptable(alternate.Address.Address, allowNonRoutable)) + { + alternate = null; + return false; + } + + alternate.MergeEnrStateFrom(node); + alternate.IsStatic = node.IsStatic; + alternate.IsTrusted = node.IsTrusted; + alternate.IsBootnode = node.IsBootnode; + return true; + } + + internal static bool IsDialAddressAcceptable(IPAddress address, bool allowNonRoutable) + { + ParsedIPAddress parsed = ParsedIPAddress.Parse(address); + return !parsed.IsWildcardOrNone && + !parsed.IsMulticast && + !parsed.IsSpecialUseAddress && + (allowNonRoutable || !parsed.IsLoopbackOrPrivateOrLinkLocal); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private void TraceRejectedDialEndpoint(Node node, IPEndPoint endpoint) => + logger.Trace($"|NetworkTrace| {node.ToString("s"):hide} rejected OUT endpoint {endpoint:hide}"); + + [MethodImpl(MethodImplOptions.NoInlining)] + private void TraceFilteredDialEndpoint(Node node) => + logger.Trace($"|NetworkTrace| {node.ToString("s"):hide} rejected filtered OUT endpoint {node.Address:hide}"); +} diff --git a/src/Nethermind/Nethermind.Network/Rlpx/RlpxHost.cs b/src/Nethermind/Nethermind.Network/Rlpx/RlpxHost.cs index a607dc6d924a..fcf4a45ff5b1 100644 --- a/src/Nethermind/Nethermind.Network/Rlpx/RlpxHost.cs +++ b/src/Nethermind/Nethermind.Network/Rlpx/RlpxHost.cs @@ -7,7 +7,6 @@ using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Net; -using System.Net.Sockets; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; @@ -22,11 +21,9 @@ using Nethermind.Core.ServiceStopper; using Nethermind.Logging; using Nethermind.Network.Config; -using Nethermind.Network.Discovery; using Nethermind.Network.Enr; using Nethermind.Network.P2P; using Nethermind.Network.P2P.Analyzers; -using Nethermind.Network.P2P.EventArg; using Nethermind.Network.Rlpx.Handshake; using Nethermind.Serialization.Rlp; using Nethermind.Stats.Model; @@ -34,7 +31,7 @@ namespace Nethermind.Network.Rlpx { - public class RlpxHost : IRlpxHost, ISessionActivityObserver, IStoppableService + public class RlpxHost : IRlpxHost, IStoppableService { private IChannel? _bootstrapChannel; private IEventLoopGroup? _bossGroup; @@ -54,12 +51,10 @@ public class RlpxHost : IRlpxHost, ISessionActivityObserver, IStoppableService private readonly IChannelFactory? _channelFactory; private readonly Func _createClientChannel; private readonly Action, object?> _disconnectConnectedChannel; - private readonly Action _onChannelCloseCompleted; - private readonly Action _markDisconnectedAfterCloseDelay; - private readonly NodeFilter _nodeFilter; - private readonly IPrivilegedIpProvider _privilegedIpProvider; + private readonly Func> _tryConnect; + private readonly RlpxDialPolicy _dialPolicy; + private readonly RlpxSessionTracker _sessions; private readonly NetworkListenerState _listenerState; - private readonly ConcurrentDictionary _trackedSessions = new(); private readonly ConcurrentDictionary _activeChannels = new(); private readonly Lock _activeChannelsLock = new(); private bool _closingActiveChannels; @@ -113,18 +108,16 @@ public RlpxHost( _channelFactory = channelFactory; _createClientChannel = CreateClientChannel; _disconnectConnectedChannel = DisconnectConnectedChannel; - _onChannelCloseCompleted = OnChannelCloseCompleted; - _markDisconnectedAfterCloseDelay = MarkDisconnectedAfterCloseDelay; + _tryConnect = TryConnect; _untrackChannel = UntrackChannel; _shutdownQuietPeriod = TimeSpan.FromMilliseconds(Math.Min(networkConfig.RlpxHostShutdownCloseTimeoutMs, 100)); _shutdownCloseTimeout = TimeSpan.FromMilliseconds(networkConfig.RlpxHostShutdownCloseTimeoutMs); - _privilegedIpProvider = privilegedIpProvider; - _nodeFilter = NodeFilter.Create(networkConfig.MaxActivePeers, networkConfig.FilterPeersByRecentIp, networkConfig.FilterPeersBySameSubnet, ips.ExternalIp); + NodeFilter nodeFilter = NodeFilter.Create(networkConfig.MaxActivePeers, networkConfig.FilterPeersByRecentIp, networkConfig.FilterPeersBySameSubnet, ips.ExternalIp); + _dialPolicy = new RlpxDialPolicy(nodeFilter, privilegedIpProvider, _logger); + _sessions = new RlpxSessionTracker(this, sessionMonitor, _dialPolicy, _logger, () => _shutdownCts?.Token ?? CancellationToken.None); } - // Privileged addresses (static and trusted nodes) bypass the recent-IP filter so they can always connect. - public bool ShouldContact(IPAddress ip, bool exactOnly = false) - => _privilegedIpProvider.IsPrivileged(ip) || _nodeFilter.TryAccept(ip, exactOnly); + public bool ShouldContact(IPAddress ip, bool exactOnly = false) => _dialPolicy.ShouldContact(ip, exactOnly); public async Task Init() { @@ -161,19 +154,7 @@ await Task.WhenAll( } } - private async Task BindListenerAsync() - { - IPAddress bindAddress = _listenerState.PreferredAddress; - try - { - return await BindAsync(bindAddress); - } - catch (Exception e) when (!bindAddress.Equals(_listenerState.FallbackAddress)) - { - if (_logger.IsWarn) _logger.Warn($"Failed to bind {nameof(RlpxHost)} on {bindAddress:hide}:{LocalPort:hide}. Retrying on {_listenerState.FallbackAddress:hide}:{LocalPort:hide}. {e:hide}"); - return await BindAsync(_listenerState.FallbackAddress); - } - } + private Task BindListenerAsync() => RlpxListener.BindAsync(_listenerState, LocalPort, _logger, nameof(RlpxHost), BindAsync); private async Task BindAsync(IPAddress address) { @@ -220,79 +201,14 @@ private IServerChannel CreateServerChannel(IPAddress address) return _channelFactory.CreateServer(); } - return new TcpServerSocketChannel(CreateServerSocket(address)); - } - - private static Socket CreateServerSocket(IPAddress address) - { - Socket socket = new(address.AddressFamily, SocketType.Stream, ProtocolType.Tcp); - try - { - if (address.AddressFamily == AddressFamily.InterNetworkV6) - { - socket.DualMode = DiscoveryAddressSupport.SupportsFamily(address, AddressFamily.InterNetwork); - if (socket.DualMode) - { - // A dual-mode bind must not share its IPv4 port, or the advertised capability is ambiguous. - socket.ExclusiveAddressUse = true; - } - } - - return socket; - } - catch - { - socket.Dispose(); - throw; - } + return new TcpServerSocketChannel(RlpxListener.CreateSocket(address)); } private IChannel CreateClientChannel() => _channelFactory?.CreateClient() ?? new TcpSocketChannel(); - public async Task ConnectAsync(Node node, CancellationToken cancellationToken = default) - { - if (_logger.IsTrace) _logger.Trace($"|NetworkTrace| {node.ToString("s"):hide} initiating OUT connection"); - - bool allowNonRoutable = node.Address.Address.IsLoopbackOrPrivateOrLinkLocal; - bool primaryAccepted = IsDialAddressAcceptable(node.Address.Address, allowNonRoutable); - if (!primaryAccepted) - { - if (_logger.IsTrace) TraceRejectedDialEndpoint(node, node.Address); - } - else if (await TryConnect(node, cancellationToken)) - { - return true; - } - - if (!TryCreateAlternateDialNode(node, allowNonRoutable, out Node? alternate)) - { - return false; - } - - bool exactOnly = alternate.IsStatic || alternate.IsBootnode; - bool privileged = _privilegedIpProvider.IsPrivileged(alternate.Address.Address); - if (!privileged && !_nodeFilter.WouldAccept(alternate.Address.Address, exactOnly)) - { - if (_logger.IsTrace) TraceFilteredDialEndpoint(alternate); - return false; - } - - cancellationToken.ThrowIfCancellationRequested(); - if (_logger.IsDebug) - { - string reason = primaryAccepted ? "Failed to connect" : "Rejected dial endpoint"; - _logger.Debug($"{reason} for {node.ToString("s"):hide} on {node.Address:hide}, retrying on {alternate.Address:hide}"); - } - - bool connected = await TryConnect(alternate, cancellationToken); - if (connected && !privileged) - { - _nodeFilter.Touch(alternate.Address.Address, exactOnly); - } - - return connected; - } + public Task ConnectAsync(Node node, CancellationToken cancellationToken = default) + => _dialPolicy.ConnectAsync(node, _tryConnect, cancellationToken); private async Task TryConnect(Node node, CancellationToken cancellationToken) { @@ -377,48 +293,6 @@ private void DisconnectWhenConnected(Task connectTask) => TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); - internal static bool TryCreateAlternateDialNode(Node node, bool allowNonRoutable, [NotNullWhen(true)] out Node? alternate) - { - NodeRecord? record = node.Enr; - AddressFamily alternateFamily = node.Address.AddressFamily switch - { - AddressFamily.InterNetwork => AddressFamily.InterNetworkV6, - AddressFamily.InterNetworkV6 => AddressFamily.InterNetwork, - _ => AddressFamily.Unknown - }; - bool familySupported = alternateFamily switch - { - AddressFamily.InterNetwork => Socket.OSSupportsIPv4, - AddressFamily.InterNetworkV6 => Socket.OSSupportsIPv6, - _ => false - }; - if (!familySupported || record is null || !node.IsVerifiedEnr(record) || - record.EnrSequence < node.HighestObservedEnrSequence || - !Node.TryFromEnr(record, alternateFamily, out alternate) || - alternate.Id != node.Id || alternate.Address.Equals(node.Address) || - (IPAddress.IsLoopback(alternate.Address.Address) && !IPAddress.IsLoopback(node.Address.Address)) || - !IsDialAddressAcceptable(alternate.Address.Address, allowNonRoutable)) - { - alternate = null; - return false; - } - - alternate.MergeEnrStateFrom(node); - alternate.IsStatic = node.IsStatic; - alternate.IsTrusted = node.IsTrusted; - alternate.IsBootnode = node.IsBootnode; - return true; - } - - internal static bool IsDialAddressAcceptable(IPAddress address, bool allowNonRoutable) - { - ParsedIPAddress parsed = ParsedIPAddress.Parse(address); - return !parsed.IsWildcardOrNone && - !parsed.IsMulticast && - !parsed.IsSpecialUseAddress && - (allowNonRoutable || !parsed.IsLoopbackOrPrivateOrLinkLocal); - } - [MethodImpl(MethodImplOptions.NoInlining)] private void TraceConnectionTimedOut(Node node) => _logger.Trace($"|NetworkTrace| {node.ToString("s"):hide} OUT connection timed out"); @@ -427,34 +301,26 @@ private void TraceConnectionTimedOut(Node node) => private void TraceConnectionFailure(Node node, Exception exception) => _logger.Trace($"|NetworkTrace| {node.ToString("s"):hide} error when OUT connecting {exception:hide}"); - [MethodImpl(MethodImplOptions.NoInlining)] - private void TraceRejectedDialEndpoint(Node node, IPEndPoint endpoint) => - _logger.Trace($"|NetworkTrace| {node.ToString("s"):hide} rejected OUT endpoint {endpoint:hide}"); - - [MethodImpl(MethodImplOptions.NoInlining)] - private void TraceFilteredDialEndpoint(Node node) => - _logger.Trace($"|NetworkTrace| {node.ToString("s"):hide} rejected filtered OUT endpoint {node.Address:hide}"); - - public event EventHandler SessionCreated; - public event SessionDisconnectedEventHandler SessionDisconnected; + public event EventHandler SessionCreated + { + add => _sessions.SessionCreated += value; + remove => _sessions.SessionCreated -= value; + } - internal void TrackSessionActivity(Session session) + public event SessionDisconnectedEventHandler SessionDisconnected { - ArgumentNullException.ThrowIfNull(session); - _trackedSessions[session.SessionId] = session; - session.SetActivityObserver(this); + add => _sessions.SessionDisconnected += value; + remove => _sessions.SessionDisconnected -= value; } - /// - /// Rejects inbound connections from IPs already seen within the filter window. - /// Primary outgoing endpoints are recorded by before ; - /// fallback endpoints are checked without mutation and recorded only after connecting. - /// + internal void TrackSessionActivity(Session session) => _sessions.Track(session); + + /// Closes an inbound connection that the dial policy does not accept. private bool ShouldRejectInbound(ISession session, IChannel channel, IPAddress? inboundRemoteIp) { if (session.Direction == ConnectionDirection.In && inboundRemoteIp is not null) { - if (!_privilegedIpProvider.IsPrivileged(inboundRemoteIp) && !_nodeFilter.TryAccept(inboundRemoteIp)) + if (!_dialPolicy.AcceptsInbound(inboundRemoteIp)) { if (_logger.IsTrace) _logger.Trace($"|NetworkTrace| Rejecting inbound connection from filtered IP {inboundRemoteIp:hide}"); _ = channel.CloseAsync(); @@ -580,20 +446,7 @@ internal static void AddTraceLoggingHandler(IChannelPipeline pipeline, string na } } - private void ActivateSession(IChannel channel, Session session) - { - TrackSessionActivity(session); - _sessionMonitor.AddSession(session); - - _ = channel.CloseCompletion.ContinueWith( - _onChannelCloseCompleted, - session, - CancellationToken.None, - TaskContinuationOptions.ExecuteSynchronously, - TaskScheduler.Default); - - SessionCreated?.Invoke(this, new SessionEventArgs(session)); - } + private void ActivateSession(IChannel channel, Session session) => _sessions.Activate(session, channel.CloseCompletion); private void SetTcpSocketOptions(IChannel channel) { @@ -626,31 +479,6 @@ private void DisconnectConnectedChannel(Task connectTask, object? _) _ = connectTask.Result.DisconnectAsync(); } - private void OnChannelCloseCompleted(Task _, object? state) - { - if (state is Session session) - { - session.MarkChannelClosed(); - } - - // The close completion is completed before actual closing or remaining packet is processed. - // So usually, we do get a disconnect reason from peer, we just receive it after this. So we need to - // add some delay to account for whatever is holding the network pipeline. - _ = Task.Delay(TimeSpan.FromSeconds(1), _shutdownCts?.Token ?? CancellationToken.None).ContinueWith( - _markDisconnectedAfterCloseDelay, - state, - CancellationToken.None, - TaskContinuationOptions.ExecuteSynchronously, - TaskScheduler.Default); - } - - private void MarkDisconnectedAfterCloseDelay(Task _, object? state) - { - ISession session = (ISession)state!; - if (_logger.IsTrace) _logger.Trace($"|NetworkTrace| {session:hide} channel disconnected"); - session.MarkDisconnected(DisconnectReason.ConnectionClosed, DisconnectType.Remote, "channel disconnected"); - } - Task IStoppableService.StopAsync() => Shutdown(); string IStoppableService.Description => "rlpx host"; @@ -697,48 +525,11 @@ public async Task Shutdown() await closingTask; } - // Sessions already disconnected during shutdown were removed by the activity observer. - foreach (KeyValuePair entry in _trackedSessions) - { - Session session = entry.Value; - try - { - session.MarkDisconnected(DisconnectReason.AppClosing, DisconnectType.Local, "shutdown"); - } - catch (InvalidOperationException e) - { - if (_logger.IsDebug) _logger.Debug($"Could not disconnect {session:hide} on shutdown: {e.Message}"); - } - } + _sessions.DisconnectRemaining(); if (_logger.IsInfo) _logger.Info("Local peer shutdown complete.. please wait for all components to close"); } - void ISessionActivityObserver.OnSessionActivity(Session session) - { - Node remoteNode = session.Node; - _nodeFilter.Touch(remoteNode.Address.Address, remoteNode.IsStatic || remoteNode.IsBootnode); - } - - void ISessionActivityObserver.OnSessionDisconnected(Session session, DisconnectEventArgs args) - { - if (!_trackedSessions.TryRemove(session.SessionId, out _)) - { - return; - } - - session.SetActivityObserver(null); - _sessionMonitor.RemoveSession(session); - try - { - SessionDisconnected?.Invoke(this, session, args); - } - finally - { - session.Dispose(); - } - } - private sealed class InboundChannelInitializer(RlpxHost rlpxHost) : ChannelInitializer { private readonly RlpxHost _rlpxHost = rlpxHost; diff --git a/src/Nethermind/Nethermind.Network/Rlpx/RlpxListener.cs b/src/Nethermind/Nethermind.Network/Rlpx/RlpxListener.cs new file mode 100644 index 000000000000..64b377fe0d40 --- /dev/null +++ b/src/Nethermind/Nethermind.Network/Rlpx/RlpxListener.cs @@ -0,0 +1,63 @@ +// SPDX-FileCopyrightText: 2026 Demerzel Solutions Limited +// SPDX-License-Identifier: LGPL-3.0-only + +using System; +using System.Net; +using System.Net.Sockets; +using System.Threading.Tasks; +using Nethermind.Logging; +using Nethermind.Network.Discovery; + +namespace Nethermind.Network.Rlpx; + +/// +/// Binds the listener of an RLPx host. +/// +/// Shared by the RLPx hosts, so that each one owns only its transport. +internal static class RlpxListener +{ + /// Binds on the preferred address, or on the fallback address if that fails. + /// The addresses to bind on. + /// The port to bind on, for the log. + /// The host's logger. + /// The host's name, for the log. + /// Binds the listener on an address. + public static async Task BindAsync(NetworkListenerState listenerState, int port, ILogger logger, string hostName, Func> bind) + { + IPAddress bindAddress = listenerState.PreferredAddress; + try + { + return await bind(bindAddress); + } + catch (Exception e) when (!bindAddress.Equals(listenerState.FallbackAddress)) + { + if (logger.IsWarn) logger.Warn($"Failed to bind {hostName} on {bindAddress:hide}:{port:hide}. Retrying on {listenerState.FallbackAddress:hide}:{port:hide}. {e:hide}"); + return await bind(listenerState.FallbackAddress); + } + } + + /// Creates a listener socket for an address, dual mode when the address and the host allow it. + public static Socket CreateSocket(IPAddress address) + { + Socket socket = new(address.AddressFamily, SocketType.Stream, ProtocolType.Tcp); + try + { + if (address.AddressFamily == AddressFamily.InterNetworkV6) + { + socket.DualMode = DiscoveryAddressSupport.SupportsFamily(address, AddressFamily.InterNetwork); + if (socket.DualMode) + { + // A dual-mode bind must not share its IPv4 port, or the advertised capability is ambiguous. + socket.ExclusiveAddressUse = true; + } + } + + return socket; + } + catch + { + socket.Dispose(); + throw; + } + } +} diff --git a/src/Nethermind/Nethermind.Network/Rlpx/RlpxSessionTracker.cs b/src/Nethermind/Nethermind.Network/Rlpx/RlpxSessionTracker.cs new file mode 100644 index 000000000000..9cb2bbd60986 --- /dev/null +++ b/src/Nethermind/Nethermind.Network/Rlpx/RlpxSessionTracker.cs @@ -0,0 +1,140 @@ +// SPDX-FileCopyrightText: 2026 Demerzel Solutions Limited +// SPDX-License-Identifier: LGPL-3.0-only + +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using Nethermind.Logging; +using Nethermind.Network.P2P; +using Nethermind.Network.P2P.EventArg; +using Nethermind.Stats.Model; + +namespace Nethermind.Network.Rlpx; + +/// +/// Tracks the sessions of an RLPx host from activation until they disconnect, and raises the host's session events. +/// +/// Shared by the RLPx hosts, so that each one owns only its transport. +internal sealed class RlpxSessionTracker : ISessionActivityObserver +{ + private readonly object _host; + private readonly ISessionMonitor _sessionMonitor; + private readonly RlpxDialPolicy _dialPolicy; + private readonly ILogger _logger; + private readonly Func _shutdownToken; + private readonly ConcurrentDictionary _trackedSessions = new(); + private readonly Action _onConnectionClosed; + private readonly Action _markDisconnectedAfterCloseDelay; + + /// The host, as the sender of the session events. + /// The monitor that pings the active sessions. + /// The policy whose filter a session's activity refreshes. + /// The host's logger. + /// Gets the token that is canceled when the host shuts down. + public RlpxSessionTracker(object host, ISessionMonitor sessionMonitor, RlpxDialPolicy dialPolicy, ILogger logger, Func shutdownToken) + { + _host = host; + _sessionMonitor = sessionMonitor; + _dialPolicy = dialPolicy; + _logger = logger; + _shutdownToken = shutdownToken; + _onConnectionClosed = OnConnectionClosed; + _markDisconnectedAfterCloseDelay = MarkDisconnectedAfterCloseDelay; + } + + public event EventHandler? SessionCreated; + + public event SessionDisconnectedEventHandler? SessionDisconnected; + + /// Starts tracking a session's activity and disconnect. + public void Track(Session session) + { + ArgumentNullException.ThrowIfNull(session); + _trackedSessions[session.SessionId] = session; + session.SetActivityObserver(this); + } + + /// Publishes a session whose connection is open, and marks it disconnected once the connection closes. + /// The session. + /// Completes when the session's connection has closed. + public void Activate(Session session, Task connectionClosed) + { + Track(session); + _sessionMonitor.AddSession(session); + + _ = connectionClosed.ContinueWith( + _onConnectionClosed, + session, + CancellationToken.None, + TaskContinuationOptions.ExecuteSynchronously, + TaskScheduler.Default); + + SessionCreated?.Invoke(_host, new SessionEventArgs(session)); + } + + /// Marks the sessions still tracked at shutdown as disconnected. + /// Sessions already disconnected during shutdown were removed by the activity observer. + public void DisconnectRemaining() + { + foreach (KeyValuePair entry in _trackedSessions) + { + Session session = entry.Value; + try + { + session.MarkDisconnected(DisconnectReason.AppClosing, DisconnectType.Local, "shutdown"); + } + catch (InvalidOperationException e) + { + if (_logger.IsDebug) _logger.Debug($"Could not disconnect {session:hide} on shutdown: {e.Message}"); + } + } + } + + private void OnConnectionClosed(Task _, object? state) + { + if (state is Session session) + { + session.MarkChannelClosed(); + } + + // The close completion is completed before actual closing or remaining packet is processed. + // So usually, we do get a disconnect reason from peer, we just receive it after this. So we need to + // add some delay to account for whatever is holding the network pipeline. + _ = Task.Delay(TimeSpan.FromSeconds(1), _shutdownToken()).ContinueWith( + _markDisconnectedAfterCloseDelay, + state, + CancellationToken.None, + TaskContinuationOptions.ExecuteSynchronously, + TaskScheduler.Default); + } + + private void MarkDisconnectedAfterCloseDelay(Task _, object? state) + { + ISession session = (ISession)state!; + if (_logger.IsTrace) _logger.Trace($"|NetworkTrace| {session:hide} channel disconnected"); + session.MarkDisconnected(DisconnectReason.ConnectionClosed, DisconnectType.Remote, "channel disconnected"); + } + + void ISessionActivityObserver.OnSessionActivity(Session session) => _dialPolicy.OnSessionActivity(session.Node); + + void ISessionActivityObserver.OnSessionDisconnected(Session session, DisconnectEventArgs args) + { + if (!_trackedSessions.TryRemove(session.SessionId, out _)) + { + return; + } + + session.SetActivityObserver(null); + _sessionMonitor.RemoveSession(session); + try + { + SessionDisconnected?.Invoke(_host, session, args); + } + finally + { + session.Dispose(); + } + } +} From ece687db30e18cb34c463948a8a464e8f0fe36b2 Mon Sep 17 00:00:00 2001 From: Ruben Buniatyan <337518+rubo@users.noreply.github.com> Date: Thu, 26 Nov 2026 22:02:03 +0100 Subject: [PATCH 02/22] feat(network): add an opt-in RLPx transport on sockets and System.IO.Pipelines Network.RlpxTransport (hidden, DotNetty by default) selects SocketRlpxHost, which runs RLPx sessions without DotNetty. It shares the dial, filter and session policy with RlpxHost, and the frame codec with the DotNetty handlers. Each connection runs three loops. A receive loop fills a pipe from the socket, waiting for data before it rents a buffer. A frame loop reads the pipe: the handshake, then frames, which it authenticates, decrypts block by block into a rented buffer and merges into packets. A send loop encodes the queued packets in batches and writes them to the socket. Each direction has its own cipher and MAC instances. Received packets are handled on ProcessingThreadCount dedicated threads, each connection pinned to one, with one FIFO per thread, as on DotNetty's executor group: the size limit, Snappy, ReceiveMessage and the error handling, in the order the frame loop queued them. A packet's queue position, Snappy mode and writability charge are fixed when it is queued, so a Hello queued before Snappy is enabled stays framed. The connection is the one owner of writability, with DotNetty's watermarks. --- .../Nethermind.Init/Modules/NetworkModule.cs | 11 +- .../Config/INetworkConfig.cs | 3 + .../Config/RlpxTransport.cs | 16 + .../Config/NetworkConfig.cs | 1 + .../Rlpx/Sockets/RlpxTransportInteropTests.cs | 168 +++ .../P2P/RlpxErrorHandler.cs | 3 +- .../Nethermind.Network/Rlpx/RlpxHost.cs | 1 - .../Rlpx/Sockets/IRlpxSocket.cs | 43 + .../Rlpx/Sockets/PooledPacket.cs | 83 ++ .../Rlpx/Sockets/RlpxProcessingThreads.cs | 116 ++ .../Rlpx/Sockets/RlpxReadTimeoutException.cs | 11 + .../Rlpx/Sockets/SocketRlpxConnection.cs | 1186 +++++++++++++++++ .../Rlpx/Sockets/SocketRlpxHost.cs | 474 +++++++ 13 files changed, 2113 insertions(+), 3 deletions(-) create mode 100644 src/Nethermind/Nethermind.Network.Contract/Config/RlpxTransport.cs create mode 100644 src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/RlpxTransportInteropTests.cs create mode 100644 src/Nethermind/Nethermind.Network/Rlpx/Sockets/IRlpxSocket.cs create mode 100644 src/Nethermind/Nethermind.Network/Rlpx/Sockets/PooledPacket.cs create mode 100644 src/Nethermind/Nethermind.Network/Rlpx/Sockets/RlpxProcessingThreads.cs create mode 100644 src/Nethermind/Nethermind.Network/Rlpx/Sockets/RlpxReadTimeoutException.cs create mode 100644 src/Nethermind/Nethermind.Network/Rlpx/Sockets/SocketRlpxConnection.cs create mode 100644 src/Nethermind/Nethermind.Network/Rlpx/Sockets/SocketRlpxHost.cs diff --git a/src/Nethermind/Nethermind.Init/Modules/NetworkModule.cs b/src/Nethermind/Nethermind.Init/Modules/NetworkModule.cs index f627bd51ab86..5cff0dcc03b6 100644 --- a/src/Nethermind/Nethermind.Init/Modules/NetworkModule.cs +++ b/src/Nethermind/Nethermind.Init/Modules/NetworkModule.cs @@ -16,6 +16,7 @@ using Nethermind.Network.P2P.Analyzers; using Nethermind.Network.P2P.ProtocolHandlers; using Nethermind.Network.Rlpx; +using Nethermind.Network.Rlpx.Sockets; using Nethermind.Serialization.Rlp; using Nethermind.Stats; using Nethermind.Synchronization.ParallelSync; @@ -63,7 +64,6 @@ protected override void Load(ContainerBuilder builder) .AddSingleton() .AddSingleton() .AddSingleton() - .AddSingleton() .AddSingleton() .AddSingleton(ctx => new NodeStatsManager( @@ -183,6 +183,15 @@ protected override void Load(ContainerBuilder builder) .AddProtocolHandler() ; + + if (configProvider.GetConfig().RlpxTransport == RlpxTransport.Sockets) + { + builder.AddSingleton(); + } + else + { + builder.AddSingleton(); + } } private sealed class TxGossipPolicySource(ILifetimeScope lifetimeScope) : ITxGossipPolicySource diff --git a/src/Nethermind/Nethermind.Network.Contract/Config/INetworkConfig.cs b/src/Nethermind/Nethermind.Network.Contract/Config/INetworkConfig.cs index bb00e912c7b9..c1c71061e8be 100644 --- a/src/Nethermind/Nethermind.Network.Contract/Config/INetworkConfig.cs +++ b/src/Nethermind/Nethermind.Network.Contract/Config/INetworkConfig.cs @@ -132,6 +132,9 @@ public interface INetworkConfig : IConfig [ConfigItem(DefaultValue = "1", HiddenFromDocs = true, Description = "[TECHNICAL] Num of thread in final processing of network packet. Set to more than 1 if you have very fast internet.")] int ProcessingThreadCount { get; set; } + [ConfigItem(DefaultValue = "DotNetty", HiddenFromDocs = true, Description = "[TECHNICAL] The RLPx transport: `DotNetty`, or the experimental `Sockets` on System.IO.Pipelines.")] + RlpxTransport RlpxTransport { get; set; } + [ConfigItem(DefaultValue = null, HiddenFromDocs = true, Description = "[TECHNICAL] Only allow peer with clientId matching this regex. Useful for testing. eg: 'besu' to only connect to BeSU")] string? ClientIdMatcher { get; set; } diff --git a/src/Nethermind/Nethermind.Network.Contract/Config/RlpxTransport.cs b/src/Nethermind/Nethermind.Network.Contract/Config/RlpxTransport.cs new file mode 100644 index 000000000000..58b1692c0884 --- /dev/null +++ b/src/Nethermind/Nethermind.Network.Contract/Config/RlpxTransport.cs @@ -0,0 +1,16 @@ +// SPDX-FileCopyrightText: 2026 Demerzel Solutions Limited +// SPDX-License-Identifier: LGPL-3.0-only + +namespace Nethermind.Network.Config; + +/// +/// The transport that RLPx connections run on. +/// +public enum RlpxTransport +{ + /// DotNetty channels. + DotNetty, + + /// Sockets and System.IO.Pipelines, without DotNetty. + Sockets +} diff --git a/src/Nethermind/Nethermind.Network.Core/Config/NetworkConfig.cs b/src/Nethermind/Nethermind.Network.Core/Config/NetworkConfig.cs index 0376b695d43e..39b496bbd6cf 100644 --- a/src/Nethermind/Nethermind.Network.Core/Config/NetworkConfig.cs +++ b/src/Nethermind/Nethermind.Network.Core/Config/NetworkConfig.cs @@ -50,6 +50,7 @@ public class NetworkConfig : INetworkConfig public int MaxOutgoingConnectPerSec { get; set; } = 20; public int ConnectTimeoutMs { get; set; } = 2000; public int ProcessingThreadCount { get; set; } = 1; + public RlpxTransport RlpxTransport { get; set; } = RlpxTransport.DotNetty; public string? ClientIdMatcher { get; set; } = null; public bool DisableDiscV4DnsFeeder { get; set; } = false; public long RlpxHostShutdownCloseTimeoutMs { get; set; } = 1000; diff --git a/src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/RlpxTransportInteropTests.cs b/src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/RlpxTransportInteropTests.cs new file mode 100644 index 000000000000..a3ff169d8a60 --- /dev/null +++ b/src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/RlpxTransportInteropTests.cs @@ -0,0 +1,168 @@ +// SPDX-FileCopyrightText: 2026 Demerzel Solutions Limited +// SPDX-License-Identifier: LGPL-3.0-only + +using System; +using System.Linq; +using System.Net; +using System.Net.Sockets; +using System.Threading; +using System.Threading.Tasks; +using Autofac; +using Nethermind.Blockchain; +using Nethermind.Blockchain.Synchronization; +using Nethermind.Config; +using Nethermind.Core; +using Nethermind.Core.Collections; +using Nethermind.Core.Crypto; +using Nethermind.Core.Specs; +using Nethermind.Core.Test.Builders; +using Nethermind.Core.Test.Modules; +using Nethermind.Crypto; +using Nethermind.Logging; +using Nethermind.Network.Config; +using Nethermind.Network.P2P; +using Nethermind.Network.P2P.EventArg; +using Nethermind.Network.Rlpx; +using Nethermind.Specs; +using Nethermind.Specs.ChainSpecStyle; +using Nethermind.Specs.Forks; +using Nethermind.Stats.Model; +using Nethermind.Synchronization.Peers; +using NUnit.Framework; + +namespace Nethermind.Network.Test.Rlpx.Sockets; + +/// +/// Connects two nodes over loopback TCP, each on a chosen RLPx transport, so the socket transport is checked against +/// DotNetty on the wire: the handshake, Hello and Snappy, requests in both directions, and a disconnect. +/// +[Parallelizable(ParallelScope.None)] +public class RlpxTransportInteropTests +{ + private const int BlockCount = 4; + private const int TransactionsPerBlock = 20; + private const int TransactionDataSize = 512; + private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(30); + + [TestCase(RlpxTransport.DotNetty, RlpxTransport.Sockets)] + [TestCase(RlpxTransport.Sockets, RlpxTransport.DotNetty)] + [TestCase(RlpxTransport.Sockets, RlpxTransport.Sockets)] + public async Task Nodes_exchange_messages_and_deliver_a_disconnect_reason(RlpxTransport serverTransport, RlpxTransport clientTransport) + { + using CancellationTokenSource cancellation = new(Timeout); + IContainer server = CreateNode(TestItem.PrivateKeyA, serverTransport); + IContainer client = CreateNode(TestItem.PrivateKeyB, clientTransport); + try + { + await StartNetwork(server); + Hash256[] blockHashes = StoreChain(server); + await StartNetwork(client); + + TaskCompletionSource clientSessionCreated = new(TaskCreationOptions.RunContinuationsAsynchronously); + client.Resolve().SessionCreated += (_, args) => clientSessionCreated.TrySetResult(args.Session); + TaskCompletionSource serverDisconnected = new(TaskCreationOptions.RunContinuationsAsynchronously); + server.Resolve().SessionDisconnected += (_, _, args) => serverDisconnected.TrySetResult(args); + + IEnode serverEnode = server.Resolve(); + Node serverNode = new(serverEnode.PublicKey, new IPEndPoint(serverEnode.HostIp, serverEnode.Port)); + Assert.That(await client.Resolve().ConnectAsync(serverNode, cancellation.Token), Is.True); + + ISyncPeer serverPeer = await WaitForPeer(client.Resolve(), cancellation.Token); + using OwnedBlockBodies bodies = await serverPeer.GetBlockBodies(blockHashes, cancellation.Token); + Assert.That(bodies.Bodies.Select(static body => body?.Transactions.Length), Is.All.EqualTo(TransactionsPerBlock)); + + ISession clientSession = await clientSessionCreated.Task.WaitAsync(cancellation.Token); + clientSession.InitiateDisconnect(DisconnectReason.TooManyPeers, "interop test"); + DisconnectEventArgs disconnect = await serverDisconnected.Task.WaitAsync(cancellation.Token); + using (Assert.EnterMultipleScope()) + { + Assert.That(disconnect.DisconnectType, Is.EqualTo(DisconnectType.Remote)); + Assert.That(disconnect.Details, Is.EqualTo("message"), "the peer's Disconnect message must arrive before the connection closes"); + } + } + finally + { + foreach (IContainer node in (IContainer[])[client, server]) + { + await node.Resolve().Shutdown(); + await node.DisposeAsync(); + } + } + } + + private static IContainer CreateNode(PrivateKey nodeKey, RlpxTransport transport) + { + ConfigProvider configProvider = new( + new NetworkConfig { P2PPort = GetAvailablePort(), FilterPeersByRecentIp = false, RlpxTransport = transport }, + new SyncConfig()); + + ChainSpec chainSpec = new() + { + Parameters = new ChainParameters(), + Allocations = [], + Genesis = Build.A.Block.WithBlobGasUsed(0).TestObject + }; + + return new ContainerBuilder() + .AddModule(new PseudoNethermindModule(chainSpec, configProvider, LimboLogs.Instance)) + .AddModule(new TestEnvironmentModule(nodeKey, null) { InMemoryNetwork = false }) + .AddSingleton(new TestSpecProvider(Osaka.Instance)) + .Build(); + } + + private static async Task StartNetwork(IContainer node) + { + await node.Resolve().StartBlockProcessing(CancellationToken.None); + node.Resolve(); + await node.Resolve().Init(); + node.Resolve().Start(); + } + + /// Stores blocks whose bodies span several frames, without processing them. + private static Hash256[] StoreChain(IContainer node) + { + IBlockTree blockTree = node.Resolve(); + IEthereumEcdsa ecdsa = node.Resolve(); + Random random = new(42); + Hash256[] hashes = new Hash256[BlockCount]; + Block parent = blockTree.Head!; + ulong nonce = 0; + for (int i = 0; i < BlockCount; i++) + { + Transaction[] transactions = new Transaction[TransactionsPerBlock]; + for (int j = 0; j < TransactionsPerBlock; j++) + { + byte[] data = new byte[TransactionDataSize]; + random.NextBytes(data); + transactions[j] = Build.A.Transaction.WithNonce(nonce++).WithData(data).SignedAndResolved(ecdsa, TestItem.PrivateKeyC).TestObject; + } + + Block block = Build.A.Block.WithParent(parent).WithTransactions(transactions).TestObject; + Assert.That(blockTree.SuggestBlock(block, BlockTreeSuggestOptions.None), Is.EqualTo(AddBlockResult.Added)); + hashes[i] = block.Hash!; + parent = block; + } + + return hashes; + } + + private static async Task WaitForPeer(ISyncPeerPool syncPeerPool, CancellationToken cancellationToken) + { + while (true) + { + if (syncPeerPool.AllPeers.FirstOrDefault() is { } peer) + { + return peer.SyncPeer; + } + + await Task.Delay(10, cancellationToken); + } + } + + private static int GetAvailablePort() + { + using TcpListener listener = new(IPAddress.Loopback, 0); + listener.Start(); + return ((IPEndPoint)listener.LocalEndpoint).Port; + } +} diff --git a/src/Nethermind/Nethermind.Network/P2P/RlpxErrorHandler.cs b/src/Nethermind/Nethermind.Network/P2P/RlpxErrorHandler.cs index ec7488eaf2bc..7140616af7c8 100644 --- a/src/Nethermind/Nethermind.Network/P2P/RlpxErrorHandler.cs +++ b/src/Nethermind/Nethermind.Network/P2P/RlpxErrorHandler.cs @@ -7,6 +7,7 @@ using DotNetty.Handlers.Timeout; using Nethermind.Core.Exceptions; using Nethermind.Logging; +using Nethermind.Network.Rlpx.Sockets; using Nethermind.Serialization.FluentRlp; using Nethermind.Stats.Model; @@ -26,7 +27,7 @@ internal static class RlpxErrorHandler /// public static bool TryHandle(ISession session, Exception exception, ILogger logger) { - if (exception is SocketException or RlpReaderException or ReadTimeoutException) + if (exception is SocketException or RlpReaderException or ReadTimeoutException or RlpxReadTimeoutException) { if (logger.IsTrace) TraceCommunicationError(session, exception, logger); } diff --git a/src/Nethermind/Nethermind.Network/Rlpx/RlpxHost.cs b/src/Nethermind/Nethermind.Network/Rlpx/RlpxHost.cs index fcf4a45ff5b1..2cc407f09426 100644 --- a/src/Nethermind/Nethermind.Network/Rlpx/RlpxHost.cs +++ b/src/Nethermind/Nethermind.Network/Rlpx/RlpxHost.cs @@ -21,7 +21,6 @@ using Nethermind.Core.ServiceStopper; using Nethermind.Logging; using Nethermind.Network.Config; -using Nethermind.Network.Enr; using Nethermind.Network.P2P; using Nethermind.Network.P2P.Analyzers; using Nethermind.Network.Rlpx.Handshake; diff --git a/src/Nethermind/Nethermind.Network/Rlpx/Sockets/IRlpxSocket.cs b/src/Nethermind/Nethermind.Network/Rlpx/Sockets/IRlpxSocket.cs new file mode 100644 index 000000000000..9c04cb63451a --- /dev/null +++ b/src/Nethermind/Nethermind.Network/Rlpx/Sockets/IRlpxSocket.cs @@ -0,0 +1,43 @@ +// SPDX-FileCopyrightText: 2026 Demerzel Solutions Limited +// SPDX-License-Identifier: LGPL-3.0-only + +using System; +using System.Net.Sockets; +using System.Threading; +using System.Threading.Tasks; + +namespace Nethermind.Network.Rlpx.Sockets; + +/// +/// The byte stream an RLPx connection runs on. +/// +/// A seam for tests, which need short sends, held reads and injected errors that a real socket can't produce on demand. +internal interface IRlpxSocket : IDisposable +{ + /// Receives into ; an empty buffer waits for data without taking any. + /// The number of bytes received, or zero at the end of the stream for a non-empty buffer. + ValueTask ReceiveAsync(Memory buffer, CancellationToken cancellationToken); + + /// Sends some or all of . + /// The number of bytes sent, which may be fewer than requested. + ValueTask SendAsync(ReadOnlyMemory buffer, CancellationToken cancellationToken); + + /// Stops both directions and releases the socket. + void Close(); +} + +/// An over a connected TCP socket. +internal sealed class TcpRlpxSocket(Socket socket) : IRlpxSocket +{ + public Socket Socket { get; } = socket; + + public ValueTask ReceiveAsync(Memory buffer, CancellationToken cancellationToken) + => Socket.ReceiveAsync(buffer, SocketFlags.None, cancellationToken); + + public ValueTask SendAsync(ReadOnlyMemory buffer, CancellationToken cancellationToken) + => Socket.SendAsync(buffer, SocketFlags.None, cancellationToken); + + public void Close() => Socket.Dispose(); + + public void Dispose() => Socket.Dispose(); +} diff --git a/src/Nethermind/Nethermind.Network/Rlpx/Sockets/PooledPacket.cs b/src/Nethermind/Nethermind.Network/Rlpx/Sockets/PooledPacket.cs new file mode 100644 index 000000000000..64158f102bc1 --- /dev/null +++ b/src/Nethermind/Nethermind.Network/Rlpx/Sockets/PooledPacket.cs @@ -0,0 +1,83 @@ +// SPDX-FileCopyrightText: 2026 Demerzel Solutions Limited +// SPDX-License-Identifier: LGPL-3.0-only + +using System; +using System.Buffers; +using System.Diagnostics; +using System.Threading; + +namespace Nethermind.Network.Rlpx.Sockets; + +/// +/// A received packet over an array rented from , which goes back to the pool when the +/// last reference is released. +/// +/// +/// The transport holds one reference and releases it once the session has handled the packet. Each +/// adds a reference, so a serializer that keeps the content needs no copy. +/// +/// A rented array, which the packet now owns. +/// Where the content starts. +/// The length of the content. +internal sealed class PooledPacket(byte[] buffer, int offset, int length) : ZeroPacket +{ + private byte[] _buffer = buffer; + private int _offset = offset; + private int _length = length; + private int _references = 1; + + public override Memory Content => _buffer.AsMemory(_offset, _length); + + /// Gets the rented array, for writing the content while the transport holds the only reference. + public byte[] Buffer => _buffer; + + /// Gets whether the transport holds the only reference, so it can reuse the buffer. + public bool IsExclusive => Volatile.Read(ref _references) == 1; + + public override IMemoryOwner LeaseContent() + { + Interlocked.Increment(ref _references); + return new Lease(this); + } + + /// Sets the content to a range of the buffer, while the transport holds the only reference. + public void SetContent(int offset, int length) + { + Debug.Assert(IsExclusive, "Only an unshared packet can be rewritten."); + _offset = offset; + _length = length; + } + + /// Replaces the buffer with a larger rented one that keeps the content, while the transport holds the only reference. + public void Grow(int capacity) + { + Debug.Assert(IsExclusive, "Only an unshared packet can be rewritten."); + byte[] buffer = ArrayPool.Shared.Rent(capacity); + _buffer.AsSpan(_offset, _length).CopyTo(buffer); + ArrayPool.Shared.Return(_buffer); + _buffer = buffer; + _offset = 0; + } + + /// Releases a reference, returning the buffer to the pool when it was the last one. + public void Release() + { + int references = Interlocked.Decrement(ref _references); + Debug.Assert(references >= 0, "A packet was released more times than it was referenced."); + if (references == 0) + { + ArrayPool.Shared.Return(_buffer); + _buffer = []; + } + } + + private sealed class Lease(PooledPacket packet) : IMemoryOwner + { + private PooledPacket? _packet = packet; + private readonly Memory _memory = packet.Content; + + public Memory Memory => _packet is null ? throw new ObjectDisposedException(nameof(Lease)) : _memory; + + public void Dispose() => Interlocked.Exchange(ref _packet, null)?.Release(); + } +} diff --git a/src/Nethermind/Nethermind.Network/Rlpx/Sockets/RlpxProcessingThreads.cs b/src/Nethermind/Nethermind.Network/Rlpx/Sockets/RlpxProcessingThreads.cs new file mode 100644 index 000000000000..2c1ac02d5c6e --- /dev/null +++ b/src/Nethermind/Nethermind.Network/Rlpx/Sockets/RlpxProcessingThreads.cs @@ -0,0 +1,116 @@ +// SPDX-FileCopyrightText: 2026 Demerzel Solutions Limited +// SPDX-License-Identifier: LGPL-3.0-only + +using System; +using System.Threading; +using System.Threading.Channels; +using System.Threading.Tasks; +using Nethermind.Logging; + +namespace Nethermind.Network.Rlpx.Sockets; + +/// +/// Dedicated threads that handle what RLPx connections receive, each connection on one of them. +/// +/// +/// As the DotNetty executor group of , each thread has one FIFO shared by its connections, so a +/// connection's items run in order and, with a single thread, every peer's messages are handled one at a time. +/// +internal sealed class RlpxProcessingThreads +{ + private readonly ProcessingThread[] _threads; + private int _next = -1; + + /// The number of threads; values of 1 or less mean one, as for the DotNetty executor group. + /// Logs an item that fails unexpectedly. + public RlpxProcessingThreads(int count, ILogger logger) + { + _threads = new ProcessingThread[Math.Max(1, count)]; + for (int i = 0; i < _threads.Length; i++) + { + _threads[i] = new ProcessingThread(i, logger); + } + } + + /// Picks the thread for a new connection, in turn. + public ProcessingThread Next() => _threads[(uint)Interlocked.Increment(ref _next) % (uint)_threads.Length]; + + /// Stops taking items, lets every thread finish the items it has, and completes when all have exited. + public Task StopAsync() + { + Task[] stopped = new Task[_threads.Length]; + for (int i = 0; i < _threads.Length; i++) + { + stopped[i] = _threads[i].StopAsync(); + } + + return Task.WhenAll(stopped); + } + + internal sealed class ProcessingThread + { + private readonly Channel _queue = Channel.CreateUnbounded(new UnboundedChannelOptions { SingleReader = true }); + private readonly TaskCompletionSource _exited = new(TaskCreationOptions.RunContinuationsAsynchronously); + private readonly ILogger _logger; + private readonly Thread _thread; + + public ProcessingThread(int index, ILogger logger) + { + _logger = logger; + _thread = new Thread(Run) { IsBackground = true, Name = $"RLPx processing {index}" }; + _thread.Start(); + } + + /// Queues an item behind those already queued. + /// once the thread has stopped taking items: the caller still owns the item. + public bool TryEnqueue(in ProcessingItem item) => _queue.Writer.TryWrite(item); + + public Task StopAsync() + { + _queue.Writer.TryComplete(); + return _exited.Task; + } + + private void Run() + { + ChannelReader reader = _queue.Reader; + try + { + while (true) + { + while (reader.TryRead(out ProcessingItem item)) + { + try + { + item.Connection.Process(in item); + } + catch (Exception e) + { + if (_logger.IsError) _logger.Error($"Unexpected failure while handling a received packet on {_thread.Name}", e); + } + } + + ValueTask waiting = reader.WaitToReadAsync(); + if (!(waiting.IsCompletedSuccessfully ? waiting.Result : waiting.AsTask().GetAwaiter().GetResult())) + { + break; + } + } + } + finally + { + _exited.TrySetResult(); + } + } + } +} + +/// What a connection hands its processing thread: a received packet, an error to classify, or the final cleanup. +internal readonly struct ProcessingItem(SocketRlpxConnection connection, PooledPacket? packet, Exception? error) +{ + public SocketRlpxConnection Connection { get; } = connection; + + public PooledPacket? Packet { get; } = packet; + + public Exception? Error { get; } = error; +} diff --git a/src/Nethermind/Nethermind.Network/Rlpx/Sockets/RlpxReadTimeoutException.cs b/src/Nethermind/Nethermind.Network/Rlpx/Sockets/RlpxReadTimeoutException.cs new file mode 100644 index 000000000000..796b2ed6515d --- /dev/null +++ b/src/Nethermind/Nethermind.Network/Rlpx/Sockets/RlpxReadTimeoutException.cs @@ -0,0 +1,11 @@ +// SPDX-FileCopyrightText: 2026 Demerzel Solutions Limited +// SPDX-License-Identifier: LGPL-3.0-only + +using System; + +namespace Nethermind.Network.Rlpx.Sockets; + +/// +/// Reports a connection on which nothing was received for the read timeout. +/// +internal sealed class RlpxReadTimeoutException() : Exception("No data received within the read timeout"); diff --git a/src/Nethermind/Nethermind.Network/Rlpx/Sockets/SocketRlpxConnection.cs b/src/Nethermind/Nethermind.Network/Rlpx/Sockets/SocketRlpxConnection.cs new file mode 100644 index 000000000000..f23e67bab6dd --- /dev/null +++ b/src/Nethermind/Nethermind.Network/Rlpx/Sockets/SocketRlpxConnection.cs @@ -0,0 +1,1186 @@ +// SPDX-FileCopyrightText: 2026 Demerzel Solutions Limited +// SPDX-License-Identifier: LGPL-3.0-only + +using System; +using System.Buffers; +using System.Buffers.Binary; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO.Pipelines; +using System.Net.Sockets; +using System.Runtime.CompilerServices; +using System.Threading; +using System.Threading.Tasks; +using Nethermind.Core.Exceptions; +using Nethermind.Logging; +using Nethermind.Network.P2P; +using Nethermind.Network.P2P.Messages; +using Nethermind.Network.Rlpx.Handshake; +using Nethermind.Serialization.FluentRlp; +using Nethermind.Serialization.Rlp; +using Nethermind.Stats.Model; + +namespace Nethermind.Network.Rlpx.Sockets; + +/// +/// An RLPx connection on a socket: the handshake, the frames in both directions, and the session's packets. +/// +/// +/// +/// Three loops run per connection. The receive loop fills a pipe from the socket. The frame loop reads the pipe: the +/// handshake, then frames, which it authenticates, decrypts and merges into packets for the connection's processing +/// thread. The send loop encodes the queued packets and writes them to the socket. Each direction has its own cipher +/// and MAC instances, so the two loops never share crypto state. +/// +/// +/// The processing thread runs what ZeroNettyP2PHandler runs on DotNetty's executor: the size limit, Snappy and +/// , and the error handling, in the order the frame loop queued them. +/// +/// +/// The connected socket. +/// Whether this side dialed the peer. +/// Builds and reads the handshake messages. +/// Serializes the session's messages. +/// The thread that handles what the connection receives. +/// The log manager. +/// The simulated latency of every packet sent, for tests and benchmarks. +/// The largest frame payload accepted. +internal sealed class SocketRlpxConnection( + IRlpxSocket socket, + HandshakeRole role, + IHandshakeService handshakeService, + IMessageSerializationService serializationService, + RlpxProcessingThreads.ProcessingThread processingThread, + ILogManager logManager, + TimeSpan sendLatency, + int maxInboundFrameSize) : IRlpxConnection, IPacketSender +{ + /// The outbound bytes at which the connection stops taking packets: the watermark gives DotNetty. + internal const long WriteBufferHighWaterMark = 3_000_000; + + /// The outbound bytes at which a connection that stopped taking packets takes them again. + internal const long WriteBufferLowWaterMark = 1_000_000; + + /// The largest handshake message, with its 2-byte size prefix, as DotNetty's length field decoder allows. + internal const int MaxHandshakeLength = ushort.MaxValue; + + internal static readonly TimeSpan ReadTimeout = TimeSpan.FromSeconds(30); + + private const int ReceiveSegmentSize = 16 * 1024; + private const int SendBatchSize = 64 * 1024; + private const int MaxRetainedSnappyOutputCapacity = 64 * 1024; + + private readonly IRlpxSocket _socket = socket; + private readonly HandshakeRole _role = role; + private readonly IHandshakeService _handshakeService = handshakeService; + private readonly IMessageSerializationService _serializationService = serializationService; + private readonly RlpxProcessingThreads.ProcessingThread _processingThread = processingThread; + private readonly ILogger _logger = logManager.GetClassLogger(); + private readonly long _sendLatencyMs = (long)sendLatency.TotalMilliseconds; + private readonly int _maxInboundFrameSize = maxInboundFrameSize; + private readonly Pipe _pipe = new(new PipeOptions( + pauseWriterThreshold: 1_000_000, + resumeWriterThreshold: 500_000, + minimumSegmentSize: ReceiveSegmentSize, + useSynchronizationContext: false)); + private readonly CancellationTokenSource _receiveCancellation = new(); + private readonly CancellationTokenSource _sendCancellation = new(); + private readonly TaskCompletionSource _closed = new(TaskCreationOptions.RunContinuationsAsynchronously); + private Session _session = null!; + private Task _completion = Task.CompletedTask; + private volatile bool _isClosed; + + // Receive loop + private Exception? _terminalCause; + private long _lastReceive; + private volatile bool _readTimedOut; + private Timer? _idleTimer; + + // Frame loop + private FrameDecoder? _decoder; + private readonly FrameMerger _merger = new(); + private FrameState _frameState; + private byte[]? _frame; + private int _frameSize; + private int _frameFilled; + private PooledPacket? _chunkedPacket; + private int _chunkedPacketTotal; + private bool _handshakeCompleted; + private bool _discarding; + + // Processing thread + private volatile bool _inboundSnappy; + private PooledPacket? _snappyOutput; + private bool _processingStopped; + private readonly SnappyOutputWriter _snappyOutputWriter = new(); + + // Send queue, under _sendLock + private readonly Lock _sendLock = new(); + private readonly Queue _sendQueue = new(); + private readonly SemaphoreSlim _sendSignal = new(0); + private bool _sendLoopWaiting; + private FrameEncoder? _encoder; + private FrameEncoder.EncodingMode _encodingMode = FrameEncoder.EncodingMode.Framed; + private long _pendingBytes; + private volatile bool _writable = true; + + /// Completes when the connection has closed, before the frames already received are handled. + public Task Closed => _closed.Task; + + /// Completes when the connection's loops have finished. + public Task Completion => _completion; + + public bool IsWritable => _writable; + + /// Starts the handshake and the loops of a connection whose session has been created. + public void Start(Session session) + { + _session = session; + _completion = Task.WhenAll( + Task.Run(SendLoopAsync), + Task.Run(ReceiveLoopAsync), + Task.Run(FrameLoopAsync)); + } + + public void EnableSnappy() + { + lock (_sendLock) + { + _encoder?.EnableSnappy(_logger); + _encodingMode = FrameEncoder.EncodingMode.Snappy; + } + + _inboundSnappy = true; + } + + public Task DisconnectAsync() + { + Close(); + return _closed.Task; + } + + private void Close() + { + lock (_sendLock) + { + if (_isClosed) + { + return; + } + + _isClosed = true; + _writable = false; + while (_sendQueue.TryDequeue(out OutboundItem item)) + { + ArrayPool.Shared.Return(item.Buffer); + } + } + + _sendSignal.Release(); + _idleTimer?.Dispose(); + _receiveCancellation.Cancel(); + _sendCancellation.Cancel(); + _socket.Close(); + _closed.TrySetResult(); + } + + #region Receive + + private async Task ReceiveLoopAsync() + { + PipeWriter writer = _pipe.Writer; + Exception? cause = null; + try + { + CancellationToken cancellation = _receiveCancellation.Token; + while (true) + { + // Waits for data without holding a buffer, so idle peers hold none. + await _socket.ReceiveAsync(Memory.Empty, cancellation); + int received = await _socket.ReceiveAsync(writer.GetMemory(ReceiveSegmentSize), cancellation); + if (received == 0) + { + break; + } + + Volatile.Write(ref _lastReceive, Environment.TickCount64); + writer.Advance(received); + FlushResult flush = await writer.FlushAsync(CancellationToken.None); + if (flush.IsCompleted) + { + break; + } + } + } + catch (Exception e) + { + // An error from or after a local close is not the peer's; the idle timer cancels the receive on a read timeout. + cause = _isClosed || e is ObjectDisposedException ? null + : _readTimedOut && e is OperationCanceledException ? new RlpxReadTimeoutException() + : e; + } + finally + { + // The cause goes after the frames already received, and the pipe completes normally, since a pipe completed + // with an exception hides the data it still holds. DotNetty also passes on what it read before the error. + _terminalCause = cause; + Close(); + await writer.CompleteAsync(); + } + } + + private void StartIdleTimer() + { + Volatile.Write(ref _lastReceive, Environment.TickCount64); + Timer timer = new(OnIdleTimer, null, Timeout.InfiniteTimeSpan, Timeout.InfiniteTimeSpan); + _idleTimer = timer; + if (_isClosed) + { + timer.Dispose(); + return; + } + + try + { + timer.Change(ReadTimeout, Timeout.InfiniteTimeSpan); + } + catch (ObjectDisposedException) + { + // Closed meanwhile. + } + } + + private void OnIdleTimer(object? _) + { + long idle = Environment.TickCount64 - Volatile.Read(ref _lastReceive); + long remaining = (long)ReadTimeout.TotalMilliseconds - idle; + if (remaining > 0) + { + try + { + _idleTimer?.Change(TimeSpan.FromMilliseconds(remaining), Timeout.InfiniteTimeSpan); + } + catch (ObjectDisposedException) + { + // Closed meanwhile. + } + + return; + } + + _readTimedOut = true; + _receiveCancellation.Cancel(); + } + + private async Task FrameLoopAsync() + { + PipeReader reader = _pipe.Reader; + try + { + if (await HandshakeAsync(reader)) + { + await ReadFramesAsync(reader); + } + } + catch (Exception e) + { + if (_logger.IsError) _logger.Error($"Unexpected failure while reading from {_session:hide}", e); + Close(); + } + finally + { + ReleaseFrame(); + ReleaseChunkedPacket(); + if (_handshakeCompleted) + { + if (_terminalCause is { } cause) + { + QueueError(cause); + } + + if (!_processingThread.TryEnqueue(new ProcessingItem(this, null, null))) + { + StopProcessing(); + } + } + + await reader.CompleteAsync(); + } + } + + private async Task HandshakeAsync(PipeReader reader) + { + EncryptionHandshake handshake = new(); + using CancellationTokenSource timeout = new(Timeouts.Handshake); + try + { + if (_role == HandshakeRole.Initiator) + { + Packet auth = _handshakeService.Auth(_session.RemoteNodeId, handshake); + if (_logger.IsTrace) _logger.Trace($"Sending AUTH to {_session.RemoteNodeId:hide} @ {_session.RemoteHost:hide}"); + QueueRaw(auth.Data); + Interlocked.Add(ref Metrics.P2PBytesSent, auth.Data.Length); + } + + byte[]? message = await ReadHandshakeMessageAsync(reader, timeout.Token); + if (message is null) + { + if (_terminalCause is { } cause) + { + LogHandshakeFailure(cause); + } + + return false; + } + + Interlocked.Add(ref Metrics.P2PBytesReceived, message.Length); + if (_role == HandshakeRole.Recipient) + { + if (_logger.IsTrace) _logger.Trace($"AUTH received from {_session.RemoteHost:hide}"); + Packet ack = _handshakeService.Ack(handshake, new Packet(message)); + if (_logger.IsTrace) _logger.Trace($"Sending ACK to {handshake.RemoteNodeId:hide} @ {_session.RemoteHost:hide}"); + QueueRaw(ack.Data); + Interlocked.Add(ref Metrics.P2PBytesSent, ack.Data.Length); + } + else + { + if (_logger.IsTrace) _logger.Trace($"Received ACK from {_session.RemoteNodeId:hide} @ {_session.RemoteHost:hide}"); + _handshakeService.Agree(handshake, new Packet(message)); + } + + _session.Handshake(handshake.RemoteNodeId); + + // Each direction gets its own instances, so the frame and send loops share no crypto state. Each MAC processor + // copies both directions' hashes when constructed, so both are built before either loop uses them. + EncryptionSecrets secrets = handshake.Secrets; + FrameMacProcessor ingressMac = new(secrets); + FrameMacProcessor egressMac = new(secrets); + _decoder = new FrameDecoder(new FrameCipher(secrets.AesSecret), ingressMac, _maxInboundFrameSize); + lock (_sendLock) + { + _encoder = new FrameEncoder(new FrameCipher(secrets.AesSecret), egressMac); + } + + _handshakeCompleted = true; + _session.Init(5, this); + StartIdleTimer(); + return true; + } + catch (OperationCanceledException) when (timeout.IsCancellationRequested && !_isClosed) + { + Metrics.HandshakeTimeouts++; + if (_logger.IsTrace) _logger.Trace($"Disconnecting due to timeout for handshake: {_session.RemoteNodeId:hide}@{_session.RemoteHost:hide}:{_session.RemotePort:hide}"); + Close(); + return false; + } + catch (Exception e) + { + LogHandshakeFailure(e); + Close(); + return false; + } + } + + /// Reads an AUTH or ACK with its 2-byte size prefix, which the handshake service takes with the message. + /// The message, or if the stream ended first. + private static async Task ReadHandshakeMessageAsync(PipeReader reader, CancellationToken cancellationToken) + { + while (true) + { + ReadResult result = await reader.ReadAsync(cancellationToken); + ReadOnlySequence buffer = result.Buffer; + if (buffer.Length >= sizeof(ushort)) + { + int length = ReadHandshakeLength(buffer); + if (length > MaxHandshakeLength) + { + reader.AdvanceTo(buffer.Start); + throw new InvalidFrameException($"Handshake message of {length} bytes exceeds {MaxHandshakeLength}"); + } + + if (buffer.Length >= length) + { + byte[] message = buffer.Slice(0, length).ToArray(); + reader.AdvanceTo(buffer.GetPosition(length)); + return message; + } + } + + reader.AdvanceTo(buffer.Start, buffer.End); + if (result.IsCompleted) + { + return null; + } + } + } + + /// Reads a handshake message's length, with its size prefix, from the prefix. + private static int ReadHandshakeLength(ReadOnlySequence buffer) + { + Span prefix = stackalloc byte[sizeof(ushort)]; + buffer.Slice(0, sizeof(ushort)).CopyTo(prefix); + return BinaryPrimitives.ReadUInt16BigEndian(prefix) + sizeof(ushort); + } + + private void LogHandshakeFailure(Exception exception) + { + string clientId = _session.RemoteNodeId is null ? $"unknown {_session.RemoteHost}" : _session.Node.ToString(Node.Format.Console); + if (exception is SocketException) + { + if (_logger.IsTrace) _logger.Trace($"Handshake failure in communication with {clientId:hide} (SocketException): {exception:hide}"); + } + else if (_logger.IsDebug) + { + _logger.Debug($"Handshake failure in communication with {clientId:hide}: {exception:hide}"); + } + } + + private async Task ReadFramesAsync(PipeReader reader) + { + while (true) + { + ReadResult result = await reader.ReadAsync(); + ReadOnlySequence buffer = result.Buffer; + SequencePosition consumed = _discarding ? buffer.End : DecodeFrames(buffer); + reader.AdvanceTo(consumed, buffer.End); + if (result.IsCompleted) + { + return; + } + } + } + + /// Decodes every whole block available, as does. + /// Where the bytes not yet consumed start. + private SequencePosition DecodeFrames(ReadOnlySequence buffer) + { + SequenceReader input = new(buffer); + Span block = stackalloc byte[Frame.HeaderSize + Frame.MacSize]; + Span plaintext = stackalloc byte[Frame.HeaderSize]; + while (input.Remaining >= Frame.BlockSize) + { + switch (_frameState) + { + case FrameState.Header: + { + if (input.Remaining < Frame.HeaderSize + Frame.MacSize) + { + return input.Position; + } + + input.TryCopyTo(block); + input.Advance(block.Length); + if (!TryReadHeader(block[..Frame.HeaderSize], block[Frame.HeaderSize..], plaintext, out int frameSize)) + { + return buffer.End; + } + + _frameSize = frameSize; + _frame = ArrayPool.Shared.Rent(Frame.HeaderSize + frameSize); + plaintext.CopyTo(_frame); + _frameFilled = Frame.HeaderSize; + + ReadOnlySpan whole = input.UnreadSpan; + if (whole.Length >= frameSize + Frame.MacSize) + { + // The frame is whole in one segment: authenticate before decrypting. + ReadOnlySpan payload = whole[..frameSize]; + _decoder!.AbsorbPayload(payload); + if (!TryCheckPayloadMac(whole.Slice(frameSize, Frame.MacSize))) + { + return buffer.End; + } + + _decoder.DecryptPayload(payload, _frame.AsSpan(Frame.HeaderSize, frameSize)); + input.Advance(frameSize + Frame.MacSize); + CompleteFrame(); + break; + } + + _frameState = FrameState.Payload; + break; + } + case FrameState.Payload: + { + // Plaintext stays in the frame buffer until the payload MAC passes. + int remaining = Frame.HeaderSize + _frameSize - _frameFilled; + ReadOnlySpan span = input.UnreadSpan; + int length = Math.Min(remaining, span.Length - span.Length % Frame.BlockSize); + scoped ReadOnlySpan ciphertext; + if (length > 0) + { + ciphertext = span[..length]; + } + else + { + // A block split across segments. + length = Frame.BlockSize; + input.TryCopyTo(block[..length]); + ciphertext = block[..length]; + } + + _decoder!.AbsorbPayload(ciphertext); + _decoder.DecryptPayload(ciphertext, _frame.AsSpan(_frameFilled, length)); + input.Advance(length); + _frameFilled += length; + if (_frameFilled == Frame.HeaderSize + _frameSize) + { + _frameState = FrameState.PayloadMac; + } + + break; + } + case FrameState.PayloadMac: + { + Span mac = block[..Frame.MacSize]; + input.TryCopyTo(mac); + input.Advance(Frame.MacSize); + if (!TryCheckPayloadMac(mac)) + { + return buffer.End; + } + + CompleteFrame(); + _frameState = FrameState.Header; + break; + } + } + } + + return input.Position; + } + + private bool TryReadHeader(ReadOnlySpan header, ReadOnlySpan mac, Span plaintext, out int frameSize) + { + try + { + frameSize = _decoder!.ReadHeader(header, mac, plaintext); + return true; + } + catch (InvalidFrameException e) + { + StopDecoding(e); + frameSize = 0; + return false; + } + } + + private bool TryCheckPayloadMac(ReadOnlySpan mac) + { + try + { + _decoder!.CheckPayloadMac(mac); + return true; + } + catch (InvalidFrameException e) + { + StopDecoding(e); + return false; + } + } + + /// + /// Stops decoding after an error that leaves the ingress cipher and MAC out of step, so that no later frame can decode. + /// + /// + /// The error is handled as DotNetty's would be: other peers are disconnected, while a static or trusted peer keeps the + /// connection, which the peer, the read timeout or the ping timeout ends. Unlike DotNetty, nothing more is decoded. + /// + private void StopDecoding(Exception exception) + { + _discarding = true; + ReleaseFrame(); + ReleaseChunkedPacket(); + QueueError(exception); + } + + private void CompleteFrame() + { + byte[] frame = _frame!; + _frame = null; + _frameState = FrameState.Header; + + MergedFrame merged; + try + { + merged = _merger.Read(frame.AsSpan(0, Frame.HeaderSize + _frameSize)); + } + catch (InvalidFrameException e) + { + // Authenticated frames stay in step, so decoding continues, as it does on DotNetty. + ArrayPool.Shared.Return(frame); + ReleaseChunkedPacket(); + QueueError(e); + return; + } + + switch (merged.Kind) + { + case MergedFrameKind.SinglePacket: + Dispatch(new PooledPacket(frame, merged.ContentOffset, merged.ContentLength) { PacketType = merged.PacketType }); + return; + case MergedFrameKind.FirstChunk: + { + // Grows from the first chunk up to the declared total, as ZeroFrameMerger's buffer does. + byte[] buffer = ArrayPool.Shared.Rent(merged.ContentLength); + frame.AsSpan(merged.ContentOffset, merged.ContentLength).CopyTo(buffer); + _chunkedPacket = new PooledPacket(buffer, 0, merged.ContentLength) { PacketType = merged.PacketType }; + _chunkedPacketTotal = merged.TotalContentLength; + break; + } + default: + { + PooledPacket packet = _chunkedPacket!; + int length = packet.Content.Length; + int needed = length + merged.ContentLength; + if (needed > packet.Buffer.Length) + { + packet.Grow(Math.Max(needed, Math.Min(packet.Buffer.Length * 2, _chunkedPacketTotal))); + } + + frame.AsSpan(merged.ContentOffset, merged.ContentLength).CopyTo(packet.Buffer.AsSpan(length)); + packet.SetContent(0, needed); + break; + } + } + + ArrayPool.Shared.Return(frame); + if (merged.IsComplete) + { + PooledPacket packet = _chunkedPacket!; + _chunkedPacket = null; + Dispatch(packet); + } + } + + private void Dispatch(PooledPacket packet) + { + if (!_processingThread.TryEnqueue(new ProcessingItem(this, packet, null))) + { + packet.Release(); + } + } + + private void QueueError(Exception exception) => _processingThread.TryEnqueue(new ProcessingItem(this, null, exception)); + + private void ReleaseFrame() + { + if (_frame is { } frame) + { + _frame = null; + ArrayPool.Shared.Return(frame); + } + + _frameState = FrameState.Header; + } + + private void ReleaseChunkedPacket() + { + _merger.Reset(); + PooledPacket? packet = _chunkedPacket; + _chunkedPacket = null; + packet?.Release(); + } + + #endregion + + #region Processing thread + + /// Handles an item on the connection's processing thread. + internal void Process(in ProcessingItem item) + { + if (item.Packet is { } packet) + { + ProcessPacket(packet); + } + else if (item.Error is { } error) + { + HandleError(error); + } + else + { + StopProcessing(); + } + } + + private void ProcessPacket(PooledPacket input) + { + try + { + ReadOnlyMemory content = input.Content; + if (!SnappyDecoder.IsWithinSizeLimit(content.Length)) + { + _session.InitiateDisconnect(DisconnectReason.BreachOfProtocol, "Max message size exceeded"); + return; + } + + if (!_inboundSnappy) + { + ReceiveMessage(input); + return; + } + + if (!SnappyDecoder.TryGetUncompressedLength(content, out int uncompressedLength, _logger)) + { + _session.InitiateDisconnect(DisconnectReason.BreachOfProtocol, "Max message size exceeded"); + return; + } + + if (_logger.IsTrace) TraceSnappyMessage(content.Length); + + PooledPacket output = TakeSnappyOutput(uncompressedLength); + try + { + _snappyOutputWriter.Packet = output; + SnappyDecoder.Decompress(content, _snappyOutputWriter, _logger); + Debug.Assert(output.Content.Length == uncompressedLength, "Validated Snappy output must match its declared length."); + } + catch + { + output.Release(); + throw; + } + finally + { + _snappyOutputWriter.Packet = null; + } + + try + { + output.Protocol = null; + output.PacketType = input.PacketType; + ReceiveMessage(output); + } + finally + { + // A consumer that kept the content holds a lease, which prevents reuse. + if (!_processingStopped && _snappyOutput is null && output.IsExclusive && output.Buffer.Length <= MaxRetainedSnappyOutputCapacity) + _snappyOutput = output; + else + output.Release(); + } + } + catch (Exception e) + { + // Errors raised while handling an item are handled before the next item, as DotNetty fires them on the same handler. + HandleError(e); + } + finally + { + input.Release(); + } + } + + private void ReceiveMessage(ZeroPacket packet) + { + try + { + _session.ReceiveMessage(packet); + } + catch (RlpReaderException exception) when (exception is not IInternalNethermindException) + { + if (!_session.IsClosing) + { + HandleError(exception); + } + } + } + + private void HandleError(Exception exception) => RlpxErrorHandler.TryHandle(_session, exception, _logger); + + private PooledPacket TakeSnappyOutput(int length) + { + PooledPacket? packet = _snappyOutput; + if (packet is not null && length <= MaxRetainedSnappyOutputCapacity) + { + _snappyOutput = null; + if (packet.Buffer.Length >= length) + { + packet.SetContent(0, 0); + return packet; + } + + packet.Release(); + } + + return new PooledPacket(ArrayPool.Shared.Rent(length), 0, 0); + } + + private void StopProcessing() + { + _processingStopped = true; + PooledPacket? packet = _snappyOutput; + _snappyOutput = null; + packet?.Release(); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private void TraceSnappyMessage(int length) + { + if (length > SnappyParameters.MaxSnappyLength / 4) + { + _logger.Trace($"Big Snappy message of length {length}"); + } + else + { + _logger.Trace($"Uncompressing with Snappy a message of length {length}"); + } + } + + #endregion + + #region Send + + public int Enqueue(T message) where T : P2PMessage + { + if (!_writable) + { + return 0; + } + + (byte[] buffer, int length) = Serialize(_serializationService, message); + TryAdmit(buffer, length, raw: false); + return length; + } + + private void QueueRaw(byte[] data) + { + byte[] buffer = ArrayPool.Shared.Rent(data.Length); + data.CopyTo(buffer, 0); + TryAdmit(buffer, data.Length, raw: true); + } + + /// + /// Queues a packet with the encoding mode and send time it has now, and charges it to the outbound bytes, or releases + /// it if the connection has closed: the one place where a packet is either published or released. + /// + private void TryAdmit(byte[] buffer, int length, bool raw) + { + long sendAfter = _sendLatencyMs == 0 ? 0 : Environment.TickCount64 + _sendLatencyMs; + bool wake; + lock (_sendLock) + { + if (_isClosed) + { + ArrayPool.Shared.Return(buffer); + return; + } + + _sendQueue.Enqueue(new OutboundItem(buffer, length, raw, _encodingMode, sendAfter)); + ChargeUnderLock(length); + wake = _sendLoopWaiting; + _sendLoopWaiting = false; + } + + if (wake) + { + _sendSignal.Release(); + } + } + + private void ChargeUnderLock(long bytes) + { + _pendingBytes += bytes; + if (_writable && _pendingBytes >= WriteBufferHighWaterMark) + { + _writable = false; + } + else if (!_writable && !_isClosed && _pendingBytes <= WriteBufferLowWaterMark) + { + _writable = true; + } + } + + private void Charge(long bytes) + { + lock (_sendLock) + { + ChargeUnderLock(bytes); + } + } + + private async Task SendLoopAsync() + { + byte[] batch = ArrayPool.Shared.Rent(SendBatchSize); + // The end of each packet in the batch and its charge, which is released once its last byte is sent. + List<(int End, int Charge)> batchPackets = []; + int used = 0; + try + { + CancellationToken cancellation = _sendCancellation.Token; + while (true) + { + OutboundItem item; + FrameEncoder? encoder; + lock (_sendLock) + { + if (_isClosed) + { + return; + } + + if (!_sendQueue.TryDequeue(out item)) + { + _sendLoopWaiting = used == 0; + } + + encoder = _encoder; + } + + if (item.Buffer is null) + { + if (used > 0) + { + await SendAsync(batch, used, batchPackets, cancellation); + used = 0; + } + else + { + await _sendSignal.WaitAsync(cancellation); + } + + continue; + } + + try + { + if (item.SendAfter != 0) + { + long delay = item.SendAfter - Environment.TickCount64; + if (delay > 0) + { + if (used > 0) + { + await SendAsync(batch, used, batchPackets, cancellation); + used = 0; + } + + await Task.Delay(TimeSpan.FromMilliseconds(delay), cancellation); + } + } + + int bound = item.Raw ? item.Length : encoder!.GetMaxEncodedLength(item.Length, item.Mode); + if (used + bound > batch.Length && used > 0) + { + await SendAsync(batch, used, batchPackets, cancellation); + used = 0; + } + + if (bound > batch.Length) + { + // A packet larger than the batch gets its own buffer, since the encoder needs it contiguous. + byte[] own = ArrayPool.Shared.Rent(bound); + try + { + if (TryEncode(item, encoder, own, out int written)) + { + batchPackets.Add((written, written)); + await SendAsync(own, written, batchPackets, cancellation); + } + } + finally + { + ArrayPool.Shared.Return(own); + } + } + else if (TryEncode(item, encoder, batch.AsSpan(used), out int written)) + { + used += written; + batchPackets.Add((used, written)); + } + } + finally + { + ArrayPool.Shared.Return(item.Buffer); + } + } + } + catch (Exception e) + { + // Cancellation and disposal follow a local close, which needs no report. + if (!_isClosed || e is not (OperationCanceledException or ObjectDisposedException)) + { + HandleSendFailure(e); + } + } + finally + { + ArrayPool.Shared.Return(batch); + } + } + + /// Encodes a packet, or copies a raw handshake message, and charges its encoded length instead of its serialized one. + private bool TryEncode(in OutboundItem item, FrameEncoder? encoder, Span destination, out int written) + { + try + { + if (item.Raw) + { + item.Buffer.AsSpan(0, item.Length).CopyTo(destination); + written = item.Length; + } + else + { + written = encoder!.Encode(item.Buffer.AsSpan(0, item.Length), destination, item.Mode); + } + } + catch (Exception e) + { + Charge(-item.Length); + if (_logger.IsError) _logger.Error("Channel is active", e); + written = 0; + return false; + } + + Charge(written - item.Length); + return true; + } + + /// Sends a buffer in full, releasing each packet's charge once its last byte has gone. + private async ValueTask SendAsync(byte[] buffer, int length, List<(int End, int Charge)> packets, CancellationToken cancellation) + { + int offset = 0; + int next = 0; + while (offset < length) + { + int sent = await _socket.SendAsync(buffer.AsMemory(offset, length - offset), cancellation); + if (sent <= 0) + { + throw new SocketException((int)SocketError.ConnectionAborted); + } + + offset += sent; + long released = 0; + while (next < packets.Count && packets[next].End <= offset) + { + released += packets[next].Charge; + next++; + } + + if (released > 0) + { + Charge(-released); + } + } + + packets.Clear(); + } + + private void HandleSendFailure(Exception exception) + { + // DotNetty closes the channel before it fails the pending writes, so a lost connection is logged at trace. + Close(); + if (_logger.IsTrace) _logger.Trace($"Channel is not active - {exception.Message}"); + } + + // Messages are enqueued from any thread, so each thread reuses its own writer. + [ThreadStatic] + private static PacketWriter? t_writer; + + /// Serializes a message into a rented buffer as its packet type followed by its content. + internal static (byte[] Buffer, int Length) Serialize(IMessageSerializationService serializationService, T message) + where T : P2PMessage + { + PacketWriter writer = t_writer ??= new(); + writer.Start(message.AdaptivePacketType); + try + { + serializationService.Serialize(message, writer); + return writer.Buffer is { } buffer + ? (buffer, writer.Length) + : throw new InvalidOperationException($"{nameof(IMessageSerializationService)} did not request a span for the message."); + } + catch + { + if (writer.Buffer is { } buffer) + { + ArrayPool.Shared.Return(buffer); + } + + throw; + } + finally + { + writer.Clear(); + } + } + + /// Writes a packet into a single rented buffer: its packet type, then its content. + /// Rents the buffer on the one call for the content, as 's writer does. + private sealed class PacketWriter : IBufferWriter + { + private int _packetType; + private int _packetTypeLength; + + public byte[]? Buffer { get; private set; } + + public int Length { get; private set; } + + public void Start(int packetType) => _packetType = packetType; + + // Keeps an idle thread's writer from holding on to the last buffer. + public void Clear() + { + Buffer = null; + Length = 0; + } + + public Span GetSpan(int sizeHint = 0) + { + if (Buffer is not null) + throw new InvalidOperationException($"{nameof(PacketWriter)} takes the content in a single span."); + + int packetTypeLength = _packetTypeLength = Rlp.LengthOf(_packetType); + // IBufferWriter requires a non-empty span when no size is requested. + int length = packetTypeLength + Math.Max(sizeHint, 1); + byte[] buffer = Buffer = ArrayPool.Shared.Rent(length); + Span packet = buffer.AsSpan(0, length); + RlpWriter writer = RlpWriter.ContentWriter(packet); + writer.Encode(_packetType); + Length = packetTypeLength; + return packet[packetTypeLength..]; + } + + public Memory GetMemory(int sizeHint = 0) => throw new NotSupportedException(); + + public void Advance(int count) => Length = _packetTypeLength + count; + } + + #endregion + + private readonly record struct OutboundItem(byte[] Buffer, int Length, bool Raw, FrameEncoder.EncodingMode Mode, long SendAfter); + + private enum FrameState + { + Header, + Payload, + PayloadMac + } + + /// Writes decompressed content into a 's buffer, growing it if needed. + private sealed class SnappyOutputWriter : IBufferWriter + { + public PooledPacket? Packet { get; set; } + + public void Advance(int count) + { + PooledPacket packet = Packet!; + packet.SetContent(0, packet.Content.Length + count); + } + + public Memory GetMemory(int sizeHint = 0) + { + PooledPacket packet = Packet!; + int length = packet.Content.Length; + int needed = length + Math.Max(1, sizeHint); + if (needed > packet.Buffer.Length) + { + packet.Grow(Math.Max(needed, packet.Buffer.Length * 2)); + } + + return packet.Buffer.AsMemory(length); + } + + public Span GetSpan(int sizeHint = 0) => GetMemory(sizeHint).Span; + } +} diff --git a/src/Nethermind/Nethermind.Network/Rlpx/Sockets/SocketRlpxHost.cs b/src/Nethermind/Nethermind.Network/Rlpx/Sockets/SocketRlpxHost.cs new file mode 100644 index 000000000000..2c9cb368fa86 --- /dev/null +++ b/src/Nethermind/Nethermind.Network/Rlpx/Sockets/SocketRlpxHost.cs @@ -0,0 +1,474 @@ +// SPDX-FileCopyrightText: 2026 Demerzel Solutions Limited +// SPDX-License-Identifier: LGPL-3.0-only + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Net; +using System.Net.Sockets; +using System.Runtime.CompilerServices; +using System.Threading; +using System.Threading.Tasks; +using Nethermind.Core.ServiceStopper; +using Nethermind.Logging; +using Nethermind.Network.Config; +using Nethermind.Network.P2P; +using Nethermind.Network.P2P.Analyzers; +using Nethermind.Network.Rlpx.Handshake; +using Nethermind.Stats.Model; + +namespace Nethermind.Network.Rlpx.Sockets; + +/// +/// An RLPx host on sockets and System.IO.Pipelines, without DotNetty. +/// +/// +/// Selected with . It shares its dial, filter and session policy with +/// , and owns only the transport: the listener, the dials and the connections. +/// +public sealed class SocketRlpxHost : IRlpxHost, IStoppableService +{ + private const int ListenBacklog = 100; + + // DotNetty starts no connect timer for a zero timeout, which leaves RlpxHost's 2-second watchdog. + private static readonly TimeSpan ZeroConnectTimeoutDeadline = TimeSpan.FromSeconds(2); + + private readonly IMessageSerializationService _serializationService; + private readonly IHandshakeService _handshakeService; + private readonly IDisconnectsAnalyzer _disconnectsAnalyzer; + private readonly ILogManager _logManager; + private readonly ILogger _logger; + private readonly NetworkListenerState _listenerState; + private readonly RlpxDialPolicy _dialPolicy; + private readonly RlpxSessionTracker _sessions; + private readonly Func> _tryConnect; + private readonly TimeSpan _sendLatency; + private readonly TimeSpan _connectTimeout; + private readonly TimeSpan _shutdownCloseTimeout; + private readonly int _processingThreadCount; + private readonly CancellationTokenSource _shutdown = new(); + private readonly TaskCompletionSource _listenerClosed = new(TaskCreationOptions.RunContinuationsAsynchronously); + + // Guards the shutdown flag, the connections and the pending dials, so that shutdown sees every one of them. + private readonly Lock _lock = new(); + private readonly HashSet _connections = []; + private readonly HashSet _pendingDials = []; + private bool _shuttingDown; + + private RlpxProcessingThreads? _processingThreads; + private Socket? _listener; + private Task _acceptLoop = Task.CompletedTask; + private bool _isInitialized; + + public SocketRlpxHost( + IMessageSerializationService serializationService, + IHandshakeService handshakeService, + ISessionMonitor sessionMonitor, + IDisconnectsAnalyzer disconnectsAnalyzer, + INetworkConfig networkConfig, + IIPResolver ipResolver, + IPrivilegedIpProvider privilegedIpProvider, + ILogManager logManager, + NetworkListenerState listenerState) + { + ArgumentNullException.ThrowIfNull(serializationService); + ArgumentNullException.ThrowIfNull(handshakeService); + ArgumentNullException.ThrowIfNull(sessionMonitor); + ArgumentNullException.ThrowIfNull(disconnectsAnalyzer); + ArgumentNullException.ThrowIfNull(networkConfig); + ArgumentNullException.ThrowIfNull(logManager); + + _serializationService = serializationService; + _handshakeService = handshakeService; + _disconnectsAnalyzer = disconnectsAnalyzer; + _logManager = logManager; + _logger = logManager.GetClassLogger(); + _listenerState = listenerState; + SessionMonitor = sessionMonitor; + LocalPort = networkConfig.P2PPort; + // The peer filter needs the resolved external address before it can accept connections. + IIPResolver.NethermindIp ips = ipResolver.Resolve().GetAwaiter().GetResult(); + _sendLatency = TimeSpan.FromMilliseconds(networkConfig.SimulateSendLatencyMs); + _connectTimeout = networkConfig.ConnectTimeoutMs > 0 ? TimeSpan.FromMilliseconds(networkConfig.ConnectTimeoutMs) : ZeroConnectTimeoutDeadline; + _shutdownCloseTimeout = TimeSpan.FromMilliseconds(networkConfig.RlpxHostShutdownCloseTimeoutMs); + _processingThreadCount = networkConfig.ProcessingThreadCount; + _tryConnect = TryConnect; + NodeFilter nodeFilter = NodeFilter.Create(networkConfig.MaxActivePeers, networkConfig.FilterPeersByRecentIp, networkConfig.FilterPeersBySameSubnet, ips.ExternalIp); + _dialPolicy = new RlpxDialPolicy(nodeFilter, privilegedIpProvider, _logger); + _sessions = new RlpxSessionTracker(this, sessionMonitor, _dialPolicy, _logger, () => _shutdown.Token); + } + + public int LocalPort { get; } + + public ISessionMonitor SessionMonitor { get; } + + public event EventHandler SessionCreated + { + add => _sessions.SessionCreated += value; + remove => _sessions.SessionCreated -= value; + } + + public event SessionDisconnectedEventHandler SessionDisconnected + { + add => _sessions.SessionDisconnected += value; + remove => _sessions.SessionDisconnected -= value; + } + + /// Gets the endpoint the listener is bound to, once initialized. + internal IPEndPoint? ListenerEndPoint => _listener?.LocalEndPoint as IPEndPoint; + + internal int ConnectionCount + { + get + { + lock (_lock) + { + return _connections.Count; + } + } + } + + public bool ShouldContact(IPAddress ip, bool exactOnly = false) => _dialPolicy.ShouldContact(ip, exactOnly); + + public async Task Init() + { + if (_isInitialized) + { + ThrowAlreadyInitialized(); + } + + _isInitialized = true; + _processingThreads = new RlpxProcessingThreads(_processingThreadCount, _logger); + try + { + _listener = await RlpxListener.BindAsync(_listenerState, LocalPort, _logger, nameof(SocketRlpxHost), Bind); + } + catch (Exception ex) + { + _logger.Error($"{nameof(Init)} failed.", ex); + await _processingThreads.StopAsync(); + throw; + } + + if (_listener.LocalEndPoint is IPEndPoint endpoint) + { + _ = _listenerState.TrackRlpxAddress(endpoint.Address, _listenerClosed.Task); + } + + _acceptLoop = Task.Run(AcceptLoopAsync); + } + + private Task Bind(IPAddress address) + { + Socket socket = RlpxListener.CreateSocket(address); + try + { + NetworkHelper.HandlePortTakenError(() => + { + socket.Bind(new IPEndPoint(address, LocalPort)); + socket.Listen(ListenBacklog); + return socket; + }, LocalPort); + return Task.FromResult(socket); + } + catch + { + socket.Dispose(); + throw; + } + } + + [DoesNotReturn, StackTraceHidden] + private static void ThrowAlreadyInitialized() + => throw new InvalidOperationException($"{nameof(SocketRlpxHost)} already initialized."); + + private async Task AcceptLoopAsync() + { + Socket listener = _listener!; + try + { + while (true) + { + Socket socket; + try + { + socket = await listener.AcceptAsync(_shutdown.Token); + } + catch (Exception e) when (e is OperationCanceledException or ObjectDisposedException || _shutdown.IsCancellationRequested) + { + return; + } + catch (SocketException e) + { + if (_logger.IsDebug) _logger.Debug($"Failed to accept an RLPx connection: {e.Message}"); + continue; + } + + Accept(socket); + } + } + finally + { + _listenerClosed.TrySetResult(); + } + } + + private void Accept(Socket socket) + { + IPEndPoint remote; + try + { + remote = (IPEndPoint)socket.RemoteEndPoint!; + } + catch (Exception e) when (e is SocketException or ObjectDisposedException) + { + socket.Dispose(); + return; + } + + SocketRlpxConnection connection = CreateConnection(socket, HandshakeRole.Recipient); + IPAddress remoteIp = remote.Address.NormalizeMappedIPv4(); + Session session = new(LocalPort, connection, _disconnectsAnalyzer, _logManager) + { + RemoteHost = remoteIp.ToString(), + RemotePort = remote.Port + }; + + if (!TryTrack(connection)) + { + return; + } + + Metrics.IncomingConnections++; + if (_logger.IsTrace) _logger.Trace($"|NetworkTrace| Initializing {session:hide} channel"); + + if (!_dialPolicy.AcceptsInbound(remoteIp)) + { + if (_logger.IsTrace) _logger.Trace($"|NetworkTrace| Rejecting inbound connection from filtered IP {remoteIp:hide}"); + Untrack(connection); + _ = connection.DisconnectAsync(); + return; + } + + StartSession(socket, connection, session); + } + + public Task ConnectAsync(Node node, CancellationToken cancellationToken = default) + => _dialPolicy.ConnectAsync(node, _tryConnect, cancellationToken); + + private async Task TryConnect(Node node, CancellationToken cancellationToken) + { + cancellationToken.ThrowIfCancellationRequested(); + TaskCompletionSource dial = new(TaskCreationOptions.RunContinuationsAsynchronously); + lock (_lock) + { + if (_shuttingDown || _processingThreads is null) + { + return false; + } + + _pendingDials.Add(dial.Task); + } + + try + { + Socket socket = new(node.Address.AddressFamily, SocketType.Stream, ProtocolType.Tcp); + SocketRlpxConnection connection = CreateConnection(socket, HandshakeRole.Initiator); + // Constructed before connecting, as RlpxHost constructs it at channel initialization; this starts its pong window. + Session session = new(LocalPort, node, connection, _disconnectsAnalyzer, _logManager); + + using CancellationTokenSource connectCancellation = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, _shutdown.Token); + connectCancellation.CancelAfter(_connectTimeout); + try + { + await socket.ConnectAsync(node.Address, connectCancellation.Token); + } + catch (Exception e) + { + _ = connection.DisconnectAsync(); + cancellationToken.ThrowIfCancellationRequested(); + if (e is OperationCanceledException) + { + if (_logger.IsTrace) TraceConnectionTimedOut(node); + } + else + { + if (_logger.IsTrace) TraceConnectionFailure(node, e); + } + + return false; + } + + // A connection that completes after its deadline was canceled above, so activation has no race to lose. + if (!TryTrack(connection)) + { + return false; + } + + Metrics.OutgoingConnections++; + if (_logger.IsTrace) _logger.Trace($"|NetworkTrace| Initializing {session:hide} channel"); + StartSession(socket, connection, session); + if (_logger.IsTrace) _logger.Trace($"|NetworkTrace| {node.ToString("s"):hide} OUT connected"); + return true; + } + finally + { + lock (_lock) + { + _pendingDials.Remove(dial.Task); + } + + dial.TrySetResult(); + } + } + + private SocketRlpxConnection CreateConnection(Socket socket, HandshakeRole role) + => new( + new TcpRlpxSocket(socket), + role, + _handshakeService, + _serializationService, + _processingThreads!.Next(), + _logManager, + _sendLatency, + ZeroFrameDecoder.DefaultMaxInboundFrameSize); + + /// Tracks a connection until its loops finish, or closes it if the host is shutting down. + private bool TryTrack(SocketRlpxConnection connection) + { + lock (_lock) + { + if (!_shuttingDown) + { + _connections.Add(connection); + return true; + } + } + + _ = connection.DisconnectAsync(); + return false; + } + + private void Untrack(SocketRlpxConnection connection) + { + lock (_lock) + { + _connections.Remove(connection); + } + } + + private void StartSession(Socket socket, SocketRlpxConnection connection, Session session) + { + SetSocketOption(socket, SocketOptionLevel.Tcp, SocketOptionName.NoDelay); + SetSocketOption(socket, SocketOptionLevel.Socket, SocketOptionName.KeepAlive); + _sessions.Activate(session, connection.Closed); + connection.Start(session); + _ = connection.Completion.ContinueWith( + static (_, state) => + { + (SocketRlpxHost host, SocketRlpxConnection connection) = ((SocketRlpxHost, SocketRlpxConnection))state!; + host.Untrack(connection); + }, + (this, connection), + CancellationToken.None, + TaskContinuationOptions.ExecuteSynchronously, + TaskScheduler.Default); + } + + private void SetSocketOption(Socket socket, SocketOptionLevel level, SocketOptionName name) + { + try + { + socket.SetSocketOption(level, name, true); + } + catch (Exception ex) + { + if (_logger.IsWarn) _logger.Warn($"Failed to set socket option {name}: {ex.Message:hide}"); + } + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private void TraceConnectionTimedOut(Node node) => + _logger.Trace($"|NetworkTrace| {node.ToString("s"):hide} OUT connection timed out"); + + [MethodImpl(MethodImplOptions.NoInlining)] + private void TraceConnectionFailure(Node node, Exception exception) => + _logger.Trace($"|NetworkTrace| {node.ToString("s"):hide} error when OUT connecting {exception:hide}"); + + Task IStoppableService.StopAsync() => Shutdown(); + + string IStoppableService.Description => "rlpx host"; + + public async Task Shutdown() + { + Task[] dials; + lock (_lock) + { + if (_shuttingDown) + { + return; + } + + _shuttingDown = true; + dials = [.. _pendingDials]; + } + + // Ends the accept loop and the pending dials, and the close delays of the sessions. + _shutdown.Cancel(); + _listener?.Dispose(); + await _acceptLoop; + await Task.WhenAll(dials); + if (_logger.IsDebug) _logger.Debug("Closed the RLPx listener"); + + SocketRlpxConnection[] connections; + lock (_lock) + { + connections = [.. _connections]; + } + + try + { + await Task.WhenAll(connections.Select(static c => c.DisconnectAsync())).WaitAsync(_shutdownCloseTimeout); + } + catch (Exception e) + { + if (_logger.IsDebug) _logger.Debug($"Closing peer channels on shutdown failed: {e.Message}"); + } + + // The connections' loops queue their last items before the processing threads finish theirs. + Task stopping = StopConnectionsAndThreadsAsync(connections); + TimeSpan warningDelay = _shutdownCloseTimeout * 3 + TimeSpan.FromSeconds(1); + try + { + await stopping.WaitAsync(warningDelay); + } + catch (TimeoutException) + { + if (_logger.IsWarn) _logger.Warn($"RLPx connections have not stopped after {warningDelay.TotalSeconds} seconds. Waiting for them to stop."); + await stopping; + } + + _sessions.DisconnectRemaining(); + + if (_logger.IsInfo) _logger.Info("Local peer shutdown complete.. please wait for all components to close"); + } + + private async Task StopConnectionsAndThreadsAsync(SocketRlpxConnection[] connections) + { + try + { + await Task.WhenAll(connections.Select(static c => c.Completion)); + } + catch (Exception e) + { + if (_logger.IsDebug) _logger.Debug($"An RLPx connection failed while stopping: {e.Message}"); + } + + if (_processingThreads is not null) + { + await _processingThreads.StopAsync(); + } + } +} From 0ea03f0b6035c346c93d895b925d5c9527d35582 Mon Sep 17 00:00:00 2001 From: Ruben Buniatyan <337518+rubo@users.noreply.github.com> Date: Thu, 26 Nov 2026 23:05:05 +0100 Subject: [PATCH 03/22] test(network): cover the socket transport against a scripted peer A connection runs on an in-memory socket against a scripted peer that holds the paired secrets, with a session that records what it is given and a pool that tracks every rental. The tests cover frames split at any offset, chunks and Snappy, failed MACs and merger errors for ordinary and privileged peers, ordering against a reset and against an error raised by a packet, the end of the stream mid-packet, the read and handshake timeouts, leases kept after shutdown, ordered sends from many threads, packets larger than the batch, short sends, the handshake without simulated latency, the encoding mode fixed at admission, and the watermarks, checked against DotNetty's channel. The host tests cover the listener, the inbound filter, refused, cancelled and pending dials, and shutdown, also through the node's service stopper. The connection takes an optional pool, a read timeout and a hook before decoding, for these tests; its writability moves into OutboundBytes. The handshake messages skip the simulated latency, as DotNetty writes them without PacketSender, and the MAC processors are disposed when the connection's loops end. An accept error other than a reset pauses the accept loop briefly. --- .../Rlpx/Sockets/InMemoryRlpxSocket.cs | 149 +++++ .../Rlpx/Sockets/OutboundBytesTests.cs | 61 ++ .../Rlpx/Sockets/RlpxTransportInteropTests.cs | 38 +- .../Rlpx/Sockets/ScriptedRlpxPeer.cs | 145 +++++ .../Rlpx/Sockets/SocketRlpxConnectionTests.cs | 574 ++++++++++++++++++ .../Rlpx/Sockets/SocketRlpxHostTests.cs | 280 +++++++++ .../Rlpx/Sockets/TrackingArrayPool.cs | 58 ++ .../RlpxHostIntegrationTests.cs | 23 +- .../Rlpx/Sockets/OutboundBytes.cs | 48 ++ .../Rlpx/Sockets/PooledPacket.cs | 12 +- .../Rlpx/Sockets/SocketRlpxConnection.cs | 144 +++-- .../Rlpx/Sockets/SocketRlpxHost.cs | 21 + 12 files changed, 1474 insertions(+), 79 deletions(-) create mode 100644 src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/InMemoryRlpxSocket.cs create mode 100644 src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/OutboundBytesTests.cs create mode 100644 src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/ScriptedRlpxPeer.cs create mode 100644 src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/SocketRlpxConnectionTests.cs create mode 100644 src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/SocketRlpxHostTests.cs create mode 100644 src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/TrackingArrayPool.cs create mode 100644 src/Nethermind/Nethermind.Network/Rlpx/Sockets/OutboundBytes.cs diff --git a/src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/InMemoryRlpxSocket.cs b/src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/InMemoryRlpxSocket.cs new file mode 100644 index 000000000000..727642584d85 --- /dev/null +++ b/src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/InMemoryRlpxSocket.cs @@ -0,0 +1,149 @@ +// SPDX-FileCopyrightText: 2026 Demerzel Solutions Limited +// SPDX-License-Identifier: LGPL-3.0-only + +using System; +using System.Buffers; +using System.IO.Pipelines; +using System.Threading; +using System.Threading.Tasks; +using Nethermind.Network.Rlpx.Sockets; + +namespace Nethermind.Network.Test.Rlpx.Sockets; + +/// +/// One end of an in-memory byte stream, with the short sends, split reads, held sends and injected errors that a real +/// socket can't produce on demand. +/// +internal sealed class InMemoryRlpxSocket : IRlpxSocket +{ + private readonly Pipe _incoming; + private readonly Pipe _outgoing; + private Exception? _receiveError; + private volatile bool _closed; + private long _received; + + private InMemoryRlpxSocket(Pipe incoming, Pipe outgoing) + { + _incoming = incoming; + _outgoing = outgoing; + } + + /// Creates both ends of a stream. + public static (InMemoryRlpxSocket Local, InMemoryRlpxSocket Remote) CreatePair() + { + Pipe toLocal = new(new PipeOptions(pauseWriterThreshold: 0, useSynchronizationContext: false)); + Pipe toRemote = new(new PipeOptions(pauseWriterThreshold: 0, useSynchronizationContext: false)); + return (new InMemoryRlpxSocket(toLocal, toRemote), new InMemoryRlpxSocket(toRemote, toLocal)); + } + + /// Gets or sets the most bytes a receive returns, so that data arrives split. + public int MaxReceiveLength { get; set; } = int.MaxValue; + + /// Gets or sets the most bytes a send takes, so that sends complete short. + public int MaxSendLength { get; set; } = int.MaxValue; + + /// Gets or sets a gate that every send waits for. + public Task SendGate { get; set; } = Task.CompletedTask; + + /// Gets or sets an error that sends throw. + public Exception? SendError { get; set; } + + /// Gets the number of bytes received so far. + public long Received => Interlocked.Read(ref _received); + + public bool IsClosed => _closed; + + /// Makes the pending and later receives throw, after the bytes already received. + public void FailReceive(Exception error) + { + _receiveError = error; + _incoming.Reader.CancelPendingRead(); + } + + public async ValueTask ReceiveAsync(Memory buffer, CancellationToken cancellationToken) + { + while (true) + { + ObjectDisposedException.ThrowIf(_closed, this); + ReadResult result = await _incoming.Reader.ReadAsync(cancellationToken); + ReadOnlySequence data = result.Buffer; + if (_receiveError is { } error) + { + _incoming.Reader.AdvanceTo(data.Start); + throw error; + } + + if (result.IsCanceled) + { + _incoming.Reader.AdvanceTo(data.Start); + continue; + } + + if (buffer.IsEmpty || data.IsEmpty) + { + // A zero-byte receive waits for data without taking it; an empty completed stream is its end. + _incoming.Reader.AdvanceTo(data.Start); + return 0; + } + + int length = (int)Math.Min(Math.Min(data.Length, buffer.Length), MaxReceiveLength); + data.Slice(0, length).CopyTo(buffer.Span); + _incoming.Reader.AdvanceTo(data.GetPosition(length)); + Interlocked.Add(ref _received, length); + return length; + } + } + + public async ValueTask SendAsync(ReadOnlyMemory buffer, CancellationToken cancellationToken) + { + await SendGate.WaitAsync(cancellationToken); + ObjectDisposedException.ThrowIf(_closed, this); + if (SendError is { } error) + { + throw error; + } + + int length = Math.Min(buffer.Length, MaxSendLength); + await _outgoing.Writer.WriteAsync(buffer[..length], cancellationToken); + return length; + } + + /// Sends all of . + public async Task SendAllAsync(ReadOnlyMemory data) + { + while (!data.IsEmpty) + { + int sent = await SendAsync(data, CancellationToken.None); + data = data[sent..]; + } + } + + /// Receives exactly bytes. + public async Task ReceiveExactlyAsync(int length, CancellationToken cancellationToken) + { + byte[] data = new byte[length]; + int received = 0; + while (received < length) + { + int read = await ReceiveAsync(data.AsMemory(received), cancellationToken); + if (read == 0) + { + throw new InvalidOperationException($"The stream ended after {received} of {length} bytes."); + } + + received += read; + } + + return data; + } + + /// Closes this end: the other end sees the end of the stream. + public void Close() + { + _closed = true; + _outgoing.Writer.Complete(); + _incoming.Reader.CancelPendingRead(); + } + + public void Dispose() => Close(); +} diff --git a/src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/OutboundBytesTests.cs b/src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/OutboundBytesTests.cs new file mode 100644 index 000000000000..ff3f413fe6bc --- /dev/null +++ b/src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/OutboundBytesTests.cs @@ -0,0 +1,61 @@ +// SPDX-FileCopyrightText: 2026 Demerzel Solutions Limited +// SPDX-License-Identifier: LGPL-3.0-only + +using DotNetty.Buffers; +using DotNetty.Transport.Channels.Embedded; +using Nethermind.Network.Rlpx.Sockets; +using NUnit.Framework; + +namespace Nethermind.Network.Test.Rlpx.Sockets; + +public class OutboundBytesTests +{ + [Test] + public void Stops_at_the_high_watermark_and_resumes_at_the_low_one() + { + OutboundBytes bytes = new(); + + bytes.Add(OutboundBytes.HighWaterMark - 1); + Assert.That(bytes.IsWritable, Is.True, "just under the high watermark"); + bytes.Add(1); + Assert.That(bytes.IsWritable, Is.False, "at the high watermark"); + bytes.Add(-(OutboundBytes.HighWaterMark - OutboundBytes.LowWaterMark - 1)); + Assert.That(bytes.IsWritable, Is.False, "just over the low watermark"); + bytes.Add(-1); + Assert.That(bytes.IsWritable, Is.True, "at the low watermark"); + } + + [Test] + public void Stays_unwritable_once_closed() + { + OutboundBytes bytes = new(); + + bytes.Close(); + bytes.Add(-OutboundBytes.HighWaterMark); + + Assert.That(bytes.IsWritable, Is.False); + } + + /// + /// The watermarks and comparisons are DotNetty's, with the marks sets: a channel stops + /// being writable once its pending bytes reach the high watermark. + /// + [Test] + public void Matches_dotnetty_at_the_high_watermark() + { + EmbeddedChannel channel = new(); + channel.Configuration.WriteBufferHighWaterMark = (int)OutboundBytes.HighWaterMark; + channel.Configuration.WriteBufferLowWaterMark = (int)OutboundBytes.LowWaterMark; + OutboundBytes bytes = new(); + + _ = channel.WriteAsync(Unpooled.WrappedBuffer(new byte[OutboundBytes.HighWaterMark - 1])); + bytes.Add(OutboundBytes.HighWaterMark - 1); + Assert.That(bytes.IsWritable, Is.EqualTo(channel.IsWritable).And.True); + + _ = channel.WriteAsync(Unpooled.WrappedBuffer(new byte[1])); + bytes.Add(1); + Assert.That(bytes.IsWritable, Is.EqualTo(channel.IsWritable).And.False); + + channel.FinishAndReleaseAll(); + } +} diff --git a/src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/RlpxTransportInteropTests.cs b/src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/RlpxTransportInteropTests.cs index a3ff169d8a60..13b4b53054a9 100644 --- a/src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/RlpxTransportInteropTests.cs +++ b/src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/RlpxTransportInteropTests.cs @@ -12,8 +12,8 @@ using Nethermind.Blockchain.Synchronization; using Nethermind.Config; using Nethermind.Core; -using Nethermind.Core.Collections; using Nethermind.Core.Crypto; +using Nethermind.Core.ServiceStopper; using Nethermind.Core.Specs; using Nethermind.Core.Test.Builders; using Nethermind.Core.Test.Modules; @@ -23,6 +23,7 @@ using Nethermind.Network.P2P; using Nethermind.Network.P2P.EventArg; using Nethermind.Network.Rlpx; +using Nethermind.Network.Rlpx.Sockets; using Nethermind.Specs; using Nethermind.Specs.ChainSpecStyle; using Nethermind.Specs.Forks; @@ -90,6 +91,41 @@ public async Task Nodes_exchange_messages_and_deliver_a_disconnect_reason(RlpxTr } } + [Test] + public async Task Socket_host_stops_with_the_node() + { + using CancellationTokenSource cancellation = new(Timeout); + IContainer server = CreateNode(TestItem.PrivateKeyA, RlpxTransport.Sockets); + IContainer client = CreateNode(TestItem.PrivateKeyB, RlpxTransport.Sockets); + try + { + await StartNetwork(server); + await StartNetwork(client); + TaskCompletionSource clientDisconnected = new(TaskCreationOptions.RunContinuationsAsynchronously); + client.Resolve().SessionDisconnected += (_, _, args) => clientDisconnected.TrySetResult(args); + IEnode serverEnode = server.Resolve(); + Assert.That(await client.Resolve().ConnectAsync(new Node(serverEnode.PublicKey, new IPEndPoint(serverEnode.HostIp, serverEnode.Port)), cancellation.Token), Is.True); + await WaitForPeer(client.Resolve(), cancellation.Token); + + // The node's shutdown finds the host as a stoppable service, as it finds RlpxHost. + await server.Resolve().StopAllServices().WaitAsync(cancellation.Token); + + using (Assert.EnterMultipleScope()) + { + Assert.That(((SocketRlpxHost)server.Resolve()).ConnectionCount, Is.Zero); + Assert.That(await clientDisconnected.Task.WaitAsync(cancellation.Token), Is.Not.Null, "the peer sees the node leave"); + } + } + finally + { + foreach (IContainer node in (IContainer[])[client, server]) + { + await node.Resolve().Shutdown(); + await node.DisposeAsync(); + } + } + } + private static IContainer CreateNode(PrivateKey nodeKey, RlpxTransport transport) { ConfigProvider configProvider = new( diff --git a/src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/ScriptedRlpxPeer.cs b/src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/ScriptedRlpxPeer.cs new file mode 100644 index 000000000000..e41a3a43c764 --- /dev/null +++ b/src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/ScriptedRlpxPeer.cs @@ -0,0 +1,145 @@ +// SPDX-FileCopyrightText: 2026 Demerzel Solutions Limited +// SPDX-License-Identifier: LGPL-3.0-only + +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using Nethermind.Core.Crypto; +using Nethermind.Logging; +using Nethermind.Network.Rlpx; +using Nethermind.Network.Rlpx.Handshake; + +namespace Nethermind.Network.Test.Rlpx.Sockets; + +/// +/// The far end of a connection under test: it writes the frames it is told to, valid or not, and reads what the +/// connection sends. +/// +/// It holds the paired secrets, so its frames decode on the connection and the connection's on it. +internal sealed class ScriptedRlpxPeer +{ + private readonly FrameEncoder _encoder; + private readonly FrameDecoder _decoder; + private readonly FrameMerger _merger = new(); + private readonly FrameCipher _egressCipher; + private readonly FrameMacProcessor _egressMac; + + public ScriptedRlpxPeer(InMemoryRlpxSocket socket, EncryptionSecrets secrets) + { + Socket = socket; + FrameMacProcessor ingressMac = new(secrets); + _egressMac = new FrameMacProcessor(secrets); + _egressCipher = new FrameCipher(secrets.AesSecret); + _encoder = new FrameEncoder(_egressCipher, _egressMac); + _encoder.EnableSnappy(LimboLogs.Instance.GetClassLogger()); + _decoder = new FrameDecoder(new FrameCipher(secrets.AesSecret), ingressMac, int.MaxValue); + } + + public InMemoryRlpxSocket Socket { get; } + + /// Encodes a packet into frames, without sending them. + public byte[] Encode(byte packetType, ReadOnlySpan content, FrameEncoder.EncodingMode mode) + { + byte[] packet = new byte[1 + content.Length]; + packet[0] = packetType; + content.CopyTo(packet.AsSpan(1)); + byte[] frames = new byte[_encoder.GetMaxEncodedLength(packet.Length, mode)]; + return frames[.._encoder.Encode(packet, frames, mode)]; + } + + /// Encrypts and authenticates a frame from a plaintext header and a padded payload, without checking either. + public byte[] EncryptFrame(ReadOnlySpan header, ReadOnlySpan payload) + { + byte[] frame = new byte[Frame.HeaderSize + Frame.MacSize + payload.Length + Frame.MacSize]; + Span encryptedHeader = frame.AsSpan(0, Frame.HeaderSize); + _egressCipher.Encrypt(header, encryptedHeader); + _egressMac.AddMac(encryptedHeader, frame.AsSpan(Frame.HeaderSize, Frame.MacSize), true); + Span encryptedPayload = frame.AsSpan(Frame.HeaderSize + Frame.MacSize, payload.Length); + _egressCipher.Encrypt(payload, encryptedPayload); + _egressMac.AddMac(encryptedPayload, frame.AsSpan(Frame.HeaderSize + Frame.MacSize + payload.Length, Frame.MacSize), false); + return frame; + } + + public Task SendAsync(byte[] data) => Socket.SendAllAsync(data); + + /// Reads a handshake message, with its 2-byte size prefix. + public async Task ReceiveHandshakeAsync(CancellationToken cancellationToken) + { + byte[] prefix = await Socket.ReceiveExactlyAsync(2, cancellationToken); + byte[] body = await Socket.ReceiveExactlyAsync(prefix[0] << 8 | prefix[1], cancellationToken); + return [.. prefix, .. body]; + } + + /// Reads, authenticates and merges frames until a packet is complete. + /// The packet type and the content as sent, so compressed if it was sent with Snappy. + public async Task<(byte PacketType, byte[] Content)> ReceivePacketAsync(CancellationToken cancellationToken) + { + List? chunks = null; + byte packetType = 0; + while (true) + { + byte[] header = await Socket.ReceiveExactlyAsync(Frame.HeaderSize + Frame.MacSize, cancellationToken); + byte[] frame = new byte[Frame.HeaderSize]; + int payloadSize = _decoder.ReadHeader(header.AsSpan(0, Frame.HeaderSize), header.AsSpan(Frame.HeaderSize), frame); + byte[] payload = await Socket.ReceiveExactlyAsync(payloadSize + Frame.MacSize, cancellationToken); + _decoder.AbsorbPayload(payload.AsSpan(0, payloadSize)); + _decoder.CheckPayloadMac(payload.AsSpan(payloadSize)); + Array.Resize(ref frame, Frame.HeaderSize + payloadSize); + _decoder.DecryptPayload(payload.AsSpan(0, payloadSize), frame.AsSpan(Frame.HeaderSize)); + + MergedFrame merged = _merger.Read(frame); + ReadOnlySpan content = frame.AsSpan(merged.ContentOffset, merged.ContentLength); + if (merged.Kind == MergedFrameKind.SinglePacket) + { + return (merged.PacketType, content.ToArray()); + } + + if (merged.Kind == MergedFrameKind.FirstChunk) + { + packetType = merged.PacketType; + chunks = []; + } + + chunks!.AddRange(content); + if (merged.IsComplete) + { + return (packetType, [.. chunks]); + } + } + } +} + +/// +/// A handshake that exchanges fixed messages and hands out given secrets, so a test can pair the connection with a +/// . +/// +internal sealed class FakeHandshakeService(EncryptionSecrets secrets, PublicKey remoteNodeId) : IHandshakeService +{ + /// Gets a handshake message: a 2-byte size prefix and a 3-byte body. + public static byte[] Message => [0, 3, 1, 2, 3]; + + /// Gets the AUTH or ACK messages the handshake was given, as received. + public List Received { get; } = []; + + public Packet Auth(PublicKey remoteNodeId, EncryptionHandshake handshake, bool preEip8Format = false) => new(Message); + + public Packet Ack(EncryptionHandshake handshake, Packet auth) + { + Received.Add(auth.Data); + Complete(handshake); + return new Packet(Message); + } + + public void Agree(EncryptionHandshake handshake, Packet ack) + { + Received.Add(ack.Data); + Complete(handshake); + } + + private void Complete(EncryptionHandshake handshake) + { + handshake.Secrets = secrets; + handshake.RemoteNodeId = remoteNodeId; + } +} diff --git a/src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/SocketRlpxConnectionTests.cs b/src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/SocketRlpxConnectionTests.cs new file mode 100644 index 000000000000..27b785727a29 --- /dev/null +++ b/src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/SocketRlpxConnectionTests.cs @@ -0,0 +1,574 @@ +// SPDX-FileCopyrightText: 2026 Demerzel Solutions Limited +// SPDX-License-Identifier: LGPL-3.0-only + +using System; +using System.Buffers; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Linq; +using System.Net.Sockets; +using System.Threading; +using System.Threading.Tasks; +using Nethermind.Core.Crypto; +using Nethermind.Core.Test.Builders; +using Nethermind.Logging; +using Nethermind.Network.P2P; +using Nethermind.Network.P2P.Messages; +using Nethermind.Network.Rlpx; +using Nethermind.Network.Rlpx.Handshake; +using Nethermind.Network.Rlpx.Sockets; +using Nethermind.Stats.Model; +using NSubstitute; +using NUnit.Framework; +using Snappier; +using static Nethermind.Network.Rlpx.FrameEncoder; + +namespace Nethermind.Network.Test.Rlpx.Sockets; + +[Parallelizable(ParallelScope.All)] +public class SocketRlpxConnectionTests +{ + private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(10); + + [Test] + public async Task Receives_framed_chunked_and_snappy_packets_split_anywhere([Values(1, 7, 16, 23, int.MaxValue)] int maxReceiveLength) + { + await using ConnectionUnderTest test = await ConnectionUnderTest.StartAsync(maxReceiveLength: maxReceiveLength); + byte[] small = Content(100, 1); + byte[] chunked = Content(3000, 2); + byte[] compressed = Content(5000, 3); + + await test.Peer.SendAsync(test.Peer.Encode(0x10, small, EncodingMode.Framed)); + await test.Peer.SendAsync(test.Peer.Encode(0x11, chunked, EncodingMode.Framed)); + await test.WaitForEventsAsync(2); + test.Connection.EnableSnappy(); + await test.Peer.SendAsync(test.Peer.Encode(0x12, compressed, EncodingMode.Snappy)); + await test.WaitForEventsAsync(3); + + Assert.That(test.Packets, Is.EqualTo(new (byte, byte[])[] { (0x10, small), (0x11, chunked), (0x12, compressed) })); + await test.StopAndAssertBuffersReturnedAsync(); + } + + [Test] + public async Task Completes_the_handshake_before_init_and_decodes_bytes_that_follow_the_auth() + { + await using ConnectionUnderTest test = ConnectionUnderTest.Create(); + byte[] content = Content(50, 1); + test.Start(); + + // The AUTH and the first frame arrive in one read. + await test.Peer.SendAsync([.. FakeHandshakeService.Message, .. test.Peer.Encode(0x10, content, EncodingMode.Framed)]); + await test.WaitForEventsAsync(1); + + using (Assert.EnterMultipleScope()) + { + Assert.That(test.Handshake.Received, Is.EqualTo(new[] { FakeHandshakeService.Message }), "the size prefix reaches the handshake service"); + Assert.That(test.Packets, Is.EqualTo(new (byte, byte[])[] { (0x10, content) })); + } + + Received.InOrder(() => + { + test.Session.Handshake(TestItem.PublicKeyB); + test.Session.Init(5, test.Connection); + }); + test.Session.Received(1).Handshake(Arg.Any()); + await test.StopAndAssertBuffersReturnedAsync(); + } + + [Test] + public async Task Stops_decoding_after_a_frame_fails_authentication( + [Values] bool header, + [Values] bool privileged, + [Values(5, int.MaxValue)] int maxReceiveLength) + { + await using ConnectionUnderTest test = await ConnectionUnderTest.StartAsync(privileged: privileged, maxReceiveLength: maxReceiveLength); + // Frames are encoded in the order they are sent, since each one advances the peer's cipher and MAC. + byte[] first = test.Peer.Encode(0x10, Content(100, 1), EncodingMode.Framed); + byte[] corrupted = test.Peer.Encode(0x11, Content(100, 2), EncodingMode.Framed); + byte[] last = test.Peer.Encode(0x12, Content(100, 3), EncodingMode.Framed); + // A header MAC byte, or the payload MAC's last byte. + corrupted[header ? Frame.HeaderSize : ^1] ^= 0xFF; + + await test.Peer.SendAsync([.. first, .. corrupted, .. last]); + string[] expected = privileged ? ["receive 16"] : ["receive 16", "disconnect Exception"]; + await test.WaitForEventsAsync(expected.Length); + await Task.Delay(200); + + using (Assert.EnterMultipleScope()) + { + Assert.That(test.Events, Is.EqualTo(expected), "nothing after the failed frame is decoded"); + Assert.That(test.Connection.Closed.IsCompleted, Is.False, "the transport leaves closing to the session"); + } + + Assert.That(() => test.Pool.OutstandingExceptSendBatch, Is.Empty.After(5000, 10), "the frame buffers are released while the connection stays open"); + await test.StopAndAssertBuffersReturnedAsync(); + } + + [Test] + public async Task Reports_a_merger_error_and_keeps_decoding([Values] bool privileged) + { + await using ConnectionUnderTest test = await ConnectionUnderTest.StartAsync(privileged: privileged); + // An authenticated frame whose header body is not a well formed RLP list. + byte[] header = new byte[Frame.HeaderSize]; + header[2] = Frame.BlockSize; + header[3] = 0xf7; + byte[] next = Content(100, 1); + + await test.Peer.SendAsync([.. test.Peer.EncryptFrame(header, new byte[Frame.BlockSize]), .. test.Peer.Encode(0x10, next, EncodingMode.Framed)]); + string[] expected = privileged ? ["receive 16"] : ["disconnect Exception", "receive 16"]; + await test.WaitForEventsAsync(expected.Length); + + Assert.That(test.Events, Is.EqualTo(expected)); + await test.StopAndAssertBuffersReturnedAsync(); + } + + [Test] + public async Task Handles_a_packet_received_before_a_reset_first() + { + TaskCompletionSource decoding = new(TaskCreationOptions.RunContinuationsAsynchronously); + await using ConnectionUnderTest test = await ConnectionUnderTest.StartAsync(beforeDecoding: () => new ValueTask(decoding.Task)); + byte[] packet = test.Peer.Encode(0x01, Content(10, 1), EncodingMode.Framed); + long received = test.Socket.Received; + + await test.Peer.SendAsync(packet); + Assert.That(() => test.Socket.Received, Is.EqualTo(received + packet.Length).After(5000, 10), "the packet is in the pipe"); + test.Socket.FailReceive(new SocketException((int)SocketError.ConnectionReset)); + await test.Connection.Closed.WaitAsync(Timeout); + decoding.SetResult(); + await test.WaitForEventsAsync(2); + + Assert.That(test.Events, Is.EqualTo(new[] { "receive 1", "disconnect ConnectionReset" })); + await test.StopAndAssertBuffersReturnedAsync(); + } + + [Test] + public async Task Handles_an_error_raised_by_a_packet_before_the_next_packet() + { + TaskCompletionSource held = new(TaskCreationOptions.RunContinuationsAsynchronously); + await using ConnectionUnderTest test = await ConnectionUnderTest.StartAsync(onReceive: packet => + { + // Holds the processing thread, so that the next two packets wait in its queue. + if (packet.PacketType == 0x20) held.Task.Wait(); + }); + test.Connection.EnableSnappy(); + // Declares 5 bytes, then copies from before the start of the output. + byte[] invalidSnappy = [0x05, 0xFF, 0xFF]; + + await test.Peer.SendAsync([ + .. test.Peer.Encode(0x20, Content(10, 1), EncodingMode.Snappy), + .. test.Peer.Encode(0x21, invalidSnappy, EncodingMode.Framed), + .. test.Peer.Encode(0x22, Content(10, 2), EncodingMode.Snappy)]); + Assert.That(() => test.Socket.Received, Is.GreaterThan(FakeHandshakeService.Message.Length).After(5000, 10)); + await Task.Delay(100); + held.SetResult(); + await test.WaitForEventsAsync(3); + + Assert.That(test.Events, Is.EqualTo(new[] { "receive 32", "disconnect Exception", "receive 34" })); + await test.StopAndAssertBuffersReturnedAsync(); + } + + [Test] + public async Task Releases_a_partly_received_packet_at_the_end_of_the_stream() + { + await using ConnectionUnderTest test = await ConnectionUnderTest.StartAsync(); + byte[] frames = test.Peer.Encode(0x10, Content(3000, 1), EncodingMode.Framed); + const int firstFrameLength = Frame.HeaderSize + Frame.MacSize + Frame.DefaultMaxFrameSize + Frame.MacSize; + + await test.Peer.SendAsync(frames[..firstFrameLength]); + test.Peer.Socket.Close(); + await test.Connection.Completion.WaitAsync(Timeout); + + Assert.That(test.Events, Is.Empty, "the end of the stream is not an error"); + await test.StopAndAssertBuffersReturnedAsync(); + } + + [Test] + public async Task Closes_after_the_read_timeout([Values] bool privileged) + { + await using ConnectionUnderTest test = await ConnectionUnderTest.StartAsync(privileged: privileged, readTimeout: TimeSpan.FromMilliseconds(200)); + + await test.Connection.Closed.WaitAsync(Timeout); + await test.Connection.Completion.WaitAsync(Timeout); + await Task.Delay(100); + + Assert.That(test.Events, Is.EqualTo(privileged ? Array.Empty() : ["disconnect Exception"])); + await test.StopAndAssertBuffersReturnedAsync(); + } + + [Test] + public async Task Closes_when_the_handshake_times_out() + { + await using ConnectionUnderTest test = ConnectionUnderTest.Create(); + long timeouts = Metrics.HandshakeTimeouts; + test.Start(); + + await test.Connection.Closed.WaitAsync(Timeout); + + using (Assert.EnterMultipleScope()) + { + Assert.That(Metrics.HandshakeTimeouts, Is.GreaterThan(timeouts)); + test.Session.DidNotReceive().Handshake(Arg.Any()); + } + + await test.StopAndAssertBuffersReturnedAsync(); + } + + [Test] + public async Task Disconnects_for_a_snappy_packet_over_the_size_limit() + { + await using ConnectionUnderTest test = await ConnectionUnderTest.StartAsync(); + test.Connection.EnableSnappy(); + // The Snappy length prefix declares 17 MiB. + byte[] content = [0x80, 0x80, 0x80, 0x11, 0x00]; + + await test.Peer.SendAsync(test.Peer.Encode(0x10, content, EncodingMode.Framed)); + await test.WaitForEventsAsync(1); + + Assert.That(test.Events, Is.EqualTo(new[] { "disconnect BreachOfProtocol" })); + await test.StopAndAssertBuffersReturnedAsync(); + } + + [Test] + public async Task Keeps_a_leased_packet_readable_after_the_connection_stops([Values] bool snappy) + { + IMemoryOwner? lease = null; + await using ConnectionUnderTest test = await ConnectionUnderTest.StartAsync(onReceive: packet => lease = packet.LeaseContent()); + byte[] content = Content(100, 1); + if (snappy) test.Connection.EnableSnappy(); + + await test.Peer.SendAsync(test.Peer.Encode(0x10, content, snappy ? EncodingMode.Snappy : EncodingMode.Framed)); + await test.WaitForEventsAsync(1); + await test.StopAsync(); + + using (Assert.EnterMultipleScope()) + { + Assert.That(lease!.Memory.ToArray(), Is.EqualTo(content)); + Assert.That(test.Pool.Outstanding, Has.Length.EqualTo(1), "the lease holds its buffer"); + } + + lease.Dispose(); + await test.StopAndAssertBuffersReturnedAsync(); + } + + [Test] + public async Task Sends_each_thread_s_packets_in_order() + { + const int Threads = 4; + const int PacketsPerThread = 100; + await using ConnectionUnderTest test = await ConnectionUnderTest.StartAsync(); + + Task[] senders = Enumerable.Range(0, Threads).Select(thread => Task.Run(() => + { + for (int i = 0; i < PacketsPerThread; i++) + { + test.Enqueue([(byte)thread, (byte)i, .. Content(100 * (i % 20), i)]); + } + })).ToArray(); + await Task.WhenAll(senders); + + int[] next = new int[Threads]; + for (int i = 0; i < Threads * PacketsPerThread; i++) + { + (_, byte[] content) = await test.Peer.ReceivePacketAsync(test.Cancellation); + Assert.That(content[1], Is.EqualTo(next[content[0]]++), $"thread {content[0]}'s packets arrive in order"); + } + + await test.StopAndAssertBuffersReturnedAsync(); + } + + [Test] + public async Task Sends_a_packet_larger_than_the_batch_and_the_one_after_it([Values(1, 7, 1000, int.MaxValue)] int maxSendLength) + { + await using ConnectionUnderTest test = await ConnectionUnderTest.StartAsync(); + test.Socket.MaxSendLength = maxSendLength; + byte[] large = Content(SocketRlpxConnection.SendBatchSize + 1000, 1); + byte[] small = Content(10, 2); + + test.Enqueue(small); + test.Enqueue(large); + test.Enqueue(small); + + using (Assert.EnterMultipleScope()) + { + Assert.That((await test.Peer.ReceivePacketAsync(test.Cancellation)).Content, Is.EqualTo(small)); + Assert.That((await test.Peer.ReceivePacketAsync(test.Cancellation)).Content, Is.EqualTo(large)); + Assert.That((await test.Peer.ReceivePacketAsync(test.Cancellation)).Content, Is.EqualTo(small)); + } + + await test.StopAndAssertBuffersReturnedAsync(); + } + + [Test] + public async Task Sends_the_handshake_without_the_simulated_latency([Values] HandshakeRole role) + { + await using ConnectionUnderTest test = ConnectionUnderTest.Create(role, sendLatency: TimeSpan.FromSeconds(30)); + using CancellationTokenSource quickly = new(TimeSpan.FromSeconds(3)); + test.Start(); + + if (role == HandshakeRole.Recipient) + { + await test.Peer.SendAsync(FakeHandshakeService.Message); + } + + Assert.That(await test.Peer.ReceiveHandshakeAsync(quickly.Token), Is.EqualTo(FakeHandshakeService.Message)); + await test.StopAndAssertBuffersReturnedAsync(); + } + + [Test] + public async Task Keeps_the_encoding_mode_a_packet_was_queued_with() + { + await using ConnectionUnderTest test = await ConnectionUnderTest.StartAsync(sendLatency: TimeSpan.FromMilliseconds(300)); + byte[] framed = Content(100, 1); + byte[] compressed = Content(100, 2); + + test.Enqueue(framed); + test.Connection.EnableSnappy(); + test.Enqueue(compressed); + + using (Assert.EnterMultipleScope()) + { + Assert.That((await test.Peer.ReceivePacketAsync(test.Cancellation)).Content, Is.EqualTo(framed)); + Assert.That(Snappy.DecompressToArray((await test.Peer.ReceivePacketAsync(test.Cancellation)).Content), Is.EqualTo(compressed)); + } + + await test.StopAndAssertBuffersReturnedAsync(); + } + + [Test] + public async Task Stops_taking_packets_at_the_high_watermark_until_they_are_sent() + { + TaskCompletionSource sending = new(TaskCreationOptions.RunContinuationsAsynchronously); + await using ConnectionUnderTest test = await ConnectionUnderTest.StartAsync(); + test.Socket.SendGate = sending.Task; + byte[] content = Content(100_000, 1); + + int queued = 0; + while (test.Connection.IsWritable && queued < 100) + { + Assert.That(test.Enqueue(content), Is.EqualTo(content.Length + 1)); + queued++; + } + + using (Assert.EnterMultipleScope()) + { + Assert.That(queued, Is.EqualTo(30), "3,000,000 bytes of 100,001-byte packets"); + Assert.That(test.Enqueue(content), Is.Zero, "a packet is dropped while the connection is not writable"); + } + + sending.SetResult(); + for (int i = 0; i < queued; i++) + { + await test.Peer.ReceivePacketAsync(test.Cancellation); + } + + Assert.That(() => test.Connection.IsWritable, Is.True.After(5000, 10)); + await test.Connection.DisconnectAsync(); + Assert.That(test.Connection.IsWritable, Is.False, "a closed connection takes nothing"); + await test.StopAndAssertBuffersReturnedAsync(); + } + + [Test] + public async Task Releases_a_packet_serialized_while_the_connection_closes() + { + await using ConnectionUnderTest test = await ConnectionUnderTest.StartAsync(); + byte[] content = Content(100, 1); + + int length = test.Connection.Enqueue(new PayloadMessage(content, () => test.Connection.DisconnectAsync()) { AdaptivePacketType = 0x10 }); + + Assert.That(length, Is.EqualTo(content.Length + 1), "as on DotNetty, the packet counts as sent"); + await test.StopAndAssertBuffersReturnedAsync(); + } + + [Test] + public async Task Closes_without_reporting_a_failed_send() + { + await using ConnectionUnderTest test = await ConnectionUnderTest.StartAsync(); + test.Socket.SendError = new SocketException((int)SocketError.ConnectionReset); + + test.Enqueue(Content(10, 1)); + await test.Connection.Closed.WaitAsync(Timeout); + await test.Connection.Completion.WaitAsync(Timeout); + + Assert.That(test.Events, Is.Empty); + await test.StopAndAssertBuffersReturnedAsync(); + } + + private static byte[] Content(int length, int seed) + { + byte[] content = new byte[length]; + new Random(seed).NextBytes(content); + return content; + } + + private sealed class PayloadMessage(byte[] payload, Action? onSerialize = null) : P2PMessage + { + public override int PacketType => 0x10; + + public override string Protocol => "test"; + + public byte[] Payload => payload; + + public Action? OnSerialize => onSerialize; + } + + private sealed class PayloadSerializer : IMessageSerializer + { + public int GetLength(PayloadMessage message) => message.Payload.Length; + + public int Serialize(Span destination, PayloadMessage message) + { + message.OnSerialize?.Invoke(); + message.Payload.CopyTo(destination); + return message.Payload.Length; + } + + public PayloadMessage Deserialize(ReadOnlySpan data) => throw new NotSupportedException(); + } + + /// A connection on an in-memory socket, its scripted peer, and a session that records what it is given. + private sealed class ConnectionUnderTest : IAsyncDisposable + { + private readonly CancellationTokenSource _cancellation = new(Timeout); + private readonly HandshakeRole _role; + private bool _stopped; + + private ConnectionUnderTest( + HandshakeRole role, + bool privileged, + int maxReceiveLength, + TimeSpan sendLatency, + TimeSpan? readTimeout, + Func? beforeDecoding, + Action? onReceive) + { + _role = role; + (EncryptionSecrets initiator, EncryptionSecrets recipient) = NetTestVectors.GetSecretsPair(); + (EncryptionSecrets local, EncryptionSecrets remote) = role == HandshakeRole.Initiator ? (initiator, recipient) : (recipient, initiator); + (Socket, InMemoryRlpxSocket peerSocket) = InMemoryRlpxSocket.CreatePair(); + Socket.MaxReceiveLength = maxReceiveLength; + Peer = new ScriptedRlpxPeer(peerSocket, remote); + Handshake = new FakeHandshakeService(local, TestItem.PublicKeyB); + Threads = new RlpxProcessingThreads(1, LimboLogs.Instance.GetClassLogger()); + Connection = new SocketRlpxConnection( + Socket, + role, + Handshake, + new MessageSerializationService(SerializerInfo.Create(new PayloadSerializer())), + Threads.Next(), + LimboLogs.Instance, + sendLatency, + ZeroFrameDecoder.DefaultMaxInboundFrameSize, + Pool) + { + ReadTimeout = readTimeout ?? SocketRlpxConnection.DefaultReadTimeout, + BeforeDecoding = beforeDecoding + }; + + Session = Substitute.For(); + Session.Node.Returns(new Node(TestItem.PublicKeyB, "127.0.0.1", 30303, isStatic: privileged)); + Session.RemoteNodeId.Returns(TestItem.PublicKeyB); + Session.When(static s => s.ReceiveMessage(Arg.Any())).Do(call => + { + ZeroPacket packet = call.Arg(); + onReceive?.Invoke(packet); + Packets.Enqueue((packet.PacketType, packet.Content.ToArray())); + Events.Enqueue($"receive {packet.PacketType}"); + }); + Session.When(static s => s.InitiateDisconnect(Arg.Any(), Arg.Any())) + .Do(call => Events.Enqueue($"disconnect {call.ArgAt(0)}")); + Session.When(static s => s.Init(Arg.Any(), Arg.Any())).Do(_ => Initialized.TrySetResult()); + } + + public SocketRlpxConnection Connection { get; } + + public InMemoryRlpxSocket Socket { get; } + + public ScriptedRlpxPeer Peer { get; } + + public FakeHandshakeService Handshake { get; } + + public ISession Session { get; } + + public RlpxProcessingThreads Threads { get; } + + public TrackingArrayPool Pool { get; } = new(); + + public ConcurrentQueue Events { get; } = new(); + + public ConcurrentQueue<(byte, byte[])> Packets { get; } = new(); + + public TaskCompletionSource Initialized { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + + public CancellationToken Cancellation => _cancellation.Token; + + public static ConnectionUnderTest Create( + HandshakeRole role = HandshakeRole.Recipient, + bool privileged = false, + int maxReceiveLength = int.MaxValue, + TimeSpan sendLatency = default, + TimeSpan? readTimeout = null, + Func? beforeDecoding = null, + Action? onReceive = null) + => new(role, privileged, maxReceiveLength, sendLatency, readTimeout, beforeDecoding, onReceive); + + /// Starts the connection and completes the handshake as the peer. + public static async Task StartAsync( + bool privileged = false, + int maxReceiveLength = int.MaxValue, + TimeSpan sendLatency = default, + TimeSpan? readTimeout = null, + Func? beforeDecoding = null, + Action? onReceive = null) + { + ConnectionUnderTest test = Create(HandshakeRole.Recipient, privileged, maxReceiveLength, sendLatency, readTimeout, beforeDecoding, onReceive); + test.Start(); + await test.Peer.SendAsync(FakeHandshakeService.Message); + await test.Peer.ReceiveHandshakeAsync(test.Cancellation); + await test.Initialized.Task.WaitAsync(Timeout); + return test; + } + + public void Start() => Connection.Start(Session); + + public int Enqueue(byte[] content) => Connection.Enqueue(new PayloadMessage(content) { AdaptivePacketType = 0x10 }); + + public async Task WaitForEventsAsync(int count) + { + while (Events.Count < count) + { + await Task.Delay(5, Cancellation); + } + } + + /// Closes the connection and waits for its loops and processing thread to finish. + public async Task StopAsync() + { + if (_stopped) + { + return; + } + + _stopped = true; + await Connection.DisconnectAsync(); + await Connection.Completion.WaitAsync(Timeout); + await Threads.StopAsync().WaitAsync(Timeout); + Peer.Socket.Close(); + } + + public async Task StopAndAssertBuffersReturnedAsync() + { + await StopAsync(); + using (Assert.EnterMultipleScope()) + { + Assert.That(Pool.Outstanding, Is.Empty, "every rented buffer is returned"); + Assert.That(Pool.DoubleReturns, Is.Zero, "no buffer is returned twice"); + } + } + + public async ValueTask DisposeAsync() + { + await StopAsync(); + _cancellation.Dispose(); + } + } +} diff --git a/src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/SocketRlpxHostTests.cs b/src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/SocketRlpxHostTests.cs new file mode 100644 index 000000000000..28b1e4ed00ff --- /dev/null +++ b/src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/SocketRlpxHostTests.cs @@ -0,0 +1,280 @@ +// SPDX-FileCopyrightText: 2026 Demerzel Solutions Limited +// SPDX-License-Identifier: LGPL-3.0-only + +using System; +using System.Net; +using System.Net.Sockets; +using System.Threading; +using System.Threading.Tasks; +using Autofac; +using Nethermind.Core; +using Nethermind.Core.Test.Builders; +using Nethermind.Logging; +using Nethermind.Network.Config; +using Nethermind.Network.P2P.EventArg; +using Nethermind.Network.Rlpx; +using Nethermind.Network.Rlpx.Sockets; +using Nethermind.Stats.Model; +using NUnit.Framework; +using static Nethermind.Network.Test.RlpxHostIntegrationTests; + +namespace Nethermind.Network.Test.Rlpx.Sockets; + +[NonParallelizable] +public class SocketRlpxHostTests +{ + private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(10); + private bool _diagTracerWasEnabled; + + /// + /// Other tests leave the tracer on, and it makes throw for an inbound + /// session that has not completed its handshake, before the disconnect is reported. + /// + [SetUp] + public void DisableDiagTracer() + { + _diagTracerWasEnabled = NetworkDiagTracer.IsEnabled; + NetworkDiagTracer.IsEnabled = false; + } + + [TearDown] + public void RestoreDiagTracer() => NetworkDiagTracer.IsEnabled = _diagTracerWasEnabled; + + [Test] + public async Task Is_the_rlpx_host_when_configured([Values] RlpxTransport transport) + { + await using IContainer container = CreateListenerContainer("127.0.0.1", IPAddress.Loopback, GetAvailablePort(), transport: transport); + IRlpxHost host = container.Resolve(); + try + { + Assert.That(host, Is.TypeOf(transport == RlpxTransport.Sockets ? typeof(SocketRlpxHost) : typeof(RlpxHost))); + } + finally + { + await host.Shutdown(); + } + } + + [TestCase("127.0.0.1", true, false)] + [TestCase("::1", false, true)] + [TestCase("::", true, true)] + public async Task Listens_on_the_configured_address_until_shut_down(string configuredIp, bool acceptsIpv4, bool acceptsIpv6) + { + IPAddress address = IPAddress.Parse(configuredIp); + if (address.AddressFamily == AddressFamily.InterNetworkV6 && !Socket.OSSupportsIPv6) + { + Assert.Ignore("IPv6 is not supported on this host."); + } + + int port = GetAvailablePort(); + await using IContainer container = CreateListenerContainer(configuredIp, address, port, transport: RlpxTransport.Sockets); + IRlpxHost host = container.Resolve(); + NetworkListenerState listenerState = container.Resolve(); + try + { + await host.Init(); + using (Assert.EnterMultipleScope()) + { + Assert.That(listenerState.RlpxAddress, Is.EqualTo(address)); + Assert.That(await CanConnect(AddressFamily.InterNetwork, port), Is.EqualTo(acceptsIpv4)); + Assert.That(await CanConnect(AddressFamily.InterNetworkV6, port), Is.EqualTo(acceptsIpv6)); + } + + await host.Shutdown(); + Assert.That(() => listenerState.RlpxAddress, Is.Null.After(5000, 10)); + } + finally + { + await host.Shutdown(); + } + } + + [Test] + public async Task Falls_back_to_ipv4_when_the_widened_bind_fails() + { + if (!Socket.OSSupportsIPv6) + { + Assert.Ignore("IPv6 is not supported on this host."); + } + + using Socket ipv6Blocker = CreateTcpListenerSocket(IPAddress.IPv6Any, 0); + int port = ((IPEndPoint)ipv6Blocker.LocalEndPoint!).Port; + NetworkListenerState listenerState = new(IPAddress.Any, IPAddress.IPv6Any, LimboLogs.Instance); + await using IContainer container = CreateListenerContainer(null, IPAddress.Any, port, listenerState, transport: RlpxTransport.Sockets); + IRlpxHost host = container.Resolve(); + try + { + await host.Init(); + using (Assert.EnterMultipleScope()) + { + Assert.That(listenerState.RlpxAddress, Is.EqualTo(IPAddress.Any)); + Assert.That(await CanConnect(AddressFamily.InterNetwork, port), Is.True); + } + } + finally + { + await host.Shutdown(); + } + } + + [Test] + public async Task Reports_a_port_in_use() + { + using Socket blocker = CreateTcpListenerSocket(IPAddress.Loopback, 0); + int port = ((IPEndPoint)blocker.LocalEndPoint!).Port; + await using IContainer container = CreateListenerContainer("127.0.0.1", IPAddress.Loopback, port, transport: RlpxTransport.Sockets); + IRlpxHost host = container.Resolve(); + NetworkListenerState listenerState = container.Resolve(); + try + { + Assert.That(async () => await host.Init(), Throws.TypeOf()); + Assert.That(listenerState.RlpxAddress, Is.Null); + } + finally + { + await host.Shutdown(); + } + } + + [Test] + public async Task Reports_an_unassigned_address() + { + // RFC 5737 documentation address, never assigned to a local interface. + const string unassignedIp = "192.0.2.1"; + await using IContainer container = CreateListenerContainer(unassignedIp, IPAddress.Parse(unassignedIp), GetAvailablePort(), transport: RlpxTransport.Sockets); + IRlpxHost host = container.Resolve(); + try + { + Assert.That(async () => await host.Init(), Throws.TypeOf().With.InnerException.TypeOf()); + } + finally + { + await host.Shutdown(); + } + } + + [Test] + public async Task Closes_an_inbound_connection_the_filter_rejects() + { + await using IContainer container = CreateFilterContainer(filterEnabled: true, subnetBucketing: false, transport: RlpxTransport.Sockets); + SocketRlpxHost host = (SocketRlpxHost)container.Resolve(); + int sessions = 0; + host.SessionCreated += (_, _) => Interlocked.Increment(ref sessions); + try + { + await host.Init(); + IPEndPoint listener = new(IPAddress.Loopback, host.ListenerEndPoint!.Port); + using Socket first = new(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); + await first.ConnectAsync(listener); + Assert.That(() => Volatile.Read(ref sessions), Is.EqualTo(1).After(5000, 10)); + + using Socket second = new(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); + await second.ConnectAsync(listener); + using CancellationTokenSource timeout = new(Timeout); + using (Assert.EnterMultipleScope()) + { + Assert.That(await ReceiveAsync(second, timeout.Token), Is.Zero, "the rejected connection is closed"); + Assert.That(Volatile.Read(ref sessions), Is.EqualTo(1)); + Assert.That(host.ConnectionCount, Is.EqualTo(1)); + } + } + finally + { + await host.Shutdown(); + } + } + + [Test] + public async Task Returns_false_for_a_refused_dial() + { + await using IContainer container = CreateFilterContainer(filterEnabled: false, subnetBucketing: false, transport: RlpxTransport.Sockets); + IRlpxHost host = container.Resolve(); + using Socket refused = ReserveRefusedPort(IPAddress.Loopback); + try + { + await host.Init(); + Assert.That(await host.ConnectAsync(new Node(TestItem.PublicKeyA, (IPEndPoint)refused.LocalEndPoint!)), Is.False); + } + finally + { + await host.Shutdown(); + } + } + + [Test] + public async Task Throws_when_the_caller_cancels_a_dial() + { + await using IContainer container = CreateFilterContainer(filterEnabled: false, subnetBucketing: false, transport: RlpxTransport.Sockets); + IRlpxHost host = container.Resolve(); + using CancellationTokenSource canceled = new(); + canceled.Cancel(); + try + { + await host.Init(); + Assert.That(async () => await host.ConnectAsync(new Node(TestItem.PublicKeyA, new IPEndPoint(IPAddress.Loopback, 30303)), canceled.Token), + Throws.InstanceOf()); + } + finally + { + await host.Shutdown(); + } + } + + [Test] + public async Task Shutdown_waits_for_a_pending_dial_which_publishes_nothing() + { + await using IContainer container = CreateFilterContainer(filterEnabled: false, subnetBucketing: false, transport: RlpxTransport.Sockets); + IRlpxHost host = container.Resolve(); + int sessions = 0; + host.SessionCreated += (_, _) => Interlocked.Increment(ref sessions); + await host.Init(); + + // A private address that answers nothing, so the dial stays pending until it is canceled. + Task dial = host.ConnectAsync(new Node(TestItem.PublicKeyA, new IPEndPoint(IPAddress.Parse("10.255.255.1"), 30303))); + await Task.Delay(100); + await host.Shutdown(); + + using (Assert.EnterMultipleScope()) + { + Assert.That(dial.IsCompleted, Is.True, "shutdown waits for the dial"); + Assert.That(await dial, Is.False); + Assert.That(sessions, Is.Zero); + } + } + + [Test] + public async Task Shutdown_closes_the_connections_and_waits_for_them() + { + await using IContainer container = CreateFilterContainer(filterEnabled: false, subnetBucketing: false, transport: RlpxTransport.Sockets); + SocketRlpxHost host = (SocketRlpxHost)container.Resolve(); + TaskCompletionSource disconnected = new(TaskCreationOptions.RunContinuationsAsynchronously); + host.SessionDisconnected += (_, _, args) => disconnected.TrySetResult(args); + await host.Init(); + + using Socket client = new(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); + await client.ConnectAsync(new IPEndPoint(IPAddress.Loopback, host.ListenerEndPoint!.Port)); + Assert.That(() => host.ConnectionCount, Is.EqualTo(1).After(5000, 10)); + await host.Shutdown(); + + using CancellationTokenSource timeout = new(Timeout); + using (Assert.EnterMultipleScope()) + { + Assert.That(host.ConnectionCount, Is.Zero); + Assert.That((await disconnected.Task.WaitAsync(timeout.Token)).DisconnectType, Is.EqualTo(DisconnectType.Remote)); + Assert.That(await ReceiveAsync(client, timeout.Token), Is.Zero, "the client sees the connection close"); + } + } + + /// The bytes received, or zero once the remote end closed or reset the connection. + private static async Task ReceiveAsync(Socket socket, CancellationToken cancellationToken) + { + try + { + return await socket.ReceiveAsync(new byte[256], SocketFlags.None, cancellationToken); + } + catch (SocketException e) when (e.SocketErrorCode == SocketError.ConnectionReset) + { + return 0; + } + } +} diff --git a/src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/TrackingArrayPool.cs b/src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/TrackingArrayPool.cs new file mode 100644 index 000000000000..3c13df2cf747 --- /dev/null +++ b/src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/TrackingArrayPool.cs @@ -0,0 +1,58 @@ +// SPDX-FileCopyrightText: 2026 Demerzel Solutions Limited +// SPDX-License-Identifier: LGPL-3.0-only + +using System.Buffers; +using System.Collections.Generic; +using System.Linq; +using System.Threading; + +namespace Nethermind.Network.Test.Rlpx.Sockets; + +/// +/// An array pool that tracks every rental, so a test can see buffers that were never returned or returned twice. +/// +internal sealed class TrackingArrayPool : ArrayPool +{ + private readonly Lock _lock = new(); + private readonly Dictionary _outstanding = [with(ReferenceEqualityComparer.Instance)]; + private int _doubleReturns; + + /// Gets the lengths requested for the buffers not yet returned. + public int[] Outstanding + { + get + { + lock (_lock) + { + return [.. _outstanding.Values.Order()]; + } + } + } + + /// Gets the lengths requested for the buffers not yet returned, apart from the send loop's batch. + public int[] OutstandingExceptSendBatch => [.. Outstanding.Where(static length => length != Nethermind.Network.Rlpx.Sockets.SocketRlpxConnection.SendBatchSize)]; + + public int DoubleReturns => Volatile.Read(ref _doubleReturns); + + public override byte[] Rent(int minimumLength) + { + byte[] buffer = new byte[minimumLength]; + lock (_lock) + { + _outstanding.Add(buffer, minimumLength); + } + + return buffer; + } + + public override void Return(byte[] array, bool clearArray = false) + { + lock (_lock) + { + if (!_outstanding.Remove(array)) + { + _doubleReturns++; + } + } + } +} diff --git a/src/Nethermind/Nethermind.Network.Test/RlpxHostIntegrationTests.cs b/src/Nethermind/Nethermind.Network.Test/RlpxHostIntegrationTests.cs index cc469859cc38..cc216077c13b 100644 --- a/src/Nethermind/Nethermind.Network.Test/RlpxHostIntegrationTests.cs +++ b/src/Nethermind/Nethermind.Network.Test/RlpxHostIntegrationTests.cs @@ -1096,8 +1096,8 @@ private static Node CreateNode(NodeRecord record, bool verified) return node!; } - private static IContainer CreateFilterContainer(bool filterEnabled, bool subnetBucketing, string? externalIp = null, - IPrivilegedIpProvider? privilegedIpProvider = null) + internal static IContainer CreateFilterContainer(bool filterEnabled, bool subnetBucketing, string? externalIp = null, + IPrivilegedIpProvider? privilegedIpProvider = null, RlpxTransport transport = RlpxTransport.DotNetty) { NetworkConfig networkConfig = new() { @@ -1106,7 +1106,8 @@ private static IContainer CreateFilterContainer(bool filterEnabled, bool subnetB FilterPeersByRecentIp = filterEnabled, FilterPeersBySameSubnet = subnetBucketing, ExternalIp = externalIp, - MaxActivePeers = 50 + MaxActivePeers = 50, + RlpxTransport = transport }; IIPResolver ipResolver = Substitute.For(); @@ -1116,7 +1117,7 @@ private static IContainer CreateFilterContainer(bool filterEnabled, bool subnetB return CreateContainer(networkConfig, ipResolver, privilegedIpProvider: privilegedIpProvider); } - private static IContainer CreateListenerContainer( + internal static IContainer CreateListenerContainer( string? localIpConfig, IPAddress resolvedLocalIp, int port, @@ -1124,7 +1125,8 @@ private static IContainer CreateListenerContainer( IChannelFactory? channelFactory = null, IPrivilegedIpProvider? privilegedIpProvider = null, ILogManager? logManager = null, - long shutdownCloseTimeoutMs = 100) + long shutdownCloseTimeoutMs = 100, + RlpxTransport transport = RlpxTransport.DotNetty) { NetworkConfig networkConfig = new() { @@ -1132,7 +1134,8 @@ private static IContainer CreateListenerContainer( P2PPort = port, LocalIp = localIpConfig, MaxActivePeers = 50, - RlpxHostShutdownCloseTimeoutMs = shutdownCloseTimeoutMs + RlpxHostShutdownCloseTimeoutMs = shutdownCloseTimeoutMs, + RlpxTransport = transport }; IIPResolver ipResolver = Substitute.For(); ipResolver.Resolve(Arg.Any()).Returns( @@ -1194,7 +1197,7 @@ private static async Task ReceiveUntilClosedAsync(Socket socket, CancellationTok } } - private static async Task CanConnect(AddressFamily addressFamily, int port) + internal static async Task CanConnect(AddressFamily addressFamily, int port) { if (addressFamily == AddressFamily.InterNetworkV6 && !Socket.OSSupportsIPv6) { @@ -1227,7 +1230,7 @@ private static void AssertChannelsClosed(IReadOnlyList channels) } } - private static Socket CreateTcpListenerSocket(IPAddress address, int port, bool exclusiveAddressUse = true) + internal static Socket CreateTcpListenerSocket(IPAddress address, int port, bool exclusiveAddressUse = true) { Socket socket = new(address.AddressFamily, SocketType.Stream, ProtocolType.Tcp); try @@ -1389,14 +1392,14 @@ public void Agree(EncryptionHandshake handshake, Packet ack) /// listener port, can be the same one and turn the dial that should be refused into a connection. Exclusive, so no /// address-reusing bind can share it either. /// - private static Socket ReserveRefusedPort(IPAddress address) + internal static Socket ReserveRefusedPort(IPAddress address) { Socket socket = new(address.AddressFamily, SocketType.Stream, ProtocolType.Tcp) { ExclusiveAddressUse = true }; socket.Bind(new IPEndPoint(address, 0)); return socket; } - private static int GetAvailablePort() + internal static int GetAvailablePort() { using System.Net.Sockets.TcpListener listener = new(IPAddress.Loopback, 0); listener.Start(); diff --git a/src/Nethermind/Nethermind.Network/Rlpx/Sockets/OutboundBytes.cs b/src/Nethermind/Nethermind.Network/Rlpx/Sockets/OutboundBytes.cs new file mode 100644 index 000000000000..736f35b0166f --- /dev/null +++ b/src/Nethermind/Nethermind.Network/Rlpx/Sockets/OutboundBytes.cs @@ -0,0 +1,48 @@ +// SPDX-FileCopyrightText: 2026 Demerzel Solutions Limited +// SPDX-License-Identifier: LGPL-3.0-only + +namespace Nethermind.Network.Rlpx.Sockets; + +/// +/// Counts the bytes a connection has taken to send and not yet sent, and tells whether it takes more. +/// +/// +/// It uses the watermarks gives DotNetty, with the comparisons of DotNetty's +/// ChannelOutboundBuffer: no longer writable at the high watermark, writable again at the low one. The +/// connection updates it under its lock; can be read from any thread. +/// +internal sealed class OutboundBytes +{ + public const long HighWaterMark = 3_000_000; + public const long LowWaterMark = 1_000_000; + + private long _pending; + private volatile bool _writable = true; + private bool _closed; + + /// Gets whether the connection takes more packets: false from the high watermark until the low one, and once closed. + public bool IsWritable => _writable; + + public long Pending => _pending; + + /// Charges bytes taken to send, or releases sent ones with a negative count. + public void Add(long bytes) + { + _pending += bytes; + if (_writable && _pending >= HighWaterMark) + { + _writable = false; + } + else if (!_writable && !_closed && _pending <= LowWaterMark) + { + _writable = true; + } + } + + /// Stops taking packets for good. + public void Close() + { + _closed = true; + _writable = false; + } +} diff --git a/src/Nethermind/Nethermind.Network/Rlpx/Sockets/PooledPacket.cs b/src/Nethermind/Nethermind.Network/Rlpx/Sockets/PooledPacket.cs index 64158f102bc1..7db94b2c17d1 100644 --- a/src/Nethermind/Nethermind.Network/Rlpx/Sockets/PooledPacket.cs +++ b/src/Nethermind/Nethermind.Network/Rlpx/Sockets/PooledPacket.cs @@ -9,17 +9,17 @@ namespace Nethermind.Network.Rlpx.Sockets; /// -/// A received packet over an array rented from , which goes back to the pool when the -/// last reference is released. +/// A received packet over a rented array, which goes back to its pool when the last reference is released. /// /// /// The transport holds one reference and releases it once the session has handled the packet. Each /// adds a reference, so a serializer that keeps the content needs no copy. /// +/// The pool the buffer was rented from. /// A rented array, which the packet now owns. /// Where the content starts. /// The length of the content. -internal sealed class PooledPacket(byte[] buffer, int offset, int length) : ZeroPacket +internal sealed class PooledPacket(ArrayPool pool, byte[] buffer, int offset, int length) : ZeroPacket { private byte[] _buffer = buffer; private int _offset = offset; @@ -52,9 +52,9 @@ public void SetContent(int offset, int length) public void Grow(int capacity) { Debug.Assert(IsExclusive, "Only an unshared packet can be rewritten."); - byte[] buffer = ArrayPool.Shared.Rent(capacity); + byte[] buffer = pool.Rent(capacity); _buffer.AsSpan(_offset, _length).CopyTo(buffer); - ArrayPool.Shared.Return(_buffer); + pool.Return(_buffer); _buffer = buffer; _offset = 0; } @@ -66,7 +66,7 @@ public void Release() Debug.Assert(references >= 0, "A packet was released more times than it was referenced."); if (references == 0) { - ArrayPool.Shared.Return(_buffer); + pool.Return(_buffer); _buffer = []; } } diff --git a/src/Nethermind/Nethermind.Network/Rlpx/Sockets/SocketRlpxConnection.cs b/src/Nethermind/Nethermind.Network/Rlpx/Sockets/SocketRlpxConnection.cs index f23e67bab6dd..3a7c886a384c 100644 --- a/src/Nethermind/Nethermind.Network/Rlpx/Sockets/SocketRlpxConnection.cs +++ b/src/Nethermind/Nethermind.Network/Rlpx/Sockets/SocketRlpxConnection.cs @@ -34,7 +34,7 @@ namespace Nethermind.Network.Rlpx.Sockets; /// /// /// The processing thread runs what ZeroNettyP2PHandler runs on DotNetty's executor: the size limit, Snappy and -/// , and the error handling, in the order the frame loop queued them. +/// , and the error handling, in the order the frame loop queued them. /// /// /// The connected socket. @@ -45,6 +45,7 @@ namespace Nethermind.Network.Rlpx.Sockets; /// The log manager. /// The simulated latency of every packet sent, for tests and benchmarks. /// The largest frame payload accepted. +/// The pool of the connection's buffers; the shared one unless a test counts rentals. internal sealed class SocketRlpxConnection( IRlpxSocket socket, HandshakeRole role, @@ -53,23 +54,22 @@ internal sealed class SocketRlpxConnection( RlpxProcessingThreads.ProcessingThread processingThread, ILogManager logManager, TimeSpan sendLatency, - int maxInboundFrameSize) : IRlpxConnection, IPacketSender + int maxInboundFrameSize, + ArrayPool? pool = null) : IRlpxConnection, IPacketSender { - /// The outbound bytes at which the connection stops taking packets: the watermark gives DotNetty. - internal const long WriteBufferHighWaterMark = 3_000_000; - - /// The outbound bytes at which a connection that stopped taking packets takes them again. - internal const long WriteBufferLowWaterMark = 1_000_000; - /// The largest handshake message, with its 2-byte size prefix, as DotNetty's length field decoder allows. internal const int MaxHandshakeLength = ushort.MaxValue; - internal static readonly TimeSpan ReadTimeout = TimeSpan.FromSeconds(30); + /// The time without receiving anything after which the connection closes, as DotNetty's ReadTimeoutHandler. + internal static readonly TimeSpan DefaultReadTimeout = TimeSpan.FromSeconds(30); + + /// The largest packet encoded into the shared send batch; a larger one gets its own buffer. + internal const int SendBatchSize = 64 * 1024; private const int ReceiveSegmentSize = 16 * 1024; - private const int SendBatchSize = 64 * 1024; private const int MaxRetainedSnappyOutputCapacity = 64 * 1024; + private readonly ArrayPool _pool = pool ?? ArrayPool.Shared; private readonly IRlpxSocket _socket = socket; private readonly HandshakeRole _role = role; private readonly IHandshakeService _handshakeService = handshakeService; @@ -86,9 +86,11 @@ internal sealed class SocketRlpxConnection( private readonly CancellationTokenSource _receiveCancellation = new(); private readonly CancellationTokenSource _sendCancellation = new(); private readonly TaskCompletionSource _closed = new(TaskCreationOptions.RunContinuationsAsynchronously); - private Session _session = null!; + private ISession _session = null!; private Task _completion = Task.CompletedTask; private volatile bool _isClosed; + private FrameMacProcessor? _ingressMac; + private FrameMacProcessor? _egressMac; // Receive loop private Exception? _terminalCause; @@ -121,8 +123,7 @@ internal sealed class SocketRlpxConnection( private bool _sendLoopWaiting; private FrameEncoder? _encoder; private FrameEncoder.EncodingMode _encodingMode = FrameEncoder.EncodingMode.Framed; - private long _pendingBytes; - private volatile bool _writable = true; + private readonly OutboundBytes _outboundBytes = new(); /// Completes when the connection has closed, before the frames already received are handled. public Task Closed => _closed.Task; @@ -130,16 +131,36 @@ internal sealed class SocketRlpxConnection( /// Completes when the connection's loops have finished. public Task Completion => _completion; - public bool IsWritable => _writable; + public bool IsWritable => _outboundBytes.IsWritable; + + /// Gets or sets the time without receiving anything after which the connection closes. + internal TimeSpan ReadTimeout { get; init; } = DefaultReadTimeout; + + /// Runs before each batch of received bytes is decoded; a test holds it to hold the frame loop. + internal Func? BeforeDecoding { get; init; } /// Starts the handshake and the loops of a connection whose session has been created. - public void Start(Session session) + public void Start(ISession session) { _session = session; - _completion = Task.WhenAll( - Task.Run(SendLoopAsync), - Task.Run(ReceiveLoopAsync), - Task.Run(FrameLoopAsync)); + _completion = RunAsync(); + } + + private async Task RunAsync() + { + try + { + await Task.WhenAll( + Task.Run(SendLoopAsync), + Task.Run(ReceiveLoopAsync), + Task.Run(FrameLoopAsync)); + } + finally + { + // Returns the MAC processors' hash copies to their pool, as DotNetty's handshake handler does. + _ingressMac?.Dispose(); + _egressMac?.Dispose(); + } } public void EnableSnappy() @@ -169,10 +190,10 @@ private void Close() } _isClosed = true; - _writable = false; + _outboundBytes.Close(); while (_sendQueue.TryDequeue(out OutboundItem item)) { - ArrayPool.Shared.Return(item.Buffer); + _pool.Return(item.Buffer); } } @@ -353,8 +374,8 @@ private async Task HandshakeAsync(PipeReader reader) // Each direction gets its own instances, so the frame and send loops share no crypto state. Each MAC processor // copies both directions' hashes when constructed, so both are built before either loop uses them. EncryptionSecrets secrets = handshake.Secrets; - FrameMacProcessor ingressMac = new(secrets); - FrameMacProcessor egressMac = new(secrets); + FrameMacProcessor ingressMac = _ingressMac = new(secrets); + FrameMacProcessor egressMac = _egressMac = new(secrets); _decoder = new FrameDecoder(new FrameCipher(secrets.AesSecret), ingressMac, _maxInboundFrameSize); lock (_sendLock) { @@ -440,6 +461,11 @@ private async Task ReadFramesAsync(PipeReader reader) while (true) { ReadResult result = await reader.ReadAsync(); + if (BeforeDecoding is { } beforeDecoding) + { + await beforeDecoding(); + } + ReadOnlySequence buffer = result.Buffer; SequencePosition consumed = _discarding ? buffer.End : DecodeFrames(buffer); reader.AdvanceTo(consumed, buffer.End); @@ -476,7 +502,7 @@ private SequencePosition DecodeFrames(ReadOnlySequence buffer) } _frameSize = frameSize; - _frame = ArrayPool.Shared.Rent(Frame.HeaderSize + frameSize); + _frame = _pool.Rent(Frame.HeaderSize + frameSize); plaintext.CopyTo(_frame); _frameFilled = Frame.HeaderSize; @@ -608,7 +634,7 @@ private void CompleteFrame() catch (InvalidFrameException e) { // Authenticated frames stay in step, so decoding continues, as it does on DotNetty. - ArrayPool.Shared.Return(frame); + _pool.Return(frame); ReleaseChunkedPacket(); QueueError(e); return; @@ -617,14 +643,14 @@ private void CompleteFrame() switch (merged.Kind) { case MergedFrameKind.SinglePacket: - Dispatch(new PooledPacket(frame, merged.ContentOffset, merged.ContentLength) { PacketType = merged.PacketType }); + Dispatch(new PooledPacket(_pool, frame, merged.ContentOffset, merged.ContentLength) { PacketType = merged.PacketType }); return; case MergedFrameKind.FirstChunk: { // Grows from the first chunk up to the declared total, as ZeroFrameMerger's buffer does. - byte[] buffer = ArrayPool.Shared.Rent(merged.ContentLength); + byte[] buffer = _pool.Rent(merged.ContentLength); frame.AsSpan(merged.ContentOffset, merged.ContentLength).CopyTo(buffer); - _chunkedPacket = new PooledPacket(buffer, 0, merged.ContentLength) { PacketType = merged.PacketType }; + _chunkedPacket = new PooledPacket(_pool, buffer, 0, merged.ContentLength) { PacketType = merged.PacketType }; _chunkedPacketTotal = merged.TotalContentLength; break; } @@ -644,7 +670,7 @@ private void CompleteFrame() } } - ArrayPool.Shared.Return(frame); + _pool.Return(frame); if (merged.IsComplete) { PooledPacket packet = _chunkedPacket!; @@ -668,7 +694,7 @@ private void ReleaseFrame() if (_frame is { } frame) { _frame = null; - ArrayPool.Shared.Return(frame); + _pool.Return(frame); } _frameState = FrameState.Header; @@ -803,7 +829,7 @@ private PooledPacket TakeSnappyOutput(int length) packet.Release(); } - return new PooledPacket(ArrayPool.Shared.Rent(length), 0, 0); + return new PooledPacket(_pool, _pool.Rent(length), 0, 0); } private void StopProcessing() @@ -833,19 +859,19 @@ private void TraceSnappyMessage(int length) public int Enqueue(T message) where T : P2PMessage { - if (!_writable) + if (!_outboundBytes.IsWritable) { return 0; } - (byte[] buffer, int length) = Serialize(_serializationService, message); + (byte[] buffer, int length) = Serialize(_serializationService, message, _pool); TryAdmit(buffer, length, raw: false); return length; } private void QueueRaw(byte[] data) { - byte[] buffer = ArrayPool.Shared.Rent(data.Length); + byte[] buffer = _pool.Rent(data.Length); data.CopyTo(buffer, 0); TryAdmit(buffer, data.Length, raw: true); } @@ -856,18 +882,19 @@ private void QueueRaw(byte[] data) /// private void TryAdmit(byte[] buffer, int length, bool raw) { - long sendAfter = _sendLatencyMs == 0 ? 0 : Environment.TickCount64 + _sendLatencyMs; + // The handshake messages are not delayed: DotNetty writes them without going through PacketSender. + long sendAfter = raw || _sendLatencyMs == 0 ? 0 : Environment.TickCount64 + _sendLatencyMs; bool wake; lock (_sendLock) { if (_isClosed) { - ArrayPool.Shared.Return(buffer); + _pool.Return(buffer); return; } _sendQueue.Enqueue(new OutboundItem(buffer, length, raw, _encodingMode, sendAfter)); - ChargeUnderLock(length); + _outboundBytes.Add(length); wake = _sendLoopWaiting; _sendLoopWaiting = false; } @@ -878,30 +905,17 @@ private void TryAdmit(byte[] buffer, int length, bool raw) } } - private void ChargeUnderLock(long bytes) - { - _pendingBytes += bytes; - if (_writable && _pendingBytes >= WriteBufferHighWaterMark) - { - _writable = false; - } - else if (!_writable && !_isClosed && _pendingBytes <= WriteBufferLowWaterMark) - { - _writable = true; - } - } - private void Charge(long bytes) { lock (_sendLock) { - ChargeUnderLock(bytes); + _outboundBytes.Add(bytes); } } private async Task SendLoopAsync() { - byte[] batch = ArrayPool.Shared.Rent(SendBatchSize); + byte[] batch = _pool.Rent(SendBatchSize); // The end of each packet in the batch and its charge, which is released once its last byte is sent. List<(int End, int Charge)> batchPackets = []; int used = 0; @@ -969,7 +983,7 @@ private async Task SendLoopAsync() if (bound > batch.Length) { // A packet larger than the batch gets its own buffer, since the encoder needs it contiguous. - byte[] own = ArrayPool.Shared.Rent(bound); + byte[] own = _pool.Rent(bound); try { if (TryEncode(item, encoder, own, out int written)) @@ -980,7 +994,7 @@ private async Task SendLoopAsync() } finally { - ArrayPool.Shared.Return(own); + _pool.Return(own); } } else if (TryEncode(item, encoder, batch.AsSpan(used), out int written)) @@ -991,7 +1005,7 @@ private async Task SendLoopAsync() } finally { - ArrayPool.Shared.Return(item.Buffer); + _pool.Return(item.Buffer); } } } @@ -1005,7 +1019,7 @@ private async Task SendLoopAsync() } finally { - ArrayPool.Shared.Return(batch); + _pool.Return(batch); } } @@ -1078,11 +1092,11 @@ private void HandleSendFailure(Exception exception) private static PacketWriter? t_writer; /// Serializes a message into a rented buffer as its packet type followed by its content. - internal static (byte[] Buffer, int Length) Serialize(IMessageSerializationService serializationService, T message) + internal static (byte[] Buffer, int Length) Serialize(IMessageSerializationService serializationService, T message, ArrayPool pool) where T : P2PMessage { PacketWriter writer = t_writer ??= new(); - writer.Start(message.AdaptivePacketType); + writer.Start(pool, message.AdaptivePacketType); try { serializationService.Serialize(message, writer); @@ -1094,7 +1108,7 @@ internal static (byte[] Buffer, int Length) Serialize(IMessageSerializationSe { if (writer.Buffer is { } buffer) { - ArrayPool.Shared.Return(buffer); + pool.Return(buffer); } throw; @@ -1109,6 +1123,7 @@ internal static (byte[] Buffer, int Length) Serialize(IMessageSerializationSe /// Rents the buffer on the one call for the content, as 's writer does. private sealed class PacketWriter : IBufferWriter { + private ArrayPool? _pool; private int _packetType; private int _packetTypeLength; @@ -1116,11 +1131,16 @@ private sealed class PacketWriter : IBufferWriter public int Length { get; private set; } - public void Start(int packetType) => _packetType = packetType; + public void Start(ArrayPool pool, int packetType) + { + _pool = pool; + _packetType = packetType; + } - // Keeps an idle thread's writer from holding on to the last buffer. + // Keeps an idle thread's writer from holding on to the last buffer and pool. public void Clear() { + _pool = null; Buffer = null; Length = 0; } @@ -1133,7 +1153,7 @@ public Span GetSpan(int sizeHint = 0) int packetTypeLength = _packetTypeLength = Rlp.LengthOf(_packetType); // IBufferWriter requires a non-empty span when no size is requested. int length = packetTypeLength + Math.Max(sizeHint, 1); - byte[] buffer = Buffer = ArrayPool.Shared.Rent(length); + byte[] buffer = Buffer = _pool!.Rent(length); Span packet = buffer.AsSpan(0, length); RlpWriter writer = RlpWriter.ContentWriter(packet); writer.Encode(_packetType); diff --git a/src/Nethermind/Nethermind.Network/Rlpx/Sockets/SocketRlpxHost.cs b/src/Nethermind/Nethermind.Network/Rlpx/Sockets/SocketRlpxHost.cs index 2c9cb368fa86..833ee6d4cb14 100644 --- a/src/Nethermind/Nethermind.Network/Rlpx/Sockets/SocketRlpxHost.cs +++ b/src/Nethermind/Nethermind.Network/Rlpx/Sockets/SocketRlpxHost.cs @@ -31,6 +31,7 @@ namespace Nethermind.Network.Rlpx.Sockets; public sealed class SocketRlpxHost : IRlpxHost, IStoppableService { private const int ListenBacklog = 100; + private static readonly TimeSpan AcceptRetryDelay = TimeSpan.FromMilliseconds(100); // DotNetty starts no connect timer for a zero timeout, which leaves RlpxHost's 2-second watchdog. private static readonly TimeSpan ZeroConnectTimeoutDeadline = TimeSpan.FromSeconds(2); @@ -203,6 +204,12 @@ private async Task AcceptLoopAsync() catch (SocketException e) { if (_logger.IsDebug) _logger.Debug($"Failed to accept an RLPx connection: {e.Message}"); + // A peer resetting before it is accepted is routine; other errors may persist, so they don't spin the loop. + if (e.SocketErrorCode != SocketError.ConnectionReset && !await PauseAcceptingAsync()) + { + return; + } + continue; } @@ -215,6 +222,20 @@ private async Task AcceptLoopAsync() } } + /// if the host shut down meanwhile. + private async Task PauseAcceptingAsync() + { + try + { + await Task.Delay(AcceptRetryDelay, _shutdown.Token); + return true; + } + catch (OperationCanceledException) + { + return false; + } + } + private void Accept(Socket socket) { IPEndPoint remote; From 9542762a03eae9323862e3d1c65a0446569061a8 Mon Sep 17 00:00:00 2001 From: Ruben Buniatyan <337518+rubo@users.noreply.github.com> Date: Thu, 26 Nov 2026 23:06:21 +0100 Subject: [PATCH 04/22] test(network): release the packets queued when a socket connection closes --- .../Rlpx/Sockets/SocketRlpxConnectionTests.cs | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/SocketRlpxConnectionTests.cs b/src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/SocketRlpxConnectionTests.cs index 27b785727a29..d91065f0d458 100644 --- a/src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/SocketRlpxConnectionTests.cs +++ b/src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/SocketRlpxConnectionTests.cs @@ -367,6 +367,23 @@ public async Task Stops_taking_packets_at_the_high_watermark_until_they_are_sent await test.StopAndAssertBuffersReturnedAsync(); } + [Test] + public async Task Releases_the_packets_still_queued_when_the_connection_closes() + { + TaskCompletionSource sending = new(TaskCreationOptions.RunContinuationsAsynchronously); + await using ConnectionUnderTest test = await ConnectionUnderTest.StartAsync(); + test.Socket.SendGate = sending.Task; + + for (int i = 0; i < 5; i++) + { + test.Enqueue(Content(100, i)); + } + + await test.Connection.DisconnectAsync(); + sending.SetResult(); + await test.StopAndAssertBuffersReturnedAsync(); + } + [Test] public async Task Releases_a_packet_serialized_while_the_connection_closes() { From 7842c235dbba47ff3cc18808fbb99452110f48d1 Mon Sep 17 00:00:00 2001 From: Ruben Buniatyan <337518+rubo@users.noreply.github.com> Date: Thu, 26 Nov 2026 23:50:48 +0100 Subject: [PATCH 05/22] test(network): check what a socket connection reports only once its thread drained --- .../Rlpx/Sockets/SocketRlpxConnectionTests.cs | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/SocketRlpxConnectionTests.cs b/src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/SocketRlpxConnectionTests.cs index d91065f0d458..a87f8fab1b50 100644 --- a/src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/SocketRlpxConnectionTests.cs +++ b/src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/SocketRlpxConnectionTests.cs @@ -112,9 +112,14 @@ public async Task Reports_a_merger_error_and_keeps_decoding([Values] bool privil byte[] header = new byte[Frame.HeaderSize]; header[2] = Frame.BlockSize; header[3] = 0xf7; - byte[] next = Content(100, 1); + byte[] malformed = test.Peer.EncryptFrame(header, new byte[Frame.BlockSize]); + long received = test.Socket.Received; - await test.Peer.SendAsync([.. test.Peer.EncryptFrame(header, new byte[Frame.BlockSize]), .. test.Peer.Encode(0x10, next, EncodingMode.Framed)]); + // The next frame comes in a later read, after the error was handled. + await test.Peer.SendAsync(malformed); + Assert.That(() => test.Socket.Received, Is.EqualTo(received + malformed.Length).After(5000, 10)); + await Task.Delay(100); + await test.Peer.SendAsync(test.Peer.Encode(0x10, Content(100, 1), EncodingMode.Framed)); string[] expected = privileged ? ["receive 16"] : ["disconnect Exception", "receive 16"]; await test.WaitForEventsAsync(expected.Length); @@ -177,6 +182,7 @@ public async Task Releases_a_partly_received_packet_at_the_end_of_the_stream() await test.Peer.SendAsync(frames[..firstFrameLength]); test.Peer.Socket.Close(); await test.Connection.Completion.WaitAsync(Timeout); + await test.StopAsync(); Assert.That(test.Events, Is.Empty, "the end of the stream is not an error"); await test.StopAndAssertBuffersReturnedAsync(); @@ -189,7 +195,7 @@ public async Task Closes_after_the_read_timeout([Values] bool privileged) await test.Connection.Closed.WaitAsync(Timeout); await test.Connection.Completion.WaitAsync(Timeout); - await Task.Delay(100); + await test.StopAsync(); Assert.That(test.Events, Is.EqualTo(privileged ? Array.Empty() : ["disconnect Exception"])); await test.StopAndAssertBuffersReturnedAsync(); @@ -405,6 +411,7 @@ public async Task Closes_without_reporting_a_failed_send() test.Enqueue(Content(10, 1)); await test.Connection.Closed.WaitAsync(Timeout); await test.Connection.Completion.WaitAsync(Timeout); + await test.StopAsync(); Assert.That(test.Events, Is.Empty); await test.StopAndAssertBuffersReturnedAsync(); From 0448caf632ad35e988fedb17264c2d78ff9a8f4c Mon Sep 17 00:00:00 2001 From: Ruben Buniatyan <337518+rubo@users.noreply.github.com> Date: Fri, 27 Nov 2026 00:09:57 +0100 Subject: [PATCH 06/22] test(network): cover a Hello that enables Snappy and benchmark the socket transport A peer's Hello and its first compressed packet can arrive in one read. The new test holds the processing thread until both are queued, then enables Snappy while handling the Hello, as P2PProtocolHandler does, and checks the second packet is decompressed. Deciding Snappy when the frame loop queues a packet instead fails it. The scripted peer now RLP-encodes packet type 0. SocketRlpxRoundTripBenchmarks runs RlpxRoundTripBenchmarks with both nodes on the socket transport; a separate class keeps the DotNetty rows' names, so they still compare with master's. SocketRlpxConnectionBenchmarks measures a connection on an in-memory stream, receiving frames and sending bursts, whole or split into small reads and sends; the peer encodes into a reused buffer and drains without decoding, so the allocations are the connection's. --- .../RlpxRoundTripBenchmarks.cs | 7 +- .../SocketRlpxConnectionBenchmarks.cs | 222 ++++++++++++++++++ .../SocketRlpxRoundTripBenchmarks.cs | 15 ++ .../Nethermind.Network.Test.csproj | 3 + .../Rlpx/Sockets/ScriptedRlpxPeer.cs | 15 +- .../Rlpx/Sockets/SocketRlpxConnectionTests.cs | 30 +++ 6 files changed, 287 insertions(+), 5 deletions(-) create mode 100644 src/Nethermind/Nethermind.Network.Benchmark/SocketRlpxConnectionBenchmarks.cs create mode 100644 src/Nethermind/Nethermind.Network.Benchmark/SocketRlpxRoundTripBenchmarks.cs diff --git a/src/Nethermind/Nethermind.Network.Benchmark/RlpxRoundTripBenchmarks.cs b/src/Nethermind/Nethermind.Network.Benchmark/RlpxRoundTripBenchmarks.cs index d42dda8ea143..c339e8a83a69 100644 --- a/src/Nethermind/Nethermind.Network.Benchmark/RlpxRoundTripBenchmarks.cs +++ b/src/Nethermind/Nethermind.Network.Benchmark/RlpxRoundTripBenchmarks.cs @@ -62,6 +62,9 @@ public class RlpxRoundTripBenchmarks private ISyncPeer _serverPeer = null!; private ISnapSyncPeer _serverSnapPeer = null!; + /// Gets the transport both nodes run on. + protected virtual RlpxTransport Transport => RlpxTransport.DotNetty; + [GlobalSetup] public void GlobalSetup() => SetUpAsync().GetAwaiter().GetResult(); @@ -166,10 +169,10 @@ private async Task WarmUpRequestSizes(CancellationToken cancellationToken) throw new InvalidOperationException($"Responses are still incomplete after {MaxAttempts} requests: {incomplete}."); } - private static IContainer CreateNode(PrivateKey nodeKey) + private IContainer CreateNode(PrivateKey nodeKey) { ConfigProvider configProvider = new( - new NetworkConfig { P2PPort = GetAvailablePort(), FilterPeersByRecentIp = false }, + new NetworkConfig { P2PPort = GetAvailablePort(), FilterPeersByRecentIp = false, RlpxTransport = Transport }, // Both ends advertise snap, so the session agrees on it. new SyncConfig { SnapServingEnabled = true }); diff --git a/src/Nethermind/Nethermind.Network.Benchmark/SocketRlpxConnectionBenchmarks.cs b/src/Nethermind/Nethermind.Network.Benchmark/SocketRlpxConnectionBenchmarks.cs new file mode 100644 index 000000000000..c22eb2ca0ca1 --- /dev/null +++ b/src/Nethermind/Nethermind.Network.Benchmark/SocketRlpxConnectionBenchmarks.cs @@ -0,0 +1,222 @@ +// SPDX-FileCopyrightText: 2026 Demerzel Solutions Limited +// SPDX-License-Identifier: LGPL-3.0-only + +using System; +using System.Threading; +using System.Threading.Tasks; +using BenchmarkDotNet.Attributes; +using Nethermind.Core.Crypto; +using Nethermind.Core.Test.Builders; +using Nethermind.Logging; +using Nethermind.Network.P2P; +using Nethermind.Network.P2P.EventArg; +using Nethermind.Network.P2P.Messages; +using Nethermind.Network.P2P.ProtocolHandlers; +using Nethermind.Network.Rlpx; +using Nethermind.Network.Rlpx.Handshake; +using Nethermind.Network.Rlpx.Sockets; +using Nethermind.Network.Test; +using Nethermind.Network.Test.Rlpx.Sockets; +using Nethermind.Stats.Model; + +namespace Nethermind.Network.Benchmarks; + +/// +/// Measures a socket transport connection on an in-memory stream: frames received into packets for the session, and a +/// burst of packets sent in batches, with the stream whole or split into small reads and sends. +/// +/// +/// The peer encodes into a reused buffer and drains what it receives without decoding, so the allocations are the +/// connection's. The time includes the peer encrypting what the connection receives. +/// +[MemoryDiagnoser] +public class SocketRlpxConnectionBenchmarks +{ + private const int PacketsPerOperation = 64; + private const int FragmentSize = 1000; + + [Params(100, 16384)] + public int PacketSize { get; set; } + + [Params(false, true)] + public bool Fragmented { get; set; } + + private InMemoryRlpxSocket _socket = null!; + private ScriptedRlpxPeer _peer = null!; + private RlpxProcessingThreads _threads = null!; + private SocketRlpxConnection _connection = null!; + private CountingSession _session = null!; + private byte[] _packet = null!; + private byte[] _frames = null!; + private byte[] _drain = null!; + private int _encodedLength; + + [GlobalSetup] + public void Setup() => SetUpAsync().GetAwaiter().GetResult(); + + private async Task SetUpAsync() + { + (EncryptionSecrets initiator, EncryptionSecrets recipient) = NetTestVectors.GetSecretsPair(); + (_socket, InMemoryRlpxSocket peerSocket) = InMemoryRlpxSocket.CreatePair(); + _peer = new ScriptedRlpxPeer(peerSocket, initiator); + _threads = new RlpxProcessingThreads(1, LimboLogs.Instance.GetClassLogger()); + _connection = new SocketRlpxConnection( + _socket, + HandshakeRole.Recipient, + new FakeHandshakeService(recipient, TestItem.PublicKeyA), + new MessageSerializationService(SerializerInfo.Create(new PayloadSerializer())), + _threads.Next(), + LimboLogs.Instance, + TimeSpan.Zero, + ZeroFrameDecoder.DefaultMaxInboundFrameSize); + _session = new CountingSession(); + _connection.Start(_session); + await _peer.SendAsync(FakeHandshakeService.Message); + await _peer.ReceiveHandshakeAsync(CancellationToken.None); + await _session.Initialized.Task; + + _packet = new byte[1 + PacketSize]; + _packet[0] = 0x10; + new Random(42).NextBytes(_packet.AsSpan(1)); + _frames = new byte[_peer.GetMaxEncodedLength(_packet.Length, FrameEncoder.EncodingMode.Framed)]; + + // A packet's encoded length doesn't depend on the cipher state, so one sample gives it for every packet. + long received = _peer.Socket.Received; + _connection.Enqueue(new PayloadMessage(_packet.AsMemory(1)) { AdaptivePacketType = 0x10 }); + await _peer.ReceivePacketAsync(CancellationToken.None); + _encodedLength = (int)(_peer.Socket.Received - received); + _drain = new byte[_encodedLength * PacketsPerOperation]; + _socket.MaxReceiveLength = _socket.MaxSendLength = Fragmented ? FragmentSize : int.MaxValue; + } + + [GlobalCleanup] + public void Cleanup() + { + _connection.DisconnectAsync().GetAwaiter().GetResult(); + _connection.Completion.GetAwaiter().GetResult(); + _threads.StopAsync().GetAwaiter().GetResult(); + _peer.Socket.Close(); + } + + [Benchmark(OperationsPerInvoke = PacketsPerOperation)] + public async Task Receive() + { + Task received = _session.WaitForPacketsAsync(PacketsPerOperation); + for (int i = 0; i < PacketsPerOperation; i++) + { + int length = _peer.EncodePacket(_packet, _frames, FrameEncoder.EncodingMode.Framed); + await _peer.Socket.SendAllAsync(_frames.AsMemory(0, length)); + } + + await received; + } + + [Benchmark(OperationsPerInvoke = PacketsPerOperation)] + public async Task SendBurst() + { + for (int i = 0; i < PacketsPerOperation; i++) + { + _connection.Enqueue(new PayloadMessage(_packet.AsMemory(1)) { AdaptivePacketType = 0x10 }); + } + + int received = 0; + while (received < _drain.Length) + { + received += await _peer.Socket.ReceiveAsync(_drain.AsMemory(received), CancellationToken.None); + } + } + + private sealed class PayloadMessage(ReadOnlyMemory payload) : P2PMessage + { + public override int PacketType => 0x10; + + public override string Protocol => "benchmark"; + + public ReadOnlyMemory Payload => payload; + } + + private sealed class PayloadSerializer : IMessageSerializer + { + public int GetLength(PayloadMessage message) => message.Payload.Length; + + public int Serialize(Span destination, PayloadMessage message) + { + message.Payload.Span.CopyTo(destination); + return message.Payload.Length; + } + + public PayloadMessage Deserialize(ReadOnlySpan data) => throw new NotSupportedException(); + } + + /// A session that counts the packets it receives, and allocates nothing doing so. + private sealed class CountingSession : ISession + { + private int _received; + private int _target; + private TaskCompletionSource _reached; + + public TaskCompletionSource Initialized { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + + public Task WaitForPacketsAsync(int count) + { + TaskCompletionSource reached = new(TaskCreationOptions.RunContinuationsAsynchronously); + Volatile.Write(ref _received, 0); + _target = count; + Volatile.Write(ref _reached, reached); + return reached.Task; + } + + public void ReceiveMessage(ZeroPacket zeroPacket) + { + if (Interlocked.Increment(ref _received) == _target) + { + Volatile.Read(ref _reached)?.TrySetResult(); + } + } + + public void Init(byte p2PVersion, IPacketSender packetSender) => Initialized.TrySetResult(); + + public void Handshake(PublicKey handshakeRemoteNodeId) + { + } + + public void InitiateDisconnect(DisconnectReason disconnectReason, string details) => + throw new InvalidOperationException($"Disconnect: {disconnectReason} {details}"); + + public bool IsClosing => false; + public PublicKey RemoteNodeId => TestItem.PublicKeyA; + public string RemoteHost { get; set; } = "127.0.0.1"; + public int RemotePort { get; set; } = 30303; + public Node Node { get; } = new(TestItem.PublicKeyA, "127.0.0.1", 30303); + + public byte P2PVersion => 5; + public SessionState State => SessionState.Initialized; + public SessionState BestStateReached => SessionState.Initialized; + public bool IsChannelClosed => false; + public bool IsOutboundBufferFull => false; + public PublicKey ObsoleteRemoteNodeId => throw new NotSupportedException(); + public int LocalPort => 30303; + public bool IsNetworkIdMatched { get; set; } + public ConnectionDirection Direction => ConnectionDirection.In; + public Guid SessionId { get; } = Guid.NewGuid(); + public DateTime LastPingUtc { get; set; } + public DateTime LastPongUtc { get; set; } + public IPingSender PingSender { get; set; } = null!; + public int DeliverMessage(T message) where T : P2PMessage => throw new NotSupportedException(); + public void EnableSnappy() => throw new NotSupportedException(); + public void AddSupportedCapability(Capability capability) => throw new NotSupportedException(); + public bool HasAvailableCapability(Capability capability) => throw new NotSupportedException(); + public bool HasAgreedCapability(Capability capability) => throw new NotSupportedException(); + public void AddProtocolHandler(IProtocolHandler handler) => throw new NotSupportedException(); + public bool TryGetProtocolHandler(string protocolCode, out IProtocolHandler handler) => throw new NotSupportedException(); + public void MarkDisconnected(DisconnectReason disconnectReason, DisconnectType disconnectType, string details) => throw new NotSupportedException(); + public void Dispose() { } + + public event EventHandler Disconnecting { add { } remove { } } + public event EventHandler Disconnected { add { } remove { } } + event EventHandler ISession.Initialized { add { } remove { } } + public event EventHandler HandshakeComplete { add { } remove { } } + public event EventHandler MsgReceived { add { } remove { } } + public event EventHandler MsgDelivered { add { } remove { } } + } +} diff --git a/src/Nethermind/Nethermind.Network.Benchmark/SocketRlpxRoundTripBenchmarks.cs b/src/Nethermind/Nethermind.Network.Benchmark/SocketRlpxRoundTripBenchmarks.cs new file mode 100644 index 000000000000..783145740f7d --- /dev/null +++ b/src/Nethermind/Nethermind.Network.Benchmark/SocketRlpxRoundTripBenchmarks.cs @@ -0,0 +1,15 @@ +// SPDX-FileCopyrightText: 2026 Demerzel Solutions Limited +// SPDX-License-Identifier: LGPL-3.0-only + +using Nethermind.Network.Config; + +namespace Nethermind.Network.Benchmarks; + +/// +/// The round trips of with both nodes on the socket transport. +/// +/// A separate class keeps the DotNetty rows' names, so they still compare with master's. +public class SocketRlpxRoundTripBenchmarks : RlpxRoundTripBenchmarks +{ + protected override RlpxTransport Transport => RlpxTransport.Sockets; +} diff --git a/src/Nethermind/Nethermind.Network.Test/Nethermind.Network.Test.csproj b/src/Nethermind/Nethermind.Network.Test/Nethermind.Network.Test.csproj index 32901df021aa..f82c4f5c7d59 100644 --- a/src/Nethermind/Nethermind.Network.Test/Nethermind.Network.Test.csproj +++ b/src/Nethermind/Nethermind.Network.Test/Nethermind.Network.Test.csproj @@ -32,6 +32,9 @@ + + + diff --git a/src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/ScriptedRlpxPeer.cs b/src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/ScriptedRlpxPeer.cs index e41a3a43c764..905a2ae822be 100644 --- a/src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/ScriptedRlpxPeer.cs +++ b/src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/ScriptedRlpxPeer.cs @@ -39,15 +39,24 @@ public ScriptedRlpxPeer(InMemoryRlpxSocket socket, EncryptionSecrets secrets) public InMemoryRlpxSocket Socket { get; } /// Encodes a packet into frames, without sending them. + /// A packet type below 0x80, which RLP encodes in one byte. public byte[] Encode(byte packetType, ReadOnlySpan content, FrameEncoder.EncodingMode mode) { byte[] packet = new byte[1 + content.Length]; - packet[0] = packetType; + // RLP encodes the integer zero as the empty string. + packet[0] = packetType == 0 ? (byte)0x80 : packetType; content.CopyTo(packet.AsSpan(1)); - byte[] frames = new byte[_encoder.GetMaxEncodedLength(packet.Length, mode)]; - return frames[.._encoder.Encode(packet, frames, mode)]; + byte[] frames = new byte[GetMaxEncodedLength(packet.Length, mode)]; + return frames[..EncodePacket(packet, frames, mode)]; } + /// Gets an upper bound of the encoded size of a packet, its packet type included. + public int GetMaxEncodedLength(int packetLength, FrameEncoder.EncodingMode mode) => _encoder.GetMaxEncodedLength(packetLength, mode); + + /// Encodes a packet, its packet type first, into frames in , without allocating. + /// The number of bytes written. + public int EncodePacket(ReadOnlySpan packet, Span destination, FrameEncoder.EncodingMode mode) => _encoder.Encode(packet, destination, mode); + /// Encrypts and authenticates a frame from a plaintext header and a padded payload, without checking either. public byte[] EncryptFrame(ReadOnlySpan header, ReadOnlySpan payload) { diff --git a/src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/SocketRlpxConnectionTests.cs b/src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/SocketRlpxConnectionTests.cs index a87f8fab1b50..1a3eb020004c 100644 --- a/src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/SocketRlpxConnectionTests.cs +++ b/src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/SocketRlpxConnectionTests.cs @@ -49,6 +49,36 @@ public async Task Receives_framed_chunked_and_snappy_packets_split_anywhere([Val await test.StopAndAssertBuffersReturnedAsync(); } + [Test] + public async Task Decompresses_a_packet_that_arrives_in_the_same_read_as_the_hello_enabling_snappy() + { + TaskCompletionSource queued = new(TaskCreationOptions.RunContinuationsAsynchronously); + SocketRlpxConnection? connection = null; + await using ConnectionUnderTest test = await ConnectionUnderTest.StartAsync(onReceive: packet => + { + if (packet.PacketType == P2PMessageCode.Hello) + { + // Waits until the next packet is queued behind it, then enables Snappy as P2PProtocolHandler does. + queued.Task.Wait(); + connection!.EnableSnappy(); + } + }); + connection = test.Connection; + byte[] hello = Content(50, 1); + byte[] compressed = Content(500, 2); + byte[] frames = [.. test.Peer.Encode(P2PMessageCode.Hello, hello, EncodingMode.Framed), .. test.Peer.Encode(0x10, compressed, EncodingMode.Snappy)]; + long received = test.Socket.Received; + + await test.Peer.SendAsync(frames); + Assert.That(() => test.Socket.Received, Is.EqualTo(received + frames.Length).After(5000, 10)); + await Task.Delay(100); + queued.SetResult(); + await test.WaitForEventsAsync(2); + + Assert.That(test.Packets, Is.EqualTo(new (byte, byte[])[] { (P2PMessageCode.Hello, hello), (0x10, compressed) })); + await test.StopAndAssertBuffersReturnedAsync(); + } + [Test] public async Task Completes_the_handshake_before_init_and_decodes_bytes_that_follow_the_auth() { From 3ecadb391c5ec75a8c3ea5bce2549a3ea91a94a1 Mon Sep 17 00:00:00 2001 From: Ruben Buniatyan <337518+rubo@users.noreply.github.com> Date: Fri, 27 Nov 2026 00:19:00 +0100 Subject: [PATCH 07/22] test(network): cover the remaining socket transport behaviours Tests for the handshake size limit at 65535 bytes with its prefix, a handshake that completes while its ACK is still being sent, traffic in both directions at once, a delayed packet charged when queued, a partly sent packet charged until its last byte is sent, the dial deadline when ConnectTimeoutMs is zero, and the ENR alternate dialed after a refused primary, which now runs on both hosts. SocketRlpxHost.Shutdown returns the first call's task to every caller, so a second caller also waits for the shutdown to finish. --- .../Rlpx/Sockets/InMemoryRlpxSocket.cs | 8 ++ .../Rlpx/Sockets/SocketRlpxConnectionTests.cs | 123 ++++++++++++++++++ .../Rlpx/Sockets/SocketRlpxHostTests.cs | 31 +++++ .../RlpxHostIntegrationTests.cs | 11 +- .../Rlpx/Sockets/SocketRlpxHost.cs | 15 ++- 5 files changed, 177 insertions(+), 11 deletions(-) diff --git a/src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/InMemoryRlpxSocket.cs b/src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/InMemoryRlpxSocket.cs index 727642584d85..727af4858720 100644 --- a/src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/InMemoryRlpxSocket.cs +++ b/src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/InMemoryRlpxSocket.cs @@ -45,6 +45,9 @@ public static (InMemoryRlpxSocket Local, InMemoryRlpxSocket Remote) CreatePair() /// Gets or sets a gate that every send waits for. public Task SendGate { get; set; } = Task.CompletedTask; + /// Gets or sets permits that each send takes one of, so that a test lets sends through one at a time. + public SemaphoreSlim? SendPermits { get; set; } + /// Gets or sets an error that sends throw. public Exception? SendError { get; set; } @@ -97,6 +100,11 @@ public async ValueTask ReceiveAsync(Memory buffer, CancellationToken public async ValueTask SendAsync(ReadOnlyMemory buffer, CancellationToken cancellationToken) { await SendGate.WaitAsync(cancellationToken); + if (SendPermits is { } permits) + { + await permits.WaitAsync(cancellationToken); + } + ObjectDisposedException.ThrowIf(_closed, this); if (SendError is { } error) { diff --git a/src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/SocketRlpxConnectionTests.cs b/src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/SocketRlpxConnectionTests.cs index 1a3eb020004c..7c0838a47504 100644 --- a/src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/SocketRlpxConnectionTests.cs +++ b/src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/SocketRlpxConnectionTests.cs @@ -105,6 +105,49 @@ public async Task Completes_the_handshake_before_init_and_decodes_bytes_that_fol await test.StopAndAssertBuffersReturnedAsync(); } + [TestCase(SocketRlpxConnection.MaxHandshakeLength, true)] + [TestCase(SocketRlpxConnection.MaxHandshakeLength + 1, false)] + public async Task Takes_a_handshake_message_up_to_the_size_limit(int length, bool accepted) + { + await using ConnectionUnderTest test = ConnectionUnderTest.Create(); + int bodyLength = length - sizeof(ushort); + byte[] prefix = [(byte)(bodyLength >> 8), (byte)bodyLength]; + test.Start(); + + if (accepted) + { + await test.Peer.SendAsync([.. prefix, .. new byte[bodyLength]]); + await test.Initialized.Task.WaitAsync(Timeout); + } + else + { + await test.Peer.SendAsync(prefix); + Task closed = test.Connection.Closed; + Assert.That(await Task.WhenAny(closed, Task.Delay(1000)), Is.SameAs(closed), "rejected on the prefix, before the handshake timeout"); + test.Session.DidNotReceive().Handshake(Arg.Any()); + } + + await test.StopAndAssertBuffersReturnedAsync(); + } + + [Test] + public async Task Completes_the_handshake_while_the_ack_is_still_being_sent() + { + TaskCompletionSource sending = new(TaskCreationOptions.RunContinuationsAsynchronously); + await using ConnectionUnderTest test = ConnectionUnderTest.Create(); + test.Socket.SendGate = sending.Task; + long sent = Interlocked.Read(ref Metrics.P2PBytesSent); + test.Start(); + + await test.Peer.SendAsync(FakeHandshakeService.Message); + await test.Initialized.Task.WaitAsync(Timeout); + Assert.That(Interlocked.Read(ref Metrics.P2PBytesSent), Is.GreaterThanOrEqualTo(sent + FakeHandshakeService.Message.Length), "the ACK counts as sent once queued"); + + sending.SetResult(); + Assert.That(await test.Peer.ReceiveHandshakeAsync(test.Cancellation), Is.EqualTo(FakeHandshakeService.Message)); + await test.StopAndAssertBuffersReturnedAsync(); + } + [Test] public async Task Stops_decoding_after_a_frame_fails_authentication( [Values] bool header, @@ -312,6 +355,47 @@ public async Task Sends_each_thread_s_packets_in_order() await test.StopAndAssertBuffersReturnedAsync(); } + [Test] + public async Task Sends_and_receives_at_the_same_time() + { + const int Packets = 200; + await using ConnectionUnderTest test = await ConnectionUnderTest.StartAsync(); + byte[][] inbound = [.. Enumerable.Range(0, Packets).Select(static i => Content(50 * (i % 40) + 1, i))]; + byte[][] outbound = [.. Enumerable.Range(0, Packets).Select(static i => Content(50 * (i % 40) + 1, Packets + i))]; + + // Each direction has its own cipher and MAC, so the frame and send loops share no state. + Task peerSends = Task.Run(async () => + { + foreach (byte[] content in inbound) + { + await test.Peer.SendAsync(test.Peer.Encode(0x10, content, EncodingMode.Framed)); + } + }); + Task connectionSends = Task.Run(() => + { + foreach (byte[] content in outbound) + { + test.Enqueue(content); + } + }); + List peerReceived = []; + for (int i = 0; i < Packets; i++) + { + peerReceived.Add((await test.Peer.ReceivePacketAsync(test.Cancellation)).Content); + } + + await Task.WhenAll(peerSends, connectionSends); + await test.WaitForEventsAsync(Packets); + + using (Assert.EnterMultipleScope()) + { + Assert.That(peerReceived, Is.EqualTo(outbound)); + Assert.That(test.Packets.Select(static packet => packet.Item2), Is.EqualTo(inbound)); + } + + await test.StopAndAssertBuffersReturnedAsync(); + } + [Test] public async Task Sends_a_packet_larger_than_the_batch_and_the_one_after_it([Values(1, 7, 1000, int.MaxValue)] int maxSendLength) { @@ -403,6 +487,45 @@ public async Task Stops_taking_packets_at_the_high_watermark_until_they_are_sent await test.StopAndAssertBuffersReturnedAsync(); } + [Test] + public async Task Charges_a_delayed_packet_when_it_is_queued() + { + await using ConnectionUnderTest test = await ConnectionUnderTest.StartAsync(sendLatency: TimeSpan.FromSeconds(30)); + byte[] content = Content(100_000, 1); + + int queued = 0; + while (test.Connection.IsWritable && queued < 100) + { + test.Enqueue(content); + queued++; + } + + Assert.That(queued, Is.EqualTo(30), "unlike DotNetty, which charges a delayed packet once its write starts"); + await test.StopAndAssertBuffersReturnedAsync(); + } + + [Test] + public async Task Keeps_a_partly_sent_packet_charged_until_its_last_byte_is_sent() + { + await using ConnectionUnderTest test = await ConnectionUnderTest.StartAsync(); + using SemaphoreSlim permits = new(0); + test.Socket.SendPermits = permits; + test.Socket.MaxSendLength = 1_000_000; + + test.Enqueue(Content(3_100_000, 1)); + Assert.That(test.Connection.IsWritable, Is.False, "over the high watermark"); + + // Three sends leave less than the low watermark unsent, but the packet is still incomplete, as DotNetty counts it. + permits.Release(3); + await test.Peer.Socket.ReceiveExactlyAsync(3_000_000, test.Cancellation); + await Task.Delay(100); + Assert.That(test.Connection.IsWritable, Is.False, "the packet is not sent until its last byte is"); + + permits.Release(int.MaxValue / 2); + Assert.That(() => test.Connection.IsWritable, Is.True.After(5000, 10)); + await test.StopAndAssertBuffersReturnedAsync(); + } + [Test] public async Task Releases_the_packets_still_queued_when_the_connection_closes() { diff --git a/src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/SocketRlpxHostTests.cs b/src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/SocketRlpxHostTests.cs index 28b1e4ed00ff..46261ac08b22 100644 --- a/src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/SocketRlpxHostTests.cs +++ b/src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/SocketRlpxHostTests.cs @@ -220,6 +220,37 @@ public async Task Throws_when_the_caller_cancels_a_dial() } } + /// DotNetty starts no connect timer for a zero timeout, which leaves 's 2-second watchdog. + [TestCase(0, 2000)] + [TestCase(500, 500)] + public async Task Gives_a_dial_the_connect_timeout_or_two_seconds_for_zero(int connectTimeoutMs, int expectedMs) + { + await using IContainer container = CreateFilterContainer(filterEnabled: false, subnetBucketing: false, transport: RlpxTransport.Sockets, connectTimeoutMs: connectTimeoutMs); + SocketRlpxHost host = (SocketRlpxHost)container.Resolve(); + try + { + Assert.That(host.ConnectTimeout, Is.EqualTo(TimeSpan.FromMilliseconds(expectedMs))); + } + finally + { + await host.Shutdown(); + } + } + + [Test] + public async Task Every_shutdown_call_waits_for_the_first() + { + await using IContainer container = CreateFilterContainer(filterEnabled: false, subnetBucketing: false, transport: RlpxTransport.Sockets); + IRlpxHost host = container.Resolve(); + await host.Init(); + + Task first = host.Shutdown(); + Task second = host.Shutdown(); + + Assert.That(second, Is.SameAs(first)); + await first; + } + [Test] public async Task Shutdown_waits_for_a_pending_dial_which_publishes_nothing() { diff --git a/src/Nethermind/Nethermind.Network.Test/RlpxHostIntegrationTests.cs b/src/Nethermind/Nethermind.Network.Test/RlpxHostIntegrationTests.cs index cc216077c13b..fa5f7bd88cc3 100644 --- a/src/Nethermind/Nethermind.Network.Test/RlpxHostIntegrationTests.cs +++ b/src/Nethermind/Nethermind.Network.Test/RlpxHostIntegrationTests.cs @@ -639,7 +639,7 @@ public async Task ListenerState_DoesNotClearReplacementWhenPreviousChannelCloses } [Test] - public async Task ConnectAsync_FallsBackToVerifiedIpv6EndpointWithoutPublishingFailedAttempt() + public async Task ConnectAsync_FallsBackToVerifiedIpv6EndpointWithoutPublishingFailedAttempt([Values] RlpxTransport transport) { if (!Socket.OSSupportsIPv6) { @@ -651,8 +651,8 @@ public async Task ConnectAsync_FallsBackToVerifiedIpv6EndpointWithoutPublishingF int listeningPort = ((IPEndPoint)ipv6Listener.LocalEndpoint).Port; using Socket refused = ReserveRefusedPort(IPAddress.Loopback); int refusedPort = ((IPEndPoint)refused.LocalEndPoint!).Port; - await using IContainer container = CreateListenerContainer("127.0.0.1", IPAddress.Loopback, GetAvailablePort()); - RlpxHost host = container.Resolve(); + await using IContainer container = CreateListenerContainer("127.0.0.1", IPAddress.Loopback, GetAvailablePort(), transport: transport); + IRlpxHost host = container.Resolve(); TaskCompletionSource sessionCreated = new(TaskCreationOptions.RunContinuationsAsynchronously); int sessionCount = 0; host.SessionCreated += (_, args) => @@ -1097,7 +1097,7 @@ private static Node CreateNode(NodeRecord record, bool verified) } internal static IContainer CreateFilterContainer(bool filterEnabled, bool subnetBucketing, string? externalIp = null, - IPrivilegedIpProvider? privilegedIpProvider = null, RlpxTransport transport = RlpxTransport.DotNetty) + IPrivilegedIpProvider? privilegedIpProvider = null, RlpxTransport transport = RlpxTransport.DotNetty, int connectTimeoutMs = 2000) { NetworkConfig networkConfig = new() { @@ -1107,7 +1107,8 @@ internal static IContainer CreateFilterContainer(bool filterEnabled, bool subnet FilterPeersBySameSubnet = subnetBucketing, ExternalIp = externalIp, MaxActivePeers = 50, - RlpxTransport = transport + RlpxTransport = transport, + ConnectTimeoutMs = connectTimeoutMs }; IIPResolver ipResolver = Substitute.For(); diff --git a/src/Nethermind/Nethermind.Network/Rlpx/Sockets/SocketRlpxHost.cs b/src/Nethermind/Nethermind.Network/Rlpx/Sockets/SocketRlpxHost.cs index 833ee6d4cb14..03d560ccd8df 100644 --- a/src/Nethermind/Nethermind.Network/Rlpx/Sockets/SocketRlpxHost.cs +++ b/src/Nethermind/Nethermind.Network/Rlpx/Sockets/SocketRlpxHost.cs @@ -50,6 +50,7 @@ public sealed class SocketRlpxHost : IRlpxHost, IStoppableService private readonly TimeSpan _shutdownCloseTimeout; private readonly int _processingThreadCount; private readonly CancellationTokenSource _shutdown = new(); + private readonly Lazy _shutdownTask; private readonly TaskCompletionSource _listenerClosed = new(TaskCreationOptions.RunContinuationsAsynchronously); // Guards the shutdown flag, the connections and the pending dials, so that shutdown sees every one of them. @@ -96,6 +97,7 @@ public SocketRlpxHost( _shutdownCloseTimeout = TimeSpan.FromMilliseconds(networkConfig.RlpxHostShutdownCloseTimeoutMs); _processingThreadCount = networkConfig.ProcessingThreadCount; _tryConnect = TryConnect; + _shutdownTask = new Lazy(ShutdownAsync); NodeFilter nodeFilter = NodeFilter.Create(networkConfig.MaxActivePeers, networkConfig.FilterPeersByRecentIp, networkConfig.FilterPeersBySameSubnet, ips.ExternalIp); _dialPolicy = new RlpxDialPolicy(nodeFilter, privilegedIpProvider, _logger); _sessions = new RlpxSessionTracker(this, sessionMonitor, _dialPolicy, _logger, () => _shutdown.Token); @@ -120,6 +122,9 @@ public event SessionDisconnectedEventHandler SessionDisconnected /// Gets the endpoint the listener is bound to, once initialized. internal IPEndPoint? ListenerEndPoint => _listener?.LocalEndPoint as IPEndPoint; + /// Gets the time a dial waits for the socket to connect. + internal TimeSpan ConnectTimeout => _connectTimeout; + internal int ConnectionCount { get @@ -422,16 +427,14 @@ private void TraceConnectionFailure(Node node, Exception exception) => string IStoppableService.Description => "rlpx host"; - public async Task Shutdown() + /// Every call returns the first call's task, so a later caller also waits for the shutdown to finish. + public Task Shutdown() => _shutdownTask.Value; + + private async Task ShutdownAsync() { Task[] dials; lock (_lock) { - if (_shuttingDown) - { - return; - } - _shuttingDown = true; dials = [.. _pendingDials]; } From 7664c171e211cc0357a4f98ba672985ee8056b35 Mon Sep 17 00:00:00 2001 From: Ruben Buniatyan <337518+rubo@users.noreply.github.com> Date: Fri, 27 Nov 2026 00:41:43 +0100 Subject: [PATCH 08/22] test(network): accept either reporter of a disconnect at socket host shutdown --- .../Rlpx/Sockets/SocketRlpxHostTests.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/SocketRlpxHostTests.cs b/src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/SocketRlpxHostTests.cs index 46261ac08b22..72e0cac22634 100644 --- a/src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/SocketRlpxHostTests.cs +++ b/src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/SocketRlpxHostTests.cs @@ -291,7 +291,8 @@ public async Task Shutdown_closes_the_connections_and_waits_for_them() using (Assert.EnterMultipleScope()) { Assert.That(host.ConnectionCount, Is.Zero); - Assert.That((await disconnected.Task.WaitAsync(timeout.Token)).DisconnectType, Is.EqualTo(DisconnectType.Remote)); + // The closed connection or the final sweep of shutdown reports it, whichever comes first, as on RlpxHost. + Assert.That(await disconnected.Task.WaitAsync(timeout.Token), Is.Not.Null, "the session is reported disconnected"); Assert.That(await ReceiveAsync(client, timeout.Token), Is.Zero, "the client sees the connection close"); } } From 77eda01376ef66ab8605b66f3db89317d04079d5 Mon Sep 17 00:00:00 2001 From: Ruben Buniatyan <337518+rubo@users.noreply.github.com> Date: Fri, 27 Nov 2026 16:53:55 +0100 Subject: [PATCH 09/22] perf(network): fill each socket receive segment before starting another --- .../Rlpx/Sockets/SocketRlpxConnectionTests.cs | 50 ++++++++++++++++++- .../Rlpx/Sockets/SocketRlpxConnection.cs | 11 +++- 2 files changed, 58 insertions(+), 3 deletions(-) diff --git a/src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/SocketRlpxConnectionTests.cs b/src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/SocketRlpxConnectionTests.cs index 7c0838a47504..755aeb6cb16b 100644 --- a/src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/SocketRlpxConnectionTests.cs +++ b/src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/SocketRlpxConnectionTests.cs @@ -219,6 +219,31 @@ public async Task Handles_a_packet_received_before_a_reset_first() await test.StopAndAssertBuffersReturnedAsync(); } + [Test] + public async Task Fills_a_receive_segment_with_reads_smaller_than_it() + { + TaskCompletionSource decoding = new(TaskCreationOptions.RunContinuationsAsynchronously); + await using ConnectionUnderTest test = await ConnectionUnderTest.StartAsync(maxReceiveLength: 1024, beforeDecoding: () => new ValueTask(decoding.Task)); + byte[] content = Content(16 * 1024, 1); + byte[] packet = test.Peer.Encode(0x10, content, EncodingMode.Framed); + long received = test.Socket.Received; + int segments = test.ReceivePool.Rentals; + + await test.Peer.SendAsync(packet); + Assert.That(() => test.Socket.Received, Is.EqualTo(received + packet.Length).After(5000, 10), "the packet is in the pipe"); + int packetSegments = test.ReceivePool.Rentals - segments; + decoding.SetResult(); + await test.WaitForEventsAsync(1); + + using (Assert.EnterMultipleScope()) + { + Assert.That(packetSegments, Is.LessThanOrEqualTo(3), "1 KiB reads share 16 KiB segments"); + Assert.That(test.Packets, Is.EqualTo(new (byte, byte[])[] { (0x10, content) })); + } + + await test.StopAndAssertBuffersReturnedAsync(); + } + [Test] public async Task Handles_an_error_raised_by_a_packet_before_the_next_packet() { @@ -602,6 +627,26 @@ public int Serialize(Span destination, PayloadMessage message) public PayloadMessage Deserialize(ReadOnlySpan data) => throw new NotSupportedException(); } + /// Rents from the shared memory pool and counts the rentals. + private sealed class CountingMemoryPool : MemoryPool + { + private int _rentals; + + public int Rentals => Volatile.Read(ref _rentals); + + public override int MaxBufferSize => Shared.MaxBufferSize; + + public override IMemoryOwner Rent(int minBufferSize = -1) + { + Interlocked.Increment(ref _rentals); + return Shared.Rent(minBufferSize); + } + + protected override void Dispose(bool disposing) + { + } + } + /// A connection on an in-memory socket, its scripted peer, and a session that records what it is given. private sealed class ConnectionUnderTest : IAsyncDisposable { @@ -635,7 +680,8 @@ private ConnectionUnderTest( LimboLogs.Instance, sendLatency, ZeroFrameDecoder.DefaultMaxInboundFrameSize, - Pool) + Pool, + ReceivePool) { ReadTimeout = readTimeout ?? SocketRlpxConnection.DefaultReadTimeout, BeforeDecoding = beforeDecoding @@ -670,6 +716,8 @@ private ConnectionUnderTest( public TrackingArrayPool Pool { get; } = new(); + public CountingMemoryPool ReceivePool { get; } = new(); + public ConcurrentQueue Events { get; } = new(); public ConcurrentQueue<(byte, byte[])> Packets { get; } = new(); diff --git a/src/Nethermind/Nethermind.Network/Rlpx/Sockets/SocketRlpxConnection.cs b/src/Nethermind/Nethermind.Network/Rlpx/Sockets/SocketRlpxConnection.cs index 3a7c886a384c..3d99ed70acd8 100644 --- a/src/Nethermind/Nethermind.Network/Rlpx/Sockets/SocketRlpxConnection.cs +++ b/src/Nethermind/Nethermind.Network/Rlpx/Sockets/SocketRlpxConnection.cs @@ -46,6 +46,7 @@ namespace Nethermind.Network.Rlpx.Sockets; /// The simulated latency of every packet sent, for tests and benchmarks. /// The largest frame payload accepted. /// The pool of the connection's buffers; the shared one unless a test counts rentals. +/// The pool of the receive pipe's segments; the shared one unless a test counts rentals. internal sealed class SocketRlpxConnection( IRlpxSocket socket, HandshakeRole role, @@ -55,7 +56,8 @@ internal sealed class SocketRlpxConnection( ILogManager logManager, TimeSpan sendLatency, int maxInboundFrameSize, - ArrayPool? pool = null) : IRlpxConnection, IPacketSender + ArrayPool? pool = null, + MemoryPool? receivePool = null) : IRlpxConnection, IPacketSender { /// The largest handshake message, with its 2-byte size prefix, as DotNetty's length field decoder allows. internal const int MaxHandshakeLength = ushort.MaxValue; @@ -67,6 +69,10 @@ internal sealed class SocketRlpxConnection( internal const int SendBatchSize = 64 * 1024; private const int ReceiveSegmentSize = 16 * 1024; + + // A read goes into the rest of the current segment while at least this much is free, so that small reads fill a + // segment instead of each starting a new one. + private const int MinReceiveBufferSize = ReceiveSegmentSize / 2; private const int MaxRetainedSnappyOutputCapacity = 64 * 1024; private readonly ArrayPool _pool = pool ?? ArrayPool.Shared; @@ -79,6 +85,7 @@ internal sealed class SocketRlpxConnection( private readonly long _sendLatencyMs = (long)sendLatency.TotalMilliseconds; private readonly int _maxInboundFrameSize = maxInboundFrameSize; private readonly Pipe _pipe = new(new PipeOptions( + pool: receivePool, pauseWriterThreshold: 1_000_000, resumeWriterThreshold: 500_000, minimumSegmentSize: ReceiveSegmentSize, @@ -218,7 +225,7 @@ private async Task ReceiveLoopAsync() { // Waits for data without holding a buffer, so idle peers hold none. await _socket.ReceiveAsync(Memory.Empty, cancellation); - int received = await _socket.ReceiveAsync(writer.GetMemory(ReceiveSegmentSize), cancellation); + int received = await _socket.ReceiveAsync(writer.GetMemory(MinReceiveBufferSize), cancellation); if (received == 0) { break; From 01bf9cc8b63c588e0bd15754ea7e840f3cdda778 Mon Sep 17 00:00:00 2001 From: Ruben Buniatyan <337518+rubo@users.noreply.github.com> Date: Sat, 28 Nov 2026 13:13:33 +0100 Subject: [PATCH 10/22] fix(network): pause reading frames while the processing thread falls behind A socket connection queued every decoded packet for its processing thread without limit, so a slow handler let a peer pin unbounded memory. The frame loop now pauses at 16 MB of received packets not yet handled; the pipe then fills and TCP slows the peer. A pause doesn't count toward the read timeout. --- .../Rlpx/Sockets/SocketRlpxConnectionTests.cs | 38 ++++++++- .../Rlpx/Sockets/SocketRlpxConnection.cs | 82 ++++++++++++++++++- 2 files changed, 115 insertions(+), 5 deletions(-) diff --git a/src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/SocketRlpxConnectionTests.cs b/src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/SocketRlpxConnectionTests.cs index 755aeb6cb16b..520bcbf6aa19 100644 --- a/src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/SocketRlpxConnectionTests.cs +++ b/src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/SocketRlpxConnectionTests.cs @@ -244,6 +244,37 @@ public async Task Fills_a_receive_segment_with_reads_smaller_than_it() await test.StopAndAssertBuffersReturnedAsync(); } + [Test] + public async Task Pauses_reading_frames_while_the_processing_thread_holds_too_many_received_bytes() + { + TaskCompletionSource handling = new(TaskCreationOptions.RunContinuationsAsynchronously); + TimeSpan readTimeout = TimeSpan.FromMilliseconds(200); + await using ConnectionUnderTest test = await ConnectionUnderTest.StartAsync( + readTimeout: readTimeout, + maxQueuedReceiveBytes: 4 * 1024, + onReceive: _ => handling.Task.Wait()); + byte[][] contents = [.. Enumerable.Range(1, 20).Select(static seed => Content(1024, seed))]; + byte[] frames = [.. contents.SelectMany(content => test.Peer.Encode(0x10, content, EncodingMode.Framed))]; + long received = test.Socket.Received; + + await test.Peer.SendAsync(frames); + Assert.That(() => test.Socket.Received, Is.EqualTo(received + frames.Length).After(5000, 10), "the packets are in the pipe"); + await Task.Delay(readTimeout * 3); + int heldPackets = test.Pool.OutstandingExceptSendBatch.Length; + bool closedWhilePaused = test.Connection.Closed.IsCompleted; + handling.SetResult(); + await test.WaitForEventsAsync(contents.Length); + + using (Assert.EnterMultipleScope()) + { + Assert.That(heldPackets, Is.EqualTo(4), "the packets up to 4 KiB, one of them being handled"); + Assert.That(closedWhilePaused, Is.False, "a pause isn't a read timeout"); + Assert.That(test.Packets, Is.EqualTo(contents.Select(static content => ((byte)0x10, content)).ToArray())); + } + + await test.StopAndAssertBuffersReturnedAsync(); + } + [Test] public async Task Handles_an_error_raised_by_a_packet_before_the_next_packet() { @@ -660,6 +691,7 @@ private ConnectionUnderTest( int maxReceiveLength, TimeSpan sendLatency, TimeSpan? readTimeout, + long? maxQueuedReceiveBytes, Func? beforeDecoding, Action? onReceive) { @@ -684,6 +716,7 @@ private ConnectionUnderTest( ReceivePool) { ReadTimeout = readTimeout ?? SocketRlpxConnection.DefaultReadTimeout, + MaxQueuedReceiveBytes = maxQueuedReceiveBytes ?? SocketRlpxConnection.DefaultMaxQueuedReceiveBytes, BeforeDecoding = beforeDecoding }; @@ -734,7 +767,7 @@ public static ConnectionUnderTest Create( TimeSpan? readTimeout = null, Func? beforeDecoding = null, Action? onReceive = null) - => new(role, privileged, maxReceiveLength, sendLatency, readTimeout, beforeDecoding, onReceive); + => new(role, privileged, maxReceiveLength, sendLatency, readTimeout, maxQueuedReceiveBytes: null, beforeDecoding, onReceive); /// Starts the connection and completes the handshake as the peer. public static async Task StartAsync( @@ -742,10 +775,11 @@ public static async Task StartAsync( int maxReceiveLength = int.MaxValue, TimeSpan sendLatency = default, TimeSpan? readTimeout = null, + long? maxQueuedReceiveBytes = null, Func? beforeDecoding = null, Action? onReceive = null) { - ConnectionUnderTest test = Create(HandshakeRole.Recipient, privileged, maxReceiveLength, sendLatency, readTimeout, beforeDecoding, onReceive); + ConnectionUnderTest test = new(HandshakeRole.Recipient, privileged, maxReceiveLength, sendLatency, readTimeout, maxQueuedReceiveBytes, beforeDecoding, onReceive); test.Start(); await test.Peer.SendAsync(FakeHandshakeService.Message); await test.Peer.ReceiveHandshakeAsync(test.Cancellation); diff --git a/src/Nethermind/Nethermind.Network/Rlpx/Sockets/SocketRlpxConnection.cs b/src/Nethermind/Nethermind.Network/Rlpx/Sockets/SocketRlpxConnection.cs index 3d99ed70acd8..b987a017d24d 100644 --- a/src/Nethermind/Nethermind.Network/Rlpx/Sockets/SocketRlpxConnection.cs +++ b/src/Nethermind/Nethermind.Network/Rlpx/Sockets/SocketRlpxConnection.cs @@ -68,6 +68,11 @@ internal sealed class SocketRlpxConnection( /// The largest packet encoded into the shared send batch; a larger one gets its own buffer. internal const int SendBatchSize = 64 * 1024; + /// + /// The bytes of received packets queued for the processing thread and not yet handled at which the frame loop pauses. + /// + internal const long DefaultMaxQueuedReceiveBytes = 16 * 1024 * 1024; + private const int ReceiveSegmentSize = 16 * 1024; // A read goes into the rest of the current segment while at least this much is free, so that small reads fill a @@ -117,6 +122,11 @@ internal sealed class SocketRlpxConnection( private bool _handshakeCompleted; private bool _discarding; + // Received packets queued and not yet handled, shared with the processing thread + private long _queuedReceiveBytes; + private TaskCompletionSource? _queueCapacity; + private volatile bool _awaitingQueueCapacity; + // Processing thread private volatile bool _inboundSnappy; private PooledPacket? _snappyOutput; @@ -146,6 +156,13 @@ internal sealed class SocketRlpxConnection( /// Runs before each batch of received bytes is decoded; a test holds it to hold the frame loop. internal Func? BeforeDecoding { get; init; } + /// Gets or sets the bytes of received packets not yet handled at which the frame loop pauses. + /// + /// While paused, the pipe fills and the receive loop stops reading, so TCP slows the peer down: a slow processing + /// thread then holds a bounded amount of memory per connection. A packet larger than the bound still passes alone. + /// + internal long MaxQueuedReceiveBytes { get; init; } = DefaultMaxQueuedReceiveBytes; + /// Starts the handshake and the loops of a connection whose session has been created. public void Start(ISession session) { @@ -209,6 +226,7 @@ private void Close() _receiveCancellation.Cancel(); _sendCancellation.Cancel(); _socket.Close(); + Interlocked.Exchange(ref _queueCapacity, null)?.TrySetResult(); _closed.TrySetResult(); } @@ -280,6 +298,12 @@ private void StartIdleTimer() private void OnIdleTimer(object? _) { + // The connection itself stopped reading, so the peer isn't idle. + if (_awaitingQueueCapacity) + { + Volatile.Write(ref _lastReceive, Environment.TickCount64); + } + long idle = Environment.TickCount64 - Volatile.Read(ref _lastReceive); long remaining = (long)ReadTimeout.TotalMilliseconds - idle; if (remaining > 0) @@ -475,6 +499,14 @@ private async Task ReadFramesAsync(PipeReader reader) ReadOnlySequence buffer = result.Buffer; SequencePosition consumed = _discarding ? buffer.End : DecodeFrames(buffer); + if (IsReceiveQueueFull) + { + // The bytes left are read again once the processing thread catches up, so they aren't marked examined. + reader.AdvanceTo(consumed); + await WaitForQueueCapacityAsync(); + continue; + } + reader.AdvanceTo(consumed, buffer.End); if (result.IsCompleted) { @@ -483,14 +515,47 @@ private async Task ReadFramesAsync(PipeReader reader) } } + private bool IsReceiveQueueFull => Volatile.Read(ref _queuedReceiveBytes) >= MaxQueuedReceiveBytes && !_isClosed; + + private async Task WaitForQueueCapacityAsync() + { + TaskCompletionSource capacity = new(TaskCreationOptions.RunContinuationsAsynchronously); + Interlocked.Exchange(ref _queueCapacity, capacity); + // Checked again after publishing, as the processing thread or a close may have released the bytes meanwhile. + if (!IsReceiveQueueFull) + { + Interlocked.Exchange(ref _queueCapacity, null); + return; + } + + _awaitingQueueCapacity = true; + try + { + await capacity.Task; + } + finally + { + _awaitingQueueCapacity = false; + } + } + + private void ReleaseQueuedBytes(int length) + { + // Both sides publish before they read, so either the frame loop sees the bytes released or this sees it waiting. + if (Interlocked.Add(ref _queuedReceiveBytes, -length) < MaxQueuedReceiveBytes && Volatile.Read(ref _queueCapacity) is not null) + { + Interlocked.Exchange(ref _queueCapacity, null)?.TrySetResult(); + } + } + /// Decodes every whole block available, as does. - /// Where the bytes not yet consumed start. + /// Where the bytes not yet consumed start: before the next frame if the processing thread fell behind. private SequencePosition DecodeFrames(ReadOnlySequence buffer) { SequenceReader input = new(buffer); Span block = stackalloc byte[Frame.HeaderSize + Frame.MacSize]; Span plaintext = stackalloc byte[Frame.HeaderSize]; - while (input.Remaining >= Frame.BlockSize) + while (input.Remaining >= Frame.BlockSize && !IsReceiveQueueFull) { switch (_frameState) { @@ -688,9 +753,12 @@ private void CompleteFrame() private void Dispatch(PooledPacket packet) { + int length = packet.Content.Length; + Interlocked.Add(ref _queuedReceiveBytes, length); if (!_processingThread.TryEnqueue(new ProcessingItem(this, packet, null))) { packet.Release(); + ReleaseQueuedBytes(length); } } @@ -724,7 +792,15 @@ internal void Process(in ProcessingItem item) { if (item.Packet is { } packet) { - ProcessPacket(packet); + int length = packet.Content.Length; + try + { + ProcessPacket(packet); + } + finally + { + ReleaseQueuedBytes(length); + } } else if (item.Error is { } error) { From c4287638f440e45d4b5b61095ee2635a09afd2da Mon Sep 17 00:00:00 2001 From: Ruben Buniatyan <337518+rubo@users.noreply.github.com> Date: Sat, 28 Nov 2026 13:34:39 +0100 Subject: [PATCH 11/22] fix(network): close only the socket connection whose session activation fails A SessionCreated subscriber that threw escaped the accept loop and ended it, so the node stopped taking inbound peers, and the connection stayed tracked and open. The host now logs the failure and closes only that connection, as DotNetty closes only the channel whose handler failed. A dial that fails this way closes its connection the same way. --- .../Rlpx/Sockets/SocketRlpxHostTests.cs | 33 +++++++++++++++++++ .../Rlpx/Sockets/SocketRlpxHost.cs | 14 +++++++- 2 files changed, 46 insertions(+), 1 deletion(-) diff --git a/src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/SocketRlpxHostTests.cs b/src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/SocketRlpxHostTests.cs index 72e0cac22634..c8cbbe428e0d 100644 --- a/src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/SocketRlpxHostTests.cs +++ b/src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/SocketRlpxHostTests.cs @@ -184,6 +184,39 @@ public async Task Closes_an_inbound_connection_the_filter_rejects() } } + [Test] + public async Task Closes_only_the_connection_whose_session_subscriber_throws() + { + await using IContainer container = CreateFilterContainer(filterEnabled: false, subnetBucketing: false, transport: RlpxTransport.Sockets); + SocketRlpxHost host = (SocketRlpxHost)container.Resolve(); + int sessions = 0; + host.SessionCreated += (_, _) => + { + if (Interlocked.Increment(ref sessions) == 1) throw new InvalidOperationException("Subscriber failure"); + }; + try + { + await host.Init(); + IPEndPoint listener = new(IPAddress.Loopback, host.ListenerEndPoint!.Port); + using Socket first = new(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); + await first.ConnectAsync(listener); + using CancellationTokenSource timeout = new(Timeout); + Assert.That(await ReceiveAsync(first, timeout.Token), Is.Zero, "the failed connection is closed"); + + using Socket second = new(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); + await second.ConnectAsync(listener); + using (Assert.EnterMultipleScope()) + { + Assert.That(() => Volatile.Read(ref sessions), Is.EqualTo(2).After(5000, 10), "the listener still accepts"); + Assert.That(host.ConnectionCount, Is.EqualTo(1), "the failed connection is no longer tracked"); + } + } + finally + { + await host.Shutdown(); + } + } + [Test] public async Task Returns_false_for_a_refused_dial() { diff --git a/src/Nethermind/Nethermind.Network/Rlpx/Sockets/SocketRlpxHost.cs b/src/Nethermind/Nethermind.Network/Rlpx/Sockets/SocketRlpxHost.cs index 03d560ccd8df..1822043767c7 100644 --- a/src/Nethermind/Nethermind.Network/Rlpx/Sockets/SocketRlpxHost.cs +++ b/src/Nethermind/Nethermind.Network/Rlpx/Sockets/SocketRlpxHost.cs @@ -389,7 +389,19 @@ private void StartSession(Socket socket, SocketRlpxConnection connection, Sessio { SetSocketOption(socket, SocketOptionLevel.Tcp, SocketOptionName.NoDelay); SetSocketOption(socket, SocketOptionLevel.Socket, SocketOptionName.KeepAlive); - _sessions.Activate(session, connection.Closed); + try + { + _sessions.Activate(session, connection.Closed); + } + catch (Exception e) + { + // A failing subscriber closes only this connection, as a failing handler closes only its channel on DotNetty. + if (_logger.IsError) _logger.Error($"Failed to activate {session:hide}", e); + Untrack(connection); + _ = connection.DisconnectAsync(); + return; + } + connection.Start(session); _ = connection.Completion.ContinueWith( static (_, state) => From 8474791eb0f85992ddfcd87a3f64bd528f503a96 Mon Sep 17 00:00:00 2001 From: Ruben Buniatyan <337518+rubo@users.noreply.github.com> Date: Sat, 28 Nov 2026 13:34:45 +0100 Subject: [PATCH 12/22] fix(network): close a socket listener bound after shutdown started A shutdown that ran while Init was binding found no listener to close, and Init then published the socket and started an accept loop that exited at once, leaving the port bound. Init now publishes the listener under the host's lock only if no shutdown has started, and closes it otherwise. --- .../Rlpx/Sockets/SocketRlpxHostTests.cs | 17 ++++++++ .../Rlpx/Sockets/SocketRlpxHost.cs | 43 +++++++++++++++---- 2 files changed, 52 insertions(+), 8 deletions(-) diff --git a/src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/SocketRlpxHostTests.cs b/src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/SocketRlpxHostTests.cs index c8cbbe428e0d..1711c555a962 100644 --- a/src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/SocketRlpxHostTests.cs +++ b/src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/SocketRlpxHostTests.cs @@ -284,6 +284,23 @@ public async Task Every_shutdown_call_waits_for_the_first() await first; } + [Test] + public async Task Closes_a_listener_bound_after_shutdown_started() + { + await using IContainer container = CreateFilterContainer(filterEnabled: false, subnetBucketing: false, transport: RlpxTransport.Sockets); + SocketRlpxHost host = (SocketRlpxHost)container.Resolve(); + + await host.Shutdown(); + await host.Init(); + + using Socket probe = new(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); + using (Assert.EnterMultipleScope()) + { + Assert.That(host.ListenerEndPoint, Is.Null, "the listener isn't published"); + Assert.That(() => probe.Bind(new IPEndPoint(IPAddress.Any, host.LocalPort)), Throws.Nothing, "the port is free"); + } + } + [Test] public async Task Shutdown_waits_for_a_pending_dial_which_publishes_nothing() { diff --git a/src/Nethermind/Nethermind.Network/Rlpx/Sockets/SocketRlpxHost.cs b/src/Nethermind/Nethermind.Network/Rlpx/Sockets/SocketRlpxHost.cs index 1822043767c7..c79dcc1c1167 100644 --- a/src/Nethermind/Nethermind.Network/Rlpx/Sockets/SocketRlpxHost.cs +++ b/src/Nethermind/Nethermind.Network/Rlpx/Sockets/SocketRlpxHost.cs @@ -146,24 +146,47 @@ public async Task Init() } _isInitialized = true; - _processingThreads = new RlpxProcessingThreads(_processingThreadCount, _logger); + RlpxProcessingThreads processingThreads = new(_processingThreadCount, _logger); + lock (_lock) + { + _processingThreads = processingThreads; + } + + Socket listener; try { - _listener = await RlpxListener.BindAsync(_listenerState, LocalPort, _logger, nameof(SocketRlpxHost), Bind); + listener = await RlpxListener.BindAsync(_listenerState, LocalPort, _logger, nameof(SocketRlpxHost), Bind); } catch (Exception ex) { _logger.Error($"{nameof(Init)} failed.", ex); - await _processingThreads.StopAsync(); + await processingThreads.StopAsync(); throw; } - if (_listener.LocalEndPoint is IPEndPoint endpoint) + // A shutdown that started meanwhile has already looked for the listener, so it is closed here instead. + bool shuttingDown; + lock (_lock) { - _ = _listenerState.TrackRlpxAddress(endpoint.Address, _listenerClosed.Task); + shuttingDown = _shuttingDown; + if (!shuttingDown) + { + _listener = listener; + _acceptLoop = Task.Run(AcceptLoopAsync); + } + } + + if (shuttingDown) + { + listener.Dispose(); + await processingThreads.StopAsync(); + return; } - _acceptLoop = Task.Run(AcceptLoopAsync); + if (listener.LocalEndPoint is IPEndPoint endpoint) + { + _ = _listenerState.TrackRlpxAddress(endpoint.Address, _listenerClosed.Task); + } } private Task Bind(IPAddress address) @@ -445,16 +468,20 @@ private void TraceConnectionFailure(Node node, Exception exception) => private async Task ShutdownAsync() { Task[] dials; + Socket? listener; + Task acceptLoop; lock (_lock) { _shuttingDown = true; dials = [.. _pendingDials]; + listener = _listener; + acceptLoop = _acceptLoop; } // Ends the accept loop and the pending dials, and the close delays of the sessions. _shutdown.Cancel(); - _listener?.Dispose(); - await _acceptLoop; + listener?.Dispose(); + await acceptLoop; await Task.WhenAll(dials); if (_logger.IsDebug) _logger.Debug("Closed the RLPx listener"); From ededaf0664329afe63e9a70d70bb93fef83dab53 Mon Sep 17 00:00:00 2001 From: Ruben Buniatyan <337518+rubo@users.noreply.github.com> Date: Sat, 28 Nov 2026 13:34:45 +0100 Subject: [PATCH 13/22] fix(network): drop a packet queued past the high watermark by a concurrent sender Senders check writability before serializing, so several could pass the check before one of them crossed the high watermark, and all of them were queued. Admission now checks writability again under the send lock and drops the packet, returning 0 as for a packet refused up front. A packet dropped by a close still counts as sent, as on DotNetty. --- .../Rlpx/Sockets/SocketRlpxConnectionTests.cs | 45 +++++++++++++++++++ .../Rlpx/Sockets/SocketRlpxConnection.cs | 19 ++++++-- 2 files changed, 60 insertions(+), 4 deletions(-) diff --git a/src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/SocketRlpxConnectionTests.cs b/src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/SocketRlpxConnectionTests.cs index 520bcbf6aa19..cd02b0cafd8d 100644 --- a/src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/SocketRlpxConnectionTests.cs +++ b/src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/SocketRlpxConnectionTests.cs @@ -543,6 +543,51 @@ public async Task Stops_taking_packets_at_the_high_watermark_until_they_are_sent await test.StopAndAssertBuffersReturnedAsync(); } + [Test] + public async Task Drops_a_packet_whose_sender_checked_writability_before_another_crossed_the_high_watermark() + { + TaskCompletionSource sending = new(TaskCreationOptions.RunContinuationsAsynchronously); + await using ConnectionUnderTest test = await ConnectionUnderTest.StartAsync(); + test.Socket.SendGate = sending.Task; + byte[] bulk = Content(100_000, 1); + byte[] late = Content(100, 2); + byte[] next = Content(100, 3); + int bulkPackets = 0; + + // The late packet passes the writability check, then another thread crosses the watermark while it serializes. + Thread other = new(() => + { + while (test.Connection.IsWritable) + { + test.Enqueue(bulk); + bulkPackets++; + } + }); + int lateLength = test.Connection.Enqueue(new PayloadMessage(late, () => + { + other.Start(); + other.Join(); + }) { AdaptivePacketType = 0x10 }); + sending.SetResult(); + for (int i = 0; i < bulkPackets; i++) + { + await test.Peer.ReceivePacketAsync(test.Cancellation); + } + + Assert.That(() => test.Connection.IsWritable, Is.True.After(5000, 10)); + test.Enqueue(next); + (byte, byte[]) received = await test.Peer.ReceivePacketAsync(test.Cancellation); + + using (Assert.EnterMultipleScope()) + { + Assert.That(lateLength, Is.Zero, "the late packet is dropped"); + Assert.That(bulkPackets, Is.EqualTo(30)); + Assert.That(received, Is.EqualTo(((byte)0x10, next)), "the late packet is never sent"); + } + + await test.StopAndAssertBuffersReturnedAsync(); + } + [Test] public async Task Charges_a_delayed_packet_when_it_is_queued() { diff --git a/src/Nethermind/Nethermind.Network/Rlpx/Sockets/SocketRlpxConnection.cs b/src/Nethermind/Nethermind.Network/Rlpx/Sockets/SocketRlpxConnection.cs index b987a017d24d..62a332332be9 100644 --- a/src/Nethermind/Nethermind.Network/Rlpx/Sockets/SocketRlpxConnection.cs +++ b/src/Nethermind/Nethermind.Network/Rlpx/Sockets/SocketRlpxConnection.cs @@ -948,8 +948,7 @@ public int Enqueue(T message) where T : P2PMessage } (byte[] buffer, int length) = Serialize(_serializationService, message, _pool); - TryAdmit(buffer, length, raw: false); - return length; + return TryAdmit(buffer, length, raw: false) ? length : 0; } private void QueueRaw(byte[] data) @@ -963,7 +962,11 @@ private void QueueRaw(byte[] data) /// Queues a packet with the encoding mode and send time it has now, and charges it to the outbound bytes, or releases /// it if the connection has closed: the one place where a packet is either published or released. /// - private void TryAdmit(byte[] buffer, int length, bool raw) + /// + /// if the packet is dropped at the high watermark, which a sender that checked + /// before another crossed it can reach. A packet dropped by a close counts as sent, as on DotNetty. + /// + private bool TryAdmit(byte[] buffer, int length, bool raw) { // The handshake messages are not delayed: DotNetty writes them without going through PacketSender. long sendAfter = raw || _sendLatencyMs == 0 ? 0 : Environment.TickCount64 + _sendLatencyMs; @@ -973,7 +976,13 @@ private void TryAdmit(byte[] buffer, int length, bool raw) if (_isClosed) { _pool.Return(buffer); - return; + return true; + } + + if (!raw && !_outboundBytes.IsWritable) + { + _pool.Return(buffer); + return false; } _sendQueue.Enqueue(new OutboundItem(buffer, length, raw, _encodingMode, sendAfter)); @@ -986,6 +995,8 @@ private void TryAdmit(byte[] buffer, int length, bool raw) { _sendSignal.Release(); } + + return true; } private void Charge(long bytes) From 9f797104a4a9799b3163560735923c7707ad2f1f Mon Sep 17 00:00:00 2001 From: Ruben Buniatyan <337518+rubo@users.noreply.github.com> Date: Sat, 28 Nov 2026 13:34:45 +0100 Subject: [PATCH 14/22] test(network): wait for queued packets instead of sleeping in socket transport tests The Hello and Snappy test and the error ordering test slept 100 ms to let packets reach the processing thread's queue. They now wait for the connection's count of queued received bytes. The pending dial test is inconclusive rather than passing when the network refuses its address at once. --- .../Rlpx/Sockets/SocketRlpxConnectionTests.cs | 13 ++++++++----- .../Rlpx/Sockets/SocketRlpxHostTests.cs | 1 + .../Rlpx/Sockets/SocketRlpxConnection.cs | 3 +++ 3 files changed, 12 insertions(+), 5 deletions(-) diff --git a/src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/SocketRlpxConnectionTests.cs b/src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/SocketRlpxConnectionTests.cs index cd02b0cafd8d..eb5a627e9270 100644 --- a/src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/SocketRlpxConnectionTests.cs +++ b/src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/SocketRlpxConnectionTests.cs @@ -71,7 +71,7 @@ public async Task Decompresses_a_packet_that_arrives_in_the_same_read_as_the_hel await test.Peer.SendAsync(frames); Assert.That(() => test.Socket.Received, Is.EqualTo(received + frames.Length).After(5000, 10)); - await Task.Delay(100); + Assert.That(() => test.Connection.QueuedReceiveBytes, Is.GreaterThan(hello.Length).After(5000, 10), "the compressed packet is queued behind the hello"); queued.SetResult(); await test.WaitForEventsAsync(2); @@ -288,12 +288,15 @@ public async Task Handles_an_error_raised_by_a_packet_before_the_next_packet() // Declares 5 bytes, then copies from before the start of the output. byte[] invalidSnappy = [0x05, 0xFF, 0xFF]; + byte[] first = Content(10, 1); + byte[] last = Content(10, 2); + int queuedBytes = Snappy.CompressToArray(first).Length + invalidSnappy.Length + Snappy.CompressToArray(last).Length; + await test.Peer.SendAsync([ - .. test.Peer.Encode(0x20, Content(10, 1), EncodingMode.Snappy), + .. test.Peer.Encode(0x20, first, EncodingMode.Snappy), .. test.Peer.Encode(0x21, invalidSnappy, EncodingMode.Framed), - .. test.Peer.Encode(0x22, Content(10, 2), EncodingMode.Snappy)]); - Assert.That(() => test.Socket.Received, Is.GreaterThan(FakeHandshakeService.Message.Length).After(5000, 10)); - await Task.Delay(100); + .. test.Peer.Encode(0x22, last, EncodingMode.Snappy)]); + Assert.That(() => test.Connection.QueuedReceiveBytes, Is.EqualTo(queuedBytes).After(5000, 10), "the next two packets are queued"); held.SetResult(); await test.WaitForEventsAsync(3); diff --git a/src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/SocketRlpxHostTests.cs b/src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/SocketRlpxHostTests.cs index 1711c555a962..6c6712f7fd08 100644 --- a/src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/SocketRlpxHostTests.cs +++ b/src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/SocketRlpxHostTests.cs @@ -313,6 +313,7 @@ public async Task Shutdown_waits_for_a_pending_dial_which_publishes_nothing() // A private address that answers nothing, so the dial stays pending until it is canceled. Task dial = host.ConnectAsync(new Node(TestItem.PublicKeyA, new IPEndPoint(IPAddress.Parse("10.255.255.1"), 30303))); await Task.Delay(100); + Assume.That(dial.IsCompleted, Is.False, "the network refused the address at once, so there is no pending dial to test"); await host.Shutdown(); using (Assert.EnterMultipleScope()) diff --git a/src/Nethermind/Nethermind.Network/Rlpx/Sockets/SocketRlpxConnection.cs b/src/Nethermind/Nethermind.Network/Rlpx/Sockets/SocketRlpxConnection.cs index 62a332332be9..131752d087ea 100644 --- a/src/Nethermind/Nethermind.Network/Rlpx/Sockets/SocketRlpxConnection.cs +++ b/src/Nethermind/Nethermind.Network/Rlpx/Sockets/SocketRlpxConnection.cs @@ -163,6 +163,9 @@ internal sealed class SocketRlpxConnection( /// internal long MaxQueuedReceiveBytes { get; init; } = DefaultMaxQueuedReceiveBytes; + /// Gets the bytes of received packets queued for the processing thread or being handled there. + internal long QueuedReceiveBytes => Volatile.Read(ref _queuedReceiveBytes); + /// Starts the handshake and the loops of a connection whose session has been created. public void Start(ISession session) { From d86427a8b6e674c24ba7421a4c6997718662f1f4 Mon Sep 17 00:00:00 2001 From: Ruben Buniatyan <337518+rubo@users.noreply.github.com> Date: Sat, 28 Nov 2026 13:47:00 +0100 Subject: [PATCH 15/22] fix(network): keep accepting after any failure to set up an inbound socket connection Only a failing session activation was caught, so an exception elsewhere while setting up an inbound connection, such as in the inbound filter, still ended the accept loop. Setting up a connection now closes only that connection on any failure. --- .../Rlpx/Sockets/SocketRlpxHostTests.cs | 14 +++-- .../Rlpx/Sockets/SocketRlpxHost.cs | 51 ++++++++++++------- 2 files changed, 44 insertions(+), 21 deletions(-) diff --git a/src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/SocketRlpxHostTests.cs b/src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/SocketRlpxHostTests.cs index 6c6712f7fd08..52b73f6d1941 100644 --- a/src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/SocketRlpxHostTests.cs +++ b/src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/SocketRlpxHostTests.cs @@ -15,6 +15,7 @@ using Nethermind.Network.Rlpx; using Nethermind.Network.Rlpx.Sockets; using Nethermind.Stats.Model; +using NSubstitute; using NUnit.Framework; using static Nethermind.Network.Test.RlpxHostIntegrationTests; @@ -185,14 +186,19 @@ public async Task Closes_an_inbound_connection_the_filter_rejects() } [Test] - public async Task Closes_only_the_connection_whose_session_subscriber_throws() + public async Task Closes_only_the_inbound_connection_whose_setup_fails([Values] bool inSessionSubscriber) { - await using IContainer container = CreateFilterContainer(filterEnabled: false, subnetBucketing: false, transport: RlpxTransport.Sockets); + // The inbound filter asks the privileged IP provider first, so it fails before the session is activated. + IPrivilegedIpProvider privilegedIps = Substitute.For(); + int filterCalls = 0; + privilegedIps.IsPrivileged(Arg.Any()).Returns(_ => + !inSessionSubscriber && Interlocked.Increment(ref filterCalls) == 1 ? throw new InvalidOperationException("Filter failure") : false); + await using IContainer container = CreateFilterContainer(filterEnabled: false, subnetBucketing: false, privilegedIpProvider: privilegedIps, transport: RlpxTransport.Sockets); SocketRlpxHost host = (SocketRlpxHost)container.Resolve(); int sessions = 0; host.SessionCreated += (_, _) => { - if (Interlocked.Increment(ref sessions) == 1) throw new InvalidOperationException("Subscriber failure"); + if (Interlocked.Increment(ref sessions) == 1 && inSessionSubscriber) throw new InvalidOperationException("Subscriber failure"); }; try { @@ -207,7 +213,7 @@ public async Task Closes_only_the_connection_whose_session_subscriber_throws() await second.ConnectAsync(listener); using (Assert.EnterMultipleScope()) { - Assert.That(() => Volatile.Read(ref sessions), Is.EqualTo(2).After(5000, 10), "the listener still accepts"); + Assert.That(() => Volatile.Read(ref sessions), Is.EqualTo(inSessionSubscriber ? 2 : 1).After(5000, 10), "the listener still accepts"); Assert.That(host.ConnectionCount, Is.EqualTo(1), "the failed connection is no longer tracked"); } } diff --git a/src/Nethermind/Nethermind.Network/Rlpx/Sockets/SocketRlpxHost.cs b/src/Nethermind/Nethermind.Network/Rlpx/Sockets/SocketRlpxHost.cs index c79dcc1c1167..0a5038886d97 100644 --- a/src/Nethermind/Nethermind.Network/Rlpx/Sockets/SocketRlpxHost.cs +++ b/src/Nethermind/Nethermind.Network/Rlpx/Sockets/SocketRlpxHost.cs @@ -277,31 +277,48 @@ private void Accept(Socket socket) return; } - SocketRlpxConnection connection = CreateConnection(socket, HandshakeRole.Recipient); - IPAddress remoteIp = remote.Address.NormalizeMappedIPv4(); - Session session = new(LocalPort, connection, _disconnectsAnalyzer, _logManager) + SocketRlpxConnection? connection = null; + try { - RemoteHost = remoteIp.ToString(), - RemotePort = remote.Port - }; + connection = CreateConnection(socket, HandshakeRole.Recipient); + IPAddress remoteIp = remote.Address.NormalizeMappedIPv4(); + Session session = new(LocalPort, connection, _disconnectsAnalyzer, _logManager) + { + RemoteHost = remoteIp.ToString(), + RemotePort = remote.Port + }; - if (!TryTrack(connection)) - { - return; - } + if (!TryTrack(connection)) + { + return; + } - Metrics.IncomingConnections++; - if (_logger.IsTrace) _logger.Trace($"|NetworkTrace| Initializing {session:hide} channel"); + Metrics.IncomingConnections++; + if (_logger.IsTrace) _logger.Trace($"|NetworkTrace| Initializing {session:hide} channel"); - if (!_dialPolicy.AcceptsInbound(remoteIp)) + if (!_dialPolicy.AcceptsInbound(remoteIp)) + { + if (_logger.IsTrace) _logger.Trace($"|NetworkTrace| Rejecting inbound connection from filtered IP {remoteIp:hide}"); + Untrack(connection); + _ = connection.DisconnectAsync(); + return; + } + + StartSession(socket, connection, session); + } + catch (Exception e) { - if (_logger.IsTrace) _logger.Trace($"|NetworkTrace| Rejecting inbound connection from filtered IP {remoteIp:hide}"); + // A failure closes only this connection, so the accept loop keeps running, as on DotNetty. + if (_logger.IsError) _logger.Error("Failed to set up an inbound RLPx connection", e); + if (connection is null) + { + socket.Dispose(); + return; + } + Untrack(connection); _ = connection.DisconnectAsync(); - return; } - - StartSession(socket, connection, session); } public Task ConnectAsync(Node node, CancellationToken cancellationToken = default) From 75fd588cf994467c0acf8f565bb50f7817676144 Mon Sep 17 00:00:00 2001 From: Ruben Buniatyan <337518+rubo@users.noreply.github.com> Date: Sat, 28 Nov 2026 16:27:45 +0100 Subject: [PATCH 16/22] style(network): fix whitespace in a socket transport test --- .../Rlpx/Sockets/SocketRlpxConnectionTests.cs | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/SocketRlpxConnectionTests.cs b/src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/SocketRlpxConnectionTests.cs index eb5a627e9270..1bcc6fcea3d3 100644 --- a/src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/SocketRlpxConnectionTests.cs +++ b/src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/SocketRlpxConnectionTests.cs @@ -566,11 +566,7 @@ public async Task Drops_a_packet_whose_sender_checked_writability_before_another bulkPackets++; } }); - int lateLength = test.Connection.Enqueue(new PayloadMessage(late, () => - { - other.Start(); - other.Join(); - }) { AdaptivePacketType = 0x10 }); + int lateLength = test.Connection.Enqueue(new PayloadMessage(late, () => { other.Start(); other.Join(); }) { AdaptivePacketType = 0x10 }); sending.SetResult(); for (int i = 0; i < bulkPackets; i++) { From e4fef2133e9c7a66fdb28aa027d0fab99fc21f0c Mon Sep 17 00:00:00 2001 From: Ruben Buniatyan <337518+rubo@users.noreply.github.com> Date: Sat, 28 Nov 2026 20:31:40 +0100 Subject: [PATCH 17/22] fix(network): decode the frames left by a receive pause that ends before the frame loop waits --- .../Rlpx/Sockets/SocketRlpxConnectionTests.cs | 37 +++++++++++++++++-- .../Rlpx/Sockets/SocketRlpxConnection.cs | 27 +++++++++++--- 2 files changed, 55 insertions(+), 9 deletions(-) diff --git a/src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/SocketRlpxConnectionTests.cs b/src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/SocketRlpxConnectionTests.cs index 1bcc6fcea3d3..8b8ca5fd37bd 100644 --- a/src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/SocketRlpxConnectionTests.cs +++ b/src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/SocketRlpxConnectionTests.cs @@ -275,6 +275,34 @@ public async Task Pauses_reading_frames_while_the_processing_thread_holds_too_ma await test.StopAndAssertBuffersReturnedAsync(); } + [Test] + public async Task Decodes_the_frames_left_by_a_pause_that_ends_before_the_frame_loop_waits() + { + TaskCompletionSource handling = new(TaskCreationOptions.RunContinuationsAsynchronously); + SocketRlpxConnection? connection = null; + await using ConnectionUnderTest test = await ConnectionUnderTest.StartAsync( + maxQueuedReceiveBytes: 1024, + afterDecoding: () => + { + // The processing thread catches up after the frame loop stopped for it, before the frame loop waits. + if (connection is { QueuedReceiveBytes: >= 1024 } paused && !handling.Task.IsCompleted) + { + handling.SetResult(); + SpinWait.SpinUntil(() => paused.QueuedReceiveBytes == 0, Timeout); + } + }, + onReceive: _ => handling.Task.Wait()); + connection = test.Connection; + byte[][] contents = [.. Enumerable.Range(1, 3).Select(static seed => Content(1024, seed))]; + + // The frames arrive in one read, so nothing received later wakes the frame loop. + await test.Peer.SendAsync([.. contents.SelectMany(content => test.Peer.Encode(0x10, content, EncodingMode.Framed))]); + await test.WaitForEventsAsync(contents.Length); + + Assert.That(test.Packets, Is.EqualTo(contents.Select(static content => ((byte)0x10, content)).ToArray())); + await test.StopAndAssertBuffersReturnedAsync(); + } + [Test] public async Task Handles_an_error_raised_by_a_packet_before_the_next_packet() { @@ -737,6 +765,7 @@ private ConnectionUnderTest( TimeSpan? readTimeout, long? maxQueuedReceiveBytes, Func? beforeDecoding, + Action? afterDecoding, Action? onReceive) { _role = role; @@ -761,7 +790,8 @@ private ConnectionUnderTest( { ReadTimeout = readTimeout ?? SocketRlpxConnection.DefaultReadTimeout, MaxQueuedReceiveBytes = maxQueuedReceiveBytes ?? SocketRlpxConnection.DefaultMaxQueuedReceiveBytes, - BeforeDecoding = beforeDecoding + BeforeDecoding = beforeDecoding, + AfterDecoding = afterDecoding }; Session = Substitute.For(); @@ -811,7 +841,7 @@ public static ConnectionUnderTest Create( TimeSpan? readTimeout = null, Func? beforeDecoding = null, Action? onReceive = null) - => new(role, privileged, maxReceiveLength, sendLatency, readTimeout, maxQueuedReceiveBytes: null, beforeDecoding, onReceive); + => new(role, privileged, maxReceiveLength, sendLatency, readTimeout, maxQueuedReceiveBytes: null, beforeDecoding, afterDecoding: null, onReceive); /// Starts the connection and completes the handshake as the peer. public static async Task StartAsync( @@ -821,9 +851,10 @@ public static async Task StartAsync( TimeSpan? readTimeout = null, long? maxQueuedReceiveBytes = null, Func? beforeDecoding = null, + Action? afterDecoding = null, Action? onReceive = null) { - ConnectionUnderTest test = new(HandshakeRole.Recipient, privileged, maxReceiveLength, sendLatency, readTimeout, maxQueuedReceiveBytes, beforeDecoding, onReceive); + ConnectionUnderTest test = new(HandshakeRole.Recipient, privileged, maxReceiveLength, sendLatency, readTimeout, maxQueuedReceiveBytes, beforeDecoding, afterDecoding, onReceive); test.Start(); await test.Peer.SendAsync(FakeHandshakeService.Message); await test.Peer.ReceiveHandshakeAsync(test.Cancellation); diff --git a/src/Nethermind/Nethermind.Network/Rlpx/Sockets/SocketRlpxConnection.cs b/src/Nethermind/Nethermind.Network/Rlpx/Sockets/SocketRlpxConnection.cs index 131752d087ea..17f3ddfae699 100644 --- a/src/Nethermind/Nethermind.Network/Rlpx/Sockets/SocketRlpxConnection.cs +++ b/src/Nethermind/Nethermind.Network/Rlpx/Sockets/SocketRlpxConnection.cs @@ -156,6 +156,9 @@ internal sealed class SocketRlpxConnection( /// Runs before each batch of received bytes is decoded; a test holds it to hold the frame loop. internal Func? BeforeDecoding { get; init; } + /// Runs after each batch of received bytes is decoded; a test frees queue capacity there to race the frame loop. + internal Action? AfterDecoding { get; init; } + /// Gets or sets the bytes of received packets not yet handled at which the frame loop pauses. /// /// While paused, the pipe fills and the receive loop stops reading, so TCP slows the peer down: a slow processing @@ -501,10 +504,13 @@ private async Task ReadFramesAsync(PipeReader reader) } ReadOnlySequence buffer = result.Buffer; - SequencePosition consumed = _discarding ? buffer.End : DecodeFrames(buffer); - if (IsReceiveQueueFull) + bool queueFull = false; + SequencePosition consumed = _discarding ? buffer.End : DecodeFrames(buffer, out queueFull); + AfterDecoding?.Invoke(); + if (queueFull) { - // The bytes left are read again once the processing thread catches up, so they aren't marked examined. + // The bytes left are read again once the processing thread catches up, which it may have done already, + // so they aren't marked examined. reader.AdvanceTo(consumed); await WaitForQueueCapacityAsync(); continue; @@ -552,14 +558,23 @@ private void ReleaseQueuedBytes(int length) } /// Decodes every whole block available, as does. - /// Where the bytes not yet consumed start: before the next frame if the processing thread fell behind. - private SequencePosition DecodeFrames(ReadOnlySequence buffer) + /// The bytes received and not yet consumed. + /// Whether decoding stopped with whole blocks left because the processing thread fell behind. + /// Where the bytes not yet consumed start. + private SequencePosition DecodeFrames(ReadOnlySequence buffer, out bool queueFull) { + queueFull = false; SequenceReader input = new(buffer); Span block = stackalloc byte[Frame.HeaderSize + Frame.MacSize]; Span plaintext = stackalloc byte[Frame.HeaderSize]; - while (input.Remaining >= Frame.BlockSize && !IsReceiveQueueFull) + while (input.Remaining >= Frame.BlockSize) { + if (IsReceiveQueueFull) + { + queueFull = true; + return input.Position; + } + switch (_frameState) { case FrameState.Header: From 3573df521e6b8deae4e9a608848fd97137545edc Mon Sep 17 00:00:00 2001 From: Ruben Buniatyan <337518+rubo@users.noreply.github.com> Date: Sat, 28 Nov 2026 20:34:41 +0100 Subject: [PATCH 18/22] fix(network): charge every queued packet and error toward the receive queue limit --- .../Rlpx/Sockets/SocketRlpxConnectionTests.cs | 40 +++++++++++++++---- .../Rlpx/Sockets/SocketRlpxConnection.cs | 37 +++++++++++++---- 2 files changed, 63 insertions(+), 14 deletions(-) diff --git a/src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/SocketRlpxConnectionTests.cs b/src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/SocketRlpxConnectionTests.cs index 8b8ca5fd37bd..88a4787cf724 100644 --- a/src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/SocketRlpxConnectionTests.cs +++ b/src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/SocketRlpxConnectionTests.cs @@ -71,7 +71,7 @@ public async Task Decompresses_a_packet_that_arrives_in_the_same_read_as_the_hel await test.Peer.SendAsync(frames); Assert.That(() => test.Socket.Received, Is.EqualTo(received + frames.Length).After(5000, 10)); - Assert.That(() => test.Connection.QueuedReceiveBytes, Is.GreaterThan(hello.Length).After(5000, 10), "the compressed packet is queued behind the hello"); + Assert.That(() => test.Connection.QueuedReceiveBytes, Is.GreaterThan(SocketRlpxConnection.MinQueuedItemCharge).After(5000, 10), "the compressed packet is queued behind the hello"); queued.SetResult(); await test.WaitForEventsAsync(2); @@ -181,11 +181,7 @@ public async Task Stops_decoding_after_a_frame_fails_authentication( public async Task Reports_a_merger_error_and_keeps_decoding([Values] bool privileged) { await using ConnectionUnderTest test = await ConnectionUnderTest.StartAsync(privileged: privileged); - // An authenticated frame whose header body is not a well formed RLP list. - byte[] header = new byte[Frame.HeaderSize]; - header[2] = Frame.BlockSize; - header[3] = 0xf7; - byte[] malformed = test.Peer.EncryptFrame(header, new byte[Frame.BlockSize]); + byte[] malformed = EncryptMalformedFrame(test.Peer); long received = test.Socket.Received; // The next frame comes in a later read, after the error was handled. @@ -303,6 +299,26 @@ public async Task Decodes_the_frames_left_by_a_pause_that_ends_before_the_frame_ await test.StopAndAssertBuffersReturnedAsync(); } + [Test] + public async Task Pauses_reading_frames_for_queued_packets_and_errors_without_content([Values] bool errors) + { + TaskCompletionSource handling = new(TaskCreationOptions.RunContinuationsAsynchronously); + const long maxQueuedReceiveBytes = 4 * SocketRlpxConnection.MinQueuedItemCharge; + await using ConnectionUnderTest test = await ConnectionUnderTest.StartAsync( + maxQueuedReceiveBytes: maxQueuedReceiveBytes, + onReceive: _ => handling.Task.Wait()); + // The first packet holds the processing thread, so everything after it stays queued. + byte[] first = test.Peer.Encode(0x10, Content(10, 1), EncodingMode.Framed); + byte[][] rest = [.. Enumerable.Range(0, 100).Select(_ => errors ? EncryptMalformedFrame(test.Peer) : test.Peer.Encode(0x11, [], EncodingMode.Framed))]; + + await test.Peer.SendAsync([.. first, .. rest.SelectMany(static frame => frame)]); + Assert.That(() => test.Connection.QueuedReceiveBytes, Is.EqualTo(maxQueuedReceiveBytes).After(5000, 10), "the frame loop pauses at the limit"); + handling.SetResult(); + + Assert.That(() => test.Connection.QueuedReceiveBytes, Is.Zero.After(5000, 10), "every charge is released once handled"); + await test.StopAndAssertBuffersReturnedAsync(); + } + [Test] public async Task Handles_an_error_raised_by_a_packet_before_the_next_packet() { @@ -318,7 +334,8 @@ public async Task Handles_an_error_raised_by_a_packet_before_the_next_packet() byte[] first = Content(10, 1); byte[] last = Content(10, 2); - int queuedBytes = Snappy.CompressToArray(first).Length + invalidSnappy.Length + Snappy.CompressToArray(last).Length; + // Each packet is smaller than the least charge. + const int queuedBytes = 3 * SocketRlpxConnection.MinQueuedItemCharge; await test.Peer.SendAsync([ .. test.Peer.Encode(0x20, first, EncodingMode.Snappy), @@ -698,6 +715,15 @@ public async Task Closes_without_reporting_a_failed_send() await test.StopAndAssertBuffersReturnedAsync(); } + /// Encrypts an authenticated frame whose header body is not a well formed RLP list. + private static byte[] EncryptMalformedFrame(ScriptedRlpxPeer peer) + { + byte[] header = new byte[Frame.HeaderSize]; + header[2] = Frame.BlockSize; + header[3] = 0xf7; + return peer.EncryptFrame(header, new byte[Frame.BlockSize]); + } + private static byte[] Content(int length, int seed) { byte[] content = new byte[length]; diff --git a/src/Nethermind/Nethermind.Network/Rlpx/Sockets/SocketRlpxConnection.cs b/src/Nethermind/Nethermind.Network/Rlpx/Sockets/SocketRlpxConnection.cs index 17f3ddfae699..101fe651fb24 100644 --- a/src/Nethermind/Nethermind.Network/Rlpx/Sockets/SocketRlpxConnection.cs +++ b/src/Nethermind/Nethermind.Network/Rlpx/Sockets/SocketRlpxConnection.cs @@ -73,6 +73,13 @@ internal sealed class SocketRlpxConnection( /// internal const long DefaultMaxQueuedReceiveBytes = 16 * 1024 * 1024; + /// + /// The least that a queued packet or error counts toward , so that small or empty + /// packets and errors, which hold memory too, can't queue without bound. + /// + /// Roughly what an error with its stack trace holds, or a small packet with its buffer and queue entry. + internal const int MinQueuedItemCharge = 1024; + private const int ReceiveSegmentSize = 16 * 1024; // A read goes into the rest of the current segment while at least this much is free, so that small reads fill a @@ -771,16 +778,25 @@ private void CompleteFrame() private void Dispatch(PooledPacket packet) { - int length = packet.Content.Length; - Interlocked.Add(ref _queuedReceiveBytes, length); + int charge = GetQueuedCharge(packet); + Interlocked.Add(ref _queuedReceiveBytes, charge); if (!_processingThread.TryEnqueue(new ProcessingItem(this, packet, null))) { packet.Release(); - ReleaseQueuedBytes(length); + ReleaseQueuedBytes(charge); + } + } + + private void QueueError(Exception exception) + { + Interlocked.Add(ref _queuedReceiveBytes, MinQueuedItemCharge); + if (!_processingThread.TryEnqueue(new ProcessingItem(this, null, exception))) + { + ReleaseQueuedBytes(MinQueuedItemCharge); } } - private void QueueError(Exception exception) => _processingThread.TryEnqueue(new ProcessingItem(this, null, exception)); + private static int GetQueuedCharge(PooledPacket packet) => Math.Max(packet.Content.Length, MinQueuedItemCharge); private void ReleaseFrame() { @@ -810,19 +826,26 @@ internal void Process(in ProcessingItem item) { if (item.Packet is { } packet) { - int length = packet.Content.Length; + int charge = GetQueuedCharge(packet); try { ProcessPacket(packet); } finally { - ReleaseQueuedBytes(length); + ReleaseQueuedBytes(charge); } } else if (item.Error is { } error) { - HandleError(error); + try + { + HandleError(error); + } + finally + { + ReleaseQueuedBytes(MinQueuedItemCharge); + } } else { From d9c9cff2a392aac681a4bf7936b62619fef98987 Mon Sep 17 00:00:00 2001 From: Ruben Buniatyan <337518+rubo@users.noreply.github.com> Date: Sat, 28 Nov 2026 20:39:27 +0100 Subject: [PATCH 19/22] fix(network): restart the read timeout when a receive pause ends --- .../Rlpx/Sockets/SocketRlpxConnectionTests.cs | 7 +++++-- .../Rlpx/Sockets/SocketRlpxConnection.cs | 2 ++ 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/SocketRlpxConnectionTests.cs b/src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/SocketRlpxConnectionTests.cs index 88a4787cf724..85fbda374fd8 100644 --- a/src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/SocketRlpxConnectionTests.cs +++ b/src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/SocketRlpxConnectionTests.cs @@ -244,7 +244,7 @@ public async Task Fills_a_receive_segment_with_reads_smaller_than_it() public async Task Pauses_reading_frames_while_the_processing_thread_holds_too_many_received_bytes() { TaskCompletionSource handling = new(TaskCreationOptions.RunContinuationsAsynchronously); - TimeSpan readTimeout = TimeSpan.FromMilliseconds(200); + TimeSpan readTimeout = TimeSpan.FromSeconds(1); await using ConnectionUnderTest test = await ConnectionUnderTest.StartAsync( readTimeout: readTimeout, maxQueuedReceiveBytes: 4 * 1024, @@ -255,16 +255,19 @@ public async Task Pauses_reading_frames_while_the_processing_thread_holds_too_ma await test.Peer.SendAsync(frames); Assert.That(() => test.Socket.Received, Is.EqualTo(received + frames.Length).After(5000, 10), "the packets are in the pipe"); - await Task.Delay(readTimeout * 3); + // The pause outlasts the read timeout and ends halfway between two checks of the idle timer. + await Task.Delay(readTimeout * 1.5); int heldPackets = test.Pool.OutstandingExceptSendBatch.Length; bool closedWhilePaused = test.Connection.Closed.IsCompleted; handling.SetResult(); await test.WaitForEventsAsync(contents.Length); + await Task.Delay(readTimeout * 0.7); using (Assert.EnterMultipleScope()) { Assert.That(heldPackets, Is.EqualTo(4), "the packets up to 4 KiB, one of them being handled"); Assert.That(closedWhilePaused, Is.False, "a pause isn't a read timeout"); + Assert.That(test.Connection.Closed.IsCompleted, Is.False, "the read timeout restarts when the pause ends"); Assert.That(test.Packets, Is.EqualTo(contents.Select(static content => ((byte)0x10, content)).ToArray())); } diff --git a/src/Nethermind/Nethermind.Network/Rlpx/Sockets/SocketRlpxConnection.cs b/src/Nethermind/Nethermind.Network/Rlpx/Sockets/SocketRlpxConnection.cs index 101fe651fb24..5b3ef4d6a814 100644 --- a/src/Nethermind/Nethermind.Network/Rlpx/Sockets/SocketRlpxConnection.cs +++ b/src/Nethermind/Nethermind.Network/Rlpx/Sockets/SocketRlpxConnection.cs @@ -551,6 +551,8 @@ private async Task WaitForQueueCapacityAsync() } finally { + // The peer wasn't read while paused, so its idle time starts when the pause ends. + Volatile.Write(ref _lastReceive, Environment.TickCount64); _awaitingQueueCapacity = false; } } From f9f307ff05024b079757869133db2d65c2afc743 Mon Sep 17 00:00:00 2001 From: Ruben Buniatyan <337518+rubo@users.noreply.github.com> Date: Sat, 28 Nov 2026 20:39:48 +0100 Subject: [PATCH 20/22] fix(network): read the socket listener's endpoint before a shutdown can dispose it --- .../Nethermind.Network/Rlpx/Sockets/SocketRlpxHost.cs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/Nethermind/Nethermind.Network/Rlpx/Sockets/SocketRlpxHost.cs b/src/Nethermind/Nethermind.Network/Rlpx/Sockets/SocketRlpxHost.cs index 0a5038886d97..2b02d9d44fe8 100644 --- a/src/Nethermind/Nethermind.Network/Rlpx/Sockets/SocketRlpxHost.cs +++ b/src/Nethermind/Nethermind.Network/Rlpx/Sockets/SocketRlpxHost.cs @@ -164,6 +164,9 @@ public async Task Init() throw; } + // Read before the listener is published, after which a shutdown may dispose it. + IPEndPoint? endpoint = listener.LocalEndPoint as IPEndPoint; + // A shutdown that started meanwhile has already looked for the listener, so it is closed here instead. bool shuttingDown; lock (_lock) @@ -183,7 +186,7 @@ public async Task Init() return; } - if (listener.LocalEndPoint is IPEndPoint endpoint) + if (endpoint is not null) { _ = _listenerState.TrackRlpxAddress(endpoint.Address, _listenerClosed.Task); } From ffc67fb845faa18c617d494b4d72f851f54b3f17 Mon Sep 17 00:00:00 2001 From: Ruben Buniatyan <337518+rubo@users.noreply.github.com> Date: Sat, 28 Nov 2026 20:39:48 +0100 Subject: [PATCH 21/22] test(network): shut the socket host down when the pending dial test is skipped --- .../Rlpx/Sockets/SocketRlpxHostTests.cs | 26 ++++++++++++------- 1 file changed, 16 insertions(+), 10 deletions(-) diff --git a/src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/SocketRlpxHostTests.cs b/src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/SocketRlpxHostTests.cs index 52b73f6d1941..d9f9dc9701ca 100644 --- a/src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/SocketRlpxHostTests.cs +++ b/src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/SocketRlpxHostTests.cs @@ -315,18 +315,24 @@ public async Task Shutdown_waits_for_a_pending_dial_which_publishes_nothing() int sessions = 0; host.SessionCreated += (_, _) => Interlocked.Increment(ref sessions); await host.Init(); + try + { + // A private address that answers nothing, so the dial stays pending until it is canceled. + Task dial = host.ConnectAsync(new Node(TestItem.PublicKeyA, new IPEndPoint(IPAddress.Parse("10.255.255.1"), 30303))); + await Task.Delay(100); + Assume.That(dial.IsCompleted, Is.False, "the network refused the address at once, so there is no pending dial to test"); + await host.Shutdown(); - // A private address that answers nothing, so the dial stays pending until it is canceled. - Task dial = host.ConnectAsync(new Node(TestItem.PublicKeyA, new IPEndPoint(IPAddress.Parse("10.255.255.1"), 30303))); - await Task.Delay(100); - Assume.That(dial.IsCompleted, Is.False, "the network refused the address at once, so there is no pending dial to test"); - await host.Shutdown(); - - using (Assert.EnterMultipleScope()) + using (Assert.EnterMultipleScope()) + { + Assert.That(dial.IsCompleted, Is.True, "shutdown waits for the dial"); + Assert.That(await dial, Is.False); + Assert.That(sessions, Is.Zero); + } + } + finally { - Assert.That(dial.IsCompleted, Is.True, "shutdown waits for the dial"); - Assert.That(await dial, Is.False); - Assert.That(sessions, Is.Zero); + await host.Shutdown(); } } From 84a2d649f71f852488fca3b41025b3fe0cf46c7f Mon Sep 17 00:00:00 2001 From: Ruben Buniatyan <337518+rubo@users.noreply.github.com> Date: Sat, 28 Nov 2026 20:40:00 +0100 Subject: [PATCH 22/22] style(network): drop the regions in the socket connection --- .../Rlpx/Sockets/SocketRlpxConnection.cs | 12 ------------ 1 file changed, 12 deletions(-) diff --git a/src/Nethermind/Nethermind.Network/Rlpx/Sockets/SocketRlpxConnection.cs b/src/Nethermind/Nethermind.Network/Rlpx/Sockets/SocketRlpxConnection.cs index 5b3ef4d6a814..83b8646701bd 100644 --- a/src/Nethermind/Nethermind.Network/Rlpx/Sockets/SocketRlpxConnection.cs +++ b/src/Nethermind/Nethermind.Network/Rlpx/Sockets/SocketRlpxConnection.cs @@ -243,8 +243,6 @@ private void Close() _closed.TrySetResult(); } - #region Receive - private async Task ReceiveLoopAsync() { PipeWriter writer = _pipe.Writer; @@ -819,10 +817,6 @@ private void ReleaseChunkedPacket() packet?.Release(); } - #endregion - - #region Processing thread - /// Handles an item on the connection's processing thread. internal void Process(in ProcessingItem item) { @@ -979,10 +973,6 @@ private void TraceSnappyMessage(int length) } } - #endregion - - #region Send - public int Enqueue(T message) where T : P2PMessage { if (!_outboundBytes.IsWritable) @@ -1303,8 +1293,6 @@ public Span GetSpan(int sizeHint = 0) public void Advance(int count) => Length = _packetTypeLength + count; } - #endregion - private readonly record struct OutboundItem(byte[] Buffer, int Length, bool Raw, FrameEncoder.EncodingMode Mode, long SendAfter); private enum FrameState