dig-slashing 0.1.0

Validator slashing, attestation participation, inactivity accounting, and fraud-proof appeals for the DIG Network L2 blockchain.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
//! Self-slashing protection for a single validator.
//!
//! Traces to: [SPEC §14](../docs/resources/SPEC.md), catalogue
//! rows
//! [DSL-094..101](../docs/requirements/domains/protection/specs/).
//!
//! # Role
//!
//! `SlashingProtection` is a per-validator local-state struct
//! that prevents a running validator from signing two
//! messages that would slash itself on restart / fork-choice
//! change. Lives on the validator's machine, not the chain —
//! purely advisory at the network level, but load-bearing at
//! the single-validator level.
//!
//! # Scope (incremental)
//!
//! Module grows one DSL at a time. First commit lands DSL-094
//! (proposal-slot monotonic check). Future DSLs add:
//!
//!   - DSL-095: attestation same-(src,tgt) different-hash check
//!   - DSL-096: would-surround self-check
//!   - DSL-097: `record_proposal` + `record_attestation`
//!     persistence
//!   - DSL-098: `rewind_attestation_to_epoch`
//!   - DSL-099/100/101: reorg, bootstrap, persistence details

use std::path::PathBuf;

use dig_protocol::Bytes32;
use serde::{Deserialize, Serialize};

/// Per-validator local slashing-protection state.
///
/// Implements [DSL-094](../docs/requirements/domains/protection/specs/DSL-094.md)
/// (+ DSL-095/096/097 in later commits). Traces to SPEC §14.
///
/// # Fields
///
/// - `last_proposed_slot` — largest slot the validator has
///   proposed at. `check_proposal_slot` requires a strictly
///   greater slot before signing a new proposal.
///
/// Future DSLs add `last_source_epoch`, `last_target_epoch`,
/// `attested_hash_by_target` and similar fields as their
/// guards come online.
///
/// # Default
///
/// `Default::default()` → `last_proposed_slot = 0`. Any slot
/// `> 0` passes `check_proposal_slot` on a fresh instance.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
pub struct SlashingProtection {
    /// Largest slot the validator has proposed at. Guards
    /// proposer-equivocation (DSL-094).
    last_proposed_slot: u64,
    /// `source.epoch` of the validator's last successful
    /// attestation. `0` on a fresh instance. Guards attester
    /// double-vote (DSL-095) + surround-vote (DSL-096).
    last_attested_source_epoch: u64,
    /// `target.epoch` of the validator's last successful
    /// attestation. `0` on a fresh instance.
    last_attested_target_epoch: u64,
    /// Block-root hex (`0x...` lowercase) of the validator's
    /// last successful attestation. `None` when no attestation
    /// has been recorded. Stored as a `String` so persistence
    /// (DSL-101) can round-trip via JSON without binary-blob
    /// plumbing.
    ///
    /// `#[serde(default)]` pins
    /// [DSL-100](../docs/requirements/domains/protection/specs/DSL-100.md)
    /// backwards compatibility: legacy on-disk JSON from the pre-
    /// hash schema deserialises with `last_attested_block_hash =
    /// None` instead of a hard "missing field" error, avoiding a
    /// "delete your state" migration step that would strip
    /// monotonic slashing-protection guarantees.
    #[serde(default)]
    last_attested_block_hash: Option<String>,
}

impl SlashingProtection {
    /// Construct with `last_proposed_slot = 0`.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Last slot at which the validator proposed. Used for
    /// introspection + persistence round-trips.
    #[must_use]
    pub fn last_proposed_slot(&self) -> u64 {
        self.last_proposed_slot
    }

    /// `true` iff the caller MAY sign a new proposal at `slot`.
    ///
    /// Implements [DSL-094](../docs/requirements/domains/protection/specs/DSL-094.md).
    ///
    /// # Predicate
    ///
    /// `slot > self.last_proposed_slot` — strict greater-than
    /// so the same slot cannot be signed twice (that would be
    /// the canonical proposer-equivocation offense).
    ///
    /// Fresh validators have `last_proposed_slot = 0`, so any
    /// slot `> 0` is safe to sign.
    #[must_use]
    pub fn check_proposal_slot(&self, slot: u64) -> bool {
        slot > self.last_proposed_slot
    }

