Skip to main content

dig_block/
lib.rs

1//! # `dig-block` — DIG L2 block format, production, and validation
2//!
3//! `dig-block` is a self-contained Rust library for the DIG Network L2 blockchain. It owns three
4//! concerns in one crate:
5//!
6//! 1. **Block format** — type definitions for [`L2BlockHeader`], [`L2Block`], [`AttestedBlock`],
7//!    [`Checkpoint`], [`CheckpointSubmission`], and supporting types ([SPEC §2](docs/resources/SPEC.md)).
8//! 2. **Block production** — [`BlockBuilder`] and [`CheckpointBuilder`] construct structurally
9//!    valid blocks and epoch summaries from their inputs ([SPEC §6](docs/resources/SPEC.md)).
10//! 3. **Block validation** — a three-tier pipeline (structural / execution / state) rejects any
11//!    block that does not match consensus rules ([SPEC §5, §7](docs/resources/SPEC.md)).
12//!
13//! ## Scope
14//!
15//! The crate operates on **single, isolated blocks**. External state (coin existence, chain tip,
16//! wall-clock time, validator set) is injected through two traits:
17//!
18//! - [`CoinLookup`] — coin-set queries for Tier-3 state validation.
19//! - [`BlockSigner`] — proposer signing hook for block production.
20//!
21//! `dig-block` never reads from a database, never makes network calls, and never maintains state
22//! across blocks ([SPEC §11](docs/resources/SPEC.md)). Downstream crates (`dig-coinstore`,
23//! `dig-epoch`, `dig-gossip`) provide the trait implementations, storage, chain management, and
24//! networking.
25//!
26//! ## Quickstart — build a block
27//!
28//! ```no_run
29//! use dig_block::{BlockBuilder, BlockSigner, Bytes32, Signature};
30//! use dig_block::traits::SignerError;
31//!
32//! // 1. Implement BlockSigner for your key material (or use a test mock).
33//! struct MySigner;
34//! impl BlockSigner for MySigner {
35//!     fn sign_block(&self, _header_hash: &Bytes32) -> Result<Signature, SignerError> {
36//!         Ok(Signature::default())
37//!     }
38//! }
39//!
40//! // 2. Construct a builder anchored to the chain / L1 context.
41//! let parent_hash = Bytes32::default();
42//! let l1_hash = Bytes32::default();
43//! let mut builder = BlockBuilder::new(/*height=*/ 1, /*epoch=*/ 0, parent_hash, 100, l1_hash, 0);
44//!
45//! // 3. (Optional) add spend bundles via builder.add_spend_bundle(...).
46//! // 4. Build a signed L2Block.
47//! let state_root = Bytes32::default();
48//! let receipts_root = Bytes32::default();
49//! let block = builder.build(state_root, receipts_root, &MySigner).expect("build");
50//! ```
51//!
52//! ## Quickstart — validate a block
53//!
54//! ```no_run
55//! use dig_block::{CoinLookup, L2Block, PublicKey};
56//! use chia_protocol::{Bytes32, CoinState};
57//! use dig_clvm::ValidationConfig;
58//!
59//! struct MyCoinLookup;
60//! impl CoinLookup for MyCoinLookup {
61//!     fn get_coin_state(&self, _id: &Bytes32) -> Option<CoinState> { None }
62//!     fn get_chain_height(&self) -> u64 { 0 }
63//!     fn get_chain_timestamp(&self) -> u64 { 0 }
64//! }
65//!
66//! fn validate(block: &L2Block, pk: &PublicKey) -> Result<Bytes32, dig_block::BlockError> {
67//!     let config = ValidationConfig::default();
68//!     let genesis = Bytes32::default();
69//!     // Runs Tier 1 (structural) → Tier 2 (execution) → Tier 3 (state) and returns the
70//!     // computed state root on success.
71//!     block.validate_full(&config, &genesis, &MyCoinLookup, pk)
72//! }
73//! ```
74//!
75//! ## Module map
76//!
77//! | Module | SPEC section | Purpose |
78//! |--------|-------------|---------|
79//! | [`primitives`] | §2.1 | [`Bytes32`], [`Cost`], [`Signature`], [`PublicKey`], version tags |
80//! | [`constants`] | §2.11 | [`EMPTY_ROOT`], [`MAX_BLOCK_SIZE`], [`MAX_COST_PER_BLOCK`], etc. |
81//! | [`types`] | §2.2–§2.10 | [`L2BlockHeader`], [`L2Block`], [`AttestedBlock`], checkpoint types, [`Receipt`], [`SignerBitmap`], status enums |
82//! | [`error`] | §4 | [`BlockError`], [`CheckpointError`], [`BuilderError`], [`SignerBitmapError`], [`ReceiptError`] |
83//! | [`hash`] | §3.3 | [`hash_leaf`], [`hash_node`] (0x01/0x02 domain separation) |
84//! | [`traits`] | §7.2 | [`CoinLookup`], [`BlockSigner`] |
85//! | [`builder`] | §6 | [`BlockBuilder`], [`CheckpointBuilder`] |
86//! | [`validation`] | §5, §7 | Structural (Tier 1), Execution (Tier 2), State (Tier 3) |
87//!
88//! ## Public API
89//!
90//! All protocol types and helpers are re-exported at the crate root ([SPEC §10](docs/resources/SPEC.md)).
91//! For convenience, [`prelude`] re-exports the most common items as a glob.
92//!
93//! ```
94//! use dig_block::prelude::*;
95//! ```
96//!
97//! ## Dependencies
98//!
99//! `dig-block` reuses the Chia Rust ecosystem and does not reimplement CLVM, BLS, or Merkle
100//! primitives ([SPEC §1.2](docs/resources/SPEC.md)):
101//!
102//! | Concern | Crate |
103//! |---------|-------|
104//! | Core protocol types ([`Bytes32`], `Coin`, `SpendBundle`, `CoinSpend`, `CoinState`) | `chia-protocol` |
105//! | BLS12-381 signatures ([`Signature`], [`PublicKey`], `verify`) | `chia-bls` |
106//! | CLVM execution + condition parsing | `dig-clvm` (wraps `chia-consensus`) |
107//! | Merkle set roots (additions, removals) | `chia-consensus::compute_merkle_set_root` |
108//! | Binary Merkle trees (spends, receipts, slash proposals) | `chia-sdk-types::MerkleTree` |
109//! | SHA-256 | `chia-sha2` |
110//! | CLVM tree hashing | `clvm-utils::tree_hash` |
111//! | Bincode serialization | `bincode` + `serde` |
112//! | BIP-158 compact block filter | `bitcoin::bip158` |
113//!
114//! CLVM execution is **always** routed through `dig_clvm::validate_spend_bundle`; dig-block never
115//! calls `chia-consensus::run_spendbundle` directly
116//! ([EXE-003](docs/requirements/domains/execution_validation/specs/EXE-003.md) enforced by a
117//! grep-based architectural lint in `tests/test_exe_003_clvm_delegation.rs`).
118
119pub mod builder;
120pub mod constants;
121pub mod error;
122pub mod hash;
123mod merkle_util;
124pub mod primitives;
125pub mod traits;
126pub mod types;
127pub mod validation;
128
129// -- Public re-exports (STR-003 / [SPEC §10](docs/resources/SPEC.md)) --
130
131// Block types (SPEC §2.2–§2.4, §2.6–§2.7)
132pub use types::attested::AttestedBlock;
133pub use types::block::L2Block;
134pub use types::checkpoint::{Checkpoint, CheckpointSubmission};
135pub use types::header::L2BlockHeader;
136
137// Test-only helper re-export (BLK-004). Kept in its own re-export block so rustfmt cannot
138// mingle the `#[doc(hidden)]` attribute with the public types above — different rustfmt
139// versions disagree on whether `__blk004…` sorts before or after `L2Block`, and splitting
140// the groups keeps the file stable across toolchains.
141#[doc(hidden)]
142pub use types::block::__blk004_first_duplicate_addition_coin_id;
143
144// Status and supporting types (SPEC §2.5, §2.8–§2.10)
145pub use types::receipt::{Receipt, ReceiptList, ReceiptStatus};
146pub use types::signer_bitmap::{SignerBitmap, MAX_VALIDATORS};
147pub use types::status::{BlockStatus, CheckpointStatus};
148
149// Error types (SPEC §4)
150pub use error::{BlockError, BuilderError, CheckpointError, ReceiptError, SignerBitmapError};
151
152// Primitive types & Chia re-exports (BLK-006 / SPEC §2.1)
153pub use primitives::{Bytes32, Cost, PublicKey, Signature, VERSION_V1, VERSION_V2};
154
155// Constants (BLK-005 / SPEC §2.11); uses [`Cost`] / [`Bytes32`] from [`primitives`]
156pub use constants::*;
157
158// Tagged Merkle hashing (SPEC §3.3 — 0x01 leaf / 0x02 node domain separation)
159pub use hash::{hash_leaf, hash_node};
160
161// Spends root (SPEC §3.3 — MerkleTree over sha256(SpendBundle))
162pub use merkle_util::compute_spends_root;
163
164// Additions Merkle set root (SPEC §3.4 — compute_merkle_set_root grouped by puzzle_hash)
165pub use merkle_util::compute_additions_root;
166
167// Removals Merkle set root (SPEC §3.5 — compute_merkle_set_root of coin IDs)
168pub use merkle_util::compute_removals_root;
169
170// BIP-158 compact block filter + filter_hash (SPEC §3.6)
171pub use merkle_util::{compact_block_filter_encoded, compute_filter_hash};
172
173// Receipts Merkle root (SPEC §3.3 — MerkleTree over sha256(bincode(Receipt)))
174pub use types::receipt::compute_receipts_root;
175
176// Traits (SPEC §7.2 — CoinLookup for state validation, BlockSigner for block production)
177pub use traits::{BlockSigner, CoinLookup};
178
179// Builder types (SPEC §6 — block and checkpoint construction)
180pub use builder::block_builder::BlockBuilder;
181pub use builder::checkpoint_builder::CheckpointBuilder;
182
183// Validation surface (SPEC §7.4–§7.5 — ExecutionResult + assertion types + Tier-2/3 helpers)
184pub use validation::execution::{
185    collect_pending_assertions_from_conditions, compute_state_root_from_delta,
186    map_clvm_validation_error, verify_coin_spend_puzzle_hash, AssertionKind, ExecutionResult,
187    PendingAssertion,
188};
189
190// ---------------------------------------------------------------------------
191// Prelude — convenience glob for consumers.
192// ---------------------------------------------------------------------------
193
194/// Common imports for `dig-block` consumers.
195///
196/// ```
197/// use dig_block::prelude::*;
198/// ```
199///
200/// Re-exports the most frequently used types so downstream code does not have to enumerate
201/// individual items. Internal helpers and architectural utilities are deliberately excluded;
202/// reach for them through the crate root (e.g. [`crate::compute_state_root_from_delta`]).
203pub mod prelude {
204    pub use crate::{
205        // Block types
206        AttestedBlock,
207        BlockBuilder,
208        BlockError,
209        // Traits
210        BlockSigner,
211        // Status
212        BlockStatus,
213        BuilderError,
214        // Core Chia primitives
215        Bytes32,
216        // Checkpoint types
217        Checkpoint,
218        CheckpointBuilder,
219        CheckpointError,
220        CheckpointStatus,
221        CheckpointSubmission,
222        CoinLookup,
223        Cost,
224        // Tier-2 output
225        ExecutionResult,
226        L2Block,
227        L2BlockHeader,
228        PublicKey,
229        // Receipt types
230        Receipt,
231        ReceiptList,
232        ReceiptStatus,
233        Signature,
234        // Attestation
235        SignerBitmap,
236    };
237}