Repository navigation
fix: ignore validations for ledgers outside the connected network - #1395
Conversation
The `validations` stream carries untrusted validations, and a node cannot tell one relayed from another network apart from one signed by a validator it does not know: validations carry no network identifier, and the `network_id` on a stream message is the serving node's own id, identical for every message on a connection. StreamsProvider added a ledger row for every validation it received, so indexes from other networks appeared in the feed. The only guard was a floor taken from the first index seen, which discarded lower foreign indexes but nothing above them, and depended on stream arrival order. Anchor on the ledger index the connected node reports, from the `ledger` stream and from our own `ledger` requests, and ignore validations outside a window around it. Entries added before the anchor was known are pruned once it arrives. A validation for a ledger no longer in state is now skipped rather than dereferenced, which previously threw inside the setLedgers updater and stopped the feed rendering.
| `Processing ledger data: ${JSON.stringify(data)}`, | ||
| 'StreamsProvider.onLedger', | ||
| ) | ||
| currentLedgerRef.current = Math.max( |
There was a problem hiding this comment.
Anchor advances in stream without pruning. Apply pruneOutOfWindowLedgers with isNewAnchor check:
const isNewAnchor = Number(data.ledger_index) > currentLedgerRef.current
currentLedgerRef.current = Math.max(
currentLedgerRef.current,
Number(data.ledger_index),
)
setLedgers((previousLedgers) => {
const retained = isNewAnchor
? pruneOutOfWindowLedgers(previousLedgers, currentLedgerRef.current)
: previousLedgers
if (!retained[data.ledger_index]) {
return { ...retained, [data.ledger_index]: {} }
}
const newLedger = Object.assign(retained[data.ledger_index], {
closeTime: convertRippleDate(data.ledger_time),
txCount: data.transaction_count,
})
return { ...retained, [data.ledger_index]: newLedger }
})
There was a problem hiding this comment.
Added so onLedger now computes isNewAnchor and calls pruneOutOfWindowLedgers before merging in the new entry here
There was a problem hiding this comment.
No issues found.
🧭 Merge confidence: 90% — no-regression estimate
-
⚠️ Large diff (-2) — 337 changed lines. -
⚠️ Inconclusive: ReplacingaddLedgerinonLedgerwith an inlinesetLedgersthat prunes and inserts changes the ledger count or ordering that LedgersPage tests andupdateMetricsrely on. (-5)- Evidence: The inline insert in
onLedgerbuilds the same entry shape asaddLedgerand truncates withtruncateLedgers(retained, MAX_LEDGERS_SHOWN - 1). The test atLedgersPage.test.js:154expects 2.ledgerrows after onlyprevLedgerMessage. I could not trace where the second row comes from, since that needs the ledger-response path and a test run. That path now also prunes and advances the anchor.
- Evidence: The inline insert in
Checked and refuted (2)
-
✅ Checked: Removing
firstLedgerRefand the old floor check breaks other readers of that ref or other code paths that calladdLedger.- Evidence: grep_repo for
firstLedgerRefacross src returns no matches, so nothing else uses it.addLedgerin StreamsProvider.tsx (lines 138-153) is now a plain add-if-missing helper.onValidationstill calls it.onLedgernow does its ownsetLedgersinsert.
- Evidence: grep_repo for
-
✅ Checked: The new window check in
onValidationdrops validations that existing tests expect to render, such as the Network validators test, whose mock validation has index 44921927 and is unrelated to any ledger message.- Evidence:
isLedgerIndexInWindowreturns true whencurrentLedgerRefis 0, which is the case before any ledger message arrives.src/containers/Network/test/validators.test.jssends onlymockValidation.json(ledger_index 44921927). I found no ledger message in that test's mocks, onlymockNodes.jsondata, so the anchor stays 0 and the validation is accepted. InLedgersPage.test.js(lines 150-161) the validation index 68992561 is within 50 below / 10 above the prevLedger anchor 68992560, so it is accepted too. I did not trace the Network test's socket mock to confirm it never returns a ledger response that sets the anchor.
- Evidence:
From reading the code only: no tests, lint or typecheck ran here, and CI is not counted.
pdp2121
left a comment
There was a problem hiding this comment.
Anchoring on the connected node's ledger index makes sense and the ledger list looks right in the common case. A few things inline: one gap where out-of-range validations still reach validators, some edge cases the new window introduces, and a hole in the test coverage.
Two things I noticed that are not from this PR and are fine as follow-ups:
currentLedgerRefonly ever moves up, so if the node's ledger index goes down while the page is open (devnet reset, restarted custom network) the feed stays on the old rows until reload.firstLedgerRefhad the same limitation.onLedgeris registered once from the first render ([]deps), so it reads first-render values:updateMetrics()computes over an emptyledgers, and!quorumis always true so nUNL and quorum are refetched on every ledger close rather than only on flag ledgers.
| if (!ledger) { | ||
| // The ledger was truncated out of state, or pruned as out of range, | ||
| // between this validation being queued and the queue being processed. | ||
| return | ||
| } |
There was a problem hiding this comment.
This skips the ledger update, but the setValidators call just below still runs over the whole queue. A validation accepted before the anchor was known (isLedgerIndexInWindow returns true while current is 0) therefore still ends up in validators, and nothing removes it afterwards. On the Validators page those keys stay in the table, hexagons and count until reload.
Suggest filtering the queue once when draining it, with isLedgerIndexInWindow(Number(validation.ledger_index), currentLedgerRef.current), and using the filtered list for both setLedgers and setValidators.
That alone doesn't cover a queue drained before the anchor arrives (the first ledger response can take longer than the 200ms throttle). For that case, either hold the queue until currentLedgerRef.current is set, or drop out-of-window entries from validators when the anchor is first set.
There was a problem hiding this comment.
Filtered the queue against isLedgerIndexInWindow() before it feeds both setLedgers and setValidators, so a validation that was accepted before the anchor was known gets dropped here once the anchor has moved past. Change here
| return ( | ||
| index >= current - MAX_LEDGERS_SHOWN && | ||
| index <= current + MAX_LEDGER_LOOKAHEAD | ||
| ) |
There was a problem hiding this comment.
What happens when the connected node's reported ledger is more than 10 behind the validations it relays (a node that is still catching up, or one whose ledger stream lags)?
Every current validation is dropped here and never replayed, so when the node later reports those ledgers the rows have no hashes and never show as validated. Before this change, anything at or above the first index seen was accepted.
The other ranges in the PR description are millions of ledgers away, so a much larger lookahead would still filter them. Alternatively, buffer ahead-of-window validations for a bounded time and apply them when the anchor advances.
There was a problem hiding this comment.
Ended up updating MAX_LEDGER_LOOKAHEAD to 50. Open to buffer and replay method if that is preferred.
| if (!ledgersRef.current[index]) { | ||
| addLedger(index) | ||
| } |
There was a problem hiding this comment.
With the firstLedgerRef floor gone, a late validation for any index in [current - 50, current) that has no row creates one here. Only onLedger fetches ledger contents, so that row never gets a close time, transaction count or fees.
Example: fresh load anchored at 68992561, then a validation for 68992530 arrives. The feed gets a 68992530 row with no close time that stays until it scrolls out.
Related edge: the lower bound admits current - 50 while only 50 rows are kept, and addLedger inserts on top of truncateLedgers(previous, 49). With 50 populated rows, a validation for current - 50 evicts the populated current - 49 row and replaces it with an empty one.
One change covers both: once the anchor is known, let validations create rows only for indexes above currentLedgerRef.current, and for indexes at or below it only attach to a row that already exists.
There was a problem hiding this comment.
onValidation now only calls addLedger when the anchor is unknown or the index is above it.
| const isNewAnchor = Number(data.ledger_index) > currentLedgerRef.current | ||
| currentLedgerRef.current = Math.max( | ||
| currentLedgerRef.current, | ||
| Number(data.ledger_index), | ||
| ) |
There was a problem hiding this comment.
If data.ledger_index is ever missing or non-numeric, Math.max(..., NaN) makes the ref NaN. From then on !current is true in isLedgerIndexInWindow, so every validation is accepted again, and no later Math.max can bring the ref back. It also adds a row keyed undefined.
populateFromLedgerResponse already guards against this. An early return here when !Number.isFinite(Number(data.ledger_index)), before touching the ref or state, would match it. Unlikely input, but the filter would switch off silently for the rest of the session.
There was a problem hiding this comment.
Added the same guard populateFromLedgerResponse already has. onLedger now has an early return and logs an error when data.ledger_index isn't finite before updating currentLedgerRef here
| ledger.hashes = [...ledger.hashes] | ||
| ledger.hashes[matchingHashIndex] = { | ||
| ...matchingHash, | ||
| } |
There was a problem hiding this comment.
Nit, and not new in this PR (these lines were only re-indented): when the hash is new, matchingHashIndex is still -1 from the findIndex above, so this assigns to hashes[-1] (a stray property on the array) rather than replacing the element that was just pushed. Using the pushed element's index (ledger.hashes.length - 1) in that case would fix it. Fine to leave for a follow-up.
There was a problem hiding this comment.
Fixed in this PR: hashIndex now falls back to ledger.hashes.length - 1 when matchingHashIndex is -1, so the just-pushed hash is the one updated
| expect(renderedIndexes(container)).not.toContain('999999999') | ||
| }) | ||
|
|
||
| it('still shows this network once an out-of-range validation arrives first', async () => { |
There was a problem hiding this comment.
The pruning added to onLedger isn't exercised by these cases. I forced isNewAnchor to false there and all 5 still pass. The prune in populateFromLedgerResponse is covered: disabling that one as well makes this case fail.
A case where the ledger stream is the first thing to set the anchor (initial ledger request rejected or delayed) would cover it.
It would also be worth asserting on validators, since nothing here checks that out-of-range keys stay out of it (see my comment on processValidationQueue).
There was a problem hiding this comment.
Added new ValidatorsProbe component that reads useStreams() and renders validator keys for assertions. Added new tests for "prunes an out-of-range ledger when the ledger stream sets the anchor first" and "does not leak an out-of-range validation into validators once the anchor is known" in this file
- drop queued validations once they fall outside the window, instead of letting them leak into `validators` unfiltered - raise MAX_LEDGER_LOOKAHEAD so a catching-up node's validations aren't dropped outright - only let a validation create a new ledger row above the known anchor - guard onLedger against a non-numeric ledger_index poisoning the anchor - fix a stray hashes[-1] write when a new hash has no matching index - add regression tests for the onLedger-level prune and the validators leak
High Level Overview of Change
The ledger feed treats every message on the
validationsstream as belonging to the connected network, so validations for ledgers of other networks are rendered as ledger rows. This PR anchors the feed on the ledger index the connected node itself reports and ignores validations whose index falls outside a window around it.StreamsProvidernow tracks the connected node's latest ledger index (currentLedgerRef), updated only from node-authoritative sources: theledgerstream and our ownledgerresponses.onValidationignores validations outside[current - MAX_LEDGERS_SHOWN, current + MAX_LEDGER_LOOKAHEAD].processValidationQueueskips a validation whose ledger is no longer in state instead of dereferencing it.Context of Change
On devnet.xrpl.org the feed interleaves three unrelated index ranges - devnet's own ~7.03M alongside ~22.4M and ~108M rows. The foreign rows have no close time, transaction count or UNL count, because nothing but a validation ever backs them, and they sort above this network's own rows in the feed.
The input really is mixed: subscribing to
s.devnet.rippletest.netfor 40s returned 1,535 validations, of which only 91 were in devnet's range; the rest were in the 22.4M and 108M ranges. This is not specific to one node - the same capture againsts1.ripple.comshowed devnet- and testnet-range validations on mainnet's stream too. The node-side cause is being followed up separately with the server team; this PR makes the Explorer resilient to it regardless of what reaches the stream.A client-side check is needed because a node cannot label these for us. Validations carry no network identifier, so a node cannot distinguish one relayed from another network from one signed by a validator it simply doesn't know. The
network_idfield on avalidationReceivedmessage is the serving node's own id -NetworkOPsImp::pubValidationpopulates it fromgetNetworkIDService().getNetworkID()- so it is identical for every message on a connection and cannot be used as a filter. Worth stating explicitly, since it is the obvious thing to reach for.The guard this replaces derived a floor from the first index observed, so it depended on stream arrival order and did not bound the index range in both directions. Anchoring on the connected node instead makes the accepted range explicit and independent of what arrives first.
processValidationQueueis included because it is reachable through the same path: it dereferencedledger.hashesbefore its ownif (ledger)guard, and that entry may already have been removed by truncation between a validation being queued and the queue being processed. The lookup is now checked before use.Type of Change
Codebase Modernization
StreamsProvider.tsxis already a hooks-based TypeScript component; no conversion was needed. The new test file follows the existingLedgersPage.test.jsharness, which is JS.Before / After
Before - devnet.xrpl.org, three index ranges in one feed:
After - same branch run against
s.devnet.rippletest.net, observed for 25s: 14 distinct ledgers, 7035106 -> 7035119, no gaps, nothing outside devnet's range, every row with a close time and UNL 5/5.Test Plan
New:
src/containers/Ledgers/test/ForeignValidations.test.js- 5 cases, one per new branch:All 5 pass. 4 of the 5 fail with the fix reverted and the tests kept - case 4 passes either way, as expected, since it asserts existing behaviour is preserved.
Also run:
jest --cifull suite: 1905 tests. 40 failures inLedgersPage.test.jsandamendmentUtils.test.ts, pre-existing and identical with the change reverted on the same base commit (82d08478). TheLedgersPageone iscontainer.querySelector('.ledger .hash .missed')returning null at line 174, which looks like markup drift rather than anything in this change.eslint --max-warnings 0andprettier --checkon both files: clean.tsc --noEmit: clean.Future Tasks
LedgersPage.test.jsfailures are worth a separate look; untouched here.validation_public_keyis not in the per-network validator listVHSValidatorsProvideralready fetches. Deliberately not the primary filter - it is unavailable until that request resolves and would hide a genuinely new validator on the network.🤖 Generated with Claude Code