Repository navigation
feat: operator slash detection + appeal via decdn appeal slash (#1032) - #1089
Conversation
Phase 1 of G-NODE-05 (operator slash detection + appeal). - Add alloy bindings for SlashAppeal (openSlashAppeal, appealBond, token, getAppeal) and SlashJudge (Slashed event, commit/reveal, evidence structs) in decdn-incentive. - Add optional blockchain.slash_appeal_address to the config schema (types/resolved/resolver + DECDN_SLASH_APPEAL_ADDRESS env + zero-address guard); required only by the appeal CLI, so the daemon path is unaffected. - Add the operator-facing `decdn appeal slash <SLASH_ID> <EVIDENCE_BUNDLE_HASH>` command: read the governable appeal bond, approve TOKEN if short, then file via openSlashAppeal. Supports --dry-run / --json. Role-gated fast-track / grant actions are intentionally not exposed. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Phase 2 of G-NODE-05 (operator slash detection + appeal). - Add a lean SlashJudge.Slashed watcher (crates/node/src/slash_watcher.rs) that backfills from genesis then live-streams, filtering to this node's operator and recording detections into a shared in-memory store (deduped by slashId). Mirrors the payment-settlement watcher's resubscribe/backoff shape without any write path. - Surface detections over a new admin_v1_slashes RPC (SlashRecordDto / SlashesResponse DTOs + SLASH_DETECTION_UNAVAILABLE_CODE) and a decdn_slashes_detected_total counter; wire SlashStatusHandles into AdminState via with_slash_detection and spawn the watcher in runtime. - Unit tests for the admin method (unavailable-without-handle, newest-first population). Co-Authored-By: Claude Opus 4.8 <[email protected]>
Phase 3 of G-NODE-05. Drives the whole journey against a real anvil deployment: a real SlashJudge phantom commit-reveal slash, daemon detection over admin_v1_slashes, the decdn appeal slash CLI posting the bond, emergency-multisig fast-track, and a real DecdnGovernor proposal (propose -> vote -> queue -> timelock -> execute) granting the appeal; asserts the escrowed bond refunded and slashedAtEpoch recomputed to 0 (vote weight restored). Plus the three negatives: non-operator cannot appeal, second appeal within 365 days rejected, appeal after the 30-day window rejected. - Extend e2e bindings: SlashAppeal (open/fastTrack/grant + status), DecdnGovernor lifecycle, TimelockController, CapacityBond slash reads; reuse the production SlashJudge binding. - Add ChainFixture verbs: slash_operator_via_judge (builds + signs the operator's own phantom evidence, commit-reveal), fast_track_appeal, governor_grant_appeal (full lifecycle with time warps), plus appeal_bond / slashed_at_epoch / appeal_status / token_balance reads. - Extend ContractAddrs + manifest read (SlashAppeal/DecdnGovernor/ TimelockController); render slash_appeal_address into the node config; expose NodeFixture.config_path + KEYSTORE_PASSWORD for CLI-driven tests. - Add ProbeSlashData/StreamSlashData::struct_hash for the evidence commit. Verified: cargo nextest run -p decdn-e2e --features anvil-e2e passes. Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
WalkthroughThis PR adds the slash appeal flow end to end: new appeal config and CLI types, ChangesSlash appeal feature
Estimated code review effort: 4 (Complex) | ~75 minutes Possibly related issues
Possibly related PRs
Suggested reviewers: 🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
Comment |
There was a problem hiding this comment.
Code Review
This pull request introduces the decdn appeal slash CLI command and a daemon slash-detection watcher to support the slashing appeal lifecycle (ADR 028). It adds configuration options, an admin RPC endpoint to query detected slashes, and comprehensive end-to-end tests. The review feedback highlights two key areas for improvement: first, updating the slash_id CLI argument from u64 to String or U256 to prevent parsing failures for on-chain IDs that exceed u64::MAX; second, refining the reconnection logic in the slash watcher stream to avoid tight CPU-spinning loops and misleading log messages.
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.
Coverage reportTotal: 80.96% (was 81.74%, ▼ 0.77%) — 43265/53437 lines
History
|
There was a problem hiding this comment.
Actionable comments posted: 4
🧹 Nitpick comments (2)
crates/cli/src/commands/chain_ctx.rs (1)
134-199: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winExtract the shared chain_id/data_dir/keystore resolution to avoid duplicating
resolve().
resolve_appealre-implements the exactchain_id/data_dir/keystoreresolution logic already inresolve(Lines 101-124) verbatim; only therpc_url-adjacent field differs (capacity_bond_addressvs.slash_appeal_address). A future change to this precedence chain (e.g. a new default source) would need to be applied in both places.♻️ Proposed extraction of shared resolution logic
+fn resolve_common(chain: &cli::ChainArgs, file: &FileConfig) -> anyhow::Result<(u64, PathBuf, PathBuf)> { + let bc = file.blockchain.as_ref(); + let chain_id = chain + .chain_id + .or_else(|| bc.and_then(|b| b.chain_id)) + .unwrap_or(DEFAULT_CHAIN_ID); + let data_dir = chain + .data_dir + .clone() + .or_else(|| file.identity.as_ref().and_then(|i| i.data_dir.clone())) + .map(|p| expand_tilde(&p)) + .or_else(cli::default_data_dir) + .ok_or_else(|| { + anyhow::anyhow!("data_dir not set and no default available (pass --data-dir)") + })?; + let keystore = chain + .keystore + .clone() + .or_else(|| bc.and_then(|b| b.eth_keystore.clone())) + .map_or_else( + || eth_identity::keystore_path(&data_dir), + |p| expand_tilde(&p), + ); + Ok((chain_id, data_dir, keystore)) +} + pub fn resolve_appeal( chain: &cli::ChainArgs, slash_appeal_flag: Option<&str>, file: &FileConfig, ) -> anyhow::Result<ResolvedAppeal> { let bc = file.blockchain.as_ref(); let rpc_url = chain .rpc_url .clone() .or_else(|| bc.and_then(|b| b.rpc_url.clone())) .ok_or_else(|| { anyhow::anyhow!("rpc_url not set (pass --rpc-url or set blockchain.rpc_url)") })?; let slash_appeal_address = slash_appeal_flag .map(str::to_string) .or_else(|| bc.and_then(|b| b.slash_appeal_address.clone())) .ok_or_else(|| { anyhow::anyhow!( "slash_appeal_address not set (pass --slash-appeal-address or set \ blockchain.slash_appeal_address)" ) })?; - let chain_id = chain - .chain_id - .or_else(|| bc.and_then(|b| b.chain_id)) - .unwrap_or(DEFAULT_CHAIN_ID); - let data_dir = chain - .data_dir - .clone() - .or_else(|| file.identity.as_ref().and_then(|i| i.data_dir.clone())) - .map(|p| expand_tilde(&p)) - .or_else(cli::default_data_dir) - .ok_or_else(|| { - anyhow::anyhow!("data_dir not set and no default available (pass --data-dir)") - })?; - let keystore = chain - .keystore - .clone() - .or_else(|| bc.and_then(|b| b.eth_keystore.clone())) - .map_or_else( - || eth_identity::keystore_path(&data_dir), - |p| expand_tilde(&p), - ); + let (chain_id, data_dir, keystore) = resolve_common(chain, file)?; Ok(ResolvedAppeal { rpc_url, chain_id, slash_appeal_address, keystore, data_dir, }) }The same helper can subsequently be applied to
resolve().🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@crates/cli/src/commands/chain_ctx.rs` around lines 134 - 199, The appeal resolver duplicates the shared chain_id, data_dir, and keystore precedence logic already implemented in resolve(), so extract that common resolution into a reusable helper and call it from both resolve_appeal and resolve. Keep the appeal-specific parts in resolve_appeal limited to rpc_url and slash_appeal_address, and preserve the existing fallback order from flags to config to defaults using the current symbols (resolve, resolve_appeal, ResolvedAppeal).crates/e2e/tests/slash_appeal.rs (1)
172-177: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winTighten the refund assertion to an exact amount.
balance_after_grant >= balance_beforeonly checks that nothing was lost, not that the full bond + escrowed slash amount was actually refunded (a partial-refund bug would still pass).SlashAppeal.slashRecords/CapacityBond.slashRecords(already bound inbindings.rs) could compute the expected exact delta.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@crates/e2e/tests/slash_appeal.rs` around lines 172 - 177, The refund check in the slash appeal test is too loose because `balance_after_grant >= balance_before` only verifies no loss, not a full refund. Update the assertion in `slash_appeal.rs` to compare against the exact expected post-grant balance by using the already bound `SlashAppeal.slashRecords` and `CapacityBond.slashRecords` helpers from `bindings.rs` to compute the bond plus escrowed slash amount. Keep the check centered around `balance_before` and `balance_after_grant`, but require the precise delta expected after a granted appeal.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@crates/common/src/config/mod.rs`:
- Around line 1063-1086: The `slash_appeal_address` validation currently checks
for zero before parsing, which can duplicate errors for malformed all-zero
inputs. Update the `slash_appeal_raw` flow in `config::mod` to mirror the
`slash_judge_address` pattern: first run `parse_contract_address` through
`bag.try_with`, then perform the zero-address `bag.check` only after parsing
succeeds, using the same `blockchain.slash_appeal_address` label and existing
`bag` helpers.
In `@crates/node/src/runtime/mod.rs`:
- Around line 707-726: The slash-watcher startup in run() is currently fatal and
the backfill starts from block 0, which can stop node startup and hit RPC range
limits. Update the SlashWatcher::bootstrap path to follow the same
warn-and-disable pattern used by other optional chain-backed bootstraps in
crates/node/src/runtime/mod.rs, so RPC/bootstrap failures log a warning and
continue without slash detection. Also change backfill_slashes to take a
configurable starting block instead of always scanning from genesis, and thread
that setting through the slash-watcher initialization and any related config or
constructor symbols.
In `@crates/node/src/slash_watcher.rs`:
- Around line 202-207: The live log handling in SlashWatcher’s `events.next()`
loop currently uses `SlashJudge::Slashed::decode_log_data(...)?`, which aborts
the entire watcher cycle on a single bad log. Update this branch to match
`backfill_slashes` by catching decode failures, logging a warning with the
decode context, and continuing to the next event instead of propagating the
error; keep the operator filter and the rest of the live processing unchanged.
- Around line 149-175: The restart loop in slash_watcher::slash_watcher resets
WATCHER_INITIAL_BACKOFF on run_once() Ok(()) and immediately resubscribes, which
can create a tight loop when the stream ends cleanly but repeatedly. Update the
Ok(()) branch in the loop to apply the same kind of delay/backoff used in the
Err(err) branch before calling run_once() again, and keep the backoff state from
collapsing to zero so repeated clean endings do not hammer the provider.
---
Nitpick comments:
In `@crates/cli/src/commands/chain_ctx.rs`:
- Around line 134-199: The appeal resolver duplicates the shared chain_id,
data_dir, and keystore precedence logic already implemented in resolve(), so
extract that common resolution into a reusable helper and call it from both
resolve_appeal and resolve. Keep the appeal-specific parts in resolve_appeal
limited to rpc_url and slash_appeal_address, and preserve the existing fallback
order from flags to config to defaults using the current symbols (resolve,
resolve_appeal, ResolvedAppeal).
In `@crates/e2e/tests/slash_appeal.rs`:
- Around line 172-177: The refund check in the slash appeal test is too loose
because `balance_after_grant >= balance_before` only verifies no loss, not a
full refund. Update the assertion in `slash_appeal.rs` to compare against the
exact expected post-grant balance by using the already bound
`SlashAppeal.slashRecords` and `CapacityBond.slashRecords` helpers from
`bindings.rs` to compute the bond plus escrowed slash amount. Keep the check
centered around `balance_before` and `balance_after_grant`, but require the
precise delta expected after a granted appeal.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro Plus
Run ID: b320df16-093a-46ab-bef5-7fcadadac214
📒 Files selected for processing (28)
crates/cli/src/commands/appeal.rscrates/cli/src/commands/chain_ctx.rscrates/cli/src/commands/mod.rscrates/cli/src/main.rscrates/cli/tests/config_validate.rscrates/common/src/admin.rscrates/common/src/cli/appeal.rscrates/common/src/cli/mod.rscrates/common/src/cli/run.rscrates/common/src/config/mod.rscrates/common/src/config/resolved.rscrates/common/src/config/types.rscrates/e2e/src/bindings.rscrates/e2e/src/chain.rscrates/e2e/src/node.rscrates/e2e/tests/slash_appeal.rscrates/incentive/src/lib.rscrates/incentive/src/probe_sig.rscrates/incentive/src/slash_appeal.rscrates/incentive/src/slash_judge.rscrates/incentive/src/stream_sig.rscrates/node/src/admin.rscrates/node/src/lib.rscrates/node/src/metrics.rscrates/node/src/runtime/mod.rscrates/node/src/runtime/reload.rscrates/node/src/slash_watcher.rscrates/node/tests/sighup_signal.rs
decdn appeal slash (#1032)
…tal startup - CLI: parse slash_id as U256 (uint256 can exceed u64); emit as decimal string. - slash_watcher: back off before resubscribing on a clean stream end (avoid a zero-delay resubscribe storm); skip an undecodable live log instead of tearing down the cycle; window the genesis backfill into 9k-block get_logs chunks so it can't exceed RPC range caps. - runtime: SlashWatcher bootstrap is now non-fatal (warn + disable) rather than aborting node bring-up; admin_v1_slashes reports unavailable when absent. - config: run the slash_appeal_address zero-address check after parse to match the slash_judge_address cascade-suppression (no duplicate errors). - chain_ctx: extract resolve_common to share chain_id/data_dir/keystore resolution between resolve and resolve_appeal. Verified: clippy --workspace --all-targets, fmt, nextest (1325 unit tests) and the gated anvil e2e all pass. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Review summaryReviewed at high effort (8 finder angles → adversarial verification). 10 inline comments posted. The theme of the top findings: the watcher's event coverage has three independent gaps (pre-filter-install window, no re-backfill on resubscribe, one-shot bootstrap), each of which can silently cost an operator the 30-day appeal window — the exact risk #1032 exists to remove. Lower-priority items verified but kept out of the inline set:
🤖 Generated with Claude Code |
Slash watcher (crates/node/src/slash_watcher.rs), closing three event-coverage
gaps that could silently burn the 30-day appeal window:
- Install the live filter before reading the head backfill bound (no pre-install
gap); constrain both live + backfill on topic2 == operator so a node never
downloads other operators' slashes; skip reorged-out (removed) logs.
- Carry a last-scanned-block cursor across every resubscribe and re-backfill
[cursor, head] via the shared payment_settlement::{backfill_windows,
MAX_BACKFILL_BLOCK_SPAN}; seed the cursor at head on the first cycle (no
genesis scan). One record_log helper feeds both live + backfill.
- bootstrap is now infallible (every RPC inside the retrying loop) so a bring-up
blip retries instead of disabling detection for the daemon's life; runtime
wires it unconditionally. Add chain_events::watch_filter for the topic filter.
Admin: reword the admin_v1_slashes unavailable message (no longer misdirects to a
required-and-set config field); correct the SlashRecordDto.appeal_window_close
doc (nominal hint, not read from CapacityBond, ignores pause extensions).
Config/CLI: add env=DECDN_SLASH_APPEAL_ADDRESS to the appeal flag; move the
zero-address validation into chain_ctx::resolve_appeal (guards the actual
consumer); drop the dead daemon-side slash_appeal_address plumbing
(ResolvedBlockchain field, resolver, run.rs flag/env, test literals), keeping
only the BlockchainConfig field the shared node.toml requires. Fold rpc_url into
resolve_common; drive appeal::execute off &Plan.
e2e: fund + approve the bond before the non-operator and frequency-cap negatives
so a zero-allowance transferFrom can't be the revert reason — the guards are now
what the tests actually prove.
Verified: clippy --workspace --all-targets, fmt, nextest (1325 unit tests) and
the gated anvil e2e all pass.
Co-Authored-By: Claude Opus 4.8 <[email protected]>
rustdoc's private-intra-doc-links lint (fatal under RUSTDOCFLAGS=-D warnings in the cargo doc CI job) rejects links from the pub module docs to the pub(crate) `MAX_BACKFILL_BLOCK_SPAN` / `backfill_windows`; render them as plain code spans. Co-Authored-By: Claude Opus 4.8 <[email protected]>
There was a problem hiding this comment.
🧹 Nitpick comments (1)
crates/node/src/slash_watcher.rs (1)
139-185: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick winConsider a down-time gauge for the slash watcher, matching the other chain watchers.
Metricsalready tracksstaker_set_watcher_down_since,node_address_watcher_down_since, andorigin_directory_watcher_down_sinceso an operator can alert when those loops are stuck in backoff.watcher_loophere uses the identical error/backoff shape but has no equivalent gauge — if this loop gets wedged in persistent backoff (e.g. a sustained RPC outage), nothing pages the operator, which is exactly the "silently miss a slash" failure mode#1032exists to prevent. Sinceadmin_v1_slashesis now always "available" (slash_detection is wired unconditionally), a stuck watcher is otherwise invisible.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@crates/node/src/slash_watcher.rs` around lines 139 - 185, The slash watcher loop lacks the same down-time tracking used by the other chain watchers, so add a `Metrics` gauge for this watcher and update it inside `watcher_loop` around the `run_once`/backoff cycle. Use the existing watcher pattern from `staker_set_watcher_down_since`, `node_address_watcher_down_since`, and `origin_directory_watcher_down_since` to set the start time when `run_once` returns an error, clear it when the loop resumes successfully, and make sure the new gauge is wired through `Metrics` and any initialization paths.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Nitpick comments:
In `@crates/node/src/slash_watcher.rs`:
- Around line 139-185: The slash watcher loop lacks the same down-time tracking
used by the other chain watchers, so add a `Metrics` gauge for this watcher and
update it inside `watcher_loop` around the `run_once`/backoff cycle. Use the
existing watcher pattern from `staker_set_watcher_down_since`,
`node_address_watcher_down_since`, and `origin_directory_watcher_down_since` to
set the start time when `run_once` returns an error, clear it when the loop
resumes successfully, and make sure the new gauge is wired through `Metrics` and
any initialization paths.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro Plus
Run ID: 2552632b-98df-41bb-b543-f529b90de071
📒 Files selected for processing (11)
crates/cli/src/commands/appeal.rscrates/cli/src/commands/chain_ctx.rscrates/common/src/admin.rscrates/common/src/cli/appeal.rscrates/common/src/config/mod.rscrates/common/src/config/types.rscrates/e2e/tests/slash_appeal.rscrates/node/src/admin.rscrates/node/src/chain_events.rscrates/node/src/runtime/mod.rscrates/node/src/slash_watcher.rs
🚧 Files skipped from review as they are similar to previous changes (5)
- crates/common/src/cli/appeal.rs
- crates/node/src/admin.rs
- crates/common/src/admin.rs
- crates/e2e/tests/slash_appeal.rs
- crates/cli/src/commands/appeal.rs
Add decdn_slash_watcher_down_seconds, mirroring the staker-set / node-address / origin-directory watcher gauges: stamped from slash_watcher_down_since on a backoff window and cleared when a cycle re-establishes (inside run_once, so a long healthy live-drain reads 0). Since admin_v1_slashes is wired unconditionally, this is the only signal that a wedged watcher could be silently missing slashes. Unit-tested for the healthy/backoff/re-establish transitions. Co-Authored-By: Claude Opus 4.8 <[email protected]>
There was a problem hiding this comment.
🧹 Nitpick comments (1)
crates/node/src/metrics.rs (1)
403-414: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick winConsider a
slash_watcher_restartscounter alongsideslash_watcher_down_seconds.Every sibling watcher (
staker_set,node_address,origin_directory) pairs its_down_secondsgauge with a_restarts_totalcounter bumped on the edge into backoff, so operators can distinguish "one long outage" from "many short flaps."slash_watcher_backoff_started(Lines 1341-1347) only stampsdown_sinceand skips that counter — given the PR's own stated concern that a wedged/flapping watcher could silently miss slash events within the 30-day appeal window, a restart counter would add useful signal here too.♻️ Proposed addition
/// Slashes detected against this node's operator by the slash watcher /// ... pub slashes_detected: Counter, + /// `decdn_slash_watcher_restarts_total` (`#1032`): distinct drift windows the + /// slash-detection watcher has entered, bumped once on the edge into the + /// error/backoff state. Mirrors `staker_set_watcher_restarts`. + pub slash_watcher_restarts: Counter, /// `decdn_slash_watcher_down_seconds` (`#1032`): ... pub slash_watcher_down_seconds: Gauge,pub fn slash_watcher_backoff_started(&self) { if let Ok(mut down_since) = self.slash_watcher_down_since.lock() && down_since.is_none() { *down_since = Some(Instant::now()); + self.decdn.slash_watcher_restarts.inc(); } }Also applies to: 1330-1357
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@crates/node/src/metrics.rs` around lines 403 - 414, Add a slash watcher restart counter to match the other watcher metrics: the `slash_watcher_backoff_started` path should bump a new `_restarts_total` counter when entering backoff, alongside maintaining `slash_watcher_down_seconds` from `slash_watcher_down_since`. Update the `metrics.rs` definitions near `slashes_detected` and `slash_watcher_down_seconds`, and wire the increment into `slash_watcher_backoff_started` so operators can distinguish a single long outage from repeated flapping.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Nitpick comments:
In `@crates/node/src/metrics.rs`:
- Around line 403-414: Add a slash watcher restart counter to match the other
watcher metrics: the `slash_watcher_backoff_started` path should bump a new
`_restarts_total` counter when entering backoff, alongside maintaining
`slash_watcher_down_seconds` from `slash_watcher_down_since`. Update the
`metrics.rs` definitions near `slashes_detected` and
`slash_watcher_down_seconds`, and wire the increment into
`slash_watcher_backoff_started` so operators can distinguish a single long
outage from repeated flapping.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro Plus
Run ID: a338adbb-0f60-485e-8073-26e232505bb1
📒 Files selected for processing (2)
crates/node/src/metrics.rscrates/node/src/slash_watcher.rs
🚧 Files skipped from review as they are similar to previous changes (1)
- crates/node/src/slash_watcher.rs
Pair the down-seconds gauge with decdn_slash_watcher_restarts_total, bumped once on the edge into backoff (mirrors the staker-set / node-address / origin-directory watchers), so operators can tell one long outage from repeated flapping. Extends the metrics unit test to assert the edge-triggered bump. Co-Authored-By: Claude Opus 4.8 <[email protected]>
altanoruc
left a comment
There was a problem hiding this comment.
There is one remaining correctness gap in the slash watcher’s initial/restart backfill.
Addresses altanoruc's P1: seeding the first cycle at head dropped a slash mined while the node was down (before start/restart) even within the 30-day appeal window; the in-process cursor only repaired gaps within one process lifetime. The detected-slash store is in-memory, so it is empty on every process start and must be rebuilt by re-scanning history — a durable scan checkpoint could not skip this (resuming from it would drop still-appealable slashes at/below the checkpoint). So the first cycle now scans [slash_judge_from_block, head] on every start, re-surfacing a slash mined while down on the next restart. Added the blockchain.slash_judge_from_block config floor (default 0 = genesis, set it to the SlashJudge deploy block; mirrors origin_directory_from_block); the in-process cursor still covers resubscribe gaps. Regression e2e: NodeFixture::restart() respawns the daemon against the same config (no re-onboarding); the G-NODE-05 test now restarts operator A after the slash and asserts admin_v1_slashes re-surfaces it. Verified: clippy --workspace --all-targets, fmt, nextest (1326 unit tests), cargo doc, and the gated anvil e2e all pass. Co-Authored-By: Claude Opus 4.8 <[email protected]>
…rom-block docs Addresses merge-readiness review findings on #1089: - The resubscribe cursor resumed at exactly `head + 1` with no reorg lookback, so a shallow reorg during the backoff could hide a `Slashed` log re-mined at a slightly different height. The resume now rewinds the cursor by the settlement watcher's `REORG_MARGIN_BLOCKS` (now `pub(crate)`), clamped to the deployment floor and head, via a pure `resolve_scan_start` helper — the `slashId` dedup makes the overlap free. - `slash_judge_from_block` docs (config types/resolved/resolver) claimed restarts resume from a persisted checkpoint; there is none — every daemon start rescans from this floor to rebuild the in-memory store, and the in-process cursor only covers resubscribe gaps within one process lifetime. - `admin_v1_slashes` doc referenced a nonexistent `decdn node slashes` subcommand; it is consumed directly by operators/keepers. - Unit tests: slashId dedup (no double insert/count), removed-log and foreign-operator skip via a pure `decode_slashed` helper, and the cursor-resume margin/clamp math. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_0184dDvFgy44w6deBQkugX7r
Union-merge of the slash-watcher feature (#1089/#1032) with the blacklist compliance loop (#1031): both config surfaces (slash_judge_from_block / slash_appeal_address alongside content_blacklist_*), both e2e binding sets (SlashAppeal/Governor/Timelock alongside ContentBlacklist/AccessControl — the blacklist challenge entry point moves to a SlashJudgeBlacklist binding so main's production-SlashJudge re-export stands), both ChainFixture verb sets (head_timestamp absorbs block_timestamp), and one reconciled NodeFixture::restart (pub config_path). Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_0184dDvFgy44w6deBQkugX7r
The #1089 merge brought crates/e2e/tests/slash_appeal.rs into the cross-layer journey step, and it shells out to the user CLI binary `decdn` (package decdn-cli), which the anvil-e2e job never built — the journey failed with "decdn binary not found". Build it alongside the daemon, and recompute the job budget for the 5-test journey set: settlement 13m + worst 2-thread schedule 43m (smoke 13m + three G-NODE-04 10m on one thread vs slash_appeal 20m on the other) + compiles and per-fixture forge deploys, raising timeout-minutes 60 -> 75. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_0184dDvFgy44w6deBQkugX7r
* feat(node): blacklist compliance loop + G-NODE-04 e2e (#1031) The node had no content-hash blacklist awareness: ContentBlacklist and SlashJudge shipped on-chain and the e2e harness existed, but nothing on the Rust side evicted, stopped announcing, or refused delivery for a blacklisted blob — the client handler explicitly deferred it as "ContentBlacklist's job". This adds the missing node-side loop and the G-NODE-04 acceptance test that exercises it end-to-end. Production (Part A): - Add optional `blockchain.content_blacklist_address` config (opt-in, modeled on origin_assignment_address). - New `decdn-incentive::content_blacklist` binding (isHashBlacklistedForOperator view + HashBlacklisted/HashRemoved events + governance writes). - New `blacklist_watcher` runtime task: reuses `watch_contract_events`, reconciles held hashes at boot and on each event, and calls `cache.evict()` for hashes blacklisted in scope for this operator (region logic delegated to the contract view). Eviction is the single lever and cascades to durable takedown (evicted.log), DHT-announce suppression, probe has_blob:false, and delivery refusal. Test (Part B): - `crates/e2e/tests/g_node_04_blacklist_compliance.rs`: global compliance (evict -> refuse delivery -> durable across restart -> full SlashJudge.submitBlacklistChallenge commit-reveal proving slashability) and regional scope (GOV-05: in-region node evicts, out-of-region keeps serving). - Fixtures: ContentBlacklist/SlashJudge/AccessControl bindings, anvil-impersonated governance helpers, NodeFixture::restart(). - Wire the (previously unrun) decdn-e2e crate into the CI anvil-e2e job. Co-Authored-By: Claude Opus 4.8 <[email protected]> * fix(node): close blacklist-watcher reconcile races + bound RPC (PR #1087 review) Address bot review on the blacklist compliance watcher: - Reconcile after the event filter is installed, not before. Establishing the subscription first (which buffers server-side) then reconciling closes the race where an event emitted between a reconcile and a later subscribe was lost — now covering startup, stream gaps, and repeated subscription failures uniformly. Collapses Cycle to {Shutdown, Resubscribe} and drops the Follow enum. Mirrors chain_origin_directory. - Add a periodic re-reconcile (10 min, matching ADR 011 §Polling) so a hash whose scope check hit a transient RPC error is retried under a stable subscription instead of staying served until the next event/gap. - Bound isHashBlacklistedForOperator with a 10s per-call timeout so a stalled provider (no RPC request timeout is configured) cannot hang a reconcile scan. Bounded-concurrency for the scan is deliberately not added: sequential is fine for a background backstop at the initial network scale, and the per-call timeout already removes the unbounded-hang risk. Co-Authored-By: Claude Opus 4.8 <[email protected]> * fix(node): event-sourced blacklist watcher + test/CI hardening (PR #1087 review) Address alpergundogdu's review of the blacklist compliance loop. Watcher redesign (crates/node/src/blacklist_watcher.rs) — the deny-set is now sourced from `HashBlacklisted` logs replayed from a checkpoint block plus a live subscription, instead of scanning currently-held blobs: - Replay-from-checkpoint lets the watcher pre-block a hash blacklisted while the node was offline and not yet held: `evict` is sticky, so the pull-through admission `is_evicted` gate refuses a later origin fill. Closes the offline-then-served slash hole; also makes each pass O(blacklist) not O(held). - Reconcile runs every cycle regardless of the subscription (eth_getLogs works even when the filter API is broken), so an eth_call/getLogs-only endpoint still enforces. - The subscribe await is bounded by RPC_CALL_TIMEOUT and raced against shutdown so a hung eth_newFilter can't wedge the watcher or block graceful shutdown. - Per-hash scope-check errors are queued and retried on the periodic tick, so a transient RPC error no longer permanently drops a sticky pre-block. - Clean stream-ends are throttled (min-survival before resetting backoff) so a filter that expires on the first poll can't spin. Config — add `blockchain.content_blacklist_from_block` (replay start, mirrors `origin_directory_from_block`), and reject the zero address for `content_blacklist_address` (a codeless address fails open: every scope call errors → nothing evicted while the operator believes compliance is active). CI — raise the anvil-e2e job timeout above the sum of the steps' in-test ceilings so a hung test hits its per-test timeout's clear message first. Tests — assert the refusal reason specifically (`EvictedSinceProbe`), drive a real probe at the daemon asserting `has_blob:false` (the phantom-blob seam), and gate the regional non-eviction on a global-sentinel ordering barrier so a one-cycle-late scope bug can't pass. Adds `NodeFixture::launch_with_blobs` and `ClientFixture::probe`. Declined: bounded-concurrency for the scan — the replay makes it O(blacklist), so it is unnecessary complexity at the current scale. Co-Authored-By: Claude Opus 4.8 <[email protected]> * fix(node): interruptible reconcile + retain/re-scope blacklist deny-set (PR #1087 review) Address the round-4 review of the blacklist compliance watcher. Shutdown interruptibility (coderabbit) — a long reconcile (many 9k-block replay windows / scope retries) could overrun the runtime's 15s SHUTDOWN_DEADLINE and force an abort. Convert the watcher's shutdown from a oneshot to `tokio_util::sync::CancellationToken` (the runtime's standard shutdown primitive): `is_cancelled()` is checked between replay windows and rescan hashes, and `cancelled()` feeds the loop/subscribe/sleep selects. Retain + re-scope the deny-set (altanoruc, P1) — the round-3 watcher dropped a hash on `Some(false)` (out-of-scope for the operator's region, or fast-track suspended). Neither a region/ripening transition (`updateRegion`) nor an appeal reversal/lapse re-emits `HashBlacklisted`, and the advanced checkpoint prevents replay, so such a hash could become live + in scope and be served indefinitely. Now every seen-but-not-yet-evicted hash is retained in a `known` set (incl. out-of-scope/suspended) and re-scoped on every periodic pass; when it comes into scope it is evicted. This supersedes the round-3 `pending` retry set. Config — add `blockchain.content_blacklist_poll_interval_sec` (default 600s, ADR 011 §Polling cadence) governing the periodic replay + re-scope; scope transitions emit no event, so this backstop is what catches them. Test — add `regional_scope_transition`: a US-regional entry is retained (not evicted) by a DE operator, then evicted after `updateRegion("US")` — a scope change with no `ContentBlacklist` event, caught only by the re-scope. Adds `CapacityBond.updateRegion` binding + `chain.update_region` helper; the e2e node config uses a 2s poll interval. The suspended-appeal-becoming-active case exercises the identical re-scope path (scope flips true when `suspended` clears); left as a follow-up rather than duplicating the mechanism with the heavy appeal-lifecycle choreography. Co-Authored-By: Claude Opus 4.8 <[email protected]> * fix(node): reject zero blacklist poll interval (PR #1087 review) `tokio::time::interval_at` panics on a zero period, so `content_blacklist_poll_interval_sec = 0` would kill the watcher task and silently stop blacklist reconciliation. Reject 0 at config resolution (0 is not a "disable" sentinel — disabling the periodic re-scope would break the retain/re-scope guarantee), mirroring the zero-slash-judge / zero-chain-id checks, with a unit test. Also clamp defensively in `blacklist_watcher::run` so the interval construction can never panic regardless of caller. Co-Authored-By: Claude Opus 4.8 <[email protected]> * fix(node): key blacklist deny-set by (region, hash); harden CI e2e budget PR #1087 review fixes: - blacklist_watcher: key `known` by (region, hash) — the contract's own `_hashEntries[region][hash]` key — so a HashRemoved for one region's entry no longer drops a surviving same-hash entry in another region (which left the node slashable after a later updateRegion into the surviving region, since region changes emit no blacklist event). Re-scoping dedupes the per-hash isHashBlacklistedForOperator eth_call across regional entries; eviction (sticky, region-independent) drops all entries for the hash. Warn on undecodable HashRemoved logs like HashBlacklisted, and add unit tests for the pure deny-set transitions. - config: test the zero-address rejection of blockchain.content_blacklist_address (mirrors slash_judge_address). - CI anvil-e2e: cap the cross-layer journeys at --test-threads 2 (each journey runs its own anvil + forge deploy + daemons; four at once oversubscribes the 4-core runner) and recompute the job budget honestly — settlement 13m + worst 2-thread journey schedule 30m plus compiles/deploys — raising timeout-minutes 30 -> 60. - e2e Cargo.toml: unstale the "only test target is the smoke test" comments now that the G-NODE-04 journeys exist. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_0184dDvFgy44w6deBQkugX7r * ci: build decdn CLI for the slash-appeal e2e journey The #1089 merge brought crates/e2e/tests/slash_appeal.rs into the cross-layer journey step, and it shells out to the user CLI binary `decdn` (package decdn-cli), which the anvil-e2e job never built — the journey failed with "decdn binary not found". Build it alongside the daemon, and recompute the job budget for the 5-test journey set: settlement 13m + worst 2-thread schedule 43m (smoke 13m + three G-NODE-04 10m on one thread vs slash_appeal 20m on the other) + compiles and per-fixture forge deploys, raising timeout-minutes 60 -> 75. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_0184dDvFgy44w6deBQkugX7r --------- Co-authored-by: Claude Opus 4.8 <[email protected]>
Implements #1032 (G-NODE-05): operator slash detection + appeal — the
decdn appeal slashCLI, daemon-side slash surfacing, and a full-flow end-to-end test.Approach (confirmed with the issue author): operator-only CLI surface, and a full on-chain e2e — a real
SlashJudgecommit-reveal challenge and a realDecdnGovernorpropose→vote→queue→timelock→execute grant (no impersonation shortcuts).What's in it
1.
decdn appeal slashCLI (f964b42)alloybindings forSlashAppeal+SlashJudgeindecdn-incentive.decdn appeal slash <SLASH_ID> <EVIDENCE_BUNDLE_HASH>: reads the governable appeal bond, approves TOKEN if the allowance is short, then files viaopenSlashAppeal.--dry-run/--json.SLASH_IDis parsed asuint256. Role-gated fast-track/grant are intentionally not exposed.blockchain.slash_appeal_address(CLI-consumed; validated inchain_ctx::resolve_appeal, incl. zero-address guard;DECDN_SLASH_APPEAL_ADDRESSenv).2. Daemon slash detection (
f05d86a)SlashJudge.Slashedwatcher, filtered server-side to this node's operator (topic2), recording detections into a shared in-memory store (deduped byslashId).blockchain.slash_judge_from_blockfloor on every start (so a slash mined while the node was down is re-surfaced on restart, within its 30-day appeal window); skip reorged-out (removed) logs; infallible bootstrap (RPCs inside the retry loop) so a bring-up blip retries rather than disabling detection.admin_v1_slashesRPC + metrics:decdn_slashes_detected_total,decdn_slash_watcher_down_seconds,decdn_slash_watcher_restarts_total(the down-seconds/restarts pair matches the other chain watchers — the signal that a wedged watcher could be silently missing slashes, since the RPC is always wired).3. Full-flow e2e (
171d5bc, gated byanvil-e2e)admin_v1_slashes→ node restart re-surfaces it →decdn appeal slashCLI posts the bond → emergency-multisig fast-track → real Governor proposal grants the appeal → asserts escrowed bond refunded andslashedAtEpochrecomputed to 0 (vote weight restored). Plus three negatives (non-operator, second appeal within 365d, appeal after the 30-day window), each funding+approving the bond first so the on-chain guard — not a zero-allowancetransferFrom— is what the test proves.SlashAppeal/DecdnGovernor/TimelockControllerbindings +CapacityBondslash reads;ChainFixtureverbs (slash_operator_via_judge,fast_track_appeal,governor_grant_appeal);NodeFixture::restart().Reviewer notes
slash_judge_from_block(not a durable checkpoint, which would skip re-recording still-appealable slashes at/below it).Verification
cargo clippy --workspace --all-targets -- -D warnings,cargo fmt --check,cargo doc— cleancargo nextest run --workspace— 1326 unit tests passcargo nextest run -p decdn-e2e --features anvil-e2e— G-NODE-05 passes (real anvil + forge + governance + restart)Incorporates two review rounds: correctness/observability hardening from @alpergundogdu (10 findings) and @altanoruc (P1 restart backfill), plus CodeRabbit nitpicks. Follow-up #1092 tracks generalizing the three hand-rolled chain watchers.
Closes #1032.
🤖 Generated with Claude Code