dig-block 0.1.0

DIG L2 block format, production, and validation
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
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
//! `L2BlockHeader` — independently hashable L2 block metadata and commitments.
//!
//! **Requirements:**
//! - [BLK-001](docs/requirements/domains/block_types/specs/BLK-001.md) — field groups /
//!   [NORMATIVE § BLK-001](docs/requirements/domains/block_types/NORMATIVE.md#blk-001-l2blockheader-struct)
//! - [BLK-002](docs/requirements/domains/block_types/specs/BLK-002.md) — constructors /
//!   [NORMATIVE § BLK-002](docs/requirements/domains/block_types/NORMATIVE.md#blk-002-l2blockheader-constructors)
//! - [BLK-007](docs/requirements/domains/block_types/specs/BLK-007.md) — version auto-detection /
//!   [NORMATIVE](docs/requirements/domains/block_types/NORMATIVE.md) (BLK-007)
//! - [SVL-001](docs/requirements/domains/structural_validation/specs/SVL-001.md) — header `version` vs height / DFSP activation ([`L2BlockHeader::validate`])
//! - [SVL-002](docs/requirements/domains/structural_validation/specs/SVL-002.md) — DFSP roots must be [`EMPTY_ROOT`] before activation ([`L2BlockHeader::validate_with_dfsp_activation`])
//! - [SVL-003](docs/requirements/domains/structural_validation/specs/SVL-003.md) — declared [`L2BlockHeader::total_cost`] / [`L2BlockHeader::block_size`] vs protocol caps ([`crate::MAX_COST_PER_BLOCK`], [`crate::MAX_BLOCK_SIZE`])
//! - [SVL-004](docs/requirements/domains/structural_validation/specs/SVL-004.md) — [`L2BlockHeader::timestamp`] vs wall clock + [`crate::MAX_FUTURE_TIMESTAMP_SECONDS`]; production [`validate`]/[`L2BlockHeader::validate_with_dfsp_activation`], tests [`L2BlockHeader::validate_with_dfsp_activation_at_unix`]
//! - [HSH-001](docs/requirements/domains/hashing/specs/HSH-001.md) — header `hash()` (SPEC §3.1 field order;
//!   preimage length [`L2BlockHeader::HASH_PREIMAGE_LEN`])
//! - [SER-002](docs/requirements/domains/serialization/specs/SER-002.md) — [`L2BlockHeader::to_bytes`] / [`L2BlockHeader::from_bytes`] (SPEC §8.2; bincode + [`BlockError::InvalidData`](crate::BlockError::InvalidData) on decode)
//! - [SER-003](docs/requirements/domains/serialization/specs/SER-003.md) — [`L2BlockHeader::genesis`] deterministic bootstrap (SPEC §8.3; see NORMATIVE § SER-003)
//! - [SPEC §2.2](docs/resources/SPEC.md), [SPEC §8.3 Genesis](docs/resources/SPEC.md#83-genesis-block)
//!
//! ## Usage
//!
//! Prefer [`L2BlockHeader::new`], [`L2BlockHeader::new_with_collateral`], [`L2BlockHeader::new_with_l1_proofs`],
//! or [`L2BlockHeader::genesis`] so **`version` is never caller-supplied** (auto-detected from `height`;
//! shared rules in [`L2BlockHeader::protocol_version_for_height`] and
//! [`L2BlockHeader::protocol_version_for_height_with_activation`] (BLK-007). Production code
//! that needs wall-clock timestamps should set `timestamp` after `new()` or use [`crate::builder::BlockBuilder`]
//! (BLD-005): [`L2BlockHeader::new`] leaves `timestamp` at **0** per SPEC’s derived-`new()` parameter list.
//!
//! Field order matches SPEC §2.2 so **bincode** layout stays deterministic (SER-001, HSH-001). Canonical
//! encode/decode helpers live on [`L2BlockHeader::to_bytes`] / [`L2BlockHeader::from_bytes`] (SER-002).
//!
//! ## Rationale
//!
//! Splitting header from body ([`super::block::L2Block`], BLK-003) mirrors an Ethereum-style header/body
//! split: attestations and light clients can process headers without deserializing `SpendBundle` payloads.
//!
//! ## Decisions
//!
//! - **`Bytes32`** and **`Cost`** come from [`crate::primitives`] so this crate has one type identity for
//!   hashes and CLVM cost (BLK-006).
//! - **L1 proof anchors** are `Option<Bytes32>`; omitted proofs serialize as `None` (default) per SPEC.
//! - **DFSP roots** are mandatory `Bytes32` fields; pre-activation they are set to [`crate::EMPTY_ROOT`]
//!   by constructors / validation (SVL-002), not by the type itself.

