Repository navigation
feat(contracts): cap governance vote weight by declared capacity per epoch - #1760
Conversation
…h getter Add a per-operator Checkpoints.Trace208 of declaredMbps written on every declareMbps / deregister, plus declaredMbpsAtEpoch(op, epoch) sampling the tier held at the epoch-end boundary. Feeds the ADR 036 per-epoch vote cap. Co-Authored-By: Claude Opus 4.8 <[email protected]>
_cappedServed sums min(bytesPerEpoch, declaredMbpsAtEpoch × epochLength × 125_000) across the window before the voteCapBps share cap, so delivered-byte weight cannot exceed committed (bonded) capacity. Payments are unaffected. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Vote weight is proven delivered bytes capped per epoch by declaredMbps-implied capacity: declared capacity caps, never grants. Regenerate the gas snapshot for the per-epoch cap loop. Co-Authored-By: Claude Opus 4.8 <[email protected]>
The § Governance "Voting weight" code block still summed uncapped FeeRouter.bytesPerEpoch, contradicting ADR 036's per-epoch declared-capacity cap and the shipped DecdnGovernor._cappedServed. Bring the duplicated formula in line, with matching symbol names. Co-Authored-By: Claude Opus 4.8 <[email protected]>
…per-epoch capacity cap Co-Authored-By: Claude Opus 4.8 <[email protected]>
…y under EIP-170 CapacityBond's runtime bytecode inlined the Checkpoints.Trace208-based declaredMbps history, pushing it 424 bytes over the EIP-170 24,576-byte limit. Move the checkpoint push/lookup logic into DeclaredMbpsHistoryLib, a deployed library with public functions taking storage pointers (the same pattern SlashEscrowLib already uses), so its bytecode is DELEGATECALLed instead of compiled into CapacityBond. External behavior and the declaredMbpsAtEpoch signature are unchanged. Co-Authored-By: Claude Opus 4.8 <[email protected]>
…yn high Use SafeCast.toUint208/toUint48 in DeclaredMbpsHistoryLib for the mbps value and epoch-end boundary. The values are band/time-bounded so the checks never trip at runtime; the explicit casts clear the static-analysis unsafe-cast high. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Gas snapshotNo gas changes vs base. |
Contracts coverageLine coverage: 89.65% (2563/2859 lines) |
There was a problem hiding this comment.
Pull request overview
This PR strengthens deCDN governance weighting (ADR 036) by capping each epoch’s delivery-based vote weight at the operator’s declared (bonded) serving capacity for that epoch, preventing under-declared operators from amplifying governance power via self-dealt traffic while preserving delivered-bytes as the primary signal.
Changes:
- Add checkpointed
declaredMbpshistory inCapacityBondand exposedeclaredMbpsAtEpoch(operator, epoch)for epoch-end sampling. - Update
DecdnGovernorvote-weight computation to summin(bytesPerEpoch, declared-capacity-bytes)per epoch, then apply the existing share cap, slashing zero-out, and age ramp. - Extend tests and ADRs to cover/describe the new declared-capacity cap behavior.
Reviewed changes
Copilot reviewed 12 out of 12 changed files in this pull request and generated 1 comment.
Show a summary per file
| File | Description |
|---|---|
| contracts/src/DecdnGovernor.sol | Implements per-epoch served-bytes capping using declaredMbpsAtEpoch and a Mbps→bytes/s conversion constant. |
| contracts/src/CapacityBond.sol | Records declared capacity changes into a per-operator checkpoint history and exposes declaredMbpsAtEpoch. |
| contracts/src/DeclaredMbpsHistoryLib.sol | New linked library for checkpointing and epoch-end sampling to keep CapacityBond under EIP-170. |
| contracts/src/interfaces/ICapacityBond.sol | Adds the declaredMbpsAtEpoch interface used by the Governor. |
| contracts/test/mocks/MockCapacityBond.sol | Extends the mock to support declaredMbpsAtEpoch in Governor unit tests. |
| contracts/test/DecdnGovernor.t.sol | Adds focused tests for declared-capacity capping and burst fairness. |
| contracts/test/DecdnGovernorDelegation.t.sol | Seeds declared capacity in fixtures so unrelated tests don’t trip the new cap. |
| contracts/test/GovernanceLifecycle.t.sol | Ensures operators declare (floor) capacity in lifecycle seeding to avoid cap-binding fixtures. |
| contracts/test/CapacityBond.t.sol | Adds a test validating non-retroactive per-epoch declared-capacity history sampling. |
| contracts/.gas-snapshot | Updates snapshots reflecting the added checkpointing and new getVotes logic. |
| adr/036-served-bytes-voting-weight.md | Updates the formula and narrative to include the declared-capacity epoch cap. |
| adr/026-tokenomics.md | Updates governance-weight descriptions to match the capped served-bytes design. |
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
Initialize `served` explicitly (clears slither uninitialized-local medium) and clamp `n` to MAX_WINDOW_EPOCHS in `_slashedInWindow` so the slash window can never span more epochs than the byte window it tracks, matching `_cappedServed`. Co-Authored-By: Claude Opus 4.8 <[email protected]>
…fixes Co-Authored-By: Claude Opus 4.8 <[email protected]>
…weight Vote weight is now capped per epoch at declaredMbpsAtEpoch, and the shared ChainFixture::onboard_operator bonds but never declares, so g_gov_02 and slash_appeal's proposers carried zero weight and propose/castVote failed. Declare the floor tier via the daemon CLI before the age warp and serve. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Coverage reportTotal: 81.10% (was 81.09%, ▲ +0.01%) — 59636/73537 lines No coverage data for changed Rust files. History
|
…ey (#1030) Review call on #1768: the gate was a node checking its OWN registration and choosing to refuse. There is no code we can force a node to run, so an operator who wants to sell unregistered deletes the check and rebuilds - it constrained only the honest, which is not enforcement. Reverts the serve path, the not_registered reject reason and counter, and the ClientHandlerDeps staker-set wiring; crates/node/src/handlers/, metrics.rs and tests/ are now byte-identical to main. The real constraints are external and already exist. An unregistered operator never called declareMbps, so DecdnGovernor._getVotes caps each epoch at declaredMbpsAtEpoch x epochSeconds x BYTES_PER_MBIT_SECOND = 0 and it accrues no vote weight (contracts/src/DecdnGovernor.sol:265, landed in #1760). And a client should not select an upstream it cannot slash. Neither can be removed by patching the daemon. ADR 019 Phase 4 now says this outright, including why a serve-side gate should not be re-added, so the acceptance criterion stops reading as a daemon obligation. Kept: registry_active on admin health, now documented as purely diagnostic. It is the answer to "my node is up and earning nothing" - more necessary without a gate, not less, since nothing on the wire says so and the traffic simply never arrives. It is also what lets the journey assert the daemon observed its own registration live. Kept: the EjectedByBlacklist topic0 fix, which is a genuine registry-route bug affecting DHT admission - a peer-side decision, not self-policing. The journey keeps its arc (bare -> real decdn setup -> paid delivery on one process, no restart) and both negatives. Only the refusal assertion is gone; the no-restart poll on registry_active stays, since it proves the registry projection is live rather than sampled at boot. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…1030) (#1768) * docs(plan): G-NODE-01 onboarding journey + ADR-019 registry serve gate (#1030) Implementation plan for issue #1030. Two halves: enforce the ADR 019 Phase 4 acceptance criterion #1 on the cdn/client/v1 serve path (the daemon never implemented it, so an unregistered and therefore unslashable node earns today), then write the bare-to-serving e2e journey that uses that gate as its hinge. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * feat(node): refuse paid delivery when not in the on-chain active set (#1030) ADR 019 Phase 4 lists `CapacityBond.isActiveNode(nodeId)` as acceptance criterion 1 for serving `cdn/client/v1`, but the daemon never enforced it. `serve_stream` read no registry state at all; the only registration awareness was `binding_check`, an advisory bring-up WARN. So a node that was never registered - or whose key was swapped out from under its binding - kept selling bytes while being unslashable, which is the one state the enforcement model cannot price. The predicate already existed. The DHT registry projection keeps a live `StakerSet` off `getRegisteredNodes` plus the CapacityBond membership events, so the gate is `staker_set.is_active(self_node_id)` against the same Arc DHT admission holds - no new poller route (a second CapacityBond route would collide on (address, topic0) and fail the daemon at boot), no new RPC, and no unconfirmed state to fail closed on. The gate sits below the two denylist checks so a takedown still answers `HashBlacklisted` rather than degrading to `NotFound`, and above everything that spends money or sends bytes. It signs `NotFound`, deliberately indistinguishable from a miss: a distinct code would be a cheap oracle for which operators cannot currently sell. The cause is operator-local, in `decdn_serve_stream_rejected_not_registered_total` and `registry_active` on `decdn node health`. Also closes a real gap in the registry route itself: `EjectedByBlacklist` was missing from its topic0 OR-set, so a blacklist ejection only landed at the 15-minute re-enumeration and every consumer of the staker set - DHT admission included - was wrong until then. Probes stay ungated (unpaid, and the canonical rate-discovery channel), as does the daemon's own buyer leg: the rule is may-not-sell, not may-not-participate. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * test(e2e): G-NODE-01 onboarding journey, bare to accepting delivery (#1030) Starts where an operator starts - a provisioned data dir, a running daemon, nothing on chain - and drives the production `decdn setup` CLI through approve/bond/declareMbps/registerNode until the same process is selling bytes. Every other journey begins already onboarded (`NodeFixture::launch` onboards before the daemon spawns), so nothing observed the bare state and no test drove a SUCCESSFUL setup end to end; `cli_setup_partial` covers only the failure path. The load-bearing assertion is the hinge, not the CLI: one process, no restart, refusing at step 1 and delivering at step 3. That is what proves the ADR 019 serve gate reads a live projection rather than a boot-time sample. The refusal is pinned by the `not_registered` counter, not by the error - every reject reason collapses to a wire `NotFound`, so asserting on the error alone would pass just as happily for a cache miss. New fixtures: `NodeFixture::launch_bare` (the only path to an un-onboarded daemon; funds gas but not TOKEN so setup's funding pre-flight has a real step to clear), `ChainFixture::register_node_raw` (the signing half of `onboard_operator`, which is now built on it, so the two cannot disagree), and `fund_and_bond`. Both negatives were previously untested anywhere in the repo. `register_below_min_bond_reverts` also corrects the issue's wording: `bond()` has no floor - it guards only `ZeroAmount` - so an under-bond succeeds and the TOKEN really moves; the floor is enforced at `registerNode`, which is why an operator can strand capital and still not be registered. The re-registration negative bonds its impostor to minBond FIRST and signs both proofs genuinely, because `_checkRegistrationPreconditions` runs before `_checkBindingOneToOne` - an unfunded impostor would revert on the bond floor and pass for the wrong reason. The admin_rpc drain stub needed `registry_active`: it hand-builds the health JSON precisely so DTO drift fails a test rather than silently deserializing. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * docs(plan): record the three deviations from the #1030 plan as executed Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * docs: drop the #1030 implementation plan from the repo The plan was scaffolding for the change, not a design artifact the repo needs to carry: ADR 019 already owns the serve-gate decision, and the PR description carries the rationale. Leaving it in docs/ would have introduced a plans/ convention the repo does not otherwise have. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * refactor(node): drop the serve-path registration gate; keep the journey (#1030) Review call on #1768: the gate was a node checking its OWN registration and choosing to refuse. There is no code we can force a node to run, so an operator who wants to sell unregistered deletes the check and rebuilds - it constrained only the honest, which is not enforcement. Reverts the serve path, the not_registered reject reason and counter, and the ClientHandlerDeps staker-set wiring; crates/node/src/handlers/, metrics.rs and tests/ are now byte-identical to main. The real constraints are external and already exist. An unregistered operator never called declareMbps, so DecdnGovernor._getVotes caps each epoch at declaredMbpsAtEpoch x epochSeconds x BYTES_PER_MBIT_SECOND = 0 and it accrues no vote weight (contracts/src/DecdnGovernor.sol:265, landed in #1760). And a client should not select an upstream it cannot slash. Neither can be removed by patching the daemon. ADR 019 Phase 4 now says this outright, including why a serve-side gate should not be re-added, so the acceptance criterion stops reading as a daemon obligation. Kept: registry_active on admin health, now documented as purely diagnostic. It is the answer to "my node is up and earning nothing" - more necessary without a gate, not less, since nothing on the wire says so and the traffic simply never arrives. It is also what lets the journey assert the daemon observed its own registration live. Kept: the EjectedByBlacklist topic0 fix, which is a genuine registry-route bug affecting DHT admission - a peer-side decision, not self-policing. The journey keeps its arc (bare -> real decdn setup -> paid delivery on one process, no restart) and both negatives. Only the refusal assertion is gone; the no-restart poll on registry_active stays, since it proves the registry projection is live rather than sampled at boot. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> --------- Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
What
Cap governance vote weight per epoch by an operator's declared serving capacity. Vote weight becomes:
(zeroed if slashed in-window).
125_000 = 1e6/8converts Mbps→bytes/s.Why
ADR 036 keyed vote weight on proven delivered bytes to stop a deeply-bonded, lightly-serving operator carrying unearned weight. The mirror case was open: a lightly-bonded, heavily-serving operator could declare the minimum tier (cheap bond via the super-linear curve) and self-deal byte volume — self-dealing only costs the FeeRouter fee cut — to buy governance power far beyond committed stake. Capping delivered-byte weight at declared (hence bonded) capacity closes that hole while keeping delivery the primary signal. This reconciles both directions:
min(delivery, capacity)satisfies ADR 036's original concern and the mirror.How
CapacityBond— checkpointsdeclaredMbpshistory (per-operator, written ondeclareMbpsandderegisterNode); new getterdeclaredMbpsAtEpoch(op, epoch)samples the tier at the epoch-end boundary viaupperLookupRecent, so the cap for an elapsed epoch cannot be raised retroactively. Checkpoint logic lives in a linked library (DeclaredMbpsHistoryLib) to keepCapacityBondunder EIP-170.DecdnGovernor._cappedServed— per-epoch capped sum, nested inside the existingvoteCapBpsshare cap, slash-zeroing, and age ramp.FeeRouter— unchanged (bytesPerEpochalready public).Payments are untouched — an operator is still paid for every byte delivered even if under-declared. Under-declaration costs governance weight, not revenue.
Behavioral notes
declareMbpsdoes not change the cap for already-elapsed epochs (checkpointed history).declaredMbps ≥ minCapacityMbps, so only inactive/deregistered operators cap at 0).Gas
Hot path unaffected:
routeSettlement,redeem/redeemManyshow zero real delta in.gas-snapshot.declareMbps+45k (one checkpoint write, infrequent).+130k at default 13 epochs) — vote-cast path only. A batched capacity getter could halve thegetVotesscales O(windowEpochs) (getVotescost later if wanted.Verification
forge fmt --check,FOUNDRY_PROFILE=ci forge build --sizes --deny warnings,forge test— 827 passed, 0 failed.CapacityBondruntime size 24,134 / 24,576 (margin +442).SafeCast; remaining Highs are pre-existing in untouched code). Note:slitherandanvil-e2ewere not run locally (slither not installed here) — deferring to remote CI.🤖 Generated with Claude Code