Repository navigation
Description
Affected layers
- Frontend (
src/): affected.mergeShareStatsEntriesinsrc/hooks/usePersistentDashboardMetrics.tscopies the top level of the previous state and nothing below it. When the aggregate bucket underAGGREGATE_KEYalready exists, the copy and the previous state point at the same bucket object, and the eviction loop adds the evicted counters to it and rewrites its reason map in place.mergeMetricEntriesis not affected: its aggregate is a number, so the shallow copy is enough.usePersistentStateruns the merge inside asetStateupdater, which React may evaluate and then evaluate again from the same previous state; in developmentsrc/main.tsxwraps the app inStrictMode, which does so on every update. - Backend (
server/): not affected. No dashboard state lives there. shared/: not affected. Nothing there touches dashboard state.
Problem
Above 256 tracked channels the merge evicts the extra entries into the aggregate bucket, so that lifetime totals never decrease. Because the bucket is shared with the previous state, one evaluation of the merge changes the state it was given. When React discards that evaluation and runs the updater again from the same previous state, the second run starts from a bucket that already holds the first run's evictions and adds them once more.
With two cohorts of 256 channels stored and a third one arriving, one discarded evaluation followed by a retry leaves 1,024 acknowledged shares in the state instead of 768. The submitted and rejected counters and the rejection reason counts inflate the same way, and the result is written to localStorage, so it survives reloads.
Impact
The operator sees acknowledged, submitted and rejected totals, and an acceptance rate, that are higher than what the channels reported, and the error persists. It takes more than 256 tracked channels with churn, which a downstream peer able to open many channels can cause, plus a replayed updater: every merge in a development build, and in production whenever React discards a render in progress. The replay schedule belongs to the React runtime and was not exercised; the in-place change and the non-idempotent retry are shown without it. Severity low.
Expected outcome
- A share-stats merge leaves the state it was given unchanged. Running it twice from the same previous state gives the same result as running it once.
- After any sequence of over-cap merges, the lifetime totals equal the counters the channels reported, with each evicted channel counted once.
- A regression test covers the discard-and-retry sequence, with entries built from a representative
/server/channelspayload asdocs/monitoring-api-compatibility.mdasks.
Possible approach (non-binding)
Copy the aggregate bucket, including its reason map, before the eviction loop touches it, or build a new bucket from the old one and assign that. The cohort setup in the eviction tests of src/hooks/usePersistentDashboardMetrics.test.ts fits the regression test, and the Loupe PoC is a sound draft of it.
Loupe findings
- project-loupe/audit-sv2-ui#62: the eviction loop updates the previous state's aggregate bucket in place, so a replayed updater banks evictions twice (reported as dashboard: replaying a share-stats update never inflates lifetime totals #333)
Related issues and PRs
- dashboard: merging an over-cap channel snapshot costs linear work per poll #340 changes the same eviction loop.
- Tracker: [Tracker] Dashboard metrics #373.
Loupe export for #333 (finding #62)
Finding
- repo:
stratum-mining/sv2-ui(https://github.com/stratum-mining/sv2-ui.git) - reviewed revision:
1a0845a2d56f3d2e964b4c68d6cbfa5a3d8794ba - title: Clone aggregate state before share-stat eviction
- severity:
low - location:
src/hooks/usePersistentDashboardMetrics.ts:327-343 - cwe: CWE-682
- scanner:
llm-code-review - fingerprint:
2df52e09850f074041798ecb60115de4a6a67cd7e8c3825fdd8ae053b3c7de1d
Description
mergeShareStatsEntries shallow-copies the top-level state, but when an aggregate bucket already exists, next[AGGREGATE_KEY] still aliases the object in prev. The eviction loop then increments its counters and replaces its reason map in place. This merge is called from a React functional state updater, whose result may be discarded and evaluated again from the same base state; after the discarded evaluation has already mutated that base, the retry banks the same evicted cohort a second time. The PoC builds two 256-channel cohorts, discards one evaluation for a third cohort, then retries it. Correct lifetime totals are 768 for each counter, while HEAD produces 1,024 because the first evaluation changed its input. A party able to trigger over-cap channel churn can therefore inflate operator-visible acknowledged/submitted/rejected totals when updater evaluation is replayed, potentially distorting acceptance-rate monitoring. The precise replay schedule depends on the pinned out-of-tree React runtime; the direct mutation and non-idempotent retry are demonstrated without assuming its internals. Prior #13080 covers reappearing channel keys being rebanked during ordinary sequential merges, not mutation of the previous state during one updater evaluation. Targeted searches for aggregate previous-state mutation and React replay found no prior match.
Proof of Concept
diff --git a/src/hooks/usePersistentDashboardMetrics.aggregate-mutation.test.ts b/src/hooks/usePersistentDashboardMetrics.aggregate-mutation.test.ts
new file mode 100644
--- /dev/null
+++ b/src/hooks/usePersistentDashboardMetrics.aggregate-mutation.test.ts
@@ -0,0 +1,33 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+
+import { mergeShareStatsEntries } from './usePersistentDashboardMetrics.js';
+
+test('replaying share-stat eviction does not double-apply aggregate counters', () => {
+ const cohort = (prefix: string) =>
+ Array.from({ length: 256 }, (_, index) => ({
+ key: `${prefix}:${index}`,
+ acknowledged: 1,
+ submitted: 1,
+ rejected: 1,
+ rejectedByReason: {},
+ }));
+ const totals = (state: ReturnType<typeof mergeShareStatsEntries>['next']) =>
+ Object.values(state).reduce(
+ (sum, entry) => ({
+ acknowledged: sum.acknowledged + entry.acknowledged,
+ submitted: sum.submitted + entry.submitted,
+ rejected: sum.rejected + entry.rejected,
+ }),
+ { acknowledged: 0, submitted: 0, rejected: 0 },
+ );
+
+ let state = mergeShareStatsEntries({}, cohort('first')).next;
+ state = mergeShareStatsEntries(state, cohort('second')).next;
+
+ // React may discard an updater evaluation and retry it from the same state.
+ mergeShareStatsEntries(state, cohort('third'));
+ const retried = mergeShareStatsEntries(state, cohort('third')).next;
+
+ assert.deepEqual(totals(retried), { acknowledged: 768, submitted: 768, rejected: 768 });
+});
Suggested Fix
diff --git a/src/hooks/usePersistentDashboardMetrics.ts b/src/hooks/usePersistentDashboardMetrics.ts
--- a/src/hooks/usePersistentDashboardMetrics.ts
+++ b/src/hooks/usePersistentDashboardMetrics.ts
@@ -255,6 +255,13 @@ export function mergeShareStatsEntries(
): { next: PersistedShareStatsState; changed: boolean } {
let changed = false;
const next: PersistedShareStatsState = { ...prev };
+ const aggregate = next[AGGREGATE_KEY];
+ if (aggregate) {
+ next[AGGREGATE_KEY] = {
+ ...aggregate,
+ rejectedByReason: { ...aggregate.rejectedByReason },
+ };
+ }
const boundedEntries = entries
.map((entry) => ({ ...entry, key: normalizeMetricKey(entry.key) }))
This finding was discovered by Project Loupe.
Activity
[-]Clone aggregate state before share-stat eviction[/-][+]dashboard: replaying a share-stats update never inflates lifetime totals[/+]