Skip to content

P2P parity: no forwarding, bounded peer queues, block announcements - #33

Merged
mwaddip merged 25 commits into
mainfrom
fix/p2p-jvm-parity
Sep 29, 2026
Merged

mwaddip merged 25 commits into
mainfrom
fix/p2p-jvm-parity

Conversation

@mwaddip

@mwaddip mwaddip commented Sep 29, 2026 •

Copy link
Copy Markdown
Owner

The node stops acting as a proxy and behaves like a JVM peer on the wire. Nothing is forwarded between peers any more: the router answers only with what the node has, and transactions are now served from the mempool through a reader that never takes the mempool lock. A peer that stops reading is aborted at the JVM 6.0.5 bounds (64 frames, one maximum frame of bytes) instead of freezing the event loop, and inbound handshakes in flight count against max_inbound, as in 6.0.6. Mined blocks, fresh applied blocks and accepted transactions are announced to every peer, and a relayed transaction over 96 KB is dropped unparsed.

Sync no longer re-requests timed-out transactions and batches its other re-requests, since its attempt limit had never fired. Also: /stats/p2p now counts block traffic, which it never had, and the parked clippy failure is cleared. Sync also skips announced transactions that are already in the mempool, as the JVM's processInv does.

Checked:

  • workspace tests 1207/1207, clippy -D warnings, fmt --check
  • 20 minutes on the mainnet node: 9 blocks, peers 1 → 14, no aborts or penalties, and 7 of 7 transaction requests served from the mempool

🤖 Generated with Claude Code

mwaddip and others added 25 commits September 29, 2026 15:11
…ssion

A peer that stops reading can freeze the whole P2P event loop: every
enqueue awaits that peer's 64-frame queue while holding peer_senders.
The contract now requires non-blocking enqueues, bounded the way the
JVM bounds them since 6.0.5 (64 frames, one maximum frame of bytes),
with a full queue aborting the connection. disconnect_peer is specified
as the same abort rather than a half-close.

max_inbound now counts in-flight inbound handshakes as well, as JVM
6.0.6 does, and peer_disconnected's reason field gets its values.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…n flight

Every enqueue onto a peer's 64-frame write queue awaited room, most of
them with peer_senders locked, and write_frame has no timeout. A peer
that stopped reading filled its queue and then blocked the event loop
with the lock held: every reader backed up behind the event channel, no
socket was read, and JVM peers dropped the node. disconnect_peer only
dropped the sender, which left the writer blocked and the reader
registered.

Write queues (facts/p2p-node.md, Peer write queues; JVM 6.0.5+):
- Enqueueing never waits. A frame beyond 64 queued frames or 16,388,621
  queued wire bytes aborts the peer (outbound_queue_full), and so does a
  queue whose writer is gone (write_failed). Bytes count until the
  writer takes the frame.
- peer_senders is a std mutex, held only for map operations and
  non-blocking enqueues, never across an await.
- send_to returns QueueFull after aborting instead of waiting;
  broadcast_outbound aborts a full peer instead of skipping it.

Aborts (Aborting a connection):
- A per-connection latch; the first reason wins. The reader loop selects
  on it, including while it waits on the event channel. The teardown
  discards queued frames, sets SO_LINGER 0 so the close is a reset, and
  emits one PeerDisconnected.
- disconnect_peer is that abort, with reason disconnected.
- "Peer removed" and PeerDisconnected.reason carry connection_closed,
  write_failed, outbound_queue_full or disconnected.
- A peer's queue exists before the peer is registered or announced.

Inbound admission (JVM 6.0.6): a slot is reserved at accept, passes to
the registered peer on a successful handshake, and is released by a
failed handshake or the peer's teardown. The count spans both listeners.

tokio floor raised to 1.50 for TcpStream::set_zero_linger.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…fetime

The byte bound counts a frame's serialized length, as the JVM's
msg.length does: an empty-body frame carries no checksum, so it is 9
bytes, not 13. And a peer's queue now exists before the peer is
registered or announced, and is removed before PeerDisconnected, which
bounds when send_to can see UnknownPeer.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The routing contract kept the proxy era's forwarding: requests the node
could not serve were relayed to another peer, SyncInfo was paired
between inbound and outbound peers, and unknown message codes went to
every peer of the opposite direction. One junk-code frame from an
inbound peer reached every outbound JVM, whose parser jams on an
unknown code.