use std::time::{SystemTime, UNIX_EPOCH};

use chia_sha2::Sha256;
use chia_streamable_macro::Streamable;
use serde::{Deserialize, Serialize};

use crate::constants::{
    DFSP_ACTIVATION_HEIGHT, EMPTY_ROOT, MAX_BLOCK_SIZE, MAX_COST_PER_BLOCK,
    MAX_FUTURE_TIMESTAMP_SECONDS, ZERO_HASH,
};
use crate::error::BlockError;
use crate::primitives::{Bytes32, Cost, VERSION_V1, VERSION_V2};

/// DIG L2 block header: identity, Merkle commitments, L1 anchor, metadata, optional L1 proofs, slash
/// proposal commitments, and DFSP data-layer roots.
///
/// Field layout and semantics follow SPEC §2.2 table **Field groups**; keep this definition in sync with
/// that section when the wire format evolves.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Streamable)]
pub struct L2BlockHeader {
    // ── Core identity ──
    /// Protocol version (`VERSION_V1` / `VERSION_V2`; BLK-007 selects from height).
    pub version: u16,
    /// Block height (genesis = 0).
    pub height: u64,
    /// Epoch number.
    pub epoch: u64,
    /// Hash of the parent block header.
    pub parent_hash: Bytes32,

    // ── State commitments ──
    /// CoinSet / state Merkle root after this block.
    pub state_root: Bytes32,
    /// Merkle root of spend-bundle hashes.
    pub spends_root: Bytes32,
    /// Merkle root of additions (Chia-style grouping by `puzzle_hash`).
    pub additions_root: Bytes32,
    /// Merkle root of removed coin IDs.
    pub removals_root: Bytes32,
    /// Merkle root of execution receipts.
    pub receipts_root: Bytes32,

    // ── L1 anchor ──
    /// Chia L1 block height this L2 block references.
    pub l1_height: u32,
    /// Chia L1 block hash.
    pub l1_hash: Bytes32,

    // ── Block metadata ──
    /// Unix timestamp (seconds).
    pub timestamp: u64,
    /// Proposer validator index.
    pub proposer_index: u32,
    /// Number of spend bundles in the block body.
    pub spend_bundle_count: u32,
    /// Aggregate CLVM cost of all spends in the block.
    pub total_cost: Cost,
    /// Total fees (value in − value out).
    pub total_fees: u64,
    /// Number of coin additions.
    pub additions_count: u32,
    /// Number of coin removals.
    pub removals_count: u32,
    /// Serialized full block size in bytes (header + body).
    pub block_size: u32,
    /// BIP158-style compact block filter hash.
    pub filter_hash: Bytes32,
    /// Reserved extension field (SPEC: default `ZERO_HASH` in constructors).
    pub extension_data: Bytes32,

    // ── L1 proof anchors ──
    /// Proposer L1 collateral proof coin id.
    #[serde(default)]
    pub l1_collateral_coin_id: Option<Bytes32>,
    /// Network validator collateral set anchor.
    #[serde(default)]
    pub l1_reserve_coin_id: Option<Bytes32>,
    /// Previous epoch finalization proof.
    #[serde(default)]
    pub l1_prev_epoch_finalizer_coin_id: Option<Bytes32>,
    /// Current epoch finalizer state.
    #[serde(default)]
    pub l1_curr_epoch_finalizer_coin_id: Option<Bytes32>,
    /// Network singleton existence proof.
    #[serde(default)]
    pub l1_network_coin_id: Option<Bytes32>,

    // ── Slash proposals ──
    /// Number of slash proposal payloads in the body.
    pub slash_proposal_count: u32,
    /// Merkle root over per-proposal hashes.
    pub slash_proposals_root: Bytes32,

