Repository navigation
fix(contracts): security audit pass — High + Medium findings - #777
Conversation
Address audit findings in the payment/fee domain: - PaymentChannel `_route`: reset USDC allowance to 0 after `routeSettlement` so an under-pulling or re-pointed router keeps no standing allowance (M-3); `setFeeRouter` zeroes the outgoing router's allowance on re-point. - PaymentChannel `openChannel`/`topUp`: credit the measured balance delta rather than the requested amount, hardening against a future fee-on-transfer USDC proxy upgrade that would otherwise over-credit the shared pool (M-2). - PaymentChannel `topUp`: gate with `whenNotPaused` — refuse new inflows during an incident while exit paths stay open (safe hardening). - FeeRouter `bytesInWindow`/`totalBytesInWindow`: clamp caller-supplied `n` to WINDOW_EPOCHS_CEILING so no on-chain caller can force an unbounded loop. - BuybackBurner: reject `minOut == 0`, bound `amountIn` by the USDC balance, add governance-gated `rescueUSDC`, and document mandatory TWAP/approval invariants for the `_performSwap` subclass (H-3). - Docs: correct stale four-bucket / 60-25-10-5 NatSpec to three-bucket 60/30/10 per ADR 026 (IFeeRouter, BuybackBurner). Tests: allowance-reset under under-pull, topUp-while-paused, FeeRouter window clamp, BuybackBurner minOut/amountIn guards + rescueUSDC. All 469 pass. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Address audit findings in the slashing domain: - H-1 unified pause accumulator: `CapacityBond.pausedTotal` is now the single combined counter for the slash path. `SlashAppeal._unpause` credits its pause time to it via the new `creditPauseTime` (SLASH_APPEAL_ROLE), and SlashAppeal's review/ratification windows read it. Previously a pause on SlashAppeal alone did NOT extend the CapacityBond filing window, so a paused appeal could be raced to finality against an operator who was blocked from filing (ADR 028 §5). - M-3 escrow escape hatch: add governance-gated `forceResolveStuckAppeal`, which resolves an `AppealOpen` record on the upheld path (50/50) when SLASH_APPEAL_ROLE was revoked mid-migration and wedged the escrow with no caller able to settle. - M-2 uphold pool fallback: `upholdAppeal` degrades the challenger-pool leg to a burn if the transfer fails, so a reverting/blocklisting pool cannot block the uphold and let `cleanupExpiredAppeal` flip it to an operator-favorable grant. Deferred (CapacityBond is at 124 B of EIP-170 headroom; a role-gated setter + getter for the SlashJudge ref overflows it by ~290 B): the `setUnbondingPeriod` mirror of the `maxEvidenceAgeUs < unbondingPeriod` invariant. Tracked as a follow-up — see issue. SlashJudge still enforces the other half of the invariant. Tests: SlashAppeal-pause extends the CapacityBond filing window; force-resolve after role revocation distributes 50/50 and reverts when not AppealOpen / not governance. All 473 pass. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Address audit findings in the blacklist/origin domain: - H-2 `_addHash` live-appeal guard: re-adding a hash now reverts (`HashHasActiveAppeal`) while an appeal is live, instead of silently clearing `suspended` and refreshing `addedAt` — which orphaned the in-flight appeal and reset the slash-eligibility boundary. Governance must terminate the appeal (reject/reverse/ratify) before re-adding. - M-1 region cap counts only fast-tracked appeals: the per-region concurrent cap is now charged at `fastTrackBlacklistAppeal` (interim relief) rather than at open, so un-acted-upon Open filings can no longer saturate a region's budget. The decrement moves to the fast-tracked termination paths accordingly. - M-4 `addOperator` is now `nonReentrant` (it makes an external `ejectNode` call), consistent with the appeal mutators. - M-2 origin↔operator blacklist: `OriginAssignment.activateAssignment` and `pruneBlacklistedAssignment` now consult BOTH `isOriginBlacklisted` and `isOperatorBlacklisted`, so an operator blacklisted via either mapping is rejected at activation and prunable (no stale authorization). Tests: re-add reverts while appeal active (and is allowed again after termination); cap counts fast-tracked not Open; activate/prune handle the operator mapping. All 476 pass. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The balance-delta deposit accounting (PaymentChannel) and the cross-contract pause-time read (SlashAppeal) introduce trusted-token / trusted-contract staticcalls under `nonReentrant`, plus a `received == 0` presence check on a derived balance delta. These trip aderyn `reentrancy-state-change` and slither `incorrect-equality`, both false positives here. Annotate them to keep the CI static-analysis gates (aderyn fail-on-high, slither fail-on-medium) green, matching the existing suppression convention in these files.
Contracts coverageLine coverage: 88.27% (1783/2020 lines) |
Gas snapshotGas changes vs baseRun: 26788065308 |
There was a problem hiding this comment.
Pull request overview
This PR addresses High + Medium severity security-audit findings in contracts/ by hardening settlement/allowance flows, unifying pause-time accounting across the slashing path, tightening blacklist/appeal invariants, and updating docs/tests to match ADR-driven behavior.
Changes:
- Slashing: unify pause-time accounting into
CapacityBond.pausedTotal, add governance escape hatch for wedged appeals, and harden bond distribution on uphold. - Payment/fees & buyback: fee-on-transfer-safe deposit accounting, stricter pause semantics, allowance hygiene, FeeRouter window clamping, and BuybackBurner guardrails + USDC rescue.
- Blacklist/origin: prevent re-adding hashes during live appeals, refine regional-cap semantics, and ensure OriginAssignment consults both blacklist mappings.
Reviewed changes
Copilot reviewed 16 out of 16 changed files in this pull request and generated no comments.
Show a summary per file
| File | Description |
|---|---|
| contracts/src/FeeRouter.sol | Clamp window length; (needs fix) current window-loop math can overflow on extreme endEpoch. |
| contracts/test/FeeRouter.t.sol | Adds regression coverage for oversized-window clamping. |
| contracts/src/PaymentChannel.sol | Credits measured USDC deltas for deposits/top-ups; adds pause gating; resets router allowances. |
| contracts/test/PaymentChannel.t.sol | Adds tests for pause-gated topUp and residual-allowance zeroing. |
| contracts/src/BuybackBurner.sol | Adds minOut/balance guards and rescueUSDC for stranded funds recovery. |
| contracts/test/BuybackBurner.t.sol | Adds coverage for new guards and rescueUSDC behavior/authorization. |
| contracts/src/SlashAppeal.sol | Uses combined pause accumulator from CapacityBond; credits pause time into CapacityBond; degrades pool transfer failures to burn. |
| contracts/test/SlashAppeal.t.sol | Adds tests for pause-time extension into filing window and governance force-resolve escape hatch. |
| contracts/src/CapacityBond.sol | Makes pausedTotal the combined accumulator; adds creditPauseTime and forceResolveStuckAppeal. |
| contracts/src/ContentBlacklist.sol | Enforces cap only on fast-track; prevents _addHash during active appeals; makes addOperator nonReentrant. |
| contracts/test/ContentBlacklist.t.sol | Updates tests for fast-track-only cap counting and active-appeal re-add revert. |
| contracts/src/OriginAssignment.sol | Consults both origin and operator blacklist mappings via _isBlacklisted. |
| contracts/test/OriginAssignment.t.sol | Adds tests to ensure activation/prune rejects operators blacklisted via operator mapping. |
| contracts/src/interfaces/IContentBlacklistOriginView.sol | Expands view interface to include isOperatorBlacklisted. |
| contracts/src/interfaces/ICapacityBondSlashEscrow.sol | Adds pausedTotal() + creditPauseTime() to support combined pause accounting. |
| contracts/src/interfaces/IFeeRouter.sol | Updates NatSpec to reflect 3-bucket 60/30/10 split. |
Comments suppressed due to low confidence (2)
contracts/src/FeeRouter.sol:262
endEpoch + 1can overflow (e.g.endEpoch == type(uint64).max) and thefor (e <= endEpoch; e++)pattern will also overflow/revert on the final increment whenendEpochis max. Even if current callers pass sane epochs, these are public view functions and should be robust against extreme inputs.
uint64 startEpoch = endEpoch + 1 > n ? endEpoch + 1 - n : 0;
for (uint64 e = startEpoch; e <= endEpoch; e++) {
sum += _bytesPerEpoch[operator][e];
}
}
contracts/src/FeeRouter.sol:273
- Same overflow issue here:
endEpoch + 1can overflow and thee++loop form will overflow/revert whenendEpoch == type(uint64).max. Using a subtraction-based start epoch and abreak-terminated loop avoids both problems.
uint64 startEpoch = endEpoch + 1 > n ? endEpoch + 1 - n : 0;
for (uint64 e = startEpoch; e <= endEpoch; e++) {
sum += _totalBytesPerEpoch[e];
}
}
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
There was a problem hiding this comment.
Code Review
This pull request introduces several security, robustness, and architectural improvements across multiple contracts. Key changes include updating the BuybackBurner to enforce non-zero slippage limits, bound spend amounts, and allow governance to rescue stranded USDC. The CapacityBond and SlashAppeal contracts now use a unified pause-time accumulator to prevent pause intervals from consuming appeal windows, and a governance escape hatch was added to resolve stuck appeals. In ContentBlacklist, the regional concurrent appeal cap was moved to only count fast-tracked appeals, and re-adding a hash with an active appeal is now blocked. FeeRouter now clamps query windows to prevent unbounded loops, while OriginAssignment checks both origin and operator blacklist mappings. Finally, PaymentChannel was updated to measure actual received deposits to handle fee-on-transfer behavior and reset router allowances to zero after routing. No review comments were provided, so there is no additional feedback.
Important
The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.
* fix: close out remaining LOW review follow-ups (#845 #864) Resolves the five still-open `[ ]` items across the two 2026-06 full-repository review umbrellas; all prior items shipped in #867/#868. node: - dht: cap per-connection served streams (MAX_DHT_REQUESTS_PER_CONN=256) and connection age (MAX_DHT_CONN_AGE=5m) so a peer staying under the per-stream rate limit can no longer pin its dispatch permit forever, mirroring handlers::client's hardcoded-constant precedent (#845). - reputation_indexer: bound the settled_seen dedup set with a companion FIFO (MAX_SETTLED_SEEN=65536), evicting the longest-settled ids first, mirroring the existing pending_settled bound — it no longer grows for the whole process lifetime (#864). cli: - bundle: consult the --exclude globset via filter_entry before canonicalize, pruning recursively-excluded directories. An escaping symlink inside an excluded subtree is no longer resolved and can't trip the escape bail!; a one-level tmp/* still keeps deeper tmp/sub/y via a sentinel-child recursion probe (#845). - config: add [gossip]/[security]/[dht.rate_limit]/[receipts] template blocks plus the missing network/blockchain/cache/payment/observability knobs to DEFAULT_CONFIG, and surface each section's kill-switch / rate-limit knobs in the validate summary; add a template round-trip parse test (#864). contracts (docs-only): - IFeeRouter: NatSpec now marks the 60/30/10 split as the default, governance-mutable within per-bucket bounds via setShares — the drift flagged in #845 was in fact still present (not resolved by #777). Verification: cargo fmt/clippy --all-targets clean; cargo nextest run 1694/1694 pass; forge fmt --check + FOUNDRY_PROFILE=ci forge build clean. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * fix(cli): use working example values for settlement_auto_* template knobs The DEFAULT_CONFIG template showed `settlement_auto_threshold_micro_usdc = 0` and `settlement_auto_by_voucher_nonce_span = 0`, but the resolver rejects `Some(0)` for both ("must be > 0 when set", mod.rs:1065-1080) — these fields disable via omission (None / commented-out), not via 0. Uncommenting the line verbatim would fail `config validate` / node startup. Show realistic positive example values (50 USDC / 1000 nonces) and reword the annotation to "leave unset/commented to disable", matching how the other commented knobs in the template carry working values. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * fix: address multi-agent review findings (#845 #864) reputation_indexer: - Correct the MAX_SETTLED_SEEN comment: a re-delivered settlement for an evicted channel re-credits the provider (resolved from the never-removed on-chain CapacityBond binding), it is NOT a no-op as previously claimed. Document it as a bounded, astronomically-unlikely double-count and explain why eviction stays at debug! (routine once saturated). Cross-reference from the mark_settled_seen doc; harmonize the #867/#868 citation to #864. node/dht: - The cap/age break dropped the peer's further requests silently. Now log (debug) which bound tripped and conn.close() with APP_ERR_RATE_LIMITED, mirroring close_stream_with_rate_limit and the client permit-exhaustion close, so the peer gets a reason and the close is observable. - Extract the accept-budget gate into accept_budget_reached() so the unit test exercises the real predicate instead of a re-implementation, and cover the previously-untested age branch. Correct the false comment that claimed tests/dht_loopback.rs exercises the cap end-to-end (it does not — it only proves multi-stream serving); state honestly what is covered. cli/bundle: - Add a test for an excluded directory that is itself an escaping symlink (tmp/** where tmp -> external dir): confirms the subtree is pruned before canonicalize and does not trip the escape bail!. Verification: cargo fmt/clippy --all-targets clean; decdn-node + decdn-cli 753 tests pass. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> --------- Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
Summary
A six-domain security scan of
decdn/contracts(corroborated by aderyn 0-High and slither Low/Info-only) surfaced 4 High, ~11 Medium, plus Lows/Info and ADR-026 doc-drift. This PR fixes High + Medium + doc-drift, in one commit per domain. Deliberate design-postures and the governance/crypto domain are intentionally untouched; large deferred ADR-031 features remain deferred (issues filed).What's fixed
Payment/fee (
d7ddcf3)PaymentChannel._routeresets the USDC allowance to 0 after settlement;setFeeRouterzeroes the outgoing router's allowance.openChannel/topUpcredit the measured balance delta (fee-on-transfer hardening).topUpgatedwhenNotPaused; FeeRouter window-views clampnto the governable ceiling.minOut == 0, boundsamountInby balance, addsrescueUSDC, documents mandatory_performSwapsubclass invariants.Slashing (
d947dec)CapacityBond.pausedTotalis now the single combined counter (SlashAppeal credits its pause time viacreditPauseTime), so a pause on SlashAppeal alone can no longer run out the filing window and let a slash finalize against an operator who couldn't appeal.forceResolveStuckAppealescape hatch for a role-revocation-wedged escrow.upholdAppealdegrades the pool leg to a burn if the transfer fails.Blacklist/origin (
2626f71)_addHashreverts while an appeal is live (was silently orphaning the appeal + resetting the slash boundary).addOperatorisnonReentrant.OriginAssignmentactivation/prune consult both the origin and operator blacklist mappings.Static-analysis hygiene (
bfdcccf): annotate the new trusted-staticcall / derived-delta-equality false positives.Deferred (tracked separately, not in this PR)
setUnbondingPeriod↔maxEvidenceAgeUsmirror: CapacityBond is at the EIP-170 ceiling (124 B headroom); a role-gated SlashJudge-ref setter overflows it by ~290 B. SlashJudge still enforces the other half of the invariant.removeOperatorun-eject.Verification
forge fmt --check✅FOUNDRY_PROFILE=ci forge build --sizes --deny warnings✅ (CapacityBond 24,452 / 24,576)forge test✅ 476 passedaderyn✅ 0 Highslither✅ exit 0 (fail-on medium)New focused tests cover every fix: pause-coupling filing-window extension, force-resolve after role revocation,
_addHashguard, region-cap-on-fasttrack, BuybackBurner guards + rescue, allowance reset, FeeRouter clamp, operator-mapping blacklist prune.🤖 Generated with Claude Code