Now every message is consumed or dropped. The router answers GetPeers
and what the local-serve hook has, emits modifiers for validation, and
drops unknown codes without penalty. Its inv table, request tracker,
sync tracker and consumed-code registry go with the forwarding.

broadcast replaces broadcast_outbound and reaches every connected
peer, as the JVM's Broadcast does. The modifier sink becomes required,
and latency_stats, fed only by relayed requests, is gone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ery peer

Nothing served transactions from the mempool: a peer asking for a tx we
had announced got its request relayed to another peer, which is what
kept relayed transactions moving and left API submissions with nobody
to relay to. With forwarding gone, the node serves them itself.

The P2P router serves inside the event loop, and the mempool sits behind
an async mutex held for whole validations, so the serve path reads a
MempoolReader instead: an index of tx bytes that changes with the pool's
membership and is read without the owner's lock, the split the JVM
makes with its published mempool reader. UnconfirmedTx.tx_bytes becomes
an Arc<[u8]> shared with that index.

Transaction Invs now go to every connected peer, as the JVM broadcasts
accepted transactions.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The router still carried the proxy era's forwarding. A ModifierRequest
the local-serve hook missed was re-requested from the Inv announcer or
any outbound peer, and the response relayed back. An inbound peer's
SyncInfo was paired with an outbound peer and sent to it, so that JVM
saw two SyncInfos from us describing different chains. An unknown code
went to every peer of the opposite direction, and the JVM's
MessageSerializer throws on an unknown code, so one junk frame from an
inbound peer wedged every outbound JVM connection.

Now every message is answered to its sender or not at all
(facts/p2p-routing.md):
- Inv and SyncInfo produce no actions. Sync and the mempool task read
  them from the subscriber.
- A ModifierRequest gets what the local-serve hook has. A miss gets
  nothing, as in the JVM's modifiersReq. A light listener's requests
  for block sections still get nothing; its transaction requests go to
  the hook like any other.
- A ModifierResponse produces Action::Validate only, and its modifiers
  move into the actions instead of being cloned.
- An unknown code is dropped, without penalty.
- A debug_assert holds every Action::Send to the source of the message
  being handled.

Removed with the forwarding: the inv table, the request and sync
trackers, the latency tracker with latency_stats, and the consumed-code
registry (Router and P2pNode::register_consumed_code). Their 21 unit
tests go with them. The 19 router tests that asserted forwarding are
rewritten to the new contract.

API (facts/p2p-node.md):
- broadcast replaces broadcast_outbound. It reaches every connected
  peer, inbound and outbound, as the JVM's SendToNetwork(msg,
  Broadcast) does, with the same enqueue/abort semantics. The keepalive
  keeps its own outbound-only GetPeers.
- start and the event loop take a required ModifierSink.

The standalone ergo-proxy-node's leftovers are gone: its release
workflow, build-deb, debian/, deploy/ (service, fail2ban jail,
dashboard), ergo-proxy.toml, and stale copies of facts/p2p-*.md and
docs/protocol/. Two comments that pointed at the deleted fail2ban
filter now point at the main repo's deploy/fail2ban/ergo-node.conf.
The penalty test's mirror of that regex drops address_sanity, which
nothing emits and ergo-node.conf does not match. CLAUDE.md and
README.md describe the crate as it is.

The workspace build breaks at src/main.rs until the root crate takes
the new API (Some(modifier_tx), register_consumed_code,
broadcast_outbound).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…y peer

The root crate follows 0a9f293: the modifier sink is passed as required,
the consumed-code registration goes (nothing is forwarded, so nothing
needs protecting from it), and accepted and rebroadcast transactions are
announced with broadcast, to every connected peer, as the JVM announces
them, rather than to the peers we dialed.

Transactions are not yet served from the mempool; that lands with the
mempool reader, before this branch merges.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…r's lock

The P2P router answers a ModifierRequest inside its event loop, and the
main crate holds the Mempool behind a tokio mutex for whole validations,
so the serve path can neither wait for that lock nor try_lock and miss
under load. Mempool::reader() hands out a MempoolReader over a
tx_id -> bytes index behind its own std RwLock, held for one map
operation per access and read and written through poison.

