Repository navigation
Conversation
…pxHost The socket transport that follows needs the same dial, filter, session tracking and listener behaviour as RlpxHost. These move unchanged into internal types both hosts can use: - RlpxDialPolicy: the recent-IP filter with privileged IPs, and dialing a node's endpoint, then the other address family its verified ENR advertises - RlpxSessionTracker: the session events, the activity observer, marking a session disconnected a second after its connection closes, and at shutdown - RlpxListener: the fallback bind and the dual-mode listener socket - RlpxErrorHandler: the logging and disconnect policy for an error in the communication with a peer, from ZeroNettyP2PHandler.ExceptionCaught
…Pipelines Network.RlpxTransport (hidden, DotNetty by default) selects SocketRlpxHost, which runs RLPx sessions without DotNetty. It shares the dial, filter and session policy with RlpxHost, and the frame codec with the DotNetty handlers. Each connection runs three loops. A receive loop fills a pipe from the socket, waiting for data before it rents a buffer. A frame loop reads the pipe: the handshake, then frames, which it authenticates, decrypts block by block into a rented buffer and merges into packets. A send loop encodes the queued packets in batches and writes them to the socket. Each direction has its own cipher and MAC instances. Received packets are handled on ProcessingThreadCount dedicated threads, each connection pinned to one, with one FIFO per thread, as on DotNetty's executor group: the size limit, Snappy, ReceiveMessage and the error handling, in the order the frame loop queued them. A packet's queue position, Snappy mode and writability charge are fixed when it is queued, so a Hello queued before Snappy is enabled stays framed. The connection is the one owner of writability, with DotNetty's watermarks.
A connection runs on an in-memory socket against a scripted peer that holds the paired secrets, with a session that records what it is given and a pool that tracks every rental. The tests cover frames split at any offset, chunks and Snappy, failed MACs and merger errors for ordinary and privileged peers, ordering against a reset and against an error raised by a packet, the end of the stream mid-packet, the read and handshake timeouts, leases kept after shutdown, ordered sends from many threads, packets larger than the batch, short sends, the handshake without simulated latency, the encoding mode fixed at admission, and the watermarks, checked against DotNetty's channel. The host tests cover the listener, the inbound filter, refused, cancelled and pending dials, and shutdown, also through the node's service stopper. The connection takes an optional pool, a read timeout and a hook before decoding, for these tests; its writability moves into OutboundBytes. The handshake messages skip the simulated latency, as DotNetty writes them without PacketSender, and the MAC processors are disposed when the connection's loops end. An accept error other than a reset pauses the accept loop briefly.
…cket transport A peer's Hello and its first compressed packet can arrive in one read. The new test holds the processing thread until both are queued, then enables Snappy while handling the Hello, as P2PProtocolHandler does, and checks the second packet is decompressed. Deciding Snappy when the frame loop queues a packet instead fails it. The scripted peer now RLP-encodes packet type 0. SocketRlpxRoundTripBenchmarks runs RlpxRoundTripBenchmarks with both nodes on the socket transport; a separate class keeps the DotNetty rows' names, so they still compare with master's. SocketRlpxConnectionBenchmarks measures a connection on an in-memory stream, receiving frames and sending bursts, whole or split into small reads and sends; the peer encodes into a reused buffer and drains without decoding, so the allocations are the connection's.
Tests for the handshake size limit at 65535 bytes with its prefix, a handshake that completes while its ACK is still being sent, traffic in both directions at once, a delayed packet charged when queued, a partly sent packet charged until its last byte is sent, the dial deadline when ConnectTimeoutMs is zero, and the ENR alternate dialed after a refused primary, which now runs on both hosts. SocketRlpxHost.Shutdown returns the first call's task to every caller, so a second caller also waits for the shutdown to finish.
|
Claude finished @rubo's task in 3m 24s —— View job Review of PR #16473: RLPx transport on sockets and System.IO.Pipelines
Summary: This is careful work. The transport stays behind a hidden flag, DotNetty remains the default, and the refactor of Medium
Low
Checked, nothing to report
Mergeable: not yet. Item 1 is Medium and hasn't been acknowledged. |
| continue; | ||
| } | ||
|
|
||
| Accept(socket); |
There was a problem hiding this comment.
Medium — an exception thrown in Accept stops all inbound connections.
Accept(socket) runs inside the accept loop with no try/catch. It does more than accept the socket: it builds the Session, calls _sessions.Activate (which runs the SessionCreated subscribers synchronously, i.e. PeerManager.RlpxHostOnSessionCreated and ProtocolsManager), then connection.Start. If any of these throws, AcceptLoopAsync exits through its finally. That completes _listenerClosed, and the node takes no more inbound peers until it restarts. Nothing is logged, because nobody observes _acceptLoop until shutdown. The accepted socket also leaks, and the connection stays in _connections.
On DotNetty, an exception in the child initializer or a handler closes only that channel and the listener keeps running. So the new transport is less robust here.
Suggested fix: wrap the per-socket work, log it, and close that socket only:
try
{
Accept(socket);
}
catch (Exception e)
{
if (_logger.IsError) _logger.Error("Failed to set up an inbound RLPx connection", e);
socket.Dispose();
}A regression test could subscribe a throwing SessionCreated handler once, then check that a second inbound connection still gets through.
TryConnect → StartSession has the same gap: if it throws after TryTrack, the connection stays tracked and its socket stays open. The exception does reach the caller there, though.
There was a problem hiding this comment.
Acceptnow catches any failure while it sets up an inbound connection. It logs the error, stops tracking the connection and closes it, and the accept loop keeps running.StartSessiondoes the same when the session fails to activate. Dials go through it too, so a dial that fails this way no longer leaves its connection tracked and open.
Closes_only_the_inbound_connection_whose_setup_fails covers a failure in the inbound filter and in a SessionCreated subscriber.
🤖 AI agent (Claude Code / Opus 5.5) on behalf of @rubo
| while (true) | ||
| { | ||
| // Waits for data without holding a buffer, so idle peers hold none. | ||
| await _socket.ReceiveAsync(Memory<byte>.Empty, cancellation); |
There was a problem hiding this comment.
Low (perf) — the zero-byte read runs before every receive.
Waiting without a buffer is the right choice for idle peers. On a busy connection, though, the zero-byte receive runs on every iteration even when the last read filled the buffer, so more data is almost certainly waiting. That is an extra socket operation for each real read during bulk sync.
Kestrel does the zero-byte read only when the previous read came back short. Something like if (lastReceived < lastBufferLength) await _socket.ReceiveAsync(Memory<byte>.Empty, ...) keeps the idle-peer benefit and skips the extra call while streaming. It's optional; the benchmarks already look good.
There was a problem hiding this comment.
Agreed that it's worth trying. I'd rather leave it for the follow-up that makes this transport the default, so this PR doesn't grow further and the change gets a benchmark of its own.
🤖 AI agent (Claude Code / Opus 5.5) on behalf of @rubo
Stateless guest cost
Variable cost by bucket, summed over shared blocks (excludes BASE)
Compared against |
…behind A socket connection queued every decoded packet for its processing thread without limit, so a slow handler let a peer pin unbounded memory. The frame loop now pauses at 16 MB of received packets not yet handled; the pipe then fills and TCP slows the peer. A pause doesn't count toward the read timeout.
…on fails A SessionCreated subscriber that threw escaped the accept loop and ended it, so the node stopped taking inbound peers, and the connection stayed tracked and open. The host now logs the failure and closes only that connection, as DotNetty closes only the channel whose handler failed. A dial that fails this way closes its connection the same way.
A shutdown that ran while Init was binding found no listener to close, and Init then published the socket and started an accept loop that exited at once, leaving the port bound. Init now publishes the listener under the host's lock only if no shutdown has started, and closes it otherwise.
…rrent sender Senders check writability before serializing, so several could pass the check before one of them crossed the high watermark, and all of them were queued. Admission now checks writability again under the send lock and drops the packet, returning 0 as for a packet refused up front. A packet dropped by a close still counts as sent, as on DotNetty.
…transport tests The Hello and Snappy test and the error ordering test slept 100 ms to let packets reach the processing thread's queue. They now wait for the connection's count of queued received bytes. The pending dial test is inconclusive rather than passing when the network refuses its address at once.
…ocket connection Only a failing session activation was caught, so an exception elsewhere while setting up an inbound connection, such as in the inbound filter, still ended the accept loop. Setting up a connection now closes only that connection on any failure.
…ore the frame loop waits
Changes
Fifth of the PRs that make the RLPx stack independent of DotNetty, after #15775, #15874, #16103 and #16427 made the sessions and the frame codec transport-neutral. This one adds an RLPx transport on sockets and System.IO.Pipelines that runs without DotNetty. The hidden
Network.RlpxTransportsetting selects it asSockets; DotNetty stays the default.System.IO.Pipelinesships with .NET, so nothing new is referenced.RlpxHost, unchanged, into internal types both hosts use:RlpxDialPolicy: the recent-IP filter, privileged IPs, and dialing the ENR alternate after the primary endpointRlpxSessionTracker: the session events, the activity observer, and marking sessions disconnected after a close and at shutdownRlpxListener: the fallback bind and the dual-mode listener socketRlpxErrorHandler: the logging and disconnect policy ofZeroNettyP2PHandler.ExceptionCaughtSocketRlpxHostaccepts and dials sockets, and owns its connections until their loops end. It is a stoppable service, asRlpxHostis, so the node's shutdown stops it.SocketRlpxConnectionruns three loops.ZeroFrameDecoderdoes. It authenticates the header, decrypts the payload block by block into a rented buffer, and passes nothing on before the payload MAC passes.ProcessingThreadCountdedicated threads, one FIFO per thread and each connection pinned to one, as on DotNetty's executor group. The size limit, Snappy,ReceiveMessageand the error handling run there in order, so a Hello enables Snappy before the next packet is read. A connection stops reading frames while 16 MB of its received packets wait there or are being handled; the socket then stops being read, so TCP slows the peer down.PacketSender.RlpxHost's watermarks.Differences from DotNetty:
Enqueuereturns 0. On DotNetty, senders that checked writability at the same time all get through.SimulateSendLatencyMs, a packet is charged as soon as it's queued.HandshakeTimeoutscounts only handshakes that run out of time on an open connection. DotNetty checks 3 seconds after connecting whether the first handshake message arrived, so it also counts connections that ended sooner for another reason. On mainnet, over the same hours, that was 971 against DotNetty's 16,443.InvalidFrameExceptionandRlpxReadTimeoutException, where DotNetty namesCorruptedFrameExceptionandReadTimeoutException. The reasons and log levels are the same.Testing
These pass:
Nethermind.Network.Test: 3,004 passed, 14 skipped (CI, e332e86)Nethermind.Xdc.Test: 881 passedKademliaAdapterTestsofNethermind.Network.Discovery.Test: 132 passedNethermind.Runner.Test: 2,271 passed, 8 skippedThe code-lint builds of
Nethermind.Network.Benchmark,Nethermind.Network.Discovery.TestandNethermind.Runner.Testreport nothing in the files this PR changes.A mainnet node on sockets ran next to a master node started at the same time, both with Lighthouse. Over the first 15 hours, it matched master on sync, bandwidth, peers, CPU, GC, pings, and peer Snappy and ECIES failures. Its handshake timeouts are fewer, for the reason above.
A second node on sockets, at 75fd588 (before the review fixes), ran for 22 hours next to a node on the same master commit, both with Lighthouse. It reached the chain head in 2h 16m against 2h 19m, and matched on peers, CPU, memory and bytes received. It sent 22% less, all of it transactions served on request, which differed by up to 2.4 times between earlier node pairs, including two on DotNetty. None of its connections ever had 16 MB of received data waiting. Two of the later fixes act only while reading is paused, so they don't change this. The third counts each waiting packet as at least 1 KiB, so the fixed code pauses sooner when many small packets pile up: after about 16,000 on one connection.
The new tests run a connection on an in-memory socket against a scripted peer that holds the paired secrets, with a pool that tracks every rental: no buffer is lost or returned twice.
Not covered:
Both need seams in the host that this PR doesn't add.
Breaking each of these on purpose, one at a time, fails the tests (38 in all):
Benchmark
In short, compared with DotNetty in the same rounds:
BlockBodiesandByteCodesare 2–6% faster,Receiptsis 5% slower; these aren't paired comparisons.6 paired rounds against master on the CI runner (AMD EPYC 7713), on 77eda01. Times are medians, and Δ is the mean of the per-round changes, with its 99% interval. The review fixes since then change no socket benchmark significantly, in time or allocations (6 paired rounds, 77eda01 against 9f79710; 6 paired rounds, 75fd588 against 84a2d64).
The round trips connect two nodes over loopback TCP, with Snappy on after Hello. The DotNetty rows run
RlpxHost, which this PR only refactors;SocketRlpxRoundTripBenchmarksruns the same round trips with both nodes on sockets, in the same rounds:SingleHeaderBlockBodiesReceiptsByteCodesSingleHeaderBlockBodiesReceiptsByteCodesThe DotNetty allocations vary from run to run: master's
ReceiptsandByteCodesrows allocate 24.88 KB and 15.62 KB here.SocketRlpxConnectionBenchmarksruns one connection on an in-memory stream, so the times and allocations are the connection's, plus the peer's encryption. It receives frames into packets for the session, and sends a burst of packets, with the stream whole or split into small reads and sends. Per packet:Remarks
New public API:
Network.RlpxTransportsetting and itsRlpxTransportenum;SocketRlpxHost, public becauseNetworkModulein Nethermind.Init registers it. It takes the nameRlpxHostonce the DotNetty host is deleted.NetworkDiagTracerstays enabled after the protocol handler tests that turn it on, and with it on,Session.MarkDisconnectedthrows for an inbound session that hasn't completed its handshake, before the disconnect is reported. That predates this PR; the new host tests turn the tracer off.🤖 AI agent (Claude Code / Opus 5.5) on behalf of @rubo