    // ── DFSP data layer roots ──
    /// Collateral registry sparse Merkle root.
    pub collateral_registry_root: Bytes32,
    /// CID lifecycle state machine root.
    pub cid_state_root: Bytes32,
    /// Node registry sparse Merkle root.
    pub node_registry_root: Bytes32,
    /// Namespace update delta root for this block.
    pub namespace_update_root: Bytes32,
    /// DFSP epoch-boundary commitment digest.
    pub dfsp_finalize_commitment_root: Bytes32,
}

impl L2BlockHeader {
    /// Protocol version for `height` given an explicit DFSP activation height (BLK-007).
    ///
    /// **Rules:** If `dfsp_activation_height == u64::MAX` (DFSP disabled sentinel), returns [`VERSION_V1`].
    /// Otherwise returns [`VERSION_V2`] when `height >= dfsp_activation_height`, else [`VERSION_V1`].
    ///
    /// **Rationale:** Parameterizing activation height lets tests cover pre/post-fork behavior without
    /// recompiling [`DFSP_ACTIVATION_HEIGHT`](crate::constants::DFSP_ACTIVATION_HEIGHT). Production code
    /// should call [`Self::protocol_version_for_height`] instead.
    #[inline]
    pub fn protocol_version_for_height_with_activation(
        height: u64,
        dfsp_activation_height: u64,
    ) -> u16 {
        if dfsp_activation_height == u64::MAX {
            VERSION_V1
        } else if height >= dfsp_activation_height {
            VERSION_V2
        } else {
            VERSION_V1
        }
    }

    /// Protocol version for `height` using the crate’s [`DFSP_ACTIVATION_HEIGHT`] constant.
    #[inline]
    pub fn protocol_version_for_height(height: u64) -> u16 {
        Self::protocol_version_for_height_with_activation(height, DFSP_ACTIVATION_HEIGHT)
    }

    /// Sample `SystemTime::now()` as whole Unix seconds for [`Self::validate_with_dfsp_activation`].
    ///
    /// **Rationale:** SVL-004 needs a monotonic-ish wall clock; if the host clock is before 1970, validation cannot
    /// define “future” sensibly — we surface [`BlockError::InvalidData`] rather than panicking.
    fn unix_secs_wall_clock() -> Result<u64, BlockError> {
        SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .map(|d| d.as_secs())
            .map_err(|_| {
                BlockError::InvalidData(
                    "system clock before UNIX epoch; cannot validate header timestamp".into(),
                )
            })
    }

    /// Tier-1 header checks **SVL-001 through SVL-004** with an explicit DFSP activation height **and** a fixed
    /// `now_secs` reference for the timestamp bound ([SVL-004](docs/requirements/domains/structural_validation/specs/SVL-004.md)).
    ///
    /// **SVL-001 / SPEC §5.1 Step 1:** [`L2BlockHeader::version`] must match [`Self::protocol_version_for_height_with_activation`]
    /// for [`L2BlockHeader::height`] and `dfsp_activation_height`; else [`BlockError::InvalidVersion`].
    ///
    /// **SVL-002 / SPEC §5.1 Step 2:** when `height < dfsp_activation_height`, all five DFSP roots must equal [`EMPTY_ROOT`];
    /// else [`BlockError::InvalidData`] (fixed message per [SVL-002 spec](docs/requirements/domains/structural_validation/specs/SVL-002.md)).
    ///
    /// **SVL-003 / SPEC §5.1 Steps 3–4:** `total_cost > `[`MAX_COST_PER_BLOCK`] ⇒ [`BlockError::CostExceeded`]; then
    /// `block_size > `[`MAX_BLOCK_SIZE`] ⇒ [`BlockError::TooLarge`] ([SVL-003 spec](docs/requirements/domains/structural_validation/specs/SVL-003.md)).
    ///
    /// **SVL-004 / SPEC §5.1 Step 5:** let `max_allowed = now_secs + `[`MAX_FUTURE_TIMESTAMP_SECONDS`]. If
    /// `timestamp > max_allowed`, reject with [`BlockError::TimestampTooFarInFuture`] (Chia `block_header_validation.py`
    /// Check 26a analogue). **Strict `>`:** `timestamp == max_allowed` is accepted.
    ///
    /// **Usage:** Production should call [`Self::validate`] or [`Self::validate_with_dfsp_activation`] (wall-clock `now`).
    /// Integration tests call **this** method with a synthetic `now_secs` so boundary arithmetic is deterministic
    /// ([SVL-004 spec — Implementation Notes](docs/requirements/domains/structural_validation/specs/SVL-004.md)).
    pub fn validate_with_dfsp_activation_at_unix(
        &self,
        dfsp_activation_height: u64,
        now_secs: u64,
    ) -> Result<(), BlockError> {
        let expected =
            Self::protocol_version_for_height_with_activation(self.height, dfsp_activation_height);
        if self.version != expected {
            return Err(BlockError::InvalidVersion {
                expected,
                actual: self.version,
            });
        }
        if self.height < dfsp_activation_height {
            let dfsp_roots = [
                self.collateral_registry_root,
                self.cid_state_root,
                self.node_registry_root,
                self.namespace_update_root,
                self.dfsp_finalize_commitment_root,
            ];
            for root in &dfsp_roots {
                if *root != EMPTY_ROOT {
                    return Err(BlockError::InvalidData(
                        "DFSP root must be EMPTY_ROOT before activation".into(),
                    ));
                }
            }
        }
        // SVL-003: strict `>` so values exactly at the limit pass (spec acceptance + ERR-001 semantics).
        if self.total_cost > MAX_COST_PER_BLOCK {
            return Err(BlockError::CostExceeded {
                cost: self.total_cost,
                max: MAX_COST_PER_BLOCK,
            });
        }
        if self.block_size > MAX_BLOCK_SIZE {
            return Err(BlockError::TooLarge {
                size: self.block_size,
                max: MAX_BLOCK_SIZE,
            });
        }
        let max_allowed = now_secs.saturating_add(MAX_FUTURE_TIMESTAMP_SECONDS);
        if self.timestamp > max_allowed {
            return Err(BlockError::TimestampTooFarInFuture {
                timestamp: self.timestamp,
                max_allowed,
            });
        }
        Ok(())
    }

    /// Same as [`Self::validate_with_dfsp_activation_at_unix`] after sampling the host wall clock ([`Self::unix_secs_wall_clock`]).
    ///
    /// **Rationale:** Parameterizing `dfsp_activation_height` mirrors SVL-001 so integration tests can inject a finite
    /// fork height; production uses [`Self::validate`] → [`DFSP_ACTIVATION_HEIGHT`](crate::constants::DFSP_ACTIVATION_HEIGHT).
    /// With the BLK-005 sentinel `u64::MAX`, every finite `height` satisfies `height < u64::MAX`, so DFSP payloads cannot
    /// appear on-chain until governance lowers the constant.
    ///
    /// **SVL-004:** Uses real `SystemTime` for `now_secs`. For deterministic timestamp tests, call
    /// [`Self::validate_with_dfsp_activation_at_unix`] directly.
    pub fn validate_with_dfsp_activation(
        &self,
        dfsp_activation_height: u64,
    ) -> Result<(), BlockError> {
        let now_secs = Self::unix_secs_wall_clock()?;
        self.validate_with_dfsp_activation_at_unix(dfsp_activation_height, now_secs)
    }

    /// Tier 1 header structural validation using crate-wide constants ([SVL-*](docs/requirements/domains/structural_validation/NORMATIVE.md)).
    ///
    /// **Current steps:** [SVL-001](docs/requirements/domains/structural_validation/specs/SVL-001.md) (version),
    /// [SVL-002](docs/requirements/domains/structural_validation/specs/SVL-002.md) (DFSP roots before activation),
    /// [SVL-003](docs/requirements/domains/structural_validation/specs/SVL-003.md) (cost/size caps on declared header fields),
    /// [SVL-004](docs/requirements/domains/structural_validation/specs/SVL-004.md) (timestamp vs wall clock + [`MAX_FUTURE_TIMESTAMP_SECONDS`]).
    pub fn validate(&self) -> Result<(), BlockError> {
        self.validate_with_dfsp_activation(DFSP_ACTIVATION_HEIGHT)?;
        Ok(())
    }

    /// Byte length of the fixed preimage fed to [`Self::hash`] (all 33 rows of [SPEC §3.1](docs/resources/SPEC.md)).
    ///
    /// **Accounting:** 20×[`Bytes32`] fields + `u16` + 6×`u64` + 7×`u32` = 640 + 70 = **710** bytes.
    /// The SPEC prose once said “626 bytes”; summing the §3.1 table yields **710** — this constant is authoritative for code.
    pub const HASH_PREIMAGE_LEN: usize = 710;

    /// Serialize the exact **710-byte** preimage for [HSH-001](docs/requirements/domains/hashing/specs/HSH-001.md) /
    /// [SPEC §3.1](docs/resources/SPEC.md) (same order as [`Self::hash`]).
    ///
    /// **Usage:** Tests and debug tooling can diff preimages without re-deriving field order; [`Self::hash`] is
    /// `SHA-256(self.hash_preimage_bytes())`.
    ///
    /// **Optionals:** Each `Option<Bytes32>` occupies 32 bytes: [`ZERO_HASH`] when `None`, raw bytes when `Some`.
    pub fn hash_preimage_bytes(&self) -> [u8; Self::HASH_PREIMAGE_LEN] {
        fn put(buf: &mut [u8; L2BlockHeader::HASH_PREIMAGE_LEN], i: &mut usize, bytes: &[u8]) {
            buf[*i..*i + bytes.len()].copy_from_slice(bytes);
            *i += bytes.len();
        }
        fn put_opt(
            buf: &mut [u8; L2BlockHeader::HASH_PREIMAGE_LEN],
            i: &mut usize,
            o: &Option<Bytes32>,
        ) {
            let slice = match o {
                Some(b) => b.as_ref(),
                None => ZERO_HASH.as_ref(),
            };
            buf[*i..*i + 32].copy_from_slice(slice);
            *i += 32;
        }
        let mut buf = [0u8; Self::HASH_PREIMAGE_LEN];
        let mut i = 0usize;
        put(&mut buf, &mut i, &self.version.to_le_bytes());
        put(&mut buf, &mut i, &self.height.to_le_bytes());
        put(&mut buf, &mut i, &self.epoch.to_le_bytes());
        put(&mut buf, &mut i, self.parent_hash.as_ref());
        put(&mut buf, &mut i, self.state_root.as_ref());
        put(&mut buf, &mut i, self.spends_root.as_ref());
        put(&mut buf, &mut i, self.additions_root.as_ref());
        put(&mut buf, &mut i, self.removals_root.as_ref());
        put(&mut buf, &mut i, self.receipts_root.as_ref());
        put(&mut buf, &mut i, &self.l1_height.to_le_bytes());
        put(&mut buf, &mut i, self.l1_hash.as_ref());
        put(&mut buf, &mut i, &self.timestamp.to_le_bytes());
        put(&mut buf, &mut i, &self.proposer_index.to_le_bytes());
        put(&mut buf, &mut i, &self.spend_bundle_count.to_le_bytes());
        put(&mut buf, &mut i, &self.total_cost.to_le_bytes());
        put(&mut buf, &mut i, &self.total_fees.to_le_bytes());
        put(&mut buf, &mut i, &self.additions_count.to_le_bytes());
        put(&mut buf, &mut i, &self.removals_count.to_le_bytes());
        put(&mut buf, &mut i, &self.block_size.to_le_bytes());
        put(&mut buf, &mut i, self.filter_hash.as_ref());
        put(&mut buf, &mut i, self.extension_data.as_ref());
        put_opt(&mut buf, &mut i, &self.l1_collateral_coin_id);
        put_opt(&mut buf, &mut i, &self.l1_reserve_coin_id);
        put_opt(&mut buf, &mut i, &self.l1_prev_epoch_finalizer_coin_id);
        put_opt(&mut buf, &mut i, &self.l1_curr_epoch_finalizer_coin_id);
        put_opt(&mut buf, &mut i, &self.l1_network_coin_id);
        put(&mut buf, &mut i, &self.slash_proposal_count.to_le_bytes());
        put(&mut buf, &mut i, self.slash_proposals_root.as_ref());
        put(&mut buf, &mut i, self.collateral_registry_root.as_ref());
        put(&mut buf, &mut i, self.cid_state_root.as_ref());
        put(&mut buf, &mut i, self.node_registry_root.as_ref());
        put(&mut buf, &mut i, self.namespace_update_root.as_ref());
        put(
            &mut buf,
            &mut i,
            self.dfsp_finalize_commitment_root.as_ref(),
        );
        debug_assert_eq!(i, Self::HASH_PREIMAGE_LEN);
        buf
    }

    /// Canonical block identity: SHA-256 over [`Self::hash_preimage_bytes`] ([HSH-001](docs/requirements/domains/hashing/specs/HSH-001.md)).
    ///
    /// **Requirement:** [SPEC §3.1](docs/resources/SPEC.md). Numeric fields are little-endian; each optional L1 anchor
    /// contributes 32 bytes of raw [`Bytes32`] or [`ZERO_HASH`] when `None` (malleability-safe encoding).
    ///
    /// **Primitive:** [`chia_sha2::Sha256`] only ([`crate::primitives`] / project crypto rules).
    pub fn hash(&self) -> Bytes32 {
        let mut hasher = Sha256::new();
        hasher.update(self.hash_preimage_bytes());
        Bytes32::new(hasher.finalize())
    }

    /// Serialize this header to **bincode** bytes for wire / storage ([SER-002](docs/requirements/domains/serialization/specs/SER-002.md),
    /// [NORMATIVE § SER-002](docs/requirements/domains/serialization/NORMATIVE.md#ser-002-to_bytes-and-from_bytes-conventions), SPEC §8.2).
    ///
    /// **Infallible:** Uses [`Result::expect`] because an in-memory, well-formed [`L2BlockHeader`] should always serialize
    /// with the crate’s serde schema; a panic indicates programmer error or schema drift, not recoverable I/O.
    #[must_use]
    pub fn to_bytes(&self) -> Vec<u8> {
        bincode::serialize(self).expect("L2BlockHeader serialization should never fail")
    }

    /// Deserialize a header from **bincode** bytes ([SER-002](docs/requirements/domains/serialization/specs/SER-002.md)).
    ///
    /// **Errors:** Any `bincode` failure maps to [`BlockError::InvalidData`] (message includes the decoder error) —
    /// covers empty input, truncated payloads, corrupted bytes, and schema mismatches.
    pub fn from_bytes(bytes: &[u8]) -> Result<Self, BlockError> {
        bincode::deserialize(bytes).map_err(|e| BlockError::InvalidData(e.to_string()))
    }

    /// Standard header constructor (SPEC §2.2 **Derived methods** / `new()`).
    ///
    /// Sets `version` via [`Self::protocol_version_for_height`]; `timestamp` to **0** (SPEC omits it from
    /// the `new` parameter list—set explicitly or use [`Self::genesis`] / block builder for wall clock);
    /// L1 proof anchors to `None`; slash summary to empty; DFSP roots to [`EMPTY_ROOT`]; `extension_data`
    /// to [`ZERO_HASH`].
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        height: u64,
        epoch: u64,
        parent_hash: Bytes32,
        state_root: Bytes32,
        spends_root: Bytes32,
        additions_root: Bytes32,
        removals_root: Bytes32,
        receipts_root: Bytes32,
        l1_height: u32,
        l1_hash: Bytes32,
        proposer_index: u32,
        spend_bundle_count: u32,
        total_cost: Cost,
        total_fees: u64,
        additions_count: u32,
        removals_count: u32,
        block_size: u32,
        filter_hash: Bytes32,
    ) -> Self {
        Self::with_l1_anchors(
            height,
            epoch,
            parent_hash,
            state_root,
            spends_root,
            additions_root,
            removals_root,
            receipts_root,
            l1_height,
            l1_hash,
            0,
            proposer_index,
            spend_bundle_count,
            total_cost,
            total_fees,
            additions_count,
            removals_count,
            block_size,
            filter_hash,
            ZERO_HASH,
            None,
            None,
            None,
            None,
            None,
            0,
            EMPTY_ROOT,
            EMPTY_ROOT,
            EMPTY_ROOT,
            EMPTY_ROOT,
            EMPTY_ROOT,
            EMPTY_ROOT,
        )
    }

    /// Like [`Self::new`] but sets [`L2BlockHeader::l1_collateral_coin_id`] to the given proof coin id.
    #[allow(clippy::too_many_arguments)]
    pub fn new_with_collateral(
        height: u64,
        epoch: u64,
        parent_hash: Bytes32,
        state_root: Bytes32,
        spends_root: Bytes32,
        additions_root: Bytes32,
        removals_root: Bytes32,
        receipts_root: Bytes32,
        l1_height: u32,
        l1_hash: Bytes32,
        proposer_index: u32,
        spend_bundle_count: u32,
        total_cost: Cost,
        total_fees: u64,
        additions_count: u32,
        removals_count: u32,
        block_size: u32,
        filter_hash: Bytes32,
        l1_collateral_coin_id: Bytes32,
    ) -> Self {
        Self::with_l1_anchors(
            height,
            epoch,
            parent_hash,
            state_root,
            spends_root,
            additions_root,
            removals_root,
            receipts_root,
            l1_height,
            l1_hash,
            0,
            proposer_index,
            spend_bundle_count,
            total_cost,
            total_fees,
            additions_count,
            removals_count,
            block_size,
            filter_hash,
            ZERO_HASH,
            Some(l1_collateral_coin_id),
            None,
            None,
            None,
            None,
            0,
            EMPTY_ROOT,
            EMPTY_ROOT,
            EMPTY_ROOT,
            EMPTY_ROOT,
            EMPTY_ROOT,
            EMPTY_ROOT,
        )
    }

    /// Full L1 proof anchor set (SPEC field order: collateral, reserve, prev/curr finalizer, network coin).
    #[allow(clippy::too_many_arguments)]
    pub fn new_with_l1_proofs(
        height: u64,
        epoch: u64,
        parent_hash: Bytes32,
        state_root: Bytes32,
        spends_root: Bytes32,
        additions_root: Bytes32,
        removals_root: Bytes32,
        receipts_root: Bytes32,
        l1_height: u32,
        l1_hash: Bytes32,
        proposer_index: u32,
        spend_bundle_count: u32,
        total_cost: Cost,
        total_fees: u64,
        additions_count: u32,
        removals_count: u32,
        block_size: u32,
        filter_hash: Bytes32,
        l1_collateral_coin_id: Bytes32,
        l1_reserve_coin_id: Bytes32,
        l1_prev_epoch_finalizer_coin_id: Bytes32,
        l1_curr_epoch_finalizer_coin_id: Bytes32,
        l1_network_coin_id: Bytes32,
    ) -> Self {
        Self::with_l1_anchors(
            height,
            epoch,
            parent_hash,
            state_root,
            spends_root,
            additions_root,
            removals_root,
            receipts_root,
            l1_height,
            l1_hash,
            0,
            proposer_index,
            spend_bundle_count,
            total_cost,
            total_fees,
            additions_count,
            removals_count,
            block_size,
            filter_hash,
            ZERO_HASH,
            Some(l1_collateral_coin_id),
            Some(l1_reserve_coin_id),
            Some(l1_prev_epoch_finalizer_coin_id),
            Some(l1_curr_epoch_finalizer_coin_id),
            Some(l1_network_coin_id),
            0,
            EMPTY_ROOT,
            EMPTY_ROOT,
            EMPTY_ROOT,
            EMPTY_ROOT,
            EMPTY_ROOT,
            EMPTY_ROOT,
        )
    }

    /// Genesis header ([SER-003](docs/requirements/domains/serialization/specs/SER-003.md), [NORMATIVE § SER-003](docs/requirements/domains/serialization/NORMATIVE.md#ser-003-genesis-block-construction), SPEC §8.3).
    ///
    /// ## Field obligations
    ///
    /// - **`height` / `epoch`:** `0` — chain bootstrap position.
    /// - **`parent_hash`:** `network_id` — there is no prior L2 block; binding the parent slot to the network identity
    ///   blocks cross-network replay of height-0 material ([SER-003](docs/requirements/domains/serialization/specs/SER-003.md) summary).
    /// - **Merkle / commitment roots:** [`EMPTY_ROOT`](crate::EMPTY_ROOT) for state, spends, additions, removals, receipts,
    ///   filter, slash proposals, and all DFSP layer roots; [`ZERO_HASH`](crate::ZERO_HASH) for `extension_data` (opaque
    ///   extension slot starts empty).
    /// - **Counts / costs / size:** all zero; **L1 anchor options:** all [`None`]; **slash count:** `0`.
    /// - **`l1_height` / `l1_hash`:** caller-supplied L1 observation the genesis L2 header is anchored to.
    /// - **`version`:** [`Self::protocol_version_for_height`](Self::protocol_version_for_height)(`0`) — same BLK-007
    ///   auto-detection as every other constructor (not `CARGO_PKG_VERSION`; see SER-003 spec errata vs older pseudocode).
    ///
    /// **`timestamp`:** wall-clock Unix seconds from [`SystemTime::now`]. Host clocks before 1970 cannot be represented;
    /// we **panic** with a clear message (same contract as “real” wall time for genesis in SPEC §8.3).
    pub fn genesis(network_id: Bytes32, l1_height: u32, l1_hash: Bytes32) -> Self {
        let timestamp = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .expect("system clock before UNIX epoch; genesis header requires wall-clock time")
            .as_secs();
        let height = 0u64;
        Self::with_l1_anchors(
            height, 0, network_id, EMPTY_ROOT, EMPTY_ROOT, EMPTY_ROOT, EMPTY_ROOT, EMPTY_ROOT,
            l1_height, l1_hash, timestamp, 0, 0, 0, 0, 0, 0, 0, EMPTY_ROOT, ZERO_HASH, None, None,
            None, None, None, 0, EMPTY_ROOT, EMPTY_ROOT, EMPTY_ROOT, EMPTY_ROOT, EMPTY_ROOT,
            EMPTY_ROOT,
        )
    }

    #[allow(clippy::too_many_arguments)]
    fn with_l1_anchors(
        height: u64,
        epoch: u64,
        parent_hash: Bytes32,
        state_root: Bytes32,
        spends_root: Bytes32,
        additions_root: Bytes32,
        removals_root: Bytes32,
        receipts_root: Bytes32,
        l1_height: u32,
        l1_hash: Bytes32,
        timestamp: u64,
        proposer_index: u32,
        spend_bundle_count: u32,
        total_cost: Cost,
        total_fees: u64,
        additions_count: u32,
        removals_count: u32,
        block_size: u32,
        filter_hash: Bytes32,
        extension_data: Bytes32,
        l1_collateral_coin_id: Option<Bytes32>,
        l1_reserve_coin_id: Option<Bytes32>,
        l1_prev_epoch_finalizer_coin_id: Option<Bytes32>,
        l1_curr_epoch_finalizer_coin_id: Option<Bytes32>,
        l1_network_coin_id: Option<Bytes32>,
        slash_proposal_count: u32,
        slash_proposals_root: Bytes32,
        collateral_registry_root: Bytes32,
        cid_state_root: Bytes32,
        node_registry_root: Bytes32,
        namespace_update_root: Bytes32,
        dfsp_finalize_commitment_root: Bytes32,
    ) -> Self {
        Self {
            version: Self::protocol_version_for_height(height),
            height,
            epoch,
            parent_hash,
            state_root,
            spends_root,
            additions_root,
            removals_root,
            receipts_root,
            l1_height,
            l1_hash,
            timestamp,
            proposer_index,
            spend_bundle_count,
            total_cost,
            total_fees,
            additions_count,
            removals_count,
            block_size,
            filter_hash,
            extension_data,
            l1_collateral_coin_id,
            l1_reserve_coin_id,
            l1_prev_epoch_finalizer_coin_id,
            l1_curr_epoch_finalizer_coin_id,
            l1_network_coin_id,
            slash_proposal_count,
            slash_proposals_root,
            collateral_registry_root,
            cid_state_root,
            node_registry_root,
            namespace_update_root,
            dfsp_finalize_commitment_root,
        }
    }
}