Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
d73d4c6
refactor(network): move the transport-free RLPx host policy out of Rl…
rubo Nov 26, 2026
ece687d
feat(network): add an opt-in RLPx transport on sockets and System.IO.…
rubo Nov 26, 2026
0ea03f0
test(network): cover the socket transport against a scripted peer
rubo Nov 26, 2026
9542762
test(network): release the packets queued when a socket connection cl…
rubo Nov 26, 2026
7842c23
test(network): check what a socket connection reports only once its t…
rubo Nov 26, 2026
0448caf
test(network): cover a Hello that enables Snappy and benchmark the so…
rubo Nov 26, 2026
3ecadb3
test(network): cover the remaining socket transport behaviours
rubo Nov 26, 2026
7664c17
test(network): accept either reporter of a disconnect at socket host …
rubo Nov 26, 2026
77eda01
perf(network): fill each socket receive segment before starting another
rubo Nov 27, 2026
01bf9cc
fix(network): pause reading frames while the processing thread falls …
rubo Nov 28, 2026
c428763
fix(network): close only the socket connection whose session activati…
rubo Nov 28, 2026
8474791
fix(network): close a socket listener bound after shutdown started
rubo Nov 28, 2026
ededaf0
fix(network): drop a packet queued past the high watermark by a concu…
rubo Nov 28, 2026
9f79710
test(network): wait for queued packets instead of sleeping in socket …
rubo Nov 28, 2026
d86427a
fix(network): keep accepting after any failure to set up an inbound s…
rubo Nov 28, 2026
75fd588
style(network): fix whitespace in a socket transport test
rubo Nov 28, 2026
e4fef21
fix(network): decode the frames left by a receive pause that ends bef…
rubo Nov 28, 2026
3573df5
fix(network): charge every queued packet and error toward the receive…
rubo Nov 28, 2026
d9c9cff
fix(network): restart the read timeout when a receive pause ends
rubo Nov 28, 2026
f9f307f
fix(network): read the socket listener's endpoint before a shutdown c…
rubo Nov 28, 2026
ffc67fb
test(network): shut the socket host down when the pending dial test i…
rubo Nov 28, 2026
84a2d64
style(network): drop the regions in the socket connection
rubo Nov 28, 2026
e332e86
Merge remote-tracking branch 'origin/master' into feat/rlpx-pipelines…
rubo Nov 28, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion src/Nethermind/Nethermind.Init/Modules/NetworkModule.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -63,7 +64,6 @@ protected override void Load(ContainerBuilder builder)
.AddSingleton<IDisconnectsAnalyzer, MetricsDisconnectsAnalyzer>()
.AddSingleton<ISessionMonitor, SessionMonitor>()
.AddSingleton<IPrivilegedIpProvider, PrivilegedIpProvider>()
.AddSingleton<IRlpxHost, RlpxHost>()
.AddSingleton<Handshake.IHandshakeService, Handshake.HandshakeService>()

.AddSingleton<INodeStatsManager>(ctx => new NodeStatsManager(
Expand Down Expand Up @@ -183,6 +183,15 @@ protected override void Load(ContainerBuilder builder)
.AddProtocolHandler<Subprotocols.Eth.V72.Eth72ProtocolHandler>()

;

if (configProvider.GetConfig<INetworkConfig>().RlpxTransport == RlpxTransport.Sockets)
{
builder.AddSingleton<IRlpxHost, SocketRlpxHost>();
}
else
{
builder.AddSingleton<IRlpxHost, RlpxHost>();
}
}

private sealed class TxGossipPolicySource(ILifetimeScope lifetimeScope) : ITxGossipPolicySource
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,9 @@ public class RlpxRoundTripBenchmarks
private ISyncPeer _serverPeer = null!;
private ISnapSyncPeer _serverSnapPeer = null!;

/// <summary>Gets the transport both nodes run on.</summary>
protected virtual RlpxTransport Transport => RlpxTransport.DotNetty;

[GlobalSetup]
public void GlobalSetup() => SetUpAsync().GetAwaiter().GetResult();

Expand Down Expand Up @@ -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 });

Expand Down
Original file line number Diff line number Diff line change
@@ -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;

/// <summary>
/// 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.
/// </summary>
/// <remarks>
/// 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.
/// </remarks>
[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<SocketRlpxConnectionBenchmarks>());
_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<byte> payload) : P2PMessage
{
public override int PacketType => 0x10;

public override string Protocol => "benchmark";

public ReadOnlyMemory<byte> Payload => payload;
}

private sealed class PayloadSerializer : IMessageSerializer<PayloadMessage>
{
public int GetLength(PayloadMessage message) => message.Payload.Length;

public int Serialize(Span<byte> destination, PayloadMessage message)
{
message.Payload.Span.CopyTo(destination);
return message.Payload.Length;
}

public PayloadMessage Deserialize(ReadOnlySpan<byte> data) => throw new NotSupportedException();
}

/// <summary>A session that counts the packets it receives, and allocates nothing doing so.</summary>
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>(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<DisconnectEventArgs> Disconnecting { add { } remove { } }
public event EventHandler<DisconnectEventArgs> Disconnected { add { } remove { } }
event EventHandler<EventArgs> ISession.Initialized { add { } remove { } }
public event EventHandler<EventArgs> HandshakeComplete { add { } remove { } }
public event EventHandler<PeerEventArgs> MsgReceived { add { } remove { } }
public event EventHandler<PeerEventArgs> MsgDelivered { add { } remove { } }
}
}
Original file line number Diff line number Diff line change
@@ -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;

/// <summary>
/// The round trips of <see cref="RlpxRoundTripBenchmarks"/> with both nodes on the socket transport.
/// </summary>
/// <remarks>A separate class keeps the DotNetty rows' names, so they still compare with master's.</remarks>
public class SocketRlpxRoundTripBenchmarks : RlpxRoundTripBenchmarks
{
protected override RlpxTransport Transport => RlpxTransport.Sockets;
}
Original file line number Diff line number Diff line change
Expand Up @@ -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; }

Expand Down
16 changes: 16 additions & 0 deletions src/Nethermind/Nethermind.Network.Contract/Config/RlpxTransport.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
// SPDX-FileCopyrightText: 2026 Demerzel Solutions Limited
// SPDX-License-Identifier: LGPL-3.0-only

namespace Nethermind.Network.Config;

/// <summary>
/// The transport that RLPx connections run on.
/// </summary>
public enum RlpxTransport
{
/// <summary>DotNetty channels.</summary>
DotNetty,

/// <summary>Sockets and System.IO.Pipelines, without DotNetty.</summary>
Sockets
}
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,9 @@
<ItemGroup>
<PackageReference Include="NSubstitute" />
</ItemGroup>
<ItemGroup>
<InternalsVisibleTo Include="Nethermind.Network.Benchmark" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Nethermind.Core.Test\Nethermind.Core.Test.csproj" />
<ProjectReference Include="..\Nethermind.Core\Nethermind.Core.csproj" />
Expand Down
Loading
Loading