The index changes in OrderedPool::insert and OrderedPool::remove, in step
with by_id, so every eviction, replacement, confirmation and revalidation
removal reaches it; a family re-weight leaves it alone.
UnconfirmedTx.tx_bytes becomes an Arc<[u8]>: process() still takes a
Vec<u8> and converts it once, on insertion, and the index shares that
allocation rather than copying it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
An outbound peer whose handshake advertised feature 64 was dropped right
after the handshake. Only the abandoned standalone ergo-proxy advertised
it, so that other proxies would not treat it as a content source. The
JVM has no such check: an unknown feature is carried and ignored. With
the node no longer a proxy, the skip, FEATURE_PROXY and is_proxy go.

A peer advertising 64 now connects like any other, and the feature stays
in its PeerSpec, as facts/p2p-transport.md requires of parse. A new test
connects to such a peer and checks both. It fails with the skip in
place.

handshake_self_built_is_not_proxy tested only is_proxy and goes with
it. our_handshake_carries_mode_and_session_features already pins our
features to exactly Mode and Session.

The pcap tests of our own handshake lose the proxy prefix:
- proxy_handshake_roundtrips -> our_handshake_roundtrips
- proxy_handshake_feature_body_lengths_are_u16_be ->
  our_handshake_carries_mode_and_session_features. The lengths are VLQ,
  not u16 BE, and the test checks which features we send.
- proxy_handshake_matches_jvm_structure ->
  our_handshake_matches_jvm_structure
- proxy_frame_roundtrips_with_testnet_magic ->
  get_peers_frame_roundtrips_with_testnet_magic

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
With forwarding gone, a peer asking for a transaction we announced has
to get it from us. The local-serve hook now answers type-2 ids from the
mempool's serving reader, which never takes the mempool lock, so the P2P
event loop never waits on a validation; block sections still come from
the store.

The mempool is built before the hook is installed, which is all the
reordering this needs: its construction depends on the node config only.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A mined block was stored and applied but never announced, and the
mining contract's step 10 would have pushed its sections unrequested,
which the JVM penalizes as spam. The node now announces blocks with one
Inv per id, the header and its three sections, to every peer: a mined
block at once, before validation (NewBlockMined), and a peer's block
when applied if its header is less than 2 hours old (RemoteBlockApplied).
A block we mined is not announced again when applied.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A transaction a peer delivers over the JVM's maxTransactionSize (98,304
bytes) is dropped before it is parsed and its sender gets a misbehavior
PENALTY, as parseAndProcessTransaction does; the REST API refuses one
over the same limit with a 400. The mempool crate exports the constant,
so both sides share one definition.

The JVM's other intake penalties (unparseable, id mismatch) wait until
our parser and id computation stop disagreeing with it, or they would
land on honest peers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The P2P intake drops a transaction over the JVM's maxTransactionSize
before parsing it, and the REST API refuses one with a 400. Both name
this constant, so the two limits can't drift apart. The value is the
reference application.conf's 98,304 bytes, pinned by a test against the
literal.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A block this node mined was stored and applied but never announced, so
it reached the network only through other peers' sync, seconds to a
minute later, and a peer's block we applied was never relayed at all.

An announcer task now broadcasts one Inv per id, the header and then
ADProofs, BlockTransactions and Extension, to every peer
(facts/sync.md § Announcing blocks). The solution endpoint's submitter
queues a mined block at once, before validation (JVM NewBlockMined);
the validator's post-apply hook queues an applied block whose header is
under two hours old (RemoteBlockApplied, isNew(2.hours)), and the
announcer skips the apply of a block it announced as mined.

The post-apply hook needed one more handle, and Validator::new already
took eight arguments, the clippy failure that has been parked since
v0.8.x. Its shared handles now travel as one ValidatorSinks, built once
and cloned into every validator, so the constructor takes three and
workspace clippy -D warnings passes again.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The P2P intake's new penalty for a transaction over the size limit is a
misbehavior kind, logged and never actioned by the shipped fail2ban
filter, like message_parse_failed and connection_limit_exceeded. The
journal contract lists the three, and says the pipeline's emission names
the peer by connection id.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The pipeline forwarded every relayed transaction to the mempool task
unchecked, so a peer could push frame-sized blobs through a 256-slot
channel, and the JVM's 96 KB maxTransactionSize went unenforced. A
transaction over ergo_mempool::MAX_TRANSACTION_SIZE is now dropped
unparsed, with an oversized_transaction PENALTY, as the JVM's
parseAndProcessTransaction does; one at the limit still goes through.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The stats contract keyed header, block_transactions, ad_proofs and
extension to modifier bytes 1, 3, 4 and 5, and the adapter followed it,
so the traffic under the real bytes (101, 102, 104, 108, the JVM's
NetworkObjectTypeId) fell through to `continue`: /stats/p2p has never
counted a block Inv, request or response. Found on the live node, where
two applied blocks showed no block traffic at all. Transactions (2) were
always right.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
On the live node, the delivery check re-requested every timed-out
modifier as its own one-id ModifierRequest, all to one peer: a tick of
sixty filled that healthy peer's 64-frame queue before its writer ran,
the queue bound aborted it, and the next tick's burst went to the next
peer, until every peer was gone.

