Skip to content

fix(net): release disconnected peers from sync request cache - #7092

Merged
kuny0707 merged 8 commits into
tronprotocol:release_v4.8.3from
317787106:hotfix/hello_ipv6_peer_retention
Nov 11, 2026
Merged

kuny0707 merged 8 commits into
tronprotocol:release_v4.8.3from
317787106:hotfix/hello_ipv6_peer_retention

Conversation

@317787106

@317787106 317787106 commented Nov 6, 2026 •

Copy link
Copy Markdown
Collaborator

What does this PR do?

  • Remove every sync request-cache entry still owned by a disconnected peer, including entries for received and processed blocks that have left syncBlockRequested.
  • Use conditional removal so disconnect cleanup preserves entries reassigned to another peer.
  • Keep the existing deduplication behavior for already-solid and successfully processed blocks while their cache owner remains connected.

Why are these changes required?

SyncService.requestBlockIds holds strong references from block IDs to PeerConnection objects. Receiving a sync block removes its ID from the peer's outstanding-request map, while the global cache can retain the entry for deduplication. Disconnect cleanup previously examined only outstanding requests and therefore missed received and processed entries.

Scanning the global cache on disconnect releases those stale owner references, allowing disconnected peers and their associated HELLO data to be reclaimed once other references are released.

This PR has been tested by:

Local validation on macOS ARM64 / JDK 17:

  • All 39 targeted tests passed: 9 SyncServiceTest, 10 HandShakeServiceTest, 2 P2P HelloMessageTest, and 18 NetUtilTest tests.
  • Sync regressions cover pending, received and processed entries, preservation of reassigned requests, and an already-solid block's initial request/response, three subsequent fetch passes without another request, and cache removal on disconnect.
  • ./gradlew clean build -x test passed.
  • The CI Checkstyle gate (:framework:checkstyleMain :framework:checkstyleTest :plugins:checkstyleMain), P2P main/test Checkstyle, bash .github/scripts/check_math_usage.sh, and git diff --check passed.
  • The full repository test suite was started but not completed. Manual node/load testing was not performed.

Follow up

  • HELLO/IPv6 validation and its regression coverage are maintained in java-tron #7098. This PR is scoped to sync request-cache cleanup and its tests.
  • Extend coverage for the two-peer post-disconnect case raised in this comment: removing A's cache entry can permit an extra fetch from B if the same already-solid ID remains queued on B. The new request repopulates the cache under B.

Extra details

  • Disconnect cleanup scans the global cache, which is capped at 10,000 entries, to find entries absent from the peer's outstanding-request map.
  • The cache also provides deduplication. Entries can be removed by disconnect cleanup, expiration or eviction; the default 60-minute TTL does not guarantee an exact retention period.

Validate raw IPv6 fields in both HELLO layers and limit IPv6 strings to
45 characters before matching. Release owned request cache entries when
a peer disconnects or a received block is already solid, using conditional
removal to preserve reassigned requests.

Add regressions for invalid and oversized IPv6, valid address variants,
solid-block cleanup and disconnect ownership.

Related: tronprotocol/libp2p#180
blockWaitToProcess.remove(unparsedBlock);
capacityReleased[0] = true;
peerConnection.getSyncBlockInProcess().remove(blockId);
invalid(blockId, peerConnection);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[SHOULD] Already-solid branch now causes an infinite refetch loop for the same block

The new invalid(blockId, peerConnection) in the blockId.getNum() <= solidNum branch removes the requestBlockIds entry, but the blockId stays in peerConnection.getSyncBlockToFetch(). That queue is only drained on the processSyncBlock success path, while ChainInventoryMsgHandler only appends to it, so a block that is already solid can never reach the success path. On the next 1-second fetch tick, startFetchSyncBlock sees requestBlockIds.getIfPresent(blockId) == null, re-puts the entry and re-sends FetchInvDataMessage; the peer re-sends the full block, it lands back in handleSyncBlock, solidNum has not decreased, and the cycle repeats indefinitely (about one full block re-download per second, with no self-healing) until the peer disconnects. Before this PR the retained cache entry was exactly what prevented this refetch. The trigger is realistic during sync catch-up: the requested block becomes already-solid via an adv broadcast or another peer advancing the solid height before this peer's copy is handled.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 566255f.

Removed the new invalid(blockId, peerConnection) call from the already-solid branch. Keeping the cache entry preserves deduplication while the block ID remains in syncBlockToFetch. The expanded onDisconnect() cleanup still releases all cache entries owned by the disconnected peer.

Updated the regression test to cover the initial request and response, three subsequent fetch passes without another request, and cache removal on disconnect. All 9 SyncServiceTest tests pass.

if (blockId.getNum() <= solidNum) {
blockWaitToProcess.remove(unparsedBlock);
capacityReleased[0] = true;
peerConnection.getSyncBlockInProcess().remove(blockId);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[NIT] Processed-success path still retains requestBlockIds entries until TTL

This PR closes the release gaps for the already-solid and disconnect paths, but the processSyncBlock success path still only removes syncBlockInProcess and keeps the cache entry (a strong reference to the owner peer, and through it the retained HELLO data) for the full 60-minute TTL. During active sync the cache can therefore sit near its 10,000 cap and effectively change from an in-flight-requests map into a processed-history map; the retained entries also suppress same-blockId refetches via the getIfPresent == null check, which is benign but makes the cache semantics harder to reason about. This is a residual gap versus the stated "release cached sync peers" goal.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The cache also serves as a global deduplication mechanism. Retaining entries for already-solid and successfully processed blocks preserves existing behavior and prevents duplicate fetches when those IDs remain in peer queues.

This PR addresses references retained after disconnect: onDisconnect() now removes every entry still owned by that peer, including received and processed entries, while preserving reassigned requests. The PR description has been updated to clarify this behavior.

}

@Test
public void testDisconnectReleasesReceivedAndProcessedRequests() {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[NIT] New disconnect test leaves one fake entry in the shared singleton cache

testDisconnectReleasesReceivedAndProcessedRequests reflects the shared Spring singleton requestBlockIds and puts 4 fake entries; onDisconnect(peer) removes the 3 owned by peer, but the reassigned -> other entry is intentionally left behind and then never cleaned up, so it lingers in the singleton Guava cache (60-minute TTL) for the rest of the JVM's test run, holding a strong reference to the other peer bean. Existing tests in this file already call requestBlockIds.invalidateAll() after themselves (e.g. lines 273 and 293); this new case should follow the same pattern so later test-order changes or whole-cache assertions do not trip over it.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This test extends BaseMethodTest, which creates a fresh TronApplicationContext in @Before and closes it in @After for each test method. The SyncService singleton and its cache belong to that individual context, so the retained entry is not shared with subsequent tests.

The reassigned -> other entry is intentionally preserved to verify ownership protection. Additional invalidateAll() cleanup is therefore not required for isolation between test methods.


public static boolean validIpV6(String ip) {
if (StringUtils.isEmpty(ip)) {
if (StringUtils.isEmpty(ip) || ip.length() > MAX_IPV6_ADDRESS_LENGTH) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[NIT] Scoped IPv6 forms longer than 45 chars go from accepted to rejected — not stated in PR description

The 45-character cap applies to the address plus any scope suffix as a whole, so every scoped IPv6 form whose total length exceeds 45 characters now fails validIpV6(), whereas the previous (%\\S+)? regex branch accepted arbitrarily long scope suffixes. This is inbound-only hardening of non-consensus HELLO data, so there is no fork risk, and real-world trigger probability is very low (advertised addresses rarely carry link-local scope suffixes, and parseIpAddress already rejects % entirely) — but it is still a wire-behavior change that the PR description does not explicitly list.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This behavior change is intentional. The 45-character limit includes any scope suffix and applies to all callers of the shared NetUtil.validIpV6() validator.

The PR description now explicitly states that scoped values longer than 45 characters are rejected. Regression coverage includes an oversized scope suffix and the maximum-length unscoped IPv6 form, which remains accepted.

@Slf4j(topic = "net")
public class NetUtil {

private static final int MAX_IPV6_ADDRESS_LENGTH = 45;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[NIT] Documentation & tracking backlog (3 items rolled up)

Grouped as one comment since all three are small documentation/tracking follow-ups; none blocks this PR.

  1. 45-char constant lacks a rationale comment. p2p/src/main/java/org/tron/p2p/utils/NetUtil.java:36 — MAX_IPV6_ADDRESS_LENGTH = 45 has no comment explaining the value, so future maintainers cannot tell whether it is safe to tune. Suggestion: one line noting it is the longest valid scope-less IPv6 text form (including the embedded-IPv4 dotted-quad form) and that scope suffixes count toward the total.

  2. onDisconnect now scans the whole global cache. framework/src/main/java/org/tron/core/net/service/sync/SyncService.java:160 — disconnect cleanup went from O(peer outstanding requests) to O(global cache) (at most 10,000 entries). Bounded and cheap today, but worth recording as a known trade-off if maximumSize is ever raised or disconnect bursts become a real scenario. Suggestion: a one-line comment near the loop noting the deliberate complexity trade-off.

  3. Dual-layer HELLO validation has no in-code tracking anchor. framework/src/main/java/org/tron/core/net/message/handshake/HelloMessage.java:158 and p2p/src/main/java/org/tron/p2p/connection/message/handshake/HelloMessage.java:64 — the raw addressIpv6 check is duplicated at both layers and must later be reconciled with upstream fix(handshake): validate HELLO/STATUS endpoints and normalize payloads libp2p#180; nothing in the code points maintainers at that dependency. Suggestion: add a short "keep in sync with the other HelloMessage.valid()" comment above each check.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added a comment beside MAX_IPV6_ADDRESS_LENGTH in 7b5eb53 explaining the 45-character bound, including the longest unscoped example and how scope suffixes count toward the limit.

The PR description now documents the global-cache scan and its 10,000-entry cap. The existing loop comment explains why cleanup must also cover entries absent from outstanding requests.

Upstream reconciliation with tronprotocol/libp2p#180 is tracked in the Follow up section, including the requirement to retain java-tron's application-layer HELLO validation and sync-cache cleanup.

Retain cached requests for already-solid blocks to suppress refetches while their IDs remain in peer queues. Release the owner references through disconnect cleanup.

Cover request delivery, repeated fetch ticks, and disconnect cleanup in the sync service regression test.
Document the longest unscoped IPv6 text form and clarify that scope suffixes count toward the 45-character limit.
Use an address derived from a fixed private key instead of a 32-byte hash so the regression reaches the solid-block handling path under the ingress address-size validation.
@alan-eth

alan-eth commented Nov 9, 2026

Copy link
Copy Markdown

One small follow-up on the disconnect cleanup: if an already-solid block was fetched from peer A and the same ID is still queued in peer B's syncBlockToFetch, onDisconnect(A) removes the shared deduplication entry. On B's next eligible fetch pass, startFetchSyncBlock() appears able to request that block again, since it checks the request cache and B's in-process set but not the solid height. The new request would repopulate the cache under B, so the concern here is a possible extra fetch after A disconnects.

Could we extend the regression with two peers, keeping the same already-solid ID queued on B, then disconnecting A and running another fetch pass? The current test verifies cache removal on disconnect, but stops before checking this case. It would be helpful to make the intended post-disconnect behavior explicit.

@SeriousCoding789 SeriousCoding789 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good fix. The IPv6 checks and the owner-scoped onDisconnect() cleanup look right to me. Two non-blocking follow-ups:

1. Bound the raw from.address too

tronprotocol/libp2p#175 makes Node drop an invalid IPv4 instead of keeping it. Once java-tron imports that change, a HELLO with a valid addressIpv6 and an oversized from.address would pass validNode(), and the raw field would stay with the connection. tronprotocol/libp2p#180 (now merged) covers the P2P layer by checking raw sizes first. The application-layer HelloMessage.getFrom() builds the same Node, so java-tron needs the bound there too. For example, in both valid() methods, with MAX_IPV4_ADDRESS_LENGTH = 15 added to NetUtil as in #180:

if (from.getAddress().size() > NetUtil.MAX_IPV4_ADDRESS_LENGTH
    || ipv6.size() > NetUtil.MAX_IPV6_ADDRESS_LENGTH
    || (!ipv6.isEmpty() && !NetUtil.validIpV6(ipv6.toStringUtf8()))
    || !NetUtil.validNode(getFrom())) {
  return false;
}

This doesn't change what is accepted today, since anything over 15 bytes already fails validIpV4(). Checking sizes first also avoids decoding a large field just to reject it.

2. Reservations added during disconnect

A race that predates this PR remains. startFetchSyncBlock() snapshots the active peers and assigns blocks afterwards. If a peer disconnects in between, a requestBlockIds.put(blockId, peer) that lands after onDisconnect() has scanned the cache is never released. Other peers then skip that block until the entry expires (blockCacheTimeout, 60 minutes by default). markDisconnected() runs before the disconnect handlers, so rechecking in send.forEach before sending would close this gap:

if (peer.isDisconnect()) {
  blockIds.forEach(blockId -> invalid(blockId, peer));
  return;
}

Keep the overlapping HELLO address validation and regression coverage in PR tronprotocol#7098, leaving this branch focused on sync request-cache cleanup.
@317787106 317787106 changed the title fix(net): validate hello IPv6 and release cached sync peers fix(net): release disconnected peers from sync request cache Nov 10, 2026
@317787106

Copy link
Copy Markdown
Collaborator Author

I have move the IPv6 check from this PR to #7098. @SeriousCoding789

// Received and processed blocks no longer appear in the peer's outstanding requests.
requestBlockIds.asMap().forEach((blockId, owner) -> {
if (peer.equals(owner)) {
invalid(blockId, peer);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[NIT] Disconnect cleanup drops the dedup entry for an already-solid block that remains queued on another peer

When peer A receives a block that is already solid, the already-solid branch keeps the requestBlockIds entry (owner=A) and the blockId stays queued in other peers' syncBlockToFetch. If A disconnects before the block reaches the success path, onDisconnect removes that entry, so on the next 1-second fetch tick another peer B that still queues the same blockId sees getIfPresent(blockId) == null and issues a fresh FetchInvDataMessage for a block that is already solid (startFetchSyncBlock checks the request cache and B's in-process set, but not the solid height). The refetched block is discarded by the already-solid branch again and the entry is rebuilt under B, so the behavior is self-limiting — at most one extra full block download per blockId per disconnect event (bounded by the ~2MB inbound block cap, discarded before deserialization and processBlock, no CPU/state side effects) — and it cannot loop. It is also arguably consistent with the intent of disconnect cleanup (releasing the owner allows a remaining peer to re-fetch). But the current single-peer regression test (testSolidBlockDoesNotRefetchBeforeDisconnect) does not lock this post-disconnect behavior, and the extra-fetch-after-disconnect tradeoff is only implicit.

Not blocking: the two-peer extension is already listed in the PR's Follow up section.


Suggestion: Either (a) in onDisconnect, when removing an entry whose blockId is still queued on another active peer's syncBlockToFetch, reassign the entry to one of those peers instead of dropping it, preserving the suppress-refetch semantics across disconnects; or (b) accept the one-extra-download cost and add a one-line comment at the removal point documenting this tradeoff. Either way, extending the regression with the two-peer case (A disconnects while B still queues the already-solid ID, then one fetch pass) would make the intended post-disconnect behavior explicit, as alan-eth suggested.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in ffdac33080, taking option (b).

Added a comment at the removal point documenting the possible extra fetch. Extended the regression to verify that:

  • A’s disconnect releases its cache entry while the same already-solid ID remains queued on B.
  • B fetches the block once and becomes the new cache owner.
  • After B’s response, three further fetch passes issue no additional request, and processBlock() is never called.
  • B’s subsequent disconnect removes the entry.

Document the extra fetch permitted when releasing a disconnected peer from the request cache. Extend the two-peer regression to verify survivor ownership, subsequent deduplication and disconnect cleanup.
@317787106

Copy link
Copy Markdown
Collaborator Author

One small follow-up on the disconnect cleanup: if an already-solid block was fetched from peer A and the same ID is still queued in peer B's syncBlockToFetch, onDisconnect(A) removes the shared deduplication entry. On B's next eligible fetch pass, startFetchSyncBlock() appears able to request that block again, since it checks the request cache and B's in-process set but not the solid height. The new request would repopulate the cache under B, so the concern here is a possible extra fetch after A disconnects.

Could we extend the regression with two peers, keeping the same already-solid ID queued on B, then disconnecting A and running another fetch pass? The current test verifies cache removal on disconnect, but stops before checking this case. It would be helpful to make the intended post-disconnect behavior explicit.

Confirmed. Added the two-peer regression in ffdac33080.

The intended behavior is to release A’s cache entry on disconnect, accepting a possible extra fetch if B still queues the already-solid ID. The test verifies that B requests it once, becomes the new cache owner, and issues no further request across three fetch passes after receiving the response. It also verifies that processBlock() is never called and B’s subsequent disconnect clears the entry.

Added an inline comment documenting this tradeoff. All 9 SyncServiceTest tests and the CI Checkstyle gate passed.

Recheck peer disconnection before sending sync fetch requests and conditionally remove reservations written after disconnect cleanup. Add a deterministic regression proving a surviving peer can retry the block.
@317787106

Copy link
Copy Markdown
Collaborator Author

@SeriousCoding789 Addressed point 2 in 78b8632a49.

Added a disconnect recheck before sending sync fetch requests. If the peer is already disconnected, the fetch pass removes its newly recorded reservations using owner-conditional invalid(blockId, peer) and skips sending. Entries reassigned to another peer are preserved.

The deterministic regression completes disconnect cleanup before the reservation is written, then verifies that the late entry is removed, no request is sent to the disconnected peer, and a surviving peer can fetch the block on the next pass.

@kuny0707
kuny0707 merged commit 94fd936 into tronprotocol:release_v4.8.3 Nov 11, 2026
15 of 16 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

7 participants