    /// Record a successful proposal at `slot`. Subsequent
    /// `check_proposal_slot(s)` calls with `s <= slot` will
    /// return `false`.
    ///
    /// Implements [DSL-094](../docs/requirements/domains/protection/specs/DSL-094.md).
    /// Persistence semantics land in DSL-097.
    pub fn record_proposal(&mut self, slot: u64) {
        self.last_proposed_slot = slot;
    }

    /// `source.epoch` of the last recorded attestation.
    #[must_use]
    pub fn last_attested_source_epoch(&self) -> u64 {
        self.last_attested_source_epoch
    }

    /// `target.epoch` of the last recorded attestation.
    #[must_use]
    pub fn last_attested_target_epoch(&self) -> u64 {
        self.last_attested_target_epoch
    }

    /// Lowercase `0x`-prefixed hex of the last recorded
    /// attestation's block hash. `None` when no attestation
    /// has been recorded.
    #[must_use]
    pub fn last_attested_block_hash(&self) -> Option<&str> {
        self.last_attested_block_hash.as_deref()
    }

    /// `true` iff the caller MAY sign an attestation at
    /// `(source_epoch, target_epoch, block_hash)`.
    ///
    /// Implements DSL-095 (same-(src, tgt) different-hash
    /// self-check). DSL-096 (surround-vote self-check) extends
    /// this method in a later commit.
    ///
    /// # DSL-095 rule
    ///
    /// When the candidate FFG coordinates match the stored
    /// last-attested pair EXACTLY, the attestation is allowed
    /// only if the candidate block hash matches the stored
    /// hash (case-insensitive hex compare). This is the
    /// "re-sign the same vote" carve-out — a validator
    /// restarting mid-epoch may re-emit its own attestation,
    /// but may NOT switch to a different block at the same
    /// source/target pair (that would be an
    /// `AttesterDoubleVote`, DSL-014).
    ///
    /// If no prior attestation is stored (`last_attested_*
    /// = 0, None`), the check falls through to the surround
    /// guard (DSL-096 — currently a no-op stub) and returns
    /// `true`.
    #[must_use]
    pub fn check_attestation(
        &self,
        source_epoch: u64,
        target_epoch: u64,
        block_hash: &Bytes32,
    ) -> bool {
        // DSL-096: surround-vote self-check. Runs BEFORE the
        // DSL-095 same-coord check — a surround is slashable
        // regardless of the stored hash, so we short-circuit
        // cheaply. Mirrors the DSL-015 verify-side predicate.
        if self.would_surround(source_epoch, target_epoch) {
            return false;
        }

        // DSL-095: exact (source, target) coordinate collision.
        // The stored hash must be present AND match the
        // candidate case-insensitively; anything else is a
        // potential double-vote.
        if source_epoch == self.last_attested_source_epoch
            && target_epoch == self.last_attested_target_epoch
        {
            let candidate = to_hex_lower(block_hash.as_ref());
            match self.last_attested_block_hash.as_deref() {
                Some(stored) if stored.eq_ignore_ascii_case(&candidate) => {
                    // Re-sign the SAME vote is allowed.
                }
                _ => return false,
            }
        }
        true
    }

    /// Would the candidate attestation surround the stored
    /// one?
    ///
    /// Implements [DSL-096](../docs/requirements/domains/protection/specs/DSL-096.md).
    /// Traces to SPEC §14.2.
    ///
    /// # Predicate
    ///
    /// ```text
    /// candidate_source < self.last_attested_source_epoch
    ///   AND
    /// candidate_target > self.last_attested_target_epoch
    /// ```
    ///
    /// Both strict — a candidate matching either epoch exactly
    /// is NOT a surround (it is either a same-coord case
    /// (DSL-095) or a non-surround flank).
    #[must_use]
    fn would_surround(&self, candidate_source: u64, candidate_target: u64) -> bool {
        candidate_source < self.last_attested_source_epoch
            && candidate_target > self.last_attested_target_epoch
    }

    /// Record a successful attestation. Updates
    /// `last_attested_source_epoch`, `last_attested_target_epoch`
    /// and `last_attested_block_hash`.
    ///
    /// Implements the DSL-095/096 persistence primitive. DSL-097
    /// pins the full contract (including the proposer-side
    /// `record_proposal` companion).
    pub fn record_attestation(
        &mut self,
        source_epoch: u64,
        target_epoch: u64,
        block_hash: &Bytes32,
    ) {
        self.last_attested_source_epoch = source_epoch;
        self.last_attested_target_epoch = target_epoch;
        self.last_attested_block_hash = Some(to_hex_lower(block_hash.as_ref()));
    }

    /// Rewind the proposal watermark on fork-choice reorg.
    ///
    /// Previews [DSL-156](../docs/requirements/domains/protection/specs/DSL-156.md)
    /// — DSL-099 composes this fn alongside [`rewind_attestation_to_epoch`]
    /// (DSL-098) inside [`reconcile_with_chain_tip`]. The DSL-156
    /// dedicated test file lands in Phase 10.
    ///
    /// # Semantics
    ///
    /// Caps `last_proposed_slot` at `new_tip_slot` using strict `>`
    /// so the boundary (stored == tip) is a no-op and already-lower
    /// slots remain untouched. Reconcile must never RAISE a
    /// watermark — doing so would weaken slashing protection.
    ///
    /// No hash-equivalent to clear on the proposal side: DSL-094
    /// only tracks the slot, not a block binding.
    pub fn rewind_proposal_to_slot(&mut self, new_tip_slot: u64) {
        if self.last_proposed_slot > new_tip_slot {
            self.last_proposed_slot = new_tip_slot;
        }
    }

    /// Persist slashing-protection state to disk as pretty-printed
    /// JSON.
    ///
    /// Implements [DSL-101](../docs/requirements/domains/protection/specs/DSL-101.md).
    /// Traces to SPEC §14.4.
    ///
    /// # On-disk format
    ///
    /// JSON, pretty-printed for operator debuggability. All fields
    /// are primitive (`u64`) except `last_attested_block_hash`,
    /// which is stored as the canonical `0x<lowercase-hex>` form
    /// produced by [`record_attestation`]. External tooling that
    /// rewrites the hash to uppercase is tolerated on reload via
    /// [`check_attestation`]'s case-insensitive compare.
    ///
    /// # Errors
    ///
    /// Returns any I/O error raised by the underlying `std::fs`
    /// write. Serialization is infallible (every field is
    /// serde-safe by construction).
    ///
    /// # Companion [`load`](Self::load)
    ///
    /// The inverse of this call. `load` handles the missing-file
    /// case by returning `Self::default()` so a first-boot
    /// validator does not need a bootstrap branch.
    pub fn save(&self, path: &PathBuf) -> std::io::Result<()> {
        let json = serde_json::to_vec_pretty(self)
            .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
        std::fs::write(path, json)
    }

    /// Load slashing-protection state from disk.
    ///
    /// Implements [DSL-101](../docs/requirements/domains/protection/specs/DSL-101.md).
    ///
    /// # Behaviour
    ///
    /// - Path exists: decode the file via `serde_json::from_slice`.
    ///   Uses the same schema as `save`; DSL-100 handles legacy
    ///   JSON lacking `last_attested_block_hash` via
    ///   `#[serde(default)]` on that field.
    /// - Path does NOT exist: return `Self::default()`. This is
    ///   the intentional first-boot path — a validator with no
    ///   prior state calls `load` and gets a clean instance,
    ///   avoiding an explicit bootstrap branch at every call site.
    ///
    /// # Errors
    ///
    /// - `std::fs::read` errors (permission, I/O) propagate.
    /// - Deserialization errors surface as `InvalidData` via
    ///   `serde_json`. NOTE: a legitimate legacy file triggers
    ///   `#[serde(default)]`, not an error.
    pub fn load(path: &PathBuf) -> std::io::Result<Self> {
        if !path.exists() {
            return Ok(Self::default());
        }
        let bytes = std::fs::read(path)?;
        serde_json::from_slice(&bytes)
            .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))
    }

    /// Reconcile local slashing-protection state with the canonical
    /// chain tip on validator startup or after a reorg.
    ///
    /// Implements [DSL-099](../docs/requirements/domains/protection/specs/DSL-099.md).
    /// Traces to SPEC §14.3.
    ///
    /// # Semantics
    ///
    /// Composes [`rewind_proposal_to_slot`] (DSL-156) with
    /// [`rewind_attestation_to_epoch`] (DSL-098) under a single
    /// entry point. Net effect:
    ///
    ///   - `last_proposed_slot` capped at `tip_slot` (never raised).
    ///   - `last_attested_source_epoch` / `last_attested_target_epoch`
    ///     capped at `tip_epoch` (never raised).
    ///   - `last_attested_block_hash` cleared unconditionally —
    ///     the hash binds to a specific block that the reorg
    ///     invalidates.
    ///
    /// Idempotent by construction: both legs are caps, and a second
    /// call with the same `(tip_slot, tip_epoch)` finds the state
    /// already satisfying both caps.
    ///
    /// Called by:
    ///
    ///   - validator boot sequence (rejoin canonical chain after
    ///     downtime),
    ///   - [DSL-130](../../docs/requirements/domains/orchestration/specs/DSL-130.md)
    ///     global-reorg orchestration.
    pub fn reconcile_with_chain_tip(&mut self, tip_slot: u64, tip_epoch: u64) {
        self.rewind_proposal_to_slot(tip_slot);
        self.rewind_attestation_to_epoch(tip_epoch);
    }

    /// Rewind attestation state on fork-choice reorg or chain-tip
    /// refresh.
    ///
    /// Implements [DSL-098](../docs/requirements/domains/protection/specs/DSL-098.md).
    /// Traces to SPEC §14.3.
    ///
    /// # Semantics
    ///
    /// The stored (source, target, hash) triple is the validator's
    /// local memory of "what I already signed." When a reorg drops
    /// the chain back below the attested epochs, that memory is
    /// a ghost watermark — the block the hash points to no longer
    /// exists on the canonical chain. Keeping it would block honest
    /// re-attestation through DSL-095/096.
    ///
    /// Two legs:
    ///
    ///   1. Cap `last_attested_source_epoch` and
    ///      `last_attested_target_epoch` at `new_tip_epoch`. Use
    ///      strict `>` so the boundary case (stored == tip) is a
    ///      no-op — the cap must never RAISE a watermark, only
    ///      lower it.
    ///   2. Clear `last_attested_block_hash` unconditionally. The
    ///      hash binds to a specific block; a reorg invalidates
    ///      that binding regardless of epoch ordering.
    ///
    /// After rewind, a re-attestation on the new canonical tip
    /// passes [`check_attestation`].
    ///
    /// Companion DSL-099 (`reconcile_with_chain_tip`) calls this
    /// alongside the proposal-rewind DSL-156; DSL-130 triggers the
    /// whole bundle on global reorg.
    pub fn rewind_attestation_to_epoch(&mut self, new_tip_epoch: u64) {
        if self.last_attested_source_epoch > new_tip_epoch {
            self.last_attested_source_epoch = new_tip_epoch;
        }
        if self.last_attested_target_epoch > new_tip_epoch {
            self.last_attested_target_epoch = new_tip_epoch;
        }
        self.last_attested_block_hash = None;
    }
}

/// Fixed-size lowercase hex encoder with `0x` prefix. Matches
/// Ethereum JSON convention used by validator-key management
/// tooling — keeps the on-disk format portable across clients.
fn to_hex_lower(bytes: &[u8]) -> String {
    const HEX: &[u8; 16] = b"0123456789abcdef";
    let mut out = String::with_capacity(2 + bytes.len() * 2);
    out.push_str("0x");
    for &b in bytes {
        out.push(HEX[(b >> 4) as usize] as char);
        out.push(HEX[(b & 0x0F) as usize] as char);
    }
    out
}