As the JVM's CheckDelivery does, a transaction that times out is now
forgotten rather than re-requested, and header and section re-requests
go out batched, one ModifierRequest per peer and type, up to 400 ids.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…hing

The transport contract still said 256 KB, the wire-format doc 2 MB, and
the v0.7.9 changelog entry credited the JVM's MaxMessageSize to v6.0.4;
it first appears in v6.0.3. The operations manual said a full listener
"forwards everything", and a reference note quoted FEATURE_PROXY as
current.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The comment above `is_block_section_type` documented
`SECTION_REQUEST_BATCH_SIZE`, which is gone, and rustdoc attached it to
the function below. `handle_delivery_check` took a `_current_peer` that
nothing read. Both callers passed one, and `synced()` computed it only to
pass it in.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The delivery check sent one single-id ModifierRequest per timed-out
modifier, nearly all of them to one peer. On 2026-09-29, sixty transaction
retries in one burst filled a peer's 64-frame write queue before its writer
ran. The full queue aborted the peer, and within ninety seconds every peer
had gone the same way.

A timed-out transaction is now forgotten, as in the JVM's CheckDelivery
(v6.0.6 :1260-1265): its pending entry is cleared and nothing is sent.
Headers and sections go out as one ModifierRequest per (target peer, type),
with at most 400 ids each. The target rule is unchanged.

The attempt limit never fired. Each retry went back through
`mark_requested`, which resets the count to zero, so with the request gate
open `max_delivery_checks` abandoned nothing, and an undeliverable modifier
was re-requested every ten seconds indefinitely. `mark_retried` keeps the
count, as the JVM's `setRequested(..., checksDone)` does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…r download window

The sync session asked two contract questions while fixing the delivery
check. A transaction request orphaned by its peer's disconnect is
forgotten like a timed-out one, never re-sent. And a download window's
section requests go to one peer, batched by type: the loop that sent the
same ids to every peer only ever reached the first, because the first
call marks them pending. Spreading them across peers, as the JVM's
requestDownload does, is not done yet.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
When the sync peer disconnected, everything it still owed was re-requested
from another peer as a header, whatever its type. Sections and
transactions were asked for, and tracked, as headers. Orphans now go back
by type, one request per type, and an orphaned transaction request is
forgotten like a timed-out one (facts/sync.md § Delivery timeouts,
638ce7f). The rule is one tracker predicate, consulted by both ways a
request can end.

`request_next_sections` looped over every outbound peer, but the first
call marked the window pending and the rest sent nothing. The code now
names the one peer it has always used (§ Download cycle). Behaviour is
unchanged, and a test pins it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Sync filters announced ids through SyncStore::has_modifier, and for a
transaction the modifier store never holds one, so every announced
transaction was requested, again after each delivery: 1628 requests for
282 announcements in four minutes on the live node. For type 2 the
adapter now asks the mempool's serving reader, as the JVM's processInv
asks its mempool. Its other filters (invalidated, recently applied,
declined, the cost cap) are not applied.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Sync's store adapter answered has_modifier from the modifier store,
which holds no transactions, so every announced transaction was
requested, and again after each delivery. For type 2 it now asks the
mempool's serving reader, as the JVM's processInv asks its mempool
before requesting (facts/sync.md § SyncStore). The mempool is already
built before sync's store, so it only hands over a second reader.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@mwaddip
mwaddip merged commit 3311a64 into main Sep 29, 2026
1 check passed
@mwaddip
mwaddip deleted the fix/p2p-jvm-parity branch September 29, 2026 17:40
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant