Skip to content

feat(contracts): cap governance vote weight by declared capacity per epoch - #1760

Merged
alpergundogdu merged 10 commits into
mainfrom
claude/declaredmbps-contract-capping-630423
Aug 20, 2026
Merged

alpergundogdu merged 10 commits into
mainfrom
claude/declaredmbps-contract-capping-630423

Conversation

@alpergundogdu

Copy link
Copy Markdown
Contributor

What

Cap governance vote weight per epoch by an operator's declared serving capacity. Vote weight becomes:

min( Σ_e min(bytesPerEpoch(op,e), declaredMbpsAtEpoch(op,e) × epochLength × 125_000),
     voteCapBps × totalBytesInWindow / 10_000 ) × age_ramp

(zeroed if slashed in-window). 125_000 = 1e6/8 converts 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 — checkpoints declaredMbps history (per-operator, written on declareMbps and deregisterNode); new getter declaredMbpsAtEpoch(op, epoch) samples the tier at the epoch-end boundary via upperLookupRecent, so the cap for an elapsed epoch cannot be raised retroactively. Checkpoint logic lives in a linked library (DeclaredMbpsHistoryLib) to keep CapacityBond under EIP-170.
  • DecdnGovernor._cappedServed — per-epoch capped sum, nested inside the existing voteCapBps share cap, slash-zeroing, and age ramp.
  • FeeRouter — unchanged (bytesPerEpoch already public).
  • ADR 036 + 026 — amended: declared capacity now caps vote weight, it does not grant it.

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

  • Non-retroactive: a later declareMbps does not change the cap for already-elapsed epochs (checkpointed history).
  • Burst-fair: each epoch is capped independently; an over-line burst in one epoch is clipped without penalizing others. The ~quarter-long window means only chronic under-declaration is capped, not bursts.
  • An operator that declared zero capacity in an epoch contributes zero vote weight for that epoch (intended: active operators always have declaredMbps ≥ minCapacityMbps, so only inactive/deregistered operators cap at 0).

Gas

Hot path unaffected: routeSettlement, redeem/redeemMany show zero real delta in .gas-snapshot. declareMbps +45k (one checkpoint write, infrequent). getVotes scales O(windowEpochs) (+130k at default 13 epochs) — vote-cast path only. A batched capacity getter could halve the getVotes cost later if wanted.

Verification

  • forge fmt --check, FOUNDRY_PROFILE=ci forge build --sizes --deny warnings, forge test — 827 passed, 0 failed.
  • CapacityBond runtime size 24,134 / 24,576 (margin +442).
  • aderyn: no new High introduced (the one new unsafe-cast finding was fixed with SafeCast; remaining Highs are pre-existing in untouched code). Note: slither and anvil-e2e were not run locally (slither not installed here) — deferring to remote CI.

🤖 Generated with Claude Code

alpergundogdu and others added 7 commits August 20, 2026 10:15
…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]>
Copilot AI lite review requested due to automatic review settings August 20, 2026 09:52
@github-actions

github-actions Bot commented Aug 20, 2026 •

Copy link
Copy Markdown

Gas snapshot

No gas changes vs base.

@github-actions

github-actions Bot commented Aug 20, 2026 •

Copy link
Copy Markdown

Contracts coverage

Line coverage: 89.65% (2563/2859 lines)
▼ -0.03pp vs base (89.67% → 89.65%)
Run: 32358384149

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 declaredMbps history in CapacityBond and expose declaredMbpsAtEpoch(operator, epoch) for epoch-end sampling.
  • Update DecdnGovernor vote-weight computation to sum min(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.

Comment thread contracts/src/DecdnGovernor.sol Resolved
alpergundogdu and others added 3 commits August 20, 2026 11:03
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]>
…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]>
@github-actions

Copy link
Copy Markdown

Coverage report

Total: 81.10% (was 81.09%, ▲ +0.01%) — 59636/73537 lines

No coverage data for changed Rust files.

History
Commit Total Δ vs base
49d6acc (HEAD) 81.10% ▲ +0.01%

@alpergundogdu
alpergundogdu merged commit fcde998 into main Aug 20, 2026
26 checks passed
@alpergundogdu
alpergundogdu deleted the claude/declaredmbps-contract-capping-630423 branch August 20, 2026 10:35
yigitdot added a commit that referenced this pull request Aug 20, 2026
…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]>
alpergundogdu pushed a commit that referenced this pull request Aug 20, 2026
…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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants