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.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.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.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/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/InMemoryRlpxSocket.cs b/src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/InMemoryRlpxSocket.cs new file mode 100644 index 000000000000..727af4858720 --- /dev/null +++ b/src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/InMemoryRlpxSocket.cs @@ -0,0 +1,157 @@ +// 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 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; } + + /// 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); + if (SendPermits is { } permits) + { + await permits.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 new file mode 100644 index 000000000000..13b4b53054a9 --- /dev/null +++ b/src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/RlpxTransportInteropTests.cs @@ -0,0 +1,204 @@ +// 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.Crypto; +using Nethermind.Core.ServiceStopper; +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.Network.Rlpx.Sockets; +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(); + } + } + } + + [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( + 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.Test/Rlpx/Sockets/ScriptedRlpxPeer.cs b/src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/ScriptedRlpxPeer.cs new file mode 100644 index 000000000000..905a2ae822be --- /dev/null +++ b/src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/ScriptedRlpxPeer.cs @@ -0,0 +1,154 @@ +// 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. + /// 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]; + // 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[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) + { + 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..85fbda374fd8 --- /dev/null +++ b/src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/SocketRlpxConnectionTests.cs @@ -0,0 +1,937 @@ +// 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 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)); + 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); + + 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() + { + 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(); + } + + [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, + [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); + byte[] malformed = EncryptMalformedFrame(test.Peer); + long received = test.Socket.Received; + + // 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); + + 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 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 Pauses_reading_frames_while_the_processing_thread_holds_too_many_received_bytes() + { + TaskCompletionSource handling = new(TaskCreationOptions.RunContinuationsAsynchronously); + TimeSpan readTimeout = TimeSpan.FromSeconds(1); + 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"); + // 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())); + } + + 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 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() + { + 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]; + + byte[] first = Content(10, 1); + byte[] last = Content(10, 2); + // 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), + .. test.Peer.Encode(0x21, invalidSnappy, EncodingMode.Framed), + .. 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); + + 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); + await test.StopAsync(); + + 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 test.StopAsync(); + + 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_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) + { + 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 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() + { + 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() + { + 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() + { + 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); + await test.StopAsync(); + + Assert.That(test.Events, Is.Empty); + 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]; + 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(); + } + + /// 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 + { + 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, + long? maxQueuedReceiveBytes, + Func? beforeDecoding, + Action? afterDecoding, + 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, + ReceivePool) + { + ReadTimeout = readTimeout ?? SocketRlpxConnection.DefaultReadTimeout, + MaxQueuedReceiveBytes = maxQueuedReceiveBytes ?? SocketRlpxConnection.DefaultMaxQueuedReceiveBytes, + BeforeDecoding = beforeDecoding, + AfterDecoding = afterDecoding + }; + + 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 CountingMemoryPool ReceivePool { 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, maxQueuedReceiveBytes: null, beforeDecoding, afterDecoding: null, 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, + long? maxQueuedReceiveBytes = null, + Func? beforeDecoding = null, + Action? afterDecoding = null, + Action? onReceive = null) + { + 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); + 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..d9f9dc9701ca --- /dev/null +++ b/src/Nethermind/Nethermind.Network.Test/Rlpx/Sockets/SocketRlpxHostTests.cs @@ -0,0 +1,375 @@ +// 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 NSubstitute; +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 Closes_only_the_inbound_connection_whose_setup_fails([Values] bool inSessionSubscriber) + { + // 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 && inSessionSubscriber) 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(inSessionSubscriber ? 2 : 1).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() + { + 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(); + } + } + + /// 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 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() + { + 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(); + 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(); + + 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 + { + await host.Shutdown(); + } + } + + [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); + // 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"); + } + } + + /// 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 b38b3566476e..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) => @@ -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) @@ -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, int connectTimeoutMs = 2000) { NetworkConfig networkConfig = new() { @@ -1106,7 +1106,9 @@ private static IContainer CreateFilterContainer(bool filterEnabled, bool subnetB FilterPeersByRecentIp = filterEnabled, FilterPeersBySameSubnet = subnetBucketing, ExternalIp = externalIp, - MaxActivePeers = 50 + MaxActivePeers = 50, + RlpxTransport = transport, + ConnectTimeoutMs = connectTimeoutMs }; IIPResolver ipResolver = Substitute.For(); @@ -1116,7 +1118,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 +1126,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 +1135,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 +1198,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 +1231,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 +1393,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/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..7140616af7c8 --- /dev/null +++ b/src/Nethermind/Nethermind.Network/P2P/RlpxErrorHandler.cs @@ -0,0 +1,66 @@ +// 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.Network.Rlpx.Sockets; +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 or RlpxReadTimeoutException) + { + 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..2cc407f09426 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,8 @@ 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 +30,7 @@ namespace Nethermind.Network.Rlpx { - public class RlpxHost : IRlpxHost, ISessionActivityObserver, IStoppableService + public class RlpxHost : IRlpxHost, IStoppableService { private IChannel? _bootstrapChannel; private IEventLoopGroup? _bossGroup; @@ -54,12 +50,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 +107,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 +153,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 +200,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 +292,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 +300,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 +445,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 +478,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 +524,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(); + } + } +} 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/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 new file mode 100644 index 000000000000..7db94b2c17d1 --- /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 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(ArrayPool pool, 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 = pool.Rent(capacity); + _buffer.AsSpan(_offset, _length).CopyTo(buffer); + pool.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) + { + pool.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..83b8646701bd --- /dev/null +++ b/src/Nethermind/Nethermind.Network/Rlpx/Sockets/SocketRlpxConnection.cs @@ -0,0 +1,1331 @@ +// 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. +/// 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, + IHandshakeService handshakeService, + IMessageSerializationService serializationService, + RlpxProcessingThreads.ProcessingThread processingThread, + ILogManager logManager, + TimeSpan sendLatency, + int maxInboundFrameSize, + 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; + + /// 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; + + /// + /// 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; + + /// + /// 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 + // 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; + 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( + pool: receivePool, + 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 ISession _session = null!; + private Task _completion = Task.CompletedTask; + private volatile bool _isClosed; + private FrameMacProcessor? _ingressMac; + private FrameMacProcessor? _egressMac; + + // 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; + + // 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; + 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 readonly OutboundBytes _outboundBytes = new(); + + /// 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 => _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; } + + /// 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 + /// 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; + + /// 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) + { + _session = session; + _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() + { + 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; + _outboundBytes.Close(); + while (_sendQueue.TryDequeue(out OutboundItem item)) + { + _pool.Return(item.Buffer); + } + } + + _sendSignal.Release(); + _idleTimer?.Dispose(); + _receiveCancellation.Cancel(); + _sendCancellation.Cancel(); + _socket.Close(); + Interlocked.Exchange(ref _queueCapacity, null)?.TrySetResult(); + _closed.TrySetResult(); + } + + 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(MinReceiveBufferSize), 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? _) + { + // 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) + { + 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 = _ingressMac = new(secrets); + FrameMacProcessor egressMac = _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(); + if (BeforeDecoding is { } beforeDecoding) + { + await beforeDecoding(); + } + + ReadOnlySequence buffer = result.Buffer; + 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, which it may have done already, + // so they aren't marked examined. + reader.AdvanceTo(consumed); + await WaitForQueueCapacityAsync(); + continue; + } + + reader.AdvanceTo(consumed, buffer.End); + if (result.IsCompleted) + { + return; + } + } + } + + 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 + { + // The peer wasn't read while paused, so its idle time starts when the pause ends. + Volatile.Write(ref _lastReceive, Environment.TickCount64); + _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. + /// 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) + { + if (IsReceiveQueueFull) + { + queueFull = true; + return input.Position; + } + + 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 = _pool.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. + _pool.Return(frame); + ReleaseChunkedPacket(); + QueueError(e); + return; + } + + switch (merged.Kind) + { + case MergedFrameKind.SinglePacket: + 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 = _pool.Rent(merged.ContentLength); + frame.AsSpan(merged.ContentOffset, merged.ContentLength).CopyTo(buffer); + _chunkedPacket = new PooledPacket(_pool, 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; + } + } + + _pool.Return(frame); + if (merged.IsComplete) + { + PooledPacket packet = _chunkedPacket!; + _chunkedPacket = null; + Dispatch(packet); + } + } + + private void Dispatch(PooledPacket packet) + { + int charge = GetQueuedCharge(packet); + Interlocked.Add(ref _queuedReceiveBytes, charge); + if (!_processingThread.TryEnqueue(new ProcessingItem(this, packet, null))) + { + packet.Release(); + ReleaseQueuedBytes(charge); + } + } + + private void QueueError(Exception exception) + { + Interlocked.Add(ref _queuedReceiveBytes, MinQueuedItemCharge); + if (!_processingThread.TryEnqueue(new ProcessingItem(this, null, exception))) + { + ReleaseQueuedBytes(MinQueuedItemCharge); + } + } + + private static int GetQueuedCharge(PooledPacket packet) => Math.Max(packet.Content.Length, MinQueuedItemCharge); + + private void ReleaseFrame() + { + if (_frame is { } frame) + { + _frame = null; + _pool.Return(frame); + } + + _frameState = FrameState.Header; + } + + private void ReleaseChunkedPacket() + { + _merger.Reset(); + PooledPacket? packet = _chunkedPacket; + _chunkedPacket = null; + packet?.Release(); + } + + /// Handles an item on the connection's processing thread. + internal void Process(in ProcessingItem item) + { + if (item.Packet is { } packet) + { + int charge = GetQueuedCharge(packet); + try + { + ProcessPacket(packet); + } + finally + { + ReleaseQueuedBytes(charge); + } + } + else if (item.Error is { } error) + { + try + { + HandleError(error); + } + finally + { + ReleaseQueuedBytes(MinQueuedItemCharge); + } + } + 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(_pool, _pool.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}"); + } + } + + public int Enqueue(T message) where T : P2PMessage + { + if (!_outboundBytes.IsWritable) + { + return 0; + } + + (byte[] buffer, int length) = Serialize(_serializationService, message, _pool); + return TryAdmit(buffer, length, raw: false) ? length : 0; + } + + private void QueueRaw(byte[] data) + { + byte[] buffer = _pool.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. + /// + /// + /// 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; + bool wake; + lock (_sendLock) + { + if (_isClosed) + { + _pool.Return(buffer); + return true; + } + + if (!raw && !_outboundBytes.IsWritable) + { + _pool.Return(buffer); + return false; + } + + _sendQueue.Enqueue(new OutboundItem(buffer, length, raw, _encodingMode, sendAfter)); + _outboundBytes.Add(length); + wake = _sendLoopWaiting; + _sendLoopWaiting = false; + } + + if (wake) + { + _sendSignal.Release(); + } + + return true; + } + + private void Charge(long bytes) + { + lock (_sendLock) + { + _outboundBytes.Add(bytes); + } + } + + private async Task SendLoopAsync() + { + 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; + 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 = _pool.Rent(bound); + try + { + if (TryEncode(item, encoder, own, out int written)) + { + batchPackets.Add((written, written)); + await SendAsync(own, written, batchPackets, cancellation); + } + } + finally + { + _pool.Return(own); + } + } + else if (TryEncode(item, encoder, batch.AsSpan(used), out int written)) + { + used += written; + batchPackets.Add((used, written)); + } + } + finally + { + _pool.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 + { + _pool.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, ArrayPool pool) + where T : P2PMessage + { + PacketWriter writer = t_writer ??= new(); + writer.Start(pool, 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) + { + pool.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 ArrayPool? _pool; + private int _packetType; + private int _packetTypeLength; + + public byte[]? Buffer { get; private set; } + + public int Length { get; private set; } + + public void Start(ArrayPool pool, int packetType) + { + _pool = pool; + _packetType = packetType; + } + + // Keeps an idle thread's writer from holding on to the last buffer and pool. + public void Clear() + { + _pool = null; + 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 = _pool!.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; + } + + 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..2b02d9d44fe8 --- /dev/null +++ b/src/Nethermind/Nethermind.Network/Rlpx/Sockets/SocketRlpxHost.cs @@ -0,0 +1,557 @@ +// 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; + 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); + + 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 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. + 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; + _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); + } + + 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; + + /// Gets the time a dial waits for the socket to connect. + internal TimeSpan ConnectTimeout => _connectTimeout; + + 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; + RlpxProcessingThreads processingThreads = new(_processingThreadCount, _logger); + lock (_lock) + { + _processingThreads = processingThreads; + } + + Socket listener; + try + { + listener = await RlpxListener.BindAsync(_listenerState, LocalPort, _logger, nameof(SocketRlpxHost), Bind); + } + catch (Exception ex) + { + _logger.Error($"{nameof(Init)} failed.", ex); + await processingThreads.StopAsync(); + 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) + { + shuttingDown = _shuttingDown; + if (!shuttingDown) + { + _listener = listener; + _acceptLoop = Task.Run(AcceptLoopAsync); + } + } + + if (shuttingDown) + { + listener.Dispose(); + await processingThreads.StopAsync(); + return; + } + + if (endpoint is not null) + { + _ = _listenerState.TrackRlpxAddress(endpoint.Address, _listenerClosed.Task); + } + } + + 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}"); + // 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; + } + + Accept(socket); + } + } + finally + { + _listenerClosed.TrySetResult(); + } + } + + /// 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; + try + { + remote = (IPEndPoint)socket.RemoteEndPoint!; + } + catch (Exception e) when (e is SocketException or ObjectDisposedException) + { + socket.Dispose(); + return; + } + + SocketRlpxConnection? connection = null; + try + { + 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); + } + catch (Exception e) + { + // 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(); + } + } + + 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); + 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) => + { + (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"; + + /// 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; + 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; + 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(); + } + } +}