Repository navigation
perf(payments): cut per-lane redemption gas 79% to bound dust-lane settlement - #1701
Merged
Merged
Conversation
…ttlement A lane is free to open while a pool is not, so an adversary funds one pool and spreads dust across many lanes. A genuine publisher with millions of client lanes has the same shape, so no per-lane minimum can separate them — only a cheaper lane helps both. The per-lane cost of a batch is what sets the floor on the balance a node can afford to collect, so this drives it down. Marginal gas per extra lane in a batch: 106,079 -> 22,517. - Settle once per call, not once per voucher. `_applyVoucher` only advances state and returns what it drew; `redeemMany` sums and makes a single `_route(msg.sender, totalBytes, totalPaid)`. Safe because every voucher is redeemed for the caller. - Pack storage to `uint64`. `Authorization` 3 slots -> 1, `Lane` 2 -> 1, `Pool` 4 -> 2 (dropping the write-only `openedAt` and the `token` that duplicated the immutable `usdc`). uint64 is ~$18.4T at USDC's six decimals and 18.4 EB for a byte count; every value is bounded by construction. The EIP-712 typehashes still declare `uint256`, which is the same 32-byte word, so no client signing changes. - Nest `redeemMany` by pool. `redeemMany(PoolBatch[])` names each pool once for its group, so the status gate is read once and `totalRedeemed` advances in one write. The group's `remaining` is read once and drawn down in a local, so a batch cannot overdraw the pool. - Drop `provider` from the voucher. It is always `msg.sender`, which the contract substitutes when rebuilding the EIP-712 hash, so a voucher signed for another node now fails as `InvalidVoucherSignature`. - Compact voucher signatures (EIP-2098). `bytes32 r, vs` makes `LaneVoucher` a static struct: no element offset, no length word, no padding, so a lane costs 160 calldata bytes instead of 288, and recovery skips a cold EXTCODESIZE. A voucher signer must now be an EOA; a pool owner may still be a Safe, since the capability path keeps `SignatureChecker`. - Emit one `PoolRedeemed` per pool group carrying `LaneSettled[]`, instead of one per lane. Drops the never-read `paid` field and pays the log base and its topics once per group. - Delete `redeem`. `redeemMany` is the sole entry point; a single lane is a one-pool batch of one. `NothingToRedeem` and `NotProvider` go with it. Rust: `to_pool_u64` narrows at the contract boundary only, leaving the ERC-20 and TOKEN paths on `U256`; the sweep buckets lanes by pool; the settlement watcher walks the event's `lanes` array. The self-owned capability cap moves from `U256::MAX` to `u64::MAX`, which the narrower field can carry and the EIP-712 hash can reconstruct. Evaluated and rejected: `ReentrancyGuardTransient` (4.7k gross, but slither 0.11.6 cannot generate IR for a contract inheriting it, degrading analysis of the whole contract); inlining the redemption helpers (measurably slower under the repo's legacy codegen). Co-Authored-By: Claude Opus 5 <[email protected]>
Contracts coverageLine coverage: 89.66% (2540/2833 lines) |
Gas snapshotNo gas changes vs base. |
There was a problem hiding this comment.
Pull request overview
This PR optimizes the PaymentPool redemption path to drastically reduce per-lane gas and calldata costs, specifically to make dust-lane settlement economically viable for nodes while preserving the same cumulative-voucher payment model across the Rust node/client stack and Solidity contracts.
Changes:
- Reworks PaymentPool redemption to a single entry point
redeemMany(PoolBatch[])that groups lanes by pool, settles once per call via FeeRouter, and emits onePoolRedeemedper pool group carrying per-lane outcomes. - Packs on-chain counters/struct fields to
uint64and updates Rust bindings + call sites (node settlement, client pool open/top-up, e2e tests) to narrow values at the contract boundary. - Switches voucher signatures to EIP-2098
(r, vs)in calldata (EOA-only voucher signers) and updates node-side signature handling plus contract-side verification.
Reviewed changes
Copilot reviewed 15 out of 15 changed files in this pull request and generated 1 comment.
Show a summary per file
| File | Description |
|---|---|
| crates/node/src/payment_settlement.rs | Updates settlement watcher + redemption planner/sweeper for new ABI (pool-grouped batches, EIP-2098 signatures, uint64 fields). |
| crates/incentive/src/payment_pool.rs | Updates Alloy sol! bindings for packed structs/new redeemMany ABI and adds to_pool_u64 helper. |
| crates/e2e/tests/g_node_07_rotate_key.rs | Adapts assertions to uint64 lane fields. |
| crates/e2e/tests/g_gov_02_rate_bounds.rs | Adapts watermark helpers/assertions to uint64 and updates implied-rate computation. |
| crates/e2e/tests/cli_fetch_delegated.rs | Updates delegated capability + settlement log checks for new packed structs and PoolRedeemed lanes array. |
| crates/e2e/tests/anvil_pool_redeem.rs | Updates pool redemption E2E test expectations for uint64 caps and new behavior (skip-empty vs revert). |
| crates/e2e/src/bindings.rs | Updates comment/docs for removed redeem and retained redeemMany. |
| crates/client-pull/src/buyer_pool.rs | Narrows open/top-up amounts to uint64 and updates “self capability cap” to a uint64-representable EIP-712 word. |
| contracts/src/PaymentPool.sol | Implements the optimized redemption design (pool batches, single settlement, packed structs, EIP-2098 voucher sigs, new events, removes redeem). |
| contracts/test/PaymentPool.t.sol | Updates and expands Foundry coverage for new ABI/behavior (pool grouping, settle-once, EOA-only voucher signers, skip-empty semantics, new events). |
| contracts/test/InterfaceFreeze.t.sol | Updates ABI freeze assertions for openPool(uint64), topUp(uint64), and new redeemMany signature. |
| contracts/test/E2EProtocol.t.sol | Updates protocol E2E test to call new redeemMany and validate new PoolRedeemed format. |
| contracts/.gas-snapshot | Refreshes gas snapshot reflecting the new redemption implementation. |
| adr/016-contract-interactions.md | Updates contract interaction documentation to match settle-once batch redemption. |
| adr/003-payments.md | Updates the payment model ADR to the new redemption entry point, packed widths, EIP-2098 vouchers, and event semantics. |
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
…ttlement `getPool` decoded into a binding still carrying the pre-packing seven-field `Pool` (`openedAt`, `token`, `uint256` amounts). The `sol!` block is a hand-written restatement of the ABI, not something derived from the Solidity source, so the drift compiled cleanly and failed only against a real chain: the node read a garbage owner, could not verify a presented capability, never registered the lane, and refused every request as an unknown lane. Pin the layouts so this cannot recur silently. `read_surface_struct_layouts_ match_contract` and `redeem_call_struct_layouts_match_contract` assert the field list of every struct the read and calldata surfaces decode into — the existing event pins covered only topic/data placement, which is why this got through. Also fixes the consumers the corrected binding surfaced: `Pool.token` is gone (the token is the contract's immutable `usdc()`, which the CLI now reads on the top-up and delegate paths, matching the open path), `pool_view` widens the packed deposits, and the `anvil-e2e`-gated tests compare against `uint64`. The node's own gated tests (`crates/node/tests/anvil_settlement_e2e.rs`) sit outside `cargo test -p decdn-e2e --features anvil-e2e`; only `cargo clippy --workspace --all-targets --all-features` reaches them, which is what CI runs and what caught this. That test also issued a self-capability at `U256::MAX`, which the narrowed field can no longer carry — it now uses the exported `SELF_CAPABILITY_CAP`, so the production path and the test share one definition. Co-Authored-By: Claude Opus 5 <[email protected]>
Compaction checked only that the top bit of `s` was free for the recovery bit. That is necessary but not sufficient: `secp256k1n / 2` sits below `2^255`, so roughly `2^128` values of `s` carry a clear top bit and are still high-`s`. Such a signature compacted cleanly and then reverted in the contract's `ECDSA.tryRecover` — reverting the whole `redeemMany`, so one hostile lane would sink every honest lane batched with it. That is the same griefing shape this batch path exists to bound, arriving through the signature instead of the balance. Use the crate's existing `sig_canon::is_high_s` rather than a hand-rolled bound, so the redeem path and the voucher-accept path share one definition of canonical; the helper is now `pub` for that. Parsing through `Signature::from_raw` also replaces the manual `r‖s‖v` splitting. `compaction_rejects_high_s_whose_top_bit_is_clear` pins the band directly, at `n / 2 + 1` — the smallest high-`s` value, whose top bit is 0. Reported by Copilot review on #1701. Co-Authored-By: Claude Opus 5 <[email protected]>
Coverage reportTotal: 80.63% (was 80.62%, ▲ +0.01%) — 58782/72904 lines
History
|
`to_pool_u64` is the single point every USDC amount crosses on its way into the contract, and it had no test — the coverage report on #1701 surfaced it as the one genuinely uncovered line in the new code. Pin both sides of the ceiling: `u64::MAX` is a legal deposit (~$18.4 trillion at six decimals) and must pass, one base unit more is not expressible on-chain and must be refused rather than truncated. A silent wrap here would understate a pool's deposit. Co-Authored-By: Claude Opus 5 <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
A lane is free to open while a pool is not. An adversary funds one pool — which costs real gas, so it is sybil-resistant — then spreads dust across many free lanes, sizing each just under whatever balance the node finds worth redeeming. The node either redeems at a loss or serves for free.
A genuine publisher with millions of client lanes has exactly the same shape, so no per-lane minimum can separate the two: any floor taxes the honest publisher just as hard. The only lever that doesn't discriminate is the per-lane cost of a batch, which sets the floor on the smallest balance a node can afford to collect. This PR drives it down.
Tally
Marginal gas per extra lane in a batch: 106,079 → 22,517 (−78.8%). The minimum economically-redeemable lane balance drops ~4.7×.
forceApprovepair,transferFrom, 3 payout legs,Settledlog, reentrancy + role checksAuthorization/Lane/Pooltouint64redeemManyby poolpoolIdin calldata; per-lane status read andtotalRedeemedwriteEXTCODESIZEper lanePoolRedeemedper pool grouppaidwordMeasured end to end, one transaction per measurement so the access list starts cold:
¹ extrapolated from the measured 106,079 baseline marginal; every other cell is measured.
Calldata matters more than the gas column suggests —
gasleft()does not see it, and on Arbitrum the L1 data fee is the larger term. A lane went 352 B → 160 B.What changed
Settle once per call.
_applyVoucheronly advances state and returns what it drew;redeemManysums and makes a single_route(msg.sender, totalBytes, totalPaid). Sound because every voucher in a call is redeemed for the caller. This also strengthens checks-effects-interactions: every lane,spentandtotalRedeemedadvance now lands before the one external call.Pack storage to
uint64.Authorization3 slots → 1,Lane2 → 1,Pool4 → 2 (dropping the write-onlyopenedAtand thetokenfield that duplicated the immutableusdc).uint64is ~$18.4T at USDC's six decimals — ~400× the token's entire supply — and 18.4 EB for a byte count. Every value is bounded by construction:spent ≤ cap,totalRedeemed ≤ deposit, and both watermarks only advance toward a presenteduint64cumulative. The EIP-712 typehashes still declareuint256, which is the same 32-byte word, so no client signing code changes.Nest by pool.
redeemMany(PoolBatch[]), each group{poolId, capabilities[], vouchers[]}. The pool is named once, its status gate read once, andtotalRedeemedadvanced in one write. The group'sremainingis read once and drawn down in a local, so each voucher is bounded by what earlier vouchers in the same group already took.Drop
providerfrom the voucher. It is alwaysmsg.sender, which the contract substitutes when rebuilding the EIP-712 hash — so a voucher signed for another node now surfaces asInvalidVoucherSignaturerather than a separateNotProvider.Compact voucher signatures (EIP-2098).
bytes32 r, vsmakesLaneVouchera static struct: no element offset, no length word, no padding. Recovery isECDSA.tryRecover(digest, r, vs), which also skips the coldEXTCODESIZEan ERC-1271 check does. High-ssignatures are refused — the same malleability bound the contract enforced anyway.One
PoolRedeemedper pool group carryingLaneSettled[] {signer, newPaidCumulative, bytesPaid}. The never-readpaiddelta is gone; the node writes the cumulative, which is what makes the stream idempotent under replay and gaps.Delete
redeem.redeemManyis the sole entry point; a single lane is a one-pool batch of one.NothingToRedeemandNotProvidergo with it.Breaking changes
Pre-launch, so no compatibility shims — every side moves in this PR.
redeemremoved;redeemManyreshaped;openPool/topUptakeuint64;getPool/getAuthorization/getWatermarkreturn packed structs;PoolRedeemedreshaped.SignatureChecker, so a Safe can own a pool and delegate to EOA signers. This matches the direction ADR 024 already took on remote/Safe voucher signing.PoolRedeemed.lanes[].bytesPaid, sinceFeeRouter.Settledis a per-batch aggregate. Nothing normative reads it — ADR 036 sources vote weight fromFeeRouter.bytesPerEpoch.Evaluated and rejected
ReentrancyGuardTransient— 4.7k gross per call, but slither 0.11.6 cannot generate IR for a contract inheriting it: 3 false-positive high-severityuninitialized-statefindings and degraded analysis of the whole contract. Not worth ~2k net on the contract holding all the money.Not closed by this
Gas reduction narrows the dust window; it does not close it. At ~22.5k/lane a 30M-gas block still holds only ~1,300 lanes, so an attacker can open lanes faster than a node sweeps them. Worth its own issue.
Also spotted: the settlement watcher filters on topic0 only and re-checks
providerclient-side after decoding, even thoughprovideris an indexed topic. This is deliberate, not an oversight, and it is not the easy win it looks like: oneeth_getLogsfilter ANDs across topic positions, and the four watched events disagree on what topic2 is —PoolRedeemedputsproviderthere,PoolCloseInitiated/PoolReclaimedputowner, andPoolToppedUphas no topic2 at all. Pinning topic2 would silently drop three of the four. Making it load-bearing needs the watcher split in two, with a secondCheckpointKey, cursor and resync path — a change to durable checkpoint machinery that belongs on its own, not appended here.Verification
814/814 Foundry · 2761/2761 Rust · clippy 0 findings ·
anvil-e2ecompiles ·forge fmt+cargo fmtclean · gas snapshot regenerated · aderyn highs unchanged (6, all pre-existing, none inPaymentPool) · slither 52 vs the 50 baseline, the two extras being Lowtimestampand informationalassembly, both under CI's medium gate.New tests worth noting:
test_redeemMany_secondVoucherOnAPoolSeesTheFirstsDrawpins the per-group solvency threading. Mutation-tested: without the- poolPaidterm the batch tries to move 1.6e9 against a 1e9 pool and only the ERC-20 balance check stops it.test_redeemMany_spansPoolsAndStillSettlesOnce,test_redeemMany_aClosedPoolRevertsEveryGroup,test_redeemMany_settlesOnceForTheWholeBatch,test_redeemMany_allEmptyBatchNeverCallsRouter.test_redeem_rejectsErc1271VoucherSignerpins the EOA-only rule with its reasoning.PoolRedeemedABI pin tests rewritten for the new topic/data split.ADR 003 gains § Voucher signatures are compact, and their signers are EOAs, and its redemption, event and struct sections are updated to present-tense canon. ADR 016's
PaymentPoolrows follow.🤖 Generated with Claude Code