Repository navigation
Conversation
There was a problem hiding this comment.
Pull request overview
Scaffolds the PoC EVM contract suite (staking, USDC payment channels, blacklist/ejection, slashing arbitration, and fee accumulation) plus Foundry tooling, deployment script, tests, and CI to match ADR 016’s interaction model.
Changes:
- Adds six PoC contracts (
TOKEN,StakingRegistry,StablePaymentChannel,ContentBlacklist,SlashJudge,BuybackBurner) with sharedErrors/Rolesand interfaces. - Introduces Foundry project scaffolding (config, remappings, linting), deployment script, and comprehensive unit + end-to-end integration tests.
- Adds a dedicated GitHub Actions workflow for forge + slither on the
contracts/subproject.
Reviewed changes
Copilot reviewed 28 out of 28 changed files in this pull request and generated 4 comments.
Show a summary per file
| File | Description |
|---|---|
| contracts/src/TOKEN.sol | PoC ERC20 + Permit token with owner-gated minting for testnets. |
| contracts/src/StakingRegistry.sol | Operator/client staking, unbonding queue, node registration binding, slashing, ejection. |
| contracts/src/StablePaymentChannel.sol | USDC single-token payment channels with EIP-712 vouchers + dispute/settlement. |
| contracts/src/ContentBlacklist.sol | Global blacklist with governance/emergency flows and operator ejection hook. |
| contracts/src/SlashJudge.sol | Challenge-response slashing arbitration with EIP-712 evidence verification. |
| contracts/src/BuybackBurner.sol | USDC fee accumulator; buyback execution disabled in PoC. |
| contracts/src/libraries/Errors.sol | Shared custom errors across contracts. |
| contracts/src/libraries/Roles.sol | Central role identifiers for AccessControl wiring. |
| contracts/src/interfaces/IStakingRegistry.sol | Cross-contract ABI for staking registry interactions. |
| contracts/src/interfaces/IContentBlacklist.sol | Cross-contract ABI for blacklist lookups/versioning. |
| contracts/script/Deploy.s.sol | Deployment + role wiring script; test entrypoint for integration test. |
| contracts/test/mocks/MockUSDC.sol | 6-decimal mintable ERC20 stand-in for local/testing. |
| contracts/test/integration/EndToEnd.t.sol | End-to-end lifecycle test across the full deployed set. |
| contracts/test/TOKEN.t.sol | Unit + fuzz tests for TOKEN minting/permit behavior. |
| contracts/test/StakingRegistry.t.sol | Unit + fuzz tests for staking/unbonding/slash/eject/register flows. |
| contracts/test/StablePaymentChannel.t.sol | Unit + fuzz tests for channel open/close/dispute/settle/expiry. |
| contracts/test/SlashJudge.t.sol | Unit tests for phantom/rate/blacklist/corruption challenge flows. |
| contracts/test/ContentBlacklist.t.sol | Unit tests for governance/emergency blacklist mutations and ejection. |
| contracts/test/BuybackBurner.t.sol | Unit tests for accumulation, governance params, and PoC-disabled execution. |
| contracts/foundry.toml | Foundry configuration (solc, profiles, fuzz/invariant settings, fmt). |
| contracts/remappings.txt | Remappings for OpenZeppelin + forge-std dependencies. |
| contracts/.solhint.json | Solhint baseline with security plugin and rules. |
| contracts/.gitignore | Ignores Foundry artifacts, env files, editor files. |
| contracts/README.md | Contracts subproject documentation (scope, build/test/deploy, layout). |
| .gitmodules | Adds OpenZeppelin and forge-std as git submodules. |
| .github/workflows/contracts.yml | CI workflow for forge fmt/build/test/coverage and slither. |
💡 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 the core smart contract suite for the deCDN Proof of Concept (PoC) on Arbitrum Sepolia, including a staking registry, USDC payment channels with EIP-712 vouchers, a content blacklist, and a slashing judge for operator arbitration. The review identifies several critical issues: a gas limit vulnerability in the staking registry's unbonding queue compaction, a logic flaw in the slashing judge's blacklist violation checks, and security risks concerning the lack of provider verification in payment channels and missing node ownership proofs during registration.
- SlashJudge: reject blacklist challenges where evidence was generated after the hash was removed from the blacklist (was silent accept). - StakingRegistry: cap unbonding queue at 32 entries per operator to bound the gas cost of slash/withdraw compaction loops. - StablePaymentChannel: distinct `NotYetExpired` error for the pre-expiry `reclaimExpired` revert (prior `ExpiredChannel` collision was misleading). - BuybackBurner: fix import paths (`./libraries/` not `../src/`) and move governable defaults to inline initializers to satisfy slither's uninitialized-state detector. - Deploy.s.sol: derive deployer from `PRIVATE_KEY` env → `DEPLOYER_ADDRESS` env → `tx.origin`. `msg.sender` in a script points at the script contract, not the broadcaster. - Add `slither.config.json` filtering `lib/`, `test/`, `script/` so CI fails only on HIGH findings in `src/`. Local run is now clean (0 findings). Declined: (1) enforce provider registration in `openChannel` — ADR 003 permits unregistered providers (client's choice; they have no stake to slash and earn no reputation). (2) on-chain ed25519 proof of NodeId ownership — cost-prohibitive (~500k gas) and out of scope per ADR 024, which mandates only the EIP-712 EVM-side binding. 112/112 tests pass (added coverage for the blacklist-removed edge case and the unbonding queue cap). Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
|
/gemini review |
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 33 out of 33 changed files in this pull request and generated 6 comments.
💡 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 implements the core smart contract infrastructure for the deCDN Proof of Concept (PoC), including the staking registry, USDC payment channels, content blacklisting, and a slashing arbitration system. The review identified several critical security and logic issues: the challenge limit per node is susceptible to griefing, the lack of evidence persistence in the challenge state allows for bypassable counter-claims, and insufficient validation of node IDs during rate challenges. Furthermore, the blacklist implementation fails to preserve historical data necessary for evidence verification, and the ejection mechanism lacks a cooldown or restriction on re-registering malicious node identities.
Addresses unresolved PR #237 review findings from Copilot and Gemini about the optimistic challenge-response soundness. C7 (Copilot/Gemini): counterRateChallenge and counterCorruptionChallenge previously accepted any self-signed RateChange / DeliveryReceipt from the accused, bypassing the whole flow. Fix: persist an evidence snapshot on the Challenge struct at submit time — - RateManipulation: keccak256(probeRate, streamRate) in `evidenceA`, `streamTimestamp` in `evidenceB`. - Corruption: `channelId` in `evidenceA`, `blobHash` in `evidenceB`. Counters recompute the hash / compare fields and revert `EvidenceMismatch` if they don't match. `effectiveAt` must be <= `streamTimestamp` for rate counters. C8 (Gemini): counterRateChallenge / counterCorruptionChallenge now verify signatures against `c.nodeIdBinding` — the NodeId bound to the accused operator at submit time, not an arbitrary nodeId the accused can pass in. Prevents cross-nodeId signature reuse by an operator controlling multiple nodes. Adds `IStakingRegistry.nodeIdOf` view for the snapshot. C9 (Gemini): `MAX_ACTIVE_CHALLENGES_PER_NODE = 10` global cap was griefable via sybil self-fill (~50 TOKEN/slot net cost). Replaced with per-(node, challenger) uniqueness: each challenger may hold at most one active challenge against a given node at a time. Node cannot challenge itself (`SelfChallenge`). Submitting requires the accused is registered (`NodeNotRegistered`). 128/128 tests pass (+6 for new invariants). Slither clean. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Addresses Gemini's unresolved findings on PR #237. ContentBlacklist now stores per-hash history as an append-only list of `Interval { addedAt, removedAt, emergencyExpiresAt }` entries instead of overwriting a single record on re-add. This preserves the ability to slash for evidence timestamped within a PRIOR blacklisting period even after the hash has been removed and later re-added. Previously such evidence was silently rejected because the old `addedAt` was overwritten. Adds `IContentBlacklist.wasBlacklistedAt(hash, timestamp)` view; `SlashJudge.submitBlacklistChallenge` uses it to walk the interval list. Removes the now-redundant `HashBlacklistedAfterEvidence` error (the combined check collapses into the single walk). StakingRegistry.ejectNode no longer clears `nodeIdToOperator[nid]`. Leaving the mapping in place permanently locks the iroh identity to the ejected address — a banned operator cannot rejoin the network under a different EVM address using the same NodeId. Ejection becomes a network-identity ban, not just a per-address one. Slither's `uninitialized-state` detector emits false positives for mapping reads-before-writes (a standard Solidity pattern; mappings default to empty). Added to the exclusion list so CI passes. 130/130 tests pass. Added coverage: - blacklist evidence from a prior interval (re-add after remove) - nodeId stays locked after ejection (no rebinding by a third party) Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
…333) * docs(adr-016): surface off-chain read API for client/node bootstrap ADR 016's cross-contract call table only covered contract-to-contract interactions, leaving the off-chain client/node read surface implicit. The view functions clients call at cold-start (`getActiveNodes`, `getActiveNodeCount`, `getFirstRegisteredAt`) are specified in ADRs 001 / 012 / 019 but were not cross-referenced here, which is why PR #237's StakingRegistry scaffolded without them. Add a dedicated "Off-Chain Read API" subsection that lists these functions, the bootstrap pagination pattern, the liveness caveat, and a pointer to #332 (settlement-weighted ranking discussion). Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]> * docs(adr-016): propose settlement-weighted bootstrap ranking Expand the off-chain read API section with a concrete proposal for biasing cold-start peer discovery toward proven deliverers. Settlement events are already going on-chain via StablePaymentChannel; surfacing them as a queryable signal (lastSettlementAt) lets clients rank candidates without adding a separate liveness oracle. Includes the contract-surface sketch, forward-compat principles (return raw signals, keep region off-chain for now), and the cold-start operator handling. Discussion remains open at #332. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]> * docs(adr-016): clarify getFirstRegisteredAt param + pagination wording - Add `ethAddress` parameter name to the `getFirstRegisteredAt` signature with a parenthetical note clarifying it's the operator address. - Cite ADR 008 (reputation) and ADR 019 (onboarding) since they formalize the cold-start bonus window the function exists to feed. - Rename "pagination contract" → "pagination pattern" to avoid collision with the Solidity "contract" sense in this section. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]> * docs(adr-016): make settlement-weighted ranking definitive Drop the "Proposed" framing and the discussion-issue pointer — the contract surface is settled and ships as part of this amendment. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]> * docs(adr-016): drop chain-specific gas-cost annotation Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]> * docs(adr-016): drop stakeMultiple from getActiveNodes return stakeMultiple is a derived staking value used for on-chain fee tiering at settlement time, not for off-chain peer selection. Including it in the cold-start tuple violates the "raw signals, not policy" principle and clutters the surface with data callers don't need for ranking. Callers that genuinely need it can fetch getStakeMultiple(operator) per-node on demand. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]> --------- Co-authored-by: Claude Opus 4.6 (1M context) <[email protected]>
Squashed baseline taken from the original PR #237 work (commits 084e53a..4017f1a). Same contract surface and tests; no content changes. Subsequent commits in this PR add the off-chain read API and settlement-weighted ranking signals from PR #333. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
…R 016/333) Adds the StakingRegistry surface ADR 016 §3 (post-#333) specifies for client/node cold-start bootstrap, and wires StablePaymentChannel to stamp settlement activity so off-chain clients can rank candidates by recent delivery. StakingRegistry: - struct NodeInfo { address operator; bytes32 nodeId; uint64 lastSettlementAt; } - getActiveNodeCount() / getActiveNodes(offset, limit) backed by an EnumerableSet.AddressSet maintained in registerNode/ejectNode. - getFirstRegisteredAt(ethAddress) — stable across re-registrations, feeds the reputation cold-start bonus window (ADR 008). - recordSettlement(operator) gated by SETTLEMENT_REPORTER_ROLE plus a per-operator lastSettlementAt mapping returned in NodeInfo. StablePaymentChannel: - settleChannel calls recordSettlement(provider) on any non-zero claim, stamping the registry. Zero-claim settlements are skipped (no liveness signal). Existing tests now grant the role in setUp; the deploy script grants it in production. Deploy.s.sol: - Atomic role-wiring step grants SETTLEMENT_REPORTER_ROLE to the StablePaymentChannel alongside BLACKLIST_ROLE/SLASH_ROLE. ADR 016: - Cross-contract call table records the recordSettlement edge. - Post-deployment initialization step + access control matrix include the new role. Tests (forge test: 142 passed, 0 failed, 0 skipped): - Eight new tests covering active-set enumeration, pagination, first-registered timestamp stability, role gating, the settlement stamp flowing into NodeInfo, and the no-stamp path on zero-claim settlements. Branch was rebased onto current main (the original PR was 18 commits behind); the contract scaffold from #237 is preserved as a single squashed baseline commit followed by this delta. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
4017f1a to
70e13b0
Compare
|
/gemini review |
There was a problem hiding this comment.
Code Review
This pull request introduces the core smart contracts for the deCDN Proof of Concept, including staking, payment channels, slashing arbitration, and content blacklisting. The review feedback suggests refactoring duplicate queue compaction logic in StakingRegistry.sol to improve maintainability. It also identifies a potential issue where matured unbonding entries could be blocked if the unbonding period is reduced and recommends considering a mechanism for nodeId migration to allow for operator key rotation in production.
…ge/ContentBlacklist Adds 24 tests covering admin governance setters, unpause restoration, constructor zero-address branches, view functions, and history reads that the original scaffold left exercised by integration only. Coverage delta (new functionality + pre-existing gaps): Lines: 91.54% → 96.79% (572/591) Functions: 88.30% → 97.87% (92/94) Branches: 69.01% → 73.24% (104/142) Per-contract: StablePaymentChannel: 85.40% → 98.54% lines, 100% on funcs SlashJudge: 91.45% → 97.37% lines, 100% on funcs ContentBlacklist: history view path now exercised StakingRegistry: already at 100% func coverage from the prior commit Total tests: 142 → 166 passing. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Three medium findings from the original PR review: 1. Compaction logic was duplicated between withdrawUnbonded and _consumeUnbonding. Extract _compactQueueFront(queue, i, len) helper. 2. Document the unbondingPeriod-decrease ordering caveat: under a monotonic period the queue is sorted by unlockTime, but a governance decrease can leave a newer matured entry behind an older non-matured one. Funds are still recoverable on the next call. Acknowledged as a production concern; queue cap (32) bounds the worst-case delay. (The third finding — nodeIdToOperator never being cleared on eject — is intentional per the existing comments in ejectNode: it makes the ejection a network-identity ban rather than a per-address one. Replied on the PR thread with the rationale.) forge test: 166 passed, 0 failed. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
|
/gemini review |
There was a problem hiding this comment.
Code Review
This pull request introduces the core smart contract suite for the deCDN Proof of Concept (PoC) on Arbitrum Sepolia, including staking, payment channels, content blacklisting, and slashing logic. The reviewer highlighted potential gas and operational inefficiencies in the unbonding queue processing, the historical blacklist lookup, and the queue compaction mechanism. These are noted as areas for potential optimization in future production iterations.
Addresses the Gemini review's gas-perf flags: ContentBlacklist: - Cap _intervals[hash] at 32 entries (MAX_INTERVALS_PER_HASH). The wasBlacklistedAt walk runs O(intervals) and is hit on every blacklist-violation slash challenge; bounding history keeps the gas cost predictable under governance churn or automated rotation. New IntervalLimitReached error fires when the cap is reached. StakingRegistry: - Document _compactQueueFront's ~5K-gas-per-slot cost and the 32-slot worst case (~160K gas). Acknowledges production should use a circular buffer or head/tail-pointer queue for O(1) front removal. (The unbondingPeriod-decrease ordering concern was already addressed in bbdadd7's withdrawUnbonded doc note. Replied on the new thread pointing at the existing fix.) forge test: 167 passed, 0 failed. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Note the implementation cap on per-hash add/remove history depth (MAX_INTERVALS_PER_HASH = 32) so the bound on wasBlacklistedAt's walk — and therefore the gas cost of SlashJudge.submitBlacklistChallenge — is part of the spec rather than an implementation curiosity. The cap was added in fb4da06; this catches the ADR up to the contract. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Closes two ADR-vs-contract gaps surfaced during the production-readiness audit. Both are required for the prod surface to match the specs auditors will use as the source of truth. ADR 004 §Auto-Ejection — StakingRegistry: - After a slash applies, if the post-slash slashable pool drops below 50% of `minStake`, auto-eject the operator. Threshold uses current `minStake` so a governance bump sweeps under-collateralized nodes. - Emit `NodeAutoEjected(operator, slashable, threshold)` so off-chain monitoring can distinguish auto-ejection from blacklist ejection. - Extract `_ejectInternal(operator)` shared between role-gated `ejectNode` (BLACKLIST_ROLE) and the slash auto-eject path. ADR 003 §Rate Bounds — StablePaymentChannel: - Add `deliveryFloor` / `deliveryCeiling` storage with hardcoded safety envelope (RATE_FLOOR_MIN=1, RATE_CEILING_MAX=10000 — 100x the PoC initial ceiling). Constructor takes both as required parameters. - `getRateBounds() returns (uint256, uint256)` for atomic refresh. - `setRateBounds(floor, ceiling)` onlyOwner with bound + ordering checks. - `RateBoundsUpdated(floor, ceiling)` event for off-chain subscribers. - Deploy script seeds initial PoC bounds (floor=1, ceiling=1000) per ADR 003 §Initial rate bounds. Tests (forge test: 175 passed, 0 failed): - Auto-eject path + the no-eject-when-above-threshold control. - Rate bounds: storage roundtrip, valid update with event, four reverts (below RATE_FLOOR_MIN, above RATE_CEILING_MAX, inverted, non-owner). - Constructor revert tests extended for the three new bound combinations. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Replace the flat-10% PoC schedule with the production escalating
schedule: tier 0 = 5%, tier 1 = 15%, tier 2 = 50% (capped). Stored
tier increments on each slash; effective tier decays with elapsed
clean time, scaled by an offense-history multiplier so repeat
offenders need progressively longer clean windows to drop tiers.
StakingRegistry:
- StakeInfo gains storedTier (uint8), lifetimeOffenseCount (uint32),
lastOffenseTimestamp (uint64). All zero on first registration;
lifetime counter is monotonic and saturating.
- New constants: SLASH_BPS_TIER_{0,1,2}, MAX_TIER, RESET_PERIOD_FLOOR,
RESET_PERIOD_CEILING.
- New governable parameter `baseResetPeriod` (90 days default,
bounds [30 days, 365 days]) with `setBaseResetPeriod` setter.
- View helpers: `currentTier(operator)`, `effectiveResetPeriod(operator)`.
- Effective period multiplier per ADR 004 formula:
lifetimeCount ≤ 1 → 1×
lifetimeCount = 2 → 2×
lifetimeCount ≥ 3 → 4× (cap)
- slash() snapshots effective tier before incrementing so a stale
stored tier can't be bumped past the correct level.
StablePaymentChannel test suite + integration test + SlashJudge test
suite updated for the new percentages (slash math no longer hard-codes
10%). Auto-eject regression test rewritten to reach the 50% threshold
via three escalating offenses rather than a contrived under-collateral
deposit.
Deploy.s.sol updated to pass the baseResetPeriod = 90 days at
construction.
Tests: 179 passed, 0 failed (was 175). New tests cover tier
escalation 0 → 1 → 2 (capped), tier decay over the effective period,
the lifetime-count multiplier (1× / 2× / 4×), and `setBaseResetPeriod`
bounds.
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
|
Closing in favor of a clean restart with the unified contract surface. The scope decisions in this draft (which contracts ship at PoC, which are deferred, which simplifications apply) have been superseded by the unified-surface plan tracked in #449 and #450:
Once those (and the ADR 026/027/028 surface lock-down, filed separately as a follow-up) close, a clean implementation issue replaces this PR with the unified scope. |
Summary
Scaffolds the full PoC EVM contract set for deCDN on Arbitrum Sepolia per ADR 016. Six contracts —
TOKEN,StakingRegistry,StablePaymentChannel,ContentBlacklist,SlashJudge,BuybackBurner— plus Foundry scaffolding, deploy script, integration test, and CI.All contracts inherit from audited OpenZeppelin v5 bases. Custom Solidity is limited to deCDN-specific business logic (channel settlement math, stake accounting, challenge arbitration, fee tiering). No proxy patterns. Immutable safety bounds for every governable parameter per ADR 009.
SignatureCheckerused everywhere a client-or-node sig is verified so ERC-4337 / ERC-1271 smart accounts work out of the box (ADR 024).Production contracts — multi-token
PaymentChannel(ADR 010),WatchtowerEscrow(ADR 007),Governor+TimelockController(ADR 009) — are deferred per ADR 023.Contents
contracts/src/— 6 contracts + sharedErrors/Roleslibraries + cross-contract interfacescontracts/script/Deploy.s.sol— atomic deployment per ADR 016 §2 withBLACKLIST_ROLE/SLASH_ROLEgrants before unpausingcontracts/test/— 6 unit suites + fuzz + 1 integration suitecontracts/lib/— OpenZeppelin v5.1.0 and forge-std as git submodules.github/workflows/contracts.yml—forge fmt --check+forge build --sizes+forge test(10k fuzz runs in CI profile) +forge coverage+slitherPoC-specific choices (all per ADR 023)
TOKENis PoC-mintable behindonlyOwner(fixed supply in production)BuybackBurner.executeBuybackrevertsBuybackDisabled(); accumulation path (depositUSDC) is live so the treasury split works end-to-endSlashJudgeuses the optimistic challenge-response path with 24h counter window; interactive Merkle proofs for corruption deferredContentBlacklistomits regional bodiesStablePaymentChannelhardcodes USDC (single-token)TimelockControllerTest plan
cd contracts && forge fmt --checkpassesforge buildclean (no errors)forge test— 110/110 passing including 1000-run fuzz on slash math and channel settlement mathforge coveragethreshold checked in CIslitherclean in CIforge script script/Deploy.s.sol --fork-url $ARB_SEPOLIA_RPCdry-run (manual, post-review)🤖 Generated with Claude Code