Skip to main content

ab_client_database/
lib.rs

1//! Client database of a single shard.
2//!
3//! ## Architecture
4//!
5//! The database is stored on a [`ClientDatabaseStorageBackend`], a file preallocated to its full
6//! size or a raw block device, so no write fails due to lack of disk space. It is read and written
7//! in whole pages of [`OwnedPages::ALIGN`] bytes, which is a multiple of the sector size of modern
8//! SSDs, and has to be formatted with [`ClientDatabase::format()`] before it can be opened.
9//!
10//! [`OwnedPages::ALIGN`]: crate::storage_backend::OwnedPages::ALIGN
11//!
12//! Pages are grouped into page groups of [`ClientDatabaseFormatOptions::page_group_size`] pages,
13//! which are the unit of allocation. A page group is either permanent or temporary. Permanent page
14//! groups are never freed, so data only goes there in amounts that fill whole pages, like segment
15//! headers once there are enough of them, or once per database, like its chain parameters.
16//! Temporary page groups store blocks and everything else until it becomes outdated or moves to
17//! permanent page groups, and are freed whole once nothing in them is needed anymore. The database
18//! starts with one permanent and one temporary page group.
19//!
20//! Page groups of each kind form an append-only log, starting with the first page group of that
21//! kind. A page group holds storage items, each occupying whole pages: a header first, then storage
22//! items in the order they were written. The last page is left for a "next page group" storage
23//! item, which names the page group the log continues in. Every storage item holds its sequence
24//! number and a link to the previous storage item of the log, so the log can only be read in the
25//! order it was written.
26//!
27//! Right after each permanent storage item, a commit entry that links to it is written to the
28//! temporary log, which effectively determines the end of the permanent log. This allows replaying
29//! both in the original write order without extra complexity.
30//!
31//! The first permanent storage item after the header holds the chain parameters of the database:
32//! the root of the genesis block of the chain it stores and the block confirmation depth, which
33//! must stay the same (see [`ClientDatabaseOptions`]). [`ClientDatabase::open()`] writes them when
34//! the database doesn't have them, and otherwise refuses to open the database with other values
35//! before anything else is replayed.
36//!
37//! Segment headers and super segment headers are all kept in memory. Each page they fill is written
38//! to permanent page groups once, and the headers after the last page go to a temporary storage
39//! item.
40//!
41//! [`ClientDatabase::open()`] reads both logs, one page group of each at a time, and reconstructs
42//! the state in memory by replaying storage items. Page groups on neither log are free. Writing
43//! continues after the last storage item of the temporary log and the last committed permanent
44//! storage item, overwriting whatever is left there. The block lifecycle in
45//! [`ClientDatabaseOptions`] describes which blocks are kept in memory and when they are written to
46//! disk.
47//!
48//! ## Worker
49//!
50//! [`ClientDatabase::open()`] returns a [`ClientDatabaseWorker`] together with the database, which
51//! the caller runs. The worker is the only writer, it writes tasks one at a time, in the order they
52//! were sent.
53//!
54//! [`ClientDatabaseWorker`]: worker::ClientDatabaseWorker
55//!
56//! A method that writes updates the state in memory and sends a task to the worker without
57//! awaiting anything in between, so a dropped future either changed nothing or its task is written
58//! completely. A block stays in memory until its write finishes.
59//!
60//! The worker returns once all database handles are dropped and everything sent to it is written,
61//! or once a write failed. After that, methods that write return `Unavailable` errors.
62//!
63//! ## Design constraints
64//!
65//! Disk usage is fixed by the size of the storage backend, so the space the database needs has an
66//! upper bound that follows from protocol parameters, and storage is reused one page group at a
67//! time.
68//!
69//! RAM usage has an upper bound too, which matters as much as disk usage, since a node participates
70//! in several shards, each with its own database instance on the same storage. Only recent blocks
71//! are kept in memory with their details, and a new fork is only supposed to start being imported
72//! if it is going to become the new best block, which limits how many forks are in memory.
73//!
74//! The blockchain is replicated by every node, after a crash the node re-syncs whatever didn't make
75//! it to disk. So writes don't need hard durability: nothing waits for data to reach the disk
76//! (there is no `fsync`), and nothing should add latency for it. Writes that are in flight complete
77//! in any order, so after a crash any of them may be missing while later ones are present. The
78//! first storage item that is broken (incomplete, corrupted, out of sequence or not linked to the
79//! previous one) is where the log ends, which is not an error. Storage items left over from before,
80//! like the ones after the end of the log or in a reused page group, never continue the log, so
81//! nothing has to be erased to keep them out. That holds even when the storage item in front of
82//! them is written again the same way, like a block imported again, since every storage item has a
83//! random value chosen when the database was opened or formatted. A storage item that continues the
84//! log, but can't be decoded or is not valid where it is, is an error though, since checksums leave
85//! nothing but a bug as the cause, like a change of the format without a change of the database
86//! version. Pruning and confirmation are not recorded either, [`ClientDatabase::open()`] prunes and
87//! confirms blocks again as it replays them, and the best block after opening doesn't have to be
88//! the best block before shutdown. Headers after the last page and the highest local segment
89//! indices of shards are written again with later storage items, which [`ClientDatabase::open()`]
90//! handles by replaying them once. A known block is never written again, so a block that continues
91//! the log a second time is an error.
92//!
93//! Storage backend read and write errors are fatal by design: if the storage backend fails, the
94//! node is broken and can't make progress anyway, so it is expected to stop. Nothing tries to
95//! recover from such errors (for example, the worker returns after a write failed), and there is no
96//! need to add recovery logic.
97
98#![feature(
99    const_block_items,
100    const_convert,
101    const_trait_impl,
102    default_field_values,
103    iter_collect_into
104)]
105
106mod page_group;
107pub mod storage_backend;
108mod storage_backend_adapter;
109#[cfg(test)]
110mod test_utils;
111#[cfg(test)]
112mod tests;
113pub mod worker;
114
115use crate::page_group::permanent::StorageItemPermanent;
116use crate::page_group::permanent::chain_parameters::StorageItemPermanentChainParameters;
117use crate::page_group::slice::StorageItemSlice;
118use crate::page_group::temporary::StorageItemTemporary;
119use crate::page_group::temporary::block::StorageItemTemporaryBlock;
120use crate::page_group::temporary::shard_max_local_segment_indices::ShardMaxLocalSegmentIndex;
121use crate::storage_backend::ClientDatabaseStorageBackend;
122use crate::storage_backend_adapter::{
123    PageGroupKind, ReplayedStorageItem, StorageBackendAdapter, StorageItemHandlerArg, WriteLocation,
124};
125use crate::worker::{BlockToWrite, ClientDatabaseWorker, Task};
126use ab_client_api::{
127    BeaconChainInfo, BeaconChainInfoWrite, BlockDetails, ChainInfo, ChainInfoWrite,
128    ContractSlotState, PersistBlockError, PersistSegmentHeadersError, PersistSuperSegmentsError,
129    PersistedBlockInfo, ReadBlockError, ShardSegmentRoot, ShardSegmentRootsError,
130};
131use ab_core_primitives::block::body::BeaconChainBody;
132use ab_core_primitives::block::body::owned::{GenericOwnedBlockBody, OwnedBeaconChainBody};
133use ab_core_primitives::block::header::GenericBlockHeader;
134use ab_core_primitives::block::header::owned::GenericOwnedBlockHeader;
135use ab_core_primitives::block::owned::{GenericOwnedBlock, OwnedBeaconChainBlock};
136use ab_core_primitives::block::{BlockNumber, BlockRoot, GenericBlock};
137use ab_core_primitives::segments::{
138    LocalSegmentIndex, SegmentHeader, SegmentIndex, ShardSegmentRootWithPosition, SuperSegment,
139    SuperSegmentHeader, SuperSegmentIndex,
140};
141use ab_core_primitives::shard::{RealShardKind, ShardIndex};
142use ab_core_primitives::trees::BlockMerkleMountainRange;
143use ab_io_type::trivial_type::{AnyBitPattern, TrivialType};
144use ab_io_type::unaligned::Unaligned;
145use async_lock::RwLock as AsyncRwLock;
146use rand::rngs::SysError;
147use replace_with::replace_with_or_abort;
148use smallvec::{SmallVec, smallvec};
149use std::any::Any;
150use std::collections::{BTreeMap, HashMap, HashSet, VecDeque};
151use std::hash::{BuildHasherDefault, Hasher};
152use std::num::{NonZeroU32, NonZeroUsize};
153use std::ops::Deref;
154use std::pin::{Pin, pin};
155use std::task::Poll;
156use std::{future, io, mem};
157use tokio::sync::{mpsc, oneshot};
158use tracing::error;
159use triomphe::Arc;
160
161/// Unique identifier for a database
162#[derive(Debug, Copy, Clone, Eq, PartialEq, TrivialType)]
163#[repr(C)]
164pub struct DatabaseId([u8; 32]);
165
166impl Deref for DatabaseId {
167    type Target = [u8; 32];
168
169    #[inline(always)]
170    fn deref(&self) -> &Self::Target {
171        &self.0
172    }
173}
174
175impl AsRef<[u8]> for DatabaseId {
176    #[inline(always)]
177    fn as_ref(&self) -> &[u8] {
178        &self.0
179    }
180}
181
182impl DatabaseId {
183    #[inline(always)]
184    pub const fn new(bytes: [u8; 32]) -> Self {
185        Self(bytes)
186    }
187}
188
189#[derive(Default)]
190struct BlockRootHasher(u64);
191
192impl Hasher for BlockRootHasher {
193    #[inline(always)]
194    fn finish(&self) -> u64 {
195        self.0
196    }
197
198    #[inline(always)]
199    fn write(&mut self, bytes: &[u8]) {
200        let Some(state) = bytes.as_chunks().0.first().copied().map(u64::from_le_bytes) else {
201            return;
202        };
203
204        self.0 = state;
205    }
206}
207
208#[derive(Debug)]
209pub struct GenesisBlockBuilderResult<Block> {
210    /// Genesis block
211    pub block: Block,
212    /// System contracts state in the genesis block
213    pub system_contract_states: Arc<[ContractSlotState]>,
214}
215
216/// Options for [`ClientDatabase`].
217///
218/// Lifecycle of a block, by block offset from the best block with block number `n`, with
219/// `block_confirmation_depth = 5` and `soft_confirmation_depth = 2` as an example:
220///
221/// ```text
222/// block   block   fork       written   block details
223/// offset  number  blocks     to disk   in memory
224///         n + 1                                    next best block, being imported
225///      0  n       accepted   no        yes         best block
226///      1  n - 1   accepted   no        yes
227///      2  n - 2   accepted   yes       yes         soft-confirmed <- soft_confirmation_depth
228///      3  n - 3   accepted   yes       yes         soft-confirmed
229///      4  n - 4   rejected   yes       yes         confirmed once n + 1 is imported
230///      5  n - 5   rejected   yes       no          confirmed <- block_confirmation_depth,
231///                                                  once written
232///    ...
233/// ```
234///
235/// When block `n` is built, the block at `n - block_confirmation_depth` is confirmed (see
236/// `ConsensusConstants::block_confirmation_depth`), and the database marks the same block as
237/// confirmed. Fork blocks are only accepted above block offset `block_confirmation_depth - 1`. The
238/// block there is only confirmed once `n + 1` is imported, but it already can't change: a fork
239/// block next to it would start a reorg of `block_confirmation_depth` blocks, more than the largest
240/// allowed reorg of `block_confirmation_depth - 1` blocks. Soft-confirmed blocks are only written
241/// to disk early, a reorg can still revert them.
242///
243/// Importing `n + 1` on any fork makes it the best block and shifts all block offsets by one. Then
244/// other blocks at block offset `block_confirmation_depth - 1` are pruned with their descendants,
245/// the block at block offset `block_confirmation_depth` is confirmed, which drops its block details
246/// (MMR and system contract states) from memory, and blocks that reached block offset
247/// `soft_confirmation_depth` are written to disk. A block whose write hasn't finished yet is
248/// confirmed once the worker marks it as persisted. Block details of confirmed blocks are only left
249/// on disk, [`ChainInfo::header_with_details()`] doesn't return them.
250#[derive(Debug, Copy, Clone)]
251#[expect(unevaluated_default_field_value, reason = "Intentional")]
252pub struct ClientDatabaseOptions<GBB, StorageBackend> {
253    /// Write buffer size.
254    ///
255    /// Each write occupies an entry of the write buffer until it finishes, so this bounds the
256    /// number of writes in flight. Larger buffer allows buffering more async writes for improved
257    /// responsiveness but requires more RAM. Zero buffer size means all writes must be completed
258    /// before returning from the operation that triggered it. Non-zero buffer means writes can
259    /// happen in the background.
260    ///
261    /// The recommended value is 5.
262    pub write_buffer_size: usize = 5,
263    /// Block confirmation depth, the value of `ConsensusConstants::block_confirmation_depth`.
264    ///
265    /// Fork blocks are only accepted above block offset `block_confirmation_depth - 1` from the
266    /// best block, other blocks at that block offset are pruned with their descendants, and blocks
267    /// are confirmed at block offset `block_confirmation_depth` (see the block lifecycle in
268    /// [`ClientDatabaseOptions`]).
269    ///
270    /// Must be at least 2. The database records it when it is opened for the first time and is not
271    /// opened with another value after that.
272    pub block_confirmation_depth: BlockNumber,
273    /// Soft confirmation depth for blocks.
274    ///
275    /// Doesn't prevent forking on the consensus level but makes it extremely unlikely.
276    ///
277    /// This parameter determines how many blocks are retained in memory before being written to
278    /// disk. Writing discarded blocks to disk is a waste of resources, so they are retained in
279    /// memory before being soft-confirmed and written to disk for longer-term storage.
280    ///
281    /// Blocks are persisted as soon as they reach this depth. More recent blocks may be lost if the
282    /// node is not shut down gracefully (crash, killed by the OS, etc.).
283    ///
284    /// A smaller number reduces memory usage while increasing the probability of unnecessary disk
285    /// writes. A larger number increases memory usage and the number of blocks that may be lost
286    /// this way, while avoiding unnecessary disk writes.
287    ///
288    /// The recommended value is 3 blocks.
289    pub soft_confirmation_depth: BlockNumber = BlockNumber::from(3),
290    /// Defines how many fork tips should be maintained in total.
291    ///
292    /// As natural forks occur, there may be more than one tip in existence, with only one of them
293    /// being considered "canonical". This parameter defines how many of these tips to maintain in a
294    /// sort of LRU style cache. Tips beyond this limit that were not extended for a long time will
295    /// be pruned automatically.
296    ///
297    /// A larger number results in higher memory usage and higher complexity of pruning algorithms.
298    ///
299    /// The recommended value is 3 blocks.
300    pub max_fork_tips: NonZeroUsize = NonZeroUsize::new(3).expect("Not zero; qed"),
301    /// Max distance between fork tip and the best block.
302    ///
303    /// When forks are deeper than this, they will be pruned, even without reaching the
304    /// `max_fork_tips` limit. This essentially means the tip was not extended for some time, and
305    /// while it is theoretically possible for the chain to continue from this tip, the probability
306    /// is so small that it is not worth storing it.
307    ///
308    /// A larger value results in higher memory usage and higher complexity of pruning algorithms.
309    ///
310    /// Fork blocks at block offset `block_confirmation_depth - 1` and deeper are pruned regardless
311    /// (see the block lifecycle in [`ClientDatabaseOptions`]), so values of
312    /// `block_confirmation_depth - 2` and larger all have the same effect as no limit.
313    ///
314    /// The recommended value is 5 blocks.
315    pub max_fork_tip_distance: BlockNumber = BlockNumber::from(5),
316    /// Genesis block builder is responsible to create genesis block and corresponding state for
317    /// bootstrapping purposes.
318    ///
319    /// It is called every time the database is opened: the root of the genesis block identifies the
320    /// chain the database stores, and the database is not opened with another one.
321    pub genesis_block_builder: GBB,
322    /// Storage backend to use for storing and retrieving storage items
323    pub storage_backend: StorageBackend,
324}
325
326/// Options for [`ClientDatabase::format()`]
327#[derive(Debug, Copy, Clone)]
328pub struct ClientDatabaseFormatOptions {
329    /// The number of pages of [`OwnedPages::ALIGN`] bytes in a single page group.
330    ///
331    /// [`OwnedPages::ALIGN`]: crate::storage_backend::OwnedPages::ALIGN
332    ///
333    /// A storage item must fit into a single page group together with the page group header and a
334    /// next page group entry, so this bounds the size of the largest storage item, like a block. A
335    /// larger number also wastes a smaller share of each page group at its end, where the next
336    /// storage item doesn't fit. A smaller number reclaims storage in smaller steps, since page
337    /// groups are freed whole, and makes [`ClientDatabase::open()`] use less RAM, since it reads a
338    /// whole page group at once.
339    ///
340    /// The recommended size is 256 MiB unless a tiny database is used for testing purposes, where
341    /// a smaller value might work too.
342    pub page_group_size: NonZeroU32,
343    /// By default, formatting will be aborted if the database appears to be already formatted.
344    ///
345    /// Setting this option to `true` skips the check and formats the database anyway.
346    pub force: bool,
347}
348
349/// Invalid page group size, see [`ClientDatabaseFormatOptions::page_group_size`]
350#[derive(Debug, thiserror::Error)]
351pub enum PageGroupSizeError {
352    /// Page group size is too small, must be at least three pages
353    #[error("Page group size is too small ({page_group_size}), must be at least three pages")]
354    TooSmall {
355        /// Page group size in pages
356        page_group_size: u32,
357    },
358    /// Page group size is larger than the storage backend
359    #[error(
360        "Page group size is too large ({page_group_size}), storage backend only has {num_pages} \
361        pages"
362    )]
363    TooLarge {
364        /// Page group size in pages
365        page_group_size: u32,
366        /// Number of pages in the storage backend
367        num_pages: u32,
368    },
369    /// Page group size is too large, the whole page group must fit into an aligned buffer, whose
370    /// max capacity is less than 4 GiB
371    #[error(
372        "Page group size is too large ({page_group_size}), the whole page group must fit into an \
373        aligned buffer"
374    )]
375    ExceedsBufferCapacity {
376        /// Page group size in pages
377        page_group_size: u32,
378    },
379}
380
381/// Why a storage item is not valid, see [`ClientDatabaseError::InvalidStorageItem`]
382#[derive(Debug, thiserror::Error)]
383pub enum InvalidStorageItemError {
384    /// Failed to decode block header
385    #[error("Failed to decode block header")]
386    BlockHeaderDecoding,
387    /// Failed to decode block body
388    #[error("Failed to decode block body")]
389    BlockBodyDecoding,
390    /// Block is already known, a known block is never written again
391    #[error("Block {block_root} is already known")]
392    BlockAlreadyKnown {
393        /// Root of the block in the storage item
394        block_root: BlockRoot,
395    },
396    /// Block above the best block must be only one block higher than the best block
397    #[error(
398        "Block {block_number} above the best block must be only one block higher than the best \
399        block {best_number}"
400    )]
401    BlockNumberAboveBestBlock {
402        /// Number of the block in the storage item
403        block_number: BlockNumber,
404        /// Number of the best block
405        best_number: BlockNumber,
406    },
407    /// Segment headers can't be added
408    #[error("Segment headers can't be added: {error}")]
409    SegmentHeaders {
410        /// Low-level error
411        error: PersistSegmentHeadersError,
412    },
413    /// Super segment headers can't be added
414    #[error("Super segment headers can't be added: {error}")]
415    SuperSegmentHeaders {
416        /// Low-level error
417        error: PersistSuperSegmentsError,
418    },
419    /// Page of headers is not full
420    #[error("Page of {num_headers} headers must hold {num_headers_per_page} headers")]
421    HeaderPage {
422        /// The number of headers in the page
423        num_headers: usize,
424        /// The number of headers that fit into a page
425        num_headers_per_page: usize,
426    },
427    /// Headers of a storage item don't start right after the headers in pages
428    #[error(
429        "Headers starting at header {first_header_position} must start right after \
430        {num_headers_in_pages} headers in pages"
431    )]
432    HeadersAfterPages {
433        /// Position of the first header among headers of its kind
434        first_header_position: u64,
435        /// The number of headers in pages
436        num_headers_in_pages: usize,
437    },
438}
439
440#[derive(Debug, thiserror::Error)]
441pub enum ClientDatabaseError {
442    /// Invalid block confirmation depth, it must be at least 2.
443    ///
444    /// Fork blocks are only accepted above block offset `block_confirmation_depth - 1`, smaller
445    /// values leave no block offset for them.
446    #[error("Invalid block confirmation depth, it must be at least 2")]
447    InvalidBlockConfirmationDepth,
448    /// Invalid soft confirmation depth, it must be smaller than block confirmation depth
449    #[error("Invalid soft confirmation depth, it must be smaller than block confirmation depth")]
450    InvalidSoftConfirmationDepth,
451    /// Storage backend has canceled read request
452    #[error("Storage backend has canceled read request")]
453    ReadRequestCancelled,
454    /// Storage backend read error
455    #[error("Storage backend read error: {error}")]
456    ReadError {
457        /// Low-level error
458        error: io::Error,
459    },
460    /// Unsupported database version
461    #[error("Unsupported database version: {database_version}")]
462    UnsupportedDatabaseVersion {
463        /// Database version
464        database_version: u8,
465    },
466    /// Invalid page group size in the page group header
467    #[error("Invalid page group size: {error}")]
468    InvalidPageGroupSize {
469        /// Low-level error
470        error: PageGroupSizeError,
471    },
472    /// Storage item was read successfully, but its contents are not valid
473    #[error("Invalid {storage_item} storage item at page offset {page_offset}: {error}")]
474    InvalidStorageItem {
475        /// Name of the storage item
476        storage_item: &'static str,
477        /// Page offset where storage item is found
478        page_offset: u32,
479        /// Why the storage item is not valid
480        error: InvalidStorageItemError,
481    },
482    /// Storage item continues the log, but can't be decoded or is not valid where it is, like after
483    /// a change of the format without a change of the database version
484    #[error("Invalid log entry {sequence_number} at page offset {page_offset}")]
485    InvalidLogEntry {
486        /// Sequence number of the storage item
487        sequence_number: u64,
488        /// Page offset where the storage item is found
489        page_offset: u32,
490    },
491    /// Page group is in the logs more than once
492    #[error("Page group {page_group_index} is in the logs more than once")]
493    PageGroupUsedMoreThanOnce {
494        /// Index of the page group
495        page_group_index: u32,
496    },
497    /// Temporary storage item is in front of the chain parameters of the database
498    #[error(
499        "Temporary storage item at page offset {page_offset} is in front of the chain parameters"
500    )]
501    TemporaryStorageItemBeforeChainParameters {
502        /// Page offset where the storage item is found
503        page_offset: u32,
504    },
505    /// Failed to adjust ancestor block forks, because not all ancestors of the block were found
506    #[error("Failed to adjust ancestor block forks, ancestors of block {block_number} not found")]
507    FailedToAdjustAncestorBlockForks {
508        /// Number of the block whose ancestors were not found
509        block_number: BlockNumber,
510    },
511    /// Database is not formatted yet
512    #[error("Database is not formatted yet")]
513    Unformatted,
514    /// Non-permanent first page group
515    #[error("Non-permanent first page group")]
516    NonPermanentFirstPageGroup,
517    /// Failed to generate the random value that storage items written after opening carry
518    #[error("Failed to generate session value: {error}")]
519    FailedToGenerateSessionValue {
520        /// Low-level error
521        error: SysError,
522    },
523    /// Database stores another chain, whose genesis root is not the root of the genesis block
524    /// built by [`ClientDatabaseOptions::genesis_block_builder`]
525    #[error("Database stores another chain: genesis root {stored}, expected {expected}")]
526    GenesisRootMismatch {
527        /// Root of the genesis block built by [`ClientDatabaseOptions::genesis_block_builder`]
528        expected: BlockRoot,
529        /// Genesis root stored in the database
530        stored: BlockRoot,
531    },
532    /// Database was opened with another block confirmation depth before, see
533    /// [`ClientDatabaseOptions::block_confirmation_depth`]
534    #[error(
535        "Database was opened with block confirmation depth {stored} before, expected {expected}"
536    )]
537    BlockConfirmationDepthMismatch {
538        /// [`ClientDatabaseOptions::block_confirmation_depth`]
539        expected: BlockNumber,
540        /// Block confirmation depth stored in the database
541        stored: BlockNumber,
542    },
543    /// Failed to write the chain parameters of the database that doesn't have them
544    #[error("Failed to write chain parameters: {error}")]
545    FailedToWriteChainParameters {
546        /// Low-level error
547        error: io::Error,
548    },
549}
550
551/// Error for [`ClientDatabase::format()`]
552#[derive(Debug, thiserror::Error)]
553pub enum ClientDatabaseFormatError {
554    /// Storage backend has canceled read request
555    #[error("Storage backend has canceled read request")]
556    ReadRequestCancelled,
557    /// Storage backend read error
558    #[error("Storage backend read error: {error}")]
559    ReadError {
560        /// Low-level error
561        error: io::Error,
562    },
563    /// Failed to generate database id
564    #[error("Failed to generate database id")]
565    FailedToGenerateDatabaseId {
566        /// Low-level error
567        #[from]
568        error: SysError,
569    },
570    /// Failed to generate the random value that the first page group header carries
571    #[error("Failed to generate session value: {error}")]
572    FailedToGenerateSessionValue {
573        /// Low-level error
574        error: SysError,
575    },
576    /// Invalid page group size
577    #[error("Invalid page group size: {error}")]
578    InvalidPageGroupSize {
579        /// Low-level error
580        error: PageGroupSizeError,
581    },
582    /// Database is already formatted yet
583    #[error("Database is already formatted yet")]
584    AlreadyFormatted,
585    /// Storage backend has canceled a writing request
586    #[error("Storage backend has canceled a writing request")]
587    WriteRequestCancelled,
588    /// Storage item write error
589    #[error("Storage item write error")]
590    StorageItemWriteError {
591        /// Low-level error
592        #[from]
593        error: io::Error,
594    },
595}
596
597#[derive(Debug, Copy, Clone)]
598struct ForkTip {
599    number: BlockNumber,
600    root: BlockRoot,
601}
602
603/// How far [`StateData::adjust_ancestor_block_forks()`] walks towards older blocks
604#[derive(Debug, Copy, Clone)]
605enum AncestorBlockForksWalk {
606    /// Stop at the first ancestor that is already at fork offset `0`, relies on the invariant
607    /// documented on [`StateData::blocks`]
608    UntilCanonical,
609    /// Walk block offsets up to and including `max_block_offset`, for when the invariant doesn't
610    /// hold (in [`ClientDatabase::open()`])
611    UpToBlockOffset { max_block_offset: usize },
612}
613
614enum FullBlock<'a, Block>
615where
616    Block: GenericOwnedBlock,
617{
618    InMemory(&'a Block),
619    Persisted {
620        header: &'a Block::Header,
621        write_location: WriteLocation,
622    },
623}
624
625#[derive(Debug)]
626struct BeaconChainBlockDetails {
627    // Shard segment roots, only present for beacon chain blocks
628    shard_segment_roots: Arc<[ShardSegmentRoot]>,
629}
630
631impl BeaconChainBlockDetails {
632    fn from_body(body: &BeaconChainBody<'_>) -> Self {
633        let shard_segment_roots = body
634            .intermediate_shard_blocks()
635            .iter()
636            .flat_map(|intermediate_shard_block_info| {
637                let own_segments = intermediate_shard_block_info
638                    .own_segments
639                    .into_iter()
640                    .flat_map({
641                        let shard_index = intermediate_shard_block_info.header.prefix.shard_index;
642
643                        move |own_segments| {
644                            own_segments
645                                .iter()
646                                .map(move |(segment_index, &segment_root)| ShardSegmentRoot {
647                                    shard_index,
648                                    segment_index,
649                                    segment_root,
650                                })
651                        }
652                    });
653                let child_shard_segment_roots = intermediate_shard_block_info
654                    .leaf_shards_segments()
655                    .flat_map(move |(_position, shard_index, own_segments)| {
656                        own_segments
657                            .iter()
658                            .map(move |(segment_index, &segment_root)| ShardSegmentRoot {
659                                shard_index,
660                                segment_index,
661                                segment_root,
662                            })
663                    });
664
665                own_segments.chain(child_shard_segment_roots)
666            })
667            .collect();
668
669        Self {
670            shard_segment_roots,
671        }
672    }
673}
674
675/// Client database block contains details about the block state in the database.
676///
677/// A block starts [`Self::InMemory`]. Once it is soft-confirmed (see
678/// [`ClientDatabaseOptions::soft_confirmation_depth`]), it is sent to the worker and is
679/// [`Self::Writing`] until its write finishes, then it is [`Self::Persisted`]. Later, at block
680/// offset `block_confirmation_depth` (see the block lifecycle in [`ClientDatabaseOptions`]), it is
681/// [`Self::PersistedConfirmed`] and its [`BlockDetails`] are dropped from memory, they are only
682/// left on disk.
683#[derive(Debug)]
684enum ClientDatabaseBlock<Block>
685where
686    Block: GenericOwnedBlock,
687{
688    /// Block is stored in memory and wasn't sent to the worker
689    InMemory {
690        block: Block,
691        block_details: BlockDetails,
692        /// Only present for beacon chain blocks
693        beacon_chain_block_details: Option<BeaconChainBlockDetails>,
694    },
695    /// Block is stored in memory and was sent to the worker, its write didn't finish yet
696    Writing {
697        block: Block,
698        block_details: BlockDetails,
699        /// Only present for beacon chain blocks
700        beacon_chain_block_details: Option<BeaconChainBlockDetails>,
701    },
702    /// Block was persisted (likely on disk)
703    Persisted {
704        header: Block::Header,
705        block_details: BlockDetails,
706        /// Only present for beacon chain blocks
707        beacon_chain_block_details: Option<BeaconChainBlockDetails>,
708        write_location: WriteLocation,
709    },
710    /// Block was persisted (likely on disk) and confirmed, its [`BlockDetails`] are only on disk
711    PersistedConfirmed {
712        header: Block::Header,
713        /// Only present for beacon chain blocks
714        beacon_chain_block_details: Option<BeaconChainBlockDetails>,
715        write_location: WriteLocation,
716    },
717}
718
719impl<Block> ClientDatabaseBlock<Block>
720where
721    Block: GenericOwnedBlock,
722{
723    #[inline(always)]
724    fn header(&self) -> &Block::Header {
725        #[expect(
726            clippy::rest_pattern_accessible_field,
727            reason = "Do not need other fields"
728        )]
729        match self {
730            Self::InMemory { block, .. } | Self::Writing { block, .. } => block.header(),
731            Self::Persisted { header, .. } | Self::PersistedConfirmed { header, .. } => header,
732        }
733    }
734
735    #[inline(always)]
736    fn full_block(&self) -> FullBlock<'_, Block> {
737        #[expect(
738            clippy::rest_pattern_accessible_field,
739            reason = "Do not need other fields"
740        )]
741        match self {
742            Self::InMemory { block, .. } | Self::Writing { block, .. } => {
743                FullBlock::InMemory(block)
744            }
745            Self::Persisted {
746                header,
747                write_location,
748                ..
749            }
750            | Self::PersistedConfirmed {
751                header,
752                write_location,
753                ..
754            } => FullBlock::Persisted {
755                header,
756                write_location: *write_location,
757            },
758        }
759    }
760
761    #[inline(always)]
762    fn block_details(&self) -> Option<&BlockDetails> {
763        #[expect(
764            clippy::rest_pattern_accessible_field,
765            reason = "Do not need other fields"
766        )]
767        match self {
768            Self::InMemory { block_details, .. }
769            | Self::Writing { block_details, .. }
770            | Self::Persisted { block_details, .. } => Some(block_details),
771            Self::PersistedConfirmed { .. } => None,
772        }
773    }
774
775    #[inline(always)]
776    fn beacon_chain_block_details(&self) -> Option<&BeaconChainBlockDetails> {
777        #[expect(
778            clippy::rest_pattern_accessible_field,
779            reason = "Do not need other fields"
780        )]
781        match self {
782            Self::InMemory {
783                beacon_chain_block_details,
784                ..
785            }
786            | Self::Writing {
787                beacon_chain_block_details,
788                ..
789            }
790            | Self::Persisted {
791                beacon_chain_block_details,
792                ..
793            }
794            | Self::PersistedConfirmed {
795                beacon_chain_block_details,
796                ..
797            } => beacon_chain_block_details.as_ref(),
798        }
799    }
800}
801
802#[derive(Debug)]
803struct StateData<Block>
804where
805    Block: GenericOwnedBlock,
806{
807    /// Tips of forks that have no descendants.
808    ///
809    /// The current best block is at the front, the rest are in the order from most recently
810    /// updated towards the front to least recently at the back.
811    fork_tips: VecDeque<ForkTip>,
812    /// Map from block root to block number.
813    ///
814    /// Is meant to be used in conjunction with `headers` and `blocks` fields, which are indexed by
815    /// block numbers.
816    block_roots: HashMap<BlockRoot, BlockNumber, BuildHasherDefault<BlockRootHasher>>,
817    /// List of blocks with the newest at the front.
818    ///
819    /// The first element of the first entry corresponds to the best block.
820    ///
821    /// It is expected that in most block numbers there will be exactly one block, some two,
822    /// anything more than that will be very rare. The list of forks for a block number is
823    /// organized in such a way that the first entry at every block number corresponds to the
824    /// canonical version of the blockchain at any point in time.
825    ///
826    /// In other words, except while reading blocks in [`ClientDatabase::open()`], the block at
827    /// block offset `n + 1` and fork offset `0` is always the parent of the block at block offset
828    /// `n` and fork offset `0`. New best blocks establish this with
829    /// [`Self::adjust_ancestor_block_forks()`], other blocks are only appended at fork
830    /// offset `1` or higher, and pruning never removes the block at fork offset `0`. Block offset
831    /// [`ClientDatabaseInnerOptions::fork_pruning_block_offset()`] and deeper ones have no forks.
832    ///
833    /// A position within this data structure is called "block offset". This is an ephemeral value
834    /// and changes as new best blocks are added. Blocks at the same height are collectively called
835    /// "block forks" and the position of the block within the same block height is called
836    /// "fork offset". While fork offset `0` always corresponds to the canonical version of the
837    /// blockchain, other offsets are not guaranteed to follow any particular ordering rules.
838    blocks: VecDeque<SmallVec<[ClientDatabaseBlock<Block>; 2]>>,
839}
840
841impl<Block> StateData<Block>
842where
843    Block: GenericOwnedBlock,
844{
845    /// Adjust the relative order of forks to ensure the first index always corresponds to
846    /// `parent_block_root` and its ancestors.
847    ///
848    /// Returns `true` on success and `false` if one of the parents was not found.
849    #[must_use = "The return value indicates whether all parent blocks were found"]
850    fn adjust_ancestor_block_forks(
851        &mut self,
852        mut parent_block_root: BlockRoot,
853        walk: AncestorBlockForksWalk,
854    ) -> bool {
855        for (block_offset, parent_blocks) in self.blocks.iter_mut().enumerate() {
856            if let AncestorBlockForksWalk::UpToBlockOffset { max_block_offset } = walk
857                && block_offset > max_block_offset
858            {
859                break;
860            }
861
862            let Some(fork_offset_parent_block_root) =
863                parent_blocks
864                    .iter()
865                    .enumerate()
866                    .find_map(|(fork_offset, fork_block)| {
867                        let fork_header = fork_block.header().header();
868                        if *fork_header.root() == parent_block_root {
869                            Some((fork_offset, fork_header.prefix.parent_root))
870                        } else {
871                            None
872                        }
873                    })
874            else {
875                return false;
876            };
877
878            let fork_offset;
879            (fork_offset, parent_block_root) = fork_offset_parent_block_root;
880
881            if fork_offset == 0 && matches!(walk, AncestorBlockForksWalk::UntilCanonical) {
882                // All older ancestors are already at fork offset `0` too
883                break;
884            }
885
886            parent_blocks.swap(0, fork_offset);
887        }
888
889        true
890    }
891
892    /// Prune outdated fork tips that are too deep and have not been updated for a long time.
893    ///
894    /// Note that actual headers, blocks and MMRs could remain if they are currently used by
895    /// something or were already persisted on disk. With persisted blocks specifically, RAM usage
896    /// implications are minimal, and we wouldn't want to re-download already stored blocks in case
897    /// they end up being necessary later.
898    fn prune_outdated_fork_tips(
899        &mut self,
900        best_number: BlockNumber,
901        options: &ClientDatabaseInnerOptions,
902    ) {
903        // These forks are just candidates because they will not be pruned if the reference count is
904        // not 1, indicating they are still in use by something
905        let mut candidate_forks_to_remove = Vec::with_capacity(options.max_fork_tips.get());
906
907        // Prune forks that are too far away from the best block
908        self.fork_tips.retain(|fork_tip| {
909            if best_number - fork_tip.number > options.max_fork_tip_distance {
910                candidate_forks_to_remove.push(*fork_tip);
911                false
912            } else {
913                true
914            }
915        });
916        // Prune forks that exceed the maximum number of forks
917        if self.fork_tips.len() > options.max_fork_tips.get() {
918            self.fork_tips
919                .drain(options.max_fork_tips.get()..)
920                .collect_into(&mut candidate_forks_to_remove);
921        }
922
923        // Prune all possible candidates
924        candidate_forks_to_remove
925            .retain(|fork_tip| !self.prune_outdated_fork(best_number, fork_tip));
926        // Return those that were not pruned back to the list of tips
927        self.fork_tips.extend(candidate_forks_to_remove);
928    }
929
930    /// Returns `true` if the tip was pruned successfully and `false` if it should be returned to
931    /// the list of fork tips
932    #[must_use = "The return value indicates whether the fork tip was pruned"]
933    fn prune_outdated_fork(&mut self, best_number: BlockNumber, fork_tip: &ForkTip) -> bool {
934        let block_offset = u64::from(best_number - fork_tip.number) as usize;
935
936        // Prune fork top and all its ancestors that are not used
937        let mut block_root_to_prune = fork_tip.root;
938        let mut pruned_tip = false;
939        for block_offset in block_offset.. {
940            let Some(fork_blocks) = self.blocks.get_mut(block_offset) else {
941                if !pruned_tip {
942                    error!(
943                        %best_number,
944                        ?fork_tip,
945                        block_offset,
946                        "Fork tip to prune is deeper than stored blocks, this is an implementation \
947                        bug"
948                    );
949                }
950                // No forks left to prune
951                break;
952            };
953
954            if fork_blocks.len() == 1 {
955                if !pruned_tip {
956                    error!(
957                        %best_number,
958                        ?fork_tip,
959                        block_offset,
960                        "Fork tip to prune is the only block at its block offset, this is an \
961                        implementation bug"
962                    );
963                }
964
965                // No forks left to prune
966                break;
967            }
968
969            let Some((fork_offset, block)) = fork_blocks
970                .iter()
971                .enumerate()
972                // Skip ancestor of the best block, it is certainly not a fork to be pruned
973                .skip(1)
974                .find(|(_fork_offset, block)| *block.header().root() == block_root_to_prune)
975            else {
976                if !pruned_tip {
977                    error!(
978                        %best_number,
979                        ?fork_tip,
980                        block_offset,
981                        "Fork tip to prune is not among fork blocks at its block offset, this is \
982                        an implementation bug"
983                    );
984                }
985
986                // Nothing left to prune
987                break;
988            };
989
990            let header = block.header();
991
992            // More than one instance means something somewhere is using this block, children are
993            // not counted here and are checked separately below
994            if header.ref_count() > 1 {
995                break;
996            }
997
998            // Blocks that are already persisted or being written
999            #[expect(
1000                clippy::rest_pattern_accessible_field,
1001                reason = "Do not care about fields"
1002            )]
1003            match block {
1004                ClientDatabaseBlock::InMemory { .. } => {
1005                    // Prune
1006                }
1007                ClientDatabaseBlock::Writing { .. }
1008                | ClientDatabaseBlock::Persisted { .. }
1009                | ClientDatabaseBlock::PersistedConfirmed { .. } => {
1010                    // On disk or about to be, keep it in memory for later, but prune the tip
1011                    pruned_tip = true;
1012                    break;
1013                }
1014            }
1015
1016            let parent_root = header.header().prefix.parent_root;
1017            self.block_roots.remove(&block_root_to_prune);
1018            fork_blocks.swap_remove(fork_offset);
1019
1020            pruned_tip = true;
1021
1022            // The parent is still needed by its other children
1023            if fork_blocks
1024                .iter()
1025                .any(|fork_block| fork_block.header().header().prefix.parent_root == parent_root)
1026            {
1027                break;
1028            }
1029
1030            block_root_to_prune = parent_root;
1031        }
1032
1033        pruned_tip
1034    }
1035
1036    /// Confirm the block at block offset `block_confirmation_depth`.
1037    ///
1038    /// The block at that block offset must be an ancestor of the block at `best_number` that was
1039    /// just added, other blocks at that block offset were pruned by
1040    /// [`Self::prune_non_canonical_blocks()`] at
1041    /// [`ClientDatabaseInnerOptions::fork_pruning_block_offset()`] already.
1042    fn confirm_canonical_block(
1043        &mut self,
1044        best_number: BlockNumber,
1045        options: &ClientDatabaseInnerOptions,
1046    ) {
1047        // Blocks keep their `BlockDetails` in memory until they are confirmed here, and
1048        // `ChainInfo::header_with_details()` only returns them from memory. Block import needs them
1049        // for the parent of every block it imports. Fork blocks are only accepted above the fork
1050        // pruning block offset, so their parents are at most at it, which is exactly what is left
1051        // in memory:
1052        //
1053        // block offset                        block details
1054        // 0 ..= block_confirmation_depth - 2  in memory, fork blocks and their parents
1055        // block_confirmation_depth - 1        in memory, parents of the deepest fork blocks
1056        // block_confirmation_depth            dropped from memory here
1057        let block_offset = u64::from(options.block_confirmation_depth) as usize;
1058
1059        let Some(fork_blocks) = self.blocks.get_mut(block_offset) else {
1060            // Nothing to confirm yet
1061            return;
1062        };
1063
1064        // Mark the canonical block as confirmed
1065        let Some(canonical_block) = fork_blocks.first_mut() else {
1066            error!(
1067                %best_number,
1068                block_offset,
1069                "Have not found a canonical block to confirm, this is an implementation bug"
1070            );
1071            return;
1072        };
1073
1074        replace_with_or_abort(canonical_block, |block| {
1075            #[expect(
1076                clippy::rest_pattern_accessible_field,
1077                reason = "Do not need other fields"
1078            )]
1079            match block {
1080                ClientDatabaseBlock::InMemory { .. } | ClientDatabaseBlock::Writing { .. } => {
1081                    // Not persisted yet, the worker confirms it once its write finishes
1082                    block
1083                }
1084                ClientDatabaseBlock::Persisted {
1085                    header,
1086                    block_details: _,
1087                    beacon_chain_block_details,
1088                    write_location,
1089                } => ClientDatabaseBlock::PersistedConfirmed {
1090                    header,
1091                    beacon_chain_block_details,
1092                    write_location,
1093                },
1094                ClientDatabaseBlock::PersistedConfirmed { .. } => {
1095                    error!(
1096                        %best_number,
1097                        block_offset,
1098                        header = ?block.header(),
1099                        "Block to be confirmed must not be confirmed yet, this is an \
1100                        implementation bug"
1101                    );
1102                    block
1103                }
1104            }
1105        });
1106    }
1107
1108    /// Prune blocks other than the one at fork offset `0` at `block_offset` with their descendants
1109    fn prune_non_canonical_blocks(&mut self, block_offset: usize) {
1110        let Some(fork_blocks) = self.blocks.get_mut(block_offset) else {
1111            return;
1112        };
1113
1114        let mut block_roots_to_prune = fork_blocks
1115            .drain(1..)
1116            .map(|block| *block.header().root())
1117            .collect::<Vec<_>>();
1118        let mut current_block_offset = block_offset;
1119        while !block_roots_to_prune.is_empty() {
1120            // Prune fork tips (if any)
1121            self.fork_tips
1122                .retain(|fork_tip| !block_roots_to_prune.contains(&fork_tip.root));
1123
1124            // Prune removed block roots
1125            for block_root in &block_roots_to_prune {
1126                self.block_roots.remove(block_root);
1127            }
1128
1129            // Block offset for direct descendants
1130            if let Some(next_block_offset) = current_block_offset.checked_sub(1) {
1131                current_block_offset = next_block_offset;
1132            } else {
1133                // Reached the tip
1134                break;
1135            }
1136
1137            let fork_blocks = self
1138                .blocks
1139                .get_mut(current_block_offset)
1140                .expect("Lower block offset always exists; qed");
1141
1142            // Collect descendants of pruned blocks to prune them next
1143            block_roots_to_prune = fork_blocks
1144                .drain_filter(|block| {
1145                    let header = block.header().header();
1146
1147                    block_roots_to_prune.contains(&header.prefix.parent_root)
1148                })
1149                .map(|block| *block.header().root())
1150                .collect();
1151        }
1152    }
1153}
1154
1155#[derive(Debug)]
1156struct SegmentHeadersCache {
1157    segment_headers_cache: Vec<SegmentHeader>,
1158}
1159
1160impl SegmentHeadersCache {
1161    #[inline(always)]
1162    fn last_segment_header(&self) -> Option<SegmentHeader> {
1163        self.segment_headers_cache.last().copied()
1164    }
1165
1166    #[inline(always)]
1167    fn max_local_segment_index(&self) -> Option<LocalSegmentIndex> {
1168        self.segment_headers_cache
1169            .last()
1170            .map(|segment_header| segment_header.index.as_inner())
1171    }
1172
1173    #[inline(always)]
1174    fn get_segment_header(&self, local_segment_index: LocalSegmentIndex) -> Option<SegmentHeader> {
1175        self.segment_headers_cache
1176            .get(u64::from(local_segment_index) as usize)
1177            .copied()
1178    }
1179
1180    /// Returns segment headers that [`Self::add_segment_headers()`] needs to add, skipping
1181    /// segment headers that are already present.
1182    ///
1183    /// Checks that segment indices of all of them follow the last segment header, without changing
1184    /// the cache.
1185    fn segment_headers_to_add(
1186        &self,
1187        mut segment_headers: Vec<SegmentHeader>,
1188    ) -> Result<Vec<SegmentHeader>, PersistSegmentHeadersError> {
1189        let mut maybe_last_local_segment_index = self.max_local_segment_index();
1190
1191        if let Some(last_segment_index) = maybe_last_local_segment_index {
1192            // Skip already stored segment headers
1193            segment_headers
1194                .retain(|segment_header| segment_header.index.as_inner() > last_segment_index);
1195        }
1196
1197        for segment_header in &segment_headers {
1198            let local_segment_index = segment_header.index.as_inner();
1199            if let Some(last_local_segment_index) = maybe_last_local_segment_index {
1200                if local_segment_index != last_local_segment_index + LocalSegmentIndex::ONE {
1201                    return Err(PersistSegmentHeadersError::MustFollowLastSegmentIndex {
1202                        local_segment_index,
1203                        last_local_segment_index,
1204                    });
1205                }
1206            } else if local_segment_index != LocalSegmentIndex::ZERO {
1207                return Err(PersistSegmentHeadersError::FirstSegmentIndexZero {
1208                    local_segment_index,
1209                });
1210            }
1211
1212            maybe_last_local_segment_index.replace(local_segment_index);
1213        }
1214
1215        Ok(segment_headers)
1216    }
1217
1218    /// Add segment headers returned by [`Self::segment_headers_to_add()`], without changes to the
1219    /// cache in between
1220    fn add_segment_headers(&mut self, segment_headers: &[SegmentHeader]) {
1221        self.segment_headers_cache
1222            .extend_from_slice(segment_headers);
1223    }
1224}
1225
1226#[derive(Debug)]
1227struct SuperSegmentHeadersCache {
1228    super_segment_headers_cache: Vec<SuperSegmentHeader>,
1229}
1230
1231impl SuperSegmentHeadersCache {
1232    #[inline(always)]
1233    fn last_super_segment_header(&self) -> Option<SuperSegmentHeader> {
1234        self.super_segment_headers_cache.last().copied()
1235    }
1236
1237    #[inline]
1238    fn previous_super_segment_header(
1239        &self,
1240        target_block_number: BlockNumber,
1241    ) -> Option<SuperSegmentHeader> {
1242        let block_number = target_block_number.checked_sub(BlockNumber::ONE)?;
1243        let index = match self.super_segment_headers_cache.binary_search_by_key(
1244            &block_number,
1245            |super_segment_header| {
1246                super_segment_header
1247                    .target_beacon_chain_block_number
1248                    .as_inner()
1249            },
1250        ) {
1251            Ok(found_index) => found_index,
1252            Err(insert_index) => insert_index.checked_sub(1)?,
1253        };
1254
1255        self.super_segment_headers_cache.get(index).copied()
1256    }
1257
1258    #[inline(always)]
1259    fn get_super_segment_header(
1260        &self,
1261        local_segment_index: SuperSegmentIndex,
1262    ) -> Option<SuperSegmentHeader> {
1263        self.super_segment_headers_cache
1264            .get(u64::from(local_segment_index) as usize)
1265            .copied()
1266    }
1267
1268    #[inline(always)]
1269    fn get_super_segment_header_for_segment_index(
1270        &self,
1271        segment_index: SegmentIndex,
1272    ) -> Option<SuperSegmentHeader> {
1273        let index = self
1274            .super_segment_headers_cache
1275            .binary_search_by_key(&segment_index, |super_segment_header| {
1276                super_segment_header.max_segment_index.as_inner()
1277            })
1278            .unwrap_or_else(|insert_index| insert_index);
1279
1280        let super_segment_header = self.super_segment_headers_cache.get(index).copied()?;
1281
1282        super_segment_header
1283            .segment_position(segment_index)
1284            .is_some()
1285            .then_some(super_segment_header)
1286    }
1287
1288    /// Returns super segment headers that [`Self::add_super_segment_headers()`] needs to add,
1289    /// skipping super segment headers that are already present.
1290    ///
1291    /// Checks that super segment indices of all of them follow the last super segment header,
1292    /// without changing the cache.
1293    fn super_segment_headers_to_add(
1294        &self,
1295        mut super_segment_headers: Vec<SuperSegmentHeader>,
1296    ) -> Result<Vec<SuperSegmentHeader>, PersistSuperSegmentsError> {
1297        let mut maybe_last_super_segment_index = self
1298            .super_segment_headers_cache
1299            .last()
1300            .map(|header| header.index.as_inner());
1301
1302        if let Some(last_super_segment_index) = maybe_last_super_segment_index {
1303            // Skip already stored super segment headers
1304            super_segment_headers.retain(|super_segment_header| {
1305                super_segment_header.index.as_inner() > last_super_segment_index
1306            });
1307        }
1308
1309        for super_segment_header in &super_segment_headers {
1310            let super_segment_index = super_segment_header.index.as_inner();
1311            if let Some(last_super_segment_index) = maybe_last_super_segment_index {
1312                if super_segment_index != last_super_segment_index + SuperSegmentIndex::ONE {
1313                    return Err(PersistSuperSegmentsError::MustFollowLastSegmentIndex {
1314                        super_segment_index,
1315                        last_super_segment_index,
1316                    });
1317                }
1318            } else if super_segment_index != SuperSegmentIndex::ZERO {
1319                return Err(PersistSuperSegmentsError::FirstSegmentIndexZero {
1320                    super_segment_index,
1321                });
1322            }
1323
1324            maybe_last_super_segment_index.replace(super_segment_index);
1325        }
1326
1327        Ok(super_segment_headers)
1328    }
1329
1330    /// Add super segment headers returned by [`Self::super_segment_headers_to_add()`], without
1331    /// changes to the cache in between
1332    fn add_super_segment_headers(&mut self, super_segment_headers: &[SuperSegmentHeader]) {
1333        self.super_segment_headers_cache
1334            .extend_from_slice(super_segment_headers);
1335    }
1336}
1337
1338/// Segment header or super segment header, which are written in pages of permanent page groups
1339trait PagedHeader: AnyBitPattern {
1340    /// Position among headers of this kind, from the first one
1341    fn position(&self) -> u64;
1342
1343    /// Permanent storage item with a page of `headers`
1344    fn permanent_storage_item(headers: StorageItemSlice<Self>) -> StorageItemPermanent;
1345
1346    /// Temporary storage item with `headers` after the last page
1347    fn temporary_storage_item(headers: StorageItemSlice<Self>) -> StorageItemTemporary;
1348}
1349
1350impl PagedHeader for SegmentHeader {
1351    #[inline(always)]
1352    fn position(&self) -> u64 {
1353        u64::from(self.index.as_inner())
1354    }
1355
1356    #[inline(always)]
1357    fn permanent_storage_item(headers: StorageItemSlice<Self>) -> StorageItemPermanent {
1358        StorageItemPermanent::SegmentHeaders(headers)
1359    }
1360
1361    #[inline(always)]
1362    fn temporary_storage_item(headers: StorageItemSlice<Self>) -> StorageItemTemporary {
1363        StorageItemTemporary::SegmentHeaders(headers)
1364    }
1365}
1366
1367impl PagedHeader for SuperSegmentHeader {
1368    #[inline(always)]
1369    fn position(&self) -> u64 {
1370        u64::from(self.index.as_inner())
1371    }
1372
1373    #[inline(always)]
1374    fn permanent_storage_item(headers: StorageItemSlice<Self>) -> StorageItemPermanent {
1375        StorageItemPermanent::SuperSegmentHeaders(headers)
1376    }
1377
1378    #[inline(always)]
1379    fn temporary_storage_item(headers: StorageItemSlice<Self>) -> StorageItemTemporary {
1380        StorageItemTemporary::SuperSegmentHeaders(headers)
1381    }
1382}
1383
1384/// Pages of headers of one kind in permanent page groups that [`ClientDatabase::open()`] replayed
1385#[derive(Debug, Default)]
1386struct HeaderPages {
1387    /// The number of headers in pages, from the first header
1388    num_headers: usize,
1389}
1390
1391impl HeaderPages {
1392    /// Check `headers` of a replayed storage item of `page_group_kind`, which must start right
1393    /// after the headers in pages. A permanent storage item must be a full page, its headers are in
1394    /// pages afterwards.
1395    fn check_read<Header>(
1396        &mut self,
1397        headers: &[Header],
1398        page_group_kind: PageGroupKind,
1399    ) -> Result<(), InvalidStorageItemError>
1400    where
1401        Header: PagedHeader,
1402    {
1403        let num_headers_per_page = StorageItemSlice::<Header>::NUM_ENTRIES_PER_PAGE;
1404        if page_group_kind == PageGroupKind::Permanent && headers.len() != num_headers_per_page {
1405            return Err(InvalidStorageItemError::HeaderPage {
1406                num_headers: headers.len(),
1407                num_headers_per_page,
1408            });
1409        }
1410        if let Some(first_header) = headers.first()
1411            && u64::try_from(self.num_headers) != Ok(first_header.position())
1412        {
1413            return Err(InvalidStorageItemError::HeadersAfterPages {
1414                first_header_position: first_header.position(),
1415                num_headers_in_pages: self.num_headers,
1416            });
1417        }
1418        if page_group_kind == PageGroupKind::Permanent {
1419            self.num_headers += num_headers_per_page;
1420        }
1421
1422        Ok(())
1423    }
1424}
1425
1426// TODO: These are consensus state that belongs to beacon chain state, which a snap-syncing node
1427//  will download and verify against the state root of a block. Beacon chain state doesn't exist
1428//  yet, so for now such a node has no verifiable way to get them.
1429/// The highest local segment index of each shard included in super segments.
1430///
1431/// The number of shards is bounded and entries only ever increase.
1432#[derive(Debug, Default)]
1433struct ShardMaxLocalSegmentIndices {
1434    max_local_segment_indices: BTreeMap<ShardIndex, LocalSegmentIndex>,
1435    /// Shards from the least to the most recently written to the database
1436    write_order: VecDeque<ShardIndex>,
1437}
1438
1439impl ShardMaxLocalSegmentIndices {
1440    /// Merge entries of a storage item that is written to the database, making them the most
1441    /// recently written
1442    fn add_written_entries(&mut self, entries: &[ShardMaxLocalSegmentIndex]) {
1443        for entry in entries {
1444            let ShardMaxLocalSegmentIndex {
1445                shard_index,
1446                local_segment_index,
1447            } = *entry;
1448            let local_segment_index = local_segment_index.as_inner();
1449            let max_local_segment_index = self
1450                .max_local_segment_indices
1451                .entry(shard_index)
1452                .or_insert(local_segment_index);
1453            *max_local_segment_index = (*max_local_segment_index).max(local_segment_index);
1454        }
1455
1456        let written_shard_indices = entries
1457            .iter()
1458            .map(|entry| entry.shard_index)
1459            .collect::<HashSet<_>>();
1460        self.write_order
1461            .retain(|shard_index| !written_shard_indices.contains(shard_index));
1462        self.write_order
1463            .extend(entries.iter().map(|entry| entry.shard_index));
1464    }
1465}
1466
1467// TODO: Hide implementation details
1468#[derive(Debug)]
1469struct State<Block>
1470where
1471    Block: GenericOwnedBlock,
1472{
1473    data: StateData<Block>,
1474    segment_headers_cache: SegmentHeadersCache,
1475    super_segment_headers_cache: SuperSegmentHeadersCache,
1476    shard_max_local_segment_indices: ShardMaxLocalSegmentIndices,
1477}
1478
1479impl<Block> State<Block>
1480where
1481    Block: GenericOwnedBlock,
1482{
1483    #[inline(always)]
1484    fn best_tip(&self) -> &ForkTip {
1485        self.data
1486            .fork_tips
1487            .front()
1488            .expect("The best block is always present; qed")
1489    }
1490
1491    #[inline(always)]
1492    fn best_block(&self) -> &ClientDatabaseBlock<Block> {
1493        self.data
1494            .blocks
1495            .front()
1496            .expect("The best block is always present; qed")
1497            .first()
1498            .expect("The best block is always present; qed")
1499    }
1500
1501    /// Block at `ancestor_block_number` on the chain ending at `descendant_block_root`.
1502    ///
1503    /// If `ancestor_block_number` is the descendant's own number, the descendant is returned.
1504    /// Returns `None` if `ancestor_block_number` is higher than the descendant's number or if
1505    /// either block is not available.
1506    fn ancestor_block(
1507        &self,
1508        ancestor_block_number: BlockNumber,
1509        descendant_block_root: &BlockRoot,
1510    ) -> Option<&ClientDatabaseBlock<Block>> {
1511        let best_number = self.best_tip().number;
1512
1513        let ancestor_block_offset =
1514            u64::from(best_number.checked_sub(ancestor_block_number)?) as usize;
1515        let ancestor_block_candidates = self.data.blocks.get(ancestor_block_offset)?;
1516
1517        let descendant_block_number = *self.data.block_roots.get(descendant_block_root)?;
1518        if ancestor_block_number > descendant_block_number {
1519            return None;
1520        }
1521        let descendant_block_offset =
1522            u64::from(best_number.checked_sub(descendant_block_number)?) as usize;
1523
1524        // Range of blocks where the first item is expected to contain a descendant
1525        let mut blocks_range_iter = self
1526            .data
1527            .blocks
1528            .iter()
1529            .enumerate()
1530            .skip(descendant_block_offset);
1531
1532        let (_offset, descendant_block_candidates) = blocks_range_iter.next()?;
1533        let descendant_block = descendant_block_candidates
1534            .iter()
1535            .find(|block| &*block.header().root() == descendant_block_root)?;
1536
1537        if ancestor_block_number == descendant_block_number {
1538            return Some(descendant_block);
1539        }
1540
1541        // If there are no forks at this level, then this is the canonical chain and ancestor
1542        // block number we're looking for is the first block at the corresponding block number.
1543        // Similarly, if there is just a single ancestor candidate and descendant exists, it must be
1544        // the one we care about.
1545        if descendant_block_candidates.len() == 1 || ancestor_block_candidates.len() == 1 {
1546            return ancestor_block_candidates.first();
1547        }
1548
1549        let mut parent_block_root = &descendant_block.header().header().prefix.parent_root;
1550
1551        // Iterate over the blocks following descendant until ancestor is reached
1552        for (block_offset, parent_candidates) in blocks_range_iter {
1553            let parent_block = parent_candidates
1554                .iter()
1555                .find(|block| &*block.header().root() == parent_block_root)?;
1556
1557            // When block offset matches, we found the block
1558            if block_offset == ancestor_block_offset {
1559                return Some(parent_block);
1560            }
1561
1562            parent_block_root = &parent_block.header().header().prefix.parent_root;
1563        }
1564
1565        None
1566    }
1567
1568    /// Mark the block with `block_root` at `block_number` as persisted at `write_location` once its
1569    /// write finished. At block offset `block_confirmation_depth` and deeper it is confirmed right
1570    /// away, since [`StateData::confirm_canonical_block()`] skipped it while it was in memory.
1571    ///
1572    /// Does nothing if the block was pruned in the meantime.
1573    fn persist_written_block(
1574        &mut self,
1575        block_root: &BlockRoot,
1576        block_number: BlockNumber,
1577        write_location: WriteLocation,
1578        block_confirmation_depth: BlockNumber,
1579    ) {
1580        let Some(block_offset) = self.best_tip().number.checked_sub(block_number) else {
1581            return;
1582        };
1583        let is_confirmed = block_offset >= block_confirmation_depth;
1584        let Some(block) = usize::try_from(u64::from(block_offset))
1585            .ok()
1586            .and_then(|block_offset| self.data.blocks.get_mut(block_offset))
1587            .and_then(|fork_blocks| {
1588                fork_blocks
1589                    .iter_mut()
1590                    .find(|fork_block| *fork_block.header().root() == *block_root)
1591            })
1592        else {
1593            return;
1594        };
1595
1596        replace_with_or_abort(block, |block| {
1597            let ClientDatabaseBlock::Writing {
1598                block,
1599                block_details,
1600                beacon_chain_block_details,
1601            } = block
1602            else {
1603                return block;
1604            };
1605            let (header, _body) = block.split();
1606
1607            if is_confirmed {
1608                ClientDatabaseBlock::PersistedConfirmed {
1609                    header,
1610                    beacon_chain_block_details,
1611                    write_location,
1612                }
1613            } else {
1614                ClientDatabaseBlock::Persisted {
1615                    header,
1616                    block_details,
1617                    beacon_chain_block_details,
1618                    write_location,
1619                }
1620            }
1621        });
1622    }
1623}
1624
1625#[derive(Debug)]
1626struct ClientDatabaseInnerOptions {
1627    block_confirmation_depth: BlockNumber,
1628    soft_confirmation_depth: BlockNumber,
1629    max_fork_tips: NonZeroUsize,
1630    max_fork_tip_distance: BlockNumber,
1631}
1632
1633impl ClientDatabaseInnerOptions {
1634    /// Create options, checking that `block_confirmation_depth` is at least 2 and
1635    /// `soft_confirmation_depth` is smaller than `block_confirmation_depth`
1636    fn new(
1637        block_confirmation_depth: BlockNumber,
1638        soft_confirmation_depth: BlockNumber,
1639        max_fork_tips: NonZeroUsize,
1640        max_fork_tip_distance: BlockNumber,
1641    ) -> Result<Self, ClientDatabaseError> {
1642        if block_confirmation_depth < BlockNumber::from(2) {
1643            return Err(ClientDatabaseError::InvalidBlockConfirmationDepth);
1644        }
1645
1646        if soft_confirmation_depth >= block_confirmation_depth {
1647            return Err(ClientDatabaseError::InvalidSoftConfirmationDepth);
1648        }
1649
1650        Ok(Self {
1651            block_confirmation_depth,
1652            soft_confirmation_depth,
1653            max_fork_tips,
1654            max_fork_tip_distance,
1655        })
1656    }
1657
1658    /// Block offset of the block that the next best block (block number `best_number + 1`)
1659    /// confirms, fork blocks are only accepted above it and other blocks there are pruned.
1660    ///
1661    /// With `block_confirmation_depth = 5` (see the block lifecycle in [`ClientDatabaseOptions`]):
1662    ///
1663    /// ```text
1664    /// block offset  block number  fork blocks
1665    ///            0  n             accepted
1666    ///            1  n - 1         accepted
1667    ///            2  n - 2         accepted
1668    ///            3  n - 3         accepted
1669    ///            4  n - 4         rejected, other blocks pruned,
1670    ///                             confirmed once n + 1 is imported
1671    /// ```
1672    #[inline(always)]
1673    fn fork_pruning_block_offset(&self) -> usize {
1674        let fork_pruning_block_offset = self
1675            .block_confirmation_depth
1676            .checked_sub(BlockNumber::ONE)
1677            .expect("Block confirmation depth is checked to be at least 2 in `Self::new()`; qed");
1678
1679        u64::from(fork_pruning_block_offset) as usize
1680    }
1681}
1682
1683#[derive(Debug)]
1684struct Inner<Block, StorageBackend>
1685where
1686    Block: GenericOwnedBlock,
1687{
1688    state: Arc<AsyncRwLock<State<Block>>>,
1689    /// Storage backend that persisted blocks are read from, the worker writes to its clone
1690    storage_backend: StorageBackend,
1691    /// Sender of tasks to the worker.
1692    ///
1693    /// Methods that write reserve a permit before they lock the state and send their task with it
1694    /// under the state lock, so tasks are in the channel in the order of state updates.
1695    task_sender: mpsc::Sender<Task>,
1696    options: ClientDatabaseInnerOptions,
1697}
1698
1699impl<Block, StorageBackend> Inner<Block, StorageBackend>
1700where
1701    Block: GenericOwnedBlock,
1702{
1703    /// Wait until the worker scheduled all writes of a task, returns `false` if it returned before
1704    /// that.
1705    ///
1706    /// A task sent after the worker returned stays in the channel, so the channel is checked too.
1707    async fn task_scheduled(&self, mut scheduled_receiver: oneshot::Receiver<()>) -> bool {
1708        let mut closed = pin!(self.task_sender.closed());
1709
1710        future::poll_fn(|context| {
1711            if let Poll::Ready(result) = Pin::new(&mut scheduled_receiver).poll(context) {
1712                return Poll::Ready(result.is_ok());
1713            }
1714            if closed.as_mut().poll(context).is_ready() {
1715                // The worker may have sent the notification before returning, polling can still
1716                // return pending due to the cooperative scheduling budget of the runtime
1717                return Poll::Ready(scheduled_receiver.try_recv().is_ok());
1718            }
1719
1720            Poll::Pending
1721        })
1722        .await
1723    }
1724}
1725
1726/// State that [`ClientDatabase::open()`] reconstructs from storage items, with one method per
1727/// storage item, in the order they were written
1728struct Replay<'a, Block>
1729where
1730    Block: GenericOwnedBlock,
1731{
1732    options: &'a ClientDatabaseInnerOptions,
1733    state_data: StateData<Block>,
1734    segment_headers_cache: SegmentHeadersCache,
1735    segment_header_pages: HeaderPages,
1736    super_segment_headers_cache: SuperSegmentHeadersCache,
1737    super_segment_header_pages: HeaderPages,
1738    shard_max_local_segment_indices: ShardMaxLocalSegmentIndices,
1739}
1740
1741impl<Block> Replay<'_, Block>
1742where
1743    Block: GenericOwnedBlock,
1744{
1745    fn add_block(
1746        &mut self,
1747        storage_item: StorageItemTemporaryBlock,
1748        page_offset: u32,
1749        num_pages: u32,
1750    ) -> Result<(), ClientDatabaseError> {
1751        let StorageItemTemporaryBlock {
1752            header,
1753            body,
1754            mmr_with_block,
1755            mut system_contract_states,
1756        } = storage_item;
1757
1758        // Headers stay in memory for a long time and must not keep the memory of the whole page
1759        // group alive
1760        let header = Block::Header::from_buffer(header.into_standalone()).map_err(|_buffer| {
1761            ClientDatabaseError::InvalidStorageItem {
1762                storage_item: "block",
1763                page_offset,
1764                error: InvalidStorageItemError::BlockHeaderDecoding,
1765            }
1766        })?;
1767        let body = Block::Body::from_buffer(body).map_err(|_buffer| {
1768            ClientDatabaseError::InvalidStorageItem {
1769                storage_item: "block",
1770                page_offset,
1771                error: InvalidStorageItemError::BlockBodyDecoding,
1772            }
1773        })?;
1774
1775        let block_root = *header.root();
1776        let block_number = header.header().prefix.number;
1777
1778        // Replaying a block again would add it as its own fork, pruning of which would also remove
1779        // the original block with its descendants
1780        if self
1781            .state_data
1782            .block_roots
1783            .insert(block_root, block_number)
1784            .is_some()
1785        {
1786            return Err(ClientDatabaseError::InvalidStorageItem {
1787                storage_item: "block",
1788                page_offset,
1789                error: InvalidStorageItemError::BlockAlreadyKnown { block_root },
1790            });
1791        }
1792
1793        let maybe_best_number = self
1794            .state_data
1795            .blocks
1796            .front()
1797            .and_then(|block_forks| block_forks.first())
1798            .map(|best_block| {
1799                // Type inference is not working here for some reason
1800                let header: &Block::Header = best_block.header();
1801
1802                header.header().prefix.number
1803            });
1804
1805        let block_offset = if let Some(best_number) = maybe_best_number {
1806            if block_number <= best_number {
1807                u64::from(best_number - block_number) as usize
1808            } else {
1809                // The new best block must follow the previous best block
1810                if block_number - best_number != BlockNumber::ONE {
1811                    return Err(ClientDatabaseError::InvalidStorageItem {
1812                        storage_item: "block",
1813                        page_offset,
1814                        error: InvalidStorageItemError::BlockNumberAboveBestBlock {
1815                            block_number,
1816                            best_number,
1817                        },
1818                    });
1819                }
1820
1821                self.state_data.blocks.push_front(SmallVec::new());
1822                // Will insert a new block at the front
1823                0
1824            }
1825        } else {
1826            self.state_data.blocks.push_front(SmallVec::new());
1827            // Will insert a new block at the front
1828            0
1829        };
1830
1831        let Some(block_forks) = self.state_data.blocks.get_mut(block_offset) else {
1832            // Ignore the older block, other blocks at its height were already pruned anyway
1833            return Ok(());
1834        };
1835
1836        // Contents stay in memory for a long time and must not keep the memory of the whole page
1837        // group alive
1838        let system_contract_states_mut = Arc::get_mut(&mut system_contract_states)
1839            .expect("Decoded above and not shared with anything yet; qed");
1840        for system_contract_state in system_contract_states_mut {
1841            system_contract_state.contents =
1842                mem::take(&mut system_contract_state.contents).into_standalone();
1843        }
1844
1845        // Push a new block to the end of the list, we'll fix it up later
1846        let beacon_chain_block_details = <dyn Any>::downcast_ref::<OwnedBeaconChainBody>(&body)
1847            .map(|body| BeaconChainBlockDetails::from_body(body.body()));
1848        block_forks.push(ClientDatabaseBlock::Persisted {
1849            header,
1850            block_details: BlockDetails {
1851                mmr_with_block,
1852                system_contract_states,
1853            },
1854            beacon_chain_block_details,
1855            write_location: WriteLocation {
1856                page_offset,
1857                num_pages,
1858            },
1859        });
1860
1861        // If a new block was inserted, prune forks and confirm a new canonical block to prune extra
1862        // in-memory information, like `ClientDatabase::insert_new_best_block()` does (see the
1863        // block lifecycle in `ClientDatabaseOptions`)
1864        if block_offset == 0 && block_forks.len() == 1 {
1865            // Deeper block offsets only have a single block, so ancestor walks stop there
1866            let fork_pruning_block_offset = self.options.fork_pruning_block_offset();
1867
1868            // Block forks are in the order they were written in rather than in canonical order
1869            // here. Any block at a new highest block number descends from the only block that was
1870            // left at the fork pruning block offset when it was written, so the forks are adjusted
1871            // towards the block just read first.
1872            if self
1873                .state_data
1874                .blocks
1875                .get(fork_pruning_block_offset)
1876                .is_some_and(|block_forks| block_forks.len() > 1)
1877            {
1878                if !self.state_data.adjust_ancestor_block_forks(
1879                    block_root,
1880                    AncestorBlockForksWalk::UpToBlockOffset {
1881                        max_block_offset: fork_pruning_block_offset,
1882                    },
1883                ) {
1884                    return Err(ClientDatabaseError::FailedToAdjustAncestorBlockForks {
1885                        block_number,
1886                    });
1887                }
1888
1889                self.state_data
1890                    .prune_non_canonical_blocks(fork_pruning_block_offset);
1891            }
1892
1893            self.state_data
1894                .confirm_canonical_block(block_number, self.options);
1895        }
1896
1897        Ok(())
1898    }
1899
1900    /// Add segment headers of a storage item of `page_group_kind`, skipping the ones that are
1901    /// already present
1902    fn add_segment_headers(
1903        &mut self,
1904        storage_item: StorageItemSlice<SegmentHeader>,
1905        page_offset: u32,
1906        page_group_kind: PageGroupKind,
1907    ) -> Result<(), ClientDatabaseError> {
1908        self.segment_header_pages
1909            .check_read(&storage_item.entries, page_group_kind)
1910            .map_err(|error| ClientDatabaseError::InvalidStorageItem {
1911                storage_item: "segment headers",
1912                page_offset,
1913                error,
1914            })?;
1915        let segment_headers = self
1916            .segment_headers_cache
1917            .segment_headers_to_add(storage_item.entries)
1918            .map_err(|error| ClientDatabaseError::InvalidStorageItem {
1919                storage_item: "segment headers",
1920                page_offset,
1921                error: InvalidStorageItemError::SegmentHeaders { error },
1922            })?;
1923        self.segment_headers_cache
1924            .add_segment_headers(&segment_headers);
1925
1926        Ok(())
1927    }
1928
1929    /// Add super segment headers of a storage item of `page_group_kind`, skipping the ones that are
1930    /// already present
1931    fn add_super_segment_headers(
1932        &mut self,
1933        storage_item: StorageItemSlice<SuperSegmentHeader>,
1934        page_offset: u32,
1935        page_group_kind: PageGroupKind,
1936    ) -> Result<(), ClientDatabaseError> {
1937        self.super_segment_header_pages
1938            .check_read(&storage_item.entries, page_group_kind)
1939            .map_err(|error| ClientDatabaseError::InvalidStorageItem {
1940                storage_item: "super segment headers",
1941                page_offset,
1942                error,
1943            })?;
1944        let super_segment_headers = self
1945            .super_segment_headers_cache
1946            .super_segment_headers_to_add(storage_item.entries)
1947            .map_err(|error| ClientDatabaseError::InvalidStorageItem {
1948                storage_item: "super segment headers",
1949                page_offset,
1950                error: InvalidStorageItemError::SuperSegmentHeaders { error },
1951            })?;
1952        self.super_segment_headers_cache
1953            .add_super_segment_headers(&super_segment_headers);
1954
1955        Ok(())
1956    }
1957
1958    fn add_shard_max_local_segment_indices(
1959        &mut self,
1960        storage_item: StorageItemSlice<ShardMaxLocalSegmentIndex>,
1961    ) {
1962        self.shard_max_local_segment_indices
1963            .add_written_entries(&storage_item.entries);
1964    }
1965}
1966
1967/// Client database
1968#[derive(Debug)]
1969pub struct ClientDatabase<Block, StorageBackend>
1970where
1971    Block: GenericOwnedBlock,
1972{
1973    inner: Arc<Inner<Block, StorageBackend>>,
1974}
1975
1976impl<Block, StorageBackend> Clone for ClientDatabase<Block, StorageBackend>
1977where
1978    Block: GenericOwnedBlock,
1979{
1980    fn clone(&self) -> Self {
1981        Self {
1982            inner: self.inner.clone(),
1983        }
1984    }
1985}
1986
1987impl<Block, StorageBackend> ChainInfo<Block> for ClientDatabase<Block, StorageBackend>
1988where
1989    Block: GenericOwnedBlock,
1990    StorageBackend: ClientDatabaseStorageBackend,
1991{
1992    #[inline]
1993    fn best_root(&self) -> BlockRoot {
1994        // Blocking read lock is fine because where a write lock is only taken for a short time and
1995        // most locks are read locks
1996        self.inner.state.read_blocking().best_tip().root
1997    }
1998
1999    #[inline]
2000    fn best_header(&self) -> Block::Header {
2001        // Blocking read lock is fine because where a write lock is only taken for a short time and
2002        // most locks are read locks
2003        self.inner
2004            .state
2005            .read_blocking()
2006            .best_block()
2007            .header()
2008            .clone()
2009    }
2010
2011    #[inline]
2012    fn best_header_with_details(&self) -> (Block::Header, BlockDetails) {
2013        // Blocking read lock is fine because where a write lock is only taken for a short time and
2014        // most locks are read locks
2015        let state = self.inner.state.read_blocking();
2016        let best_block = state.best_block();
2017        (
2018            best_block.header().clone(),
2019            best_block
2020                .block_details()
2021                .expect("Always present for the best block; qed")
2022                .clone(),
2023        )
2024    }
2025
2026    // TODO: Add fast path when `descendant_block_root` is the best block
2027    #[inline]
2028    fn ancestor_header(
2029        &self,
2030        ancestor_block_number: BlockNumber,
2031        descendant_block_root: &BlockRoot,
2032    ) -> Option<Block::Header> {
2033        // Blocking read lock is fine because where a write lock is only taken for a short time and
2034        // most locks are read locks
2035        let state = self.inner.state.read_blocking();
2036
2037        state
2038            .ancestor_block(ancestor_block_number, descendant_block_root)
2039            .map(|block| block.header().clone())
2040    }
2041
2042    #[inline]
2043    fn header(&self, block_root: &BlockRoot) -> Option<Block::Header> {
2044        // Blocking read lock is fine because where a write lock is only taken for a short time and
2045        // most locks are read locks
2046        let state = self.inner.state.read_blocking();
2047        let best_number = state.best_tip().number;
2048
2049        let block_number = *state.data.block_roots.get(block_root)?;
2050        let block_offset = u64::from(best_number.checked_sub(block_number)?) as usize;
2051        let block_candidates = state.data.blocks.get(block_offset)?;
2052
2053        block_candidates.iter().find_map(|block| {
2054            let header = block.header();
2055
2056            if &*header.root() == block_root {
2057                Some(header.clone())
2058            } else {
2059                None
2060            }
2061        })
2062    }
2063
2064    #[inline]
2065    fn header_with_details(&self, block_root: &BlockRoot) -> Option<(Block::Header, BlockDetails)> {
2066        // Blocking read lock is fine because where a write lock is only taken for a short time and
2067        // most locks are read locks
2068        let state = self.inner.state.read_blocking();
2069        let best_number = state.best_tip().number;
2070
2071        let block_number = *state.data.block_roots.get(block_root)?;
2072        let block_offset = u64::from(best_number.checked_sub(block_number)?) as usize;
2073        let block_candidates = state.data.blocks.get(block_offset)?;
2074
2075        block_candidates.iter().find_map(|block| {
2076            let header = block.header();
2077            let block_details = block.block_details().cloned()?;
2078
2079            if &*header.root() == block_root {
2080                Some((header.clone(), block_details))
2081            } else {
2082                None
2083            }
2084        })
2085    }
2086
2087    #[inline]
2088    async fn block(&self, block_root: &BlockRoot) -> Result<Block, ReadBlockError> {
2089        let (header, write_location) = {
2090            let state = self.inner.state.read().await;
2091            let best_number = state.best_tip().number;
2092
2093            let block_number = *state
2094                .data
2095                .block_roots
2096                .get(block_root)
2097                .ok_or(ReadBlockError::UnknownBlockRoot)?;
2098            let block_offset = u64::from(
2099                best_number
2100                    .checked_sub(block_number)
2101                    .expect("Known block roots always have valid block offset; qed"),
2102            ) as usize;
2103            let block = state
2104                .data
2105                .blocks
2106                .get(block_offset)
2107                .expect("Valid block offsets always have block entries; qed")
2108                .iter()
2109                .find(|block_candidate| &*block_candidate.header().root() == block_root)
2110                .expect("Known block root always has block candidate associated with it; qed");
2111
2112            match block.full_block() {
2113                FullBlock::InMemory(block) => {
2114                    return Ok(block.clone());
2115                }
2116                FullBlock::Persisted {
2117                    header,
2118                    write_location,
2119                } => (header.clone(), write_location),
2120            }
2121        };
2122
2123        // Blocks are only persisted once their writes finished, so the storage backend has them
2124        let storage_item = StorageBackendAdapter::read_storage_item::<StorageItemTemporary>(
2125            &self.inner.storage_backend,
2126            write_location,
2127        )
2128        .await?;
2129
2130        let StorageItemTemporary::Block(storage_item_block) = storage_item else {
2131            return Err(ReadBlockError::StorageItemReadError {
2132                error: io::Error::other("Storage item is not a block"),
2133            });
2134        };
2135
2136        let StorageItemTemporaryBlock {
2137            header: _,
2138            body,
2139            mmr_with_block: _,
2140            system_contract_states: _,
2141        } = storage_item_block;
2142
2143        let body =
2144            Block::Body::from_buffer(body).map_err(|_buffer| ReadBlockError::FailedToDecode)?;
2145
2146        Block::from_parts(header, body).map_err(|_parts| ReadBlockError::FailedToDecode)
2147    }
2148
2149    #[inline]
2150    fn last_segment_header(&self) -> Option<SegmentHeader> {
2151        // Blocking read lock is fine because where a write lock is only taken for a short time and
2152        // most locks are read locks
2153        let state = self.inner.state.read_blocking();
2154        state.segment_headers_cache.last_segment_header()
2155    }
2156
2157    #[inline]
2158    fn get_segment_header(&self, segment_index: LocalSegmentIndex) -> Option<SegmentHeader> {
2159        // Blocking read lock is fine because where a write lock is only taken for a short time and
2160        // most locks are read locks
2161        let state = self.inner.state.read_blocking();
2162
2163        state
2164            .segment_headers_cache
2165            .get_segment_header(segment_index)
2166    }
2167
2168    fn segment_headers_for_block(&self, block_number: BlockNumber) -> Vec<SegmentHeader> {
2169        // Blocking read lock is fine because where a write lock is only taken for a short time and
2170        // most locks are read locks
2171        let state = self.inner.state.read_blocking();
2172
2173        let Some(last_local_segment_index) = state.segment_headers_cache.max_local_segment_index()
2174        else {
2175            // Not initialized
2176            return Vec::new();
2177        };
2178
2179        // Special case for the initial segment (for beacon chain genesis block)
2180        if Block::Block::SHARD_KIND == RealShardKind::BeaconChain
2181            && block_number == BlockNumber::ONE
2182        {
2183            // If there is a segment index present, and we store monotonically increasing segment
2184            // headers, then the first header exists
2185            return vec![
2186                state
2187                    .segment_headers_cache
2188                    .get_segment_header(LocalSegmentIndex::ZERO)
2189                    .expect("Segment headers are stored in monotonically increasing order; qed"),
2190            ];
2191        }
2192
2193        if last_local_segment_index == LocalSegmentIndex::ZERO {
2194            // Genesis segment already included in block #1
2195            return Vec::new();
2196        }
2197
2198        let mut current_local_segment_index = last_local_segment_index;
2199        loop {
2200            // If the current segment index present, and we store monotonically increasing segment
2201            // headers, then the current segment header exists as well.
2202            let current_segment_header = state
2203                .segment_headers_cache
2204                .get_segment_header(current_local_segment_index)
2205                .expect("Segment headers are stored in monotonically increasing order; qed");
2206
2207            // The block immediately after the archived segment adding the confirmation depth
2208            let target_block_number = current_segment_header.last_archived_block.number()
2209                + BlockNumber::ONE
2210                + self.inner.options.block_confirmation_depth;
2211            if target_block_number == block_number {
2212                let mut headers_for_block = vec![current_segment_header];
2213
2214                // Check block spanning multiple segments
2215                let last_archived_block_number = current_segment_header.last_archived_block.number;
2216                let mut local_segment_index = current_local_segment_index - LocalSegmentIndex::ONE;
2217
2218                while let Some(segment_header) = state
2219                    .segment_headers_cache
2220                    .get_segment_header(local_segment_index)
2221                {
2222                    if segment_header.last_archived_block.number == last_archived_block_number {
2223                        headers_for_block.insert(0, segment_header);
2224                        local_segment_index -= LocalSegmentIndex::ONE;
2225                    } else {
2226                        break;
2227                    }
2228                }
2229
2230                return headers_for_block;
2231            }
2232
2233            // iterate segments further
2234            if target_block_number > block_number {
2235                // no need to check the initial segment
2236                if current_local_segment_index > LocalSegmentIndex::ONE {
2237                    current_local_segment_index -= LocalSegmentIndex::ONE;
2238                } else {
2239                    break;
2240                }
2241            } else {
2242                // No segment headers required
2243                return Vec::new();
2244            }
2245        }
2246
2247        // No segment headers required
2248        Vec::new()
2249    }
2250}
2251
2252impl<Block, StorageBackend> ChainInfoWrite<Block> for ClientDatabase<Block, StorageBackend>
2253where
2254    Block: GenericOwnedBlock,
2255    StorageBackend: ClientDatabaseStorageBackend,
2256{
2257    async fn persist_block(
2258        &self,
2259        block: Block,
2260        block_details: BlockDetails,
2261    ) -> Result<PersistedBlockInfo, PersistBlockError> {
2262        let permit = self
2263            .inner
2264            .task_sender
2265            .reserve()
2266            .await
2267            .map_err(|_error| PersistBlockError::Unavailable)?;
2268        let mut state = self.inner.state.write().await;
2269        let best_number = state.best_tip().number;
2270
2271        let header = block.header().header();
2272
2273        let block_number = header.prefix.number;
2274        let block_root = *header.root();
2275
2276        // A known block would be stored again as a separate fork block, pruning of which would
2277        // also remove the original block
2278        if state.data.block_roots.contains_key(&block_root) {
2279            return Err(PersistBlockError::AlreadyKnown);
2280        }
2281
2282        if best_number == BlockNumber::ZERO && block_number != BlockNumber::ONE {
2283            // Special case when syncing on top of the fresh database
2284            Self::insert_first_block(&mut state.data, block, block_details);
2285
2286            return Ok(PersistedBlockInfo { is_new_best: true });
2287        }
2288
2289        if block_number == best_number + BlockNumber::ONE {
2290            let blocks =
2291                Self::insert_new_best_block(&mut state, &self.inner.options, block, block_details)?;
2292
2293            if !blocks.is_empty() {
2294                let (scheduled_sender, scheduled_receiver) = oneshot::channel();
2295                permit.send(Task::Blocks {
2296                    blocks,
2297                    scheduled_sender,
2298                });
2299                drop(state);
2300
2301                if !self.inner.task_scheduled(scheduled_receiver).await {
2302                    return Err(PersistBlockError::Unavailable);
2303                }
2304            }
2305
2306            return Ok(PersistedBlockInfo { is_new_best: true });
2307        }
2308
2309        let block_offset = u64::from(
2310            best_number
2311                .checked_sub(block_number)
2312                .ok_or(PersistBlockError::MissingParent)?,
2313        ) as usize;
2314
2315        // A fork block at the fork pruning block offset or deeper could only become a part of the
2316        // best chain with a reorg of at least `block_confirmation_depth` blocks (see the block
2317        // lifecycle in `ClientDatabaseOptions`)
2318        if block_offset >= self.inner.options.fork_pruning_block_offset() {
2319            return Err(PersistBlockError::OutsideAcceptableRange);
2320        }
2321
2322        // The parent may have been pruned after block import checked it and before this write
2323        // lock was taken
2324        if !state
2325            .data
2326            .block_roots
2327            .contains_key(&header.prefix.parent_root)
2328        {
2329            return Err(PersistBlockError::MissingParent);
2330        }
2331
2332        let state = &mut *state;
2333
2334        let block_forks = state.data.blocks.get_mut(block_offset).ok_or_else(|| {
2335            error!(
2336                %block_number,
2337                %block_offset,
2338                "Block offset of the fork block is missing even though its parent is known, this \
2339                is an implementation bug"
2340            );
2341
2342            PersistBlockError::OutsideAcceptableRange
2343        })?;
2344
2345        for (index, fork_tip) in state.data.fork_tips.iter_mut().enumerate() {
2346            // Block's parent is no longer a fork tip, remove it
2347            if fork_tip.root == header.prefix.parent_root {
2348                state.data.fork_tips.remove(index);
2349                break;
2350            }
2351        }
2352
2353        // Insert at position 1, which means the most recent tip, which doesn't correspond to
2354        // the best block
2355        state.data.fork_tips.insert(
2356            1,
2357            ForkTip {
2358                number: block_number,
2359                root: block_root,
2360            },
2361        );
2362        state.data.block_roots.insert(block_root, block_number);
2363        let beacon_chain_block_details = <dyn Any>::downcast_ref::<OwnedBeaconChainBlock>(&block)
2364            .map(|block| BeaconChainBlockDetails::from_body(block.body.body()));
2365        block_forks.push(ClientDatabaseBlock::InMemory {
2366            block,
2367            block_details,
2368            beacon_chain_block_details,
2369        });
2370
2371        // Forks at or below soft confirmation depth are not persisted here, such forks are only
2372        // imported as part of a chain that is about to become the best chain and are persisted by
2373        // `Self::insert_new_best_block()` once it does
2374
2375        state
2376            .data
2377            .prune_outdated_fork_tips(best_number, &self.inner.options);
2378
2379        Ok(PersistedBlockInfo { is_new_best: false })
2380    }
2381
2382    async fn persist_segment_headers(
2383        &self,
2384        segment_headers: Vec<SegmentHeader>,
2385    ) -> Result<(), PersistSegmentHeadersError> {
2386        let permit = self
2387            .inner
2388            .task_sender
2389            .reserve()
2390            .await
2391            .map_err(|_error| PersistSegmentHeadersError::Unavailable)?;
2392        let mut state = self.inner.state.write().await;
2393
2394        let segment_headers = state
2395            .segment_headers_cache
2396            .segment_headers_to_add(segment_headers)?;
2397
2398        if segment_headers.is_empty() {
2399            return Ok(());
2400        }
2401
2402        state
2403            .segment_headers_cache
2404            .add_segment_headers(&segment_headers);
2405        let (scheduled_sender, scheduled_receiver) = oneshot::channel();
2406        permit.send(Task::SegmentHeaders {
2407            segment_headers,
2408            scheduled_sender,
2409        });
2410        drop(state);
2411
2412        if !self.inner.task_scheduled(scheduled_receiver).await {
2413            return Err(PersistSegmentHeadersError::Unavailable);
2414        }
2415
2416        Ok(())
2417    }
2418}
2419
2420impl<StorageBackend> BeaconChainInfo for ClientDatabase<OwnedBeaconChainBlock, StorageBackend>
2421where
2422    StorageBackend: ClientDatabaseStorageBackend,
2423{
2424    fn shard_segment_roots(
2425        &self,
2426        ancestor_block_number: BlockNumber,
2427        descendant_block_root: &BlockRoot,
2428    ) -> Result<Arc<[ShardSegmentRoot]>, ShardSegmentRootsError> {
2429        // Blocking read lock is fine because where a write lock is only taken for a short time and
2430        // most locks are read locks
2431        let state = self.inner.state.read_blocking();
2432
2433        let block = state
2434            .ancestor_block(ancestor_block_number, descendant_block_root)
2435            .ok_or(ShardSegmentRootsError::BlockMissing {
2436                block_number: ancestor_block_number,
2437            })?;
2438
2439        Ok(Arc::clone(
2440            &block
2441                .beacon_chain_block_details()
2442                .as_ref()
2443                .expect("Always present in the beacon chain block; qed")
2444                .shard_segment_roots,
2445        ))
2446    }
2447
2448    #[inline]
2449    fn last_super_segment_header(&self) -> Option<SuperSegmentHeader> {
2450        // Blocking read lock is fine because where a write lock is only taken for a short time and
2451        // most locks are read locks
2452        let state = self.inner.state.read_blocking();
2453        state
2454            .super_segment_headers_cache
2455            .last_super_segment_header()
2456    }
2457
2458    #[inline]
2459    fn previous_super_segment_header(
2460        &self,
2461        block_number: BlockNumber,
2462    ) -> Option<SuperSegmentHeader> {
2463        // Blocking read lock is fine because where a write lock is only taken for a short time and
2464        // most locks are read locks
2465        let state = self.inner.state.read_blocking();
2466
2467        state
2468            .super_segment_headers_cache
2469            .previous_super_segment_header(block_number)
2470    }
2471
2472    #[inline]
2473    fn get_super_segment_header(
2474        &self,
2475        super_segment_index: SuperSegmentIndex,
2476    ) -> Option<SuperSegmentHeader> {
2477        // Blocking read lock is fine because where a write lock is only taken for a short time and
2478        // most locks are read locks
2479        let state = self.inner.state.read_blocking();
2480
2481        state
2482            .super_segment_headers_cache
2483            .get_super_segment_header(super_segment_index)
2484    }
2485
2486    fn get_super_segment_header_for_segment_index(
2487        &self,
2488        segment_index: SegmentIndex,
2489    ) -> Option<SuperSegmentHeader> {
2490        // Blocking read lock is fine because where a write lock is only taken for a short time and
2491        // most locks are read locks
2492        let state = self.inner.state.read_blocking();
2493
2494        state
2495            .super_segment_headers_cache
2496            .get_super_segment_header_for_segment_index(segment_index)
2497    }
2498
2499    #[inline]
2500    fn shard_max_local_segment_index(&self, shard_index: ShardIndex) -> Option<LocalSegmentIndex> {
2501        // Blocking read lock is fine because where a write lock is only taken for a short time and
2502        // most locks are read locks
2503        let state = self.inner.state.read_blocking();
2504
2505        state
2506            .shard_max_local_segment_indices
2507            .max_local_segment_indices
2508            .get(&shard_index)
2509            .copied()
2510    }
2511}
2512
2513impl<StorageBackend> BeaconChainInfoWrite for ClientDatabase<OwnedBeaconChainBlock, StorageBackend>
2514where
2515    StorageBackend: ClientDatabaseStorageBackend,
2516{
2517    async fn persist_super_segments(
2518        &self,
2519        super_segments: &[SuperSegment],
2520    ) -> Result<bool, PersistSuperSegmentsError> {
2521        let permit = self
2522            .inner
2523            .task_sender
2524            .reserve()
2525            .await
2526            .map_err(|_error| PersistSuperSegmentsError::Unavailable)?;
2527        let mut state = self.inner.state.write().await;
2528
2529        let super_segment_headers = state
2530            .super_segment_headers_cache
2531            .super_segment_headers_to_add(
2532                super_segments
2533                    .iter()
2534                    .map(|super_segment| super_segment.header)
2535                    .collect(),
2536            )?;
2537
2538        let Some(first_added_super_segment_index) = super_segment_headers
2539            .first()
2540            .map(|super_segment_header| super_segment_header.index.as_inner())
2541        else {
2542            return Ok(false);
2543        };
2544
2545        let mut changed_entries = BTreeMap::<ShardIndex, LocalSegmentIndex>::new();
2546        // Super segments that were already present are skipped
2547        for super_segment in super_segments.iter().filter(|super_segment| {
2548            super_segment.header.index.as_inner() >= first_added_super_segment_index
2549        }) {
2550            for segment_root in super_segment.segment_roots.iter() {
2551                let ShardSegmentRootWithPosition {
2552                    shard_index,
2553                    segment_position: _,
2554                    local_segment_index,
2555                    segment_root: _,
2556                } = *segment_root;
2557
2558                if state
2559                    .shard_max_local_segment_indices
2560                    .max_local_segment_indices
2561                    .get(&shard_index)
2562                    .is_none_or(|&max_local_segment_index| {
2563                        max_local_segment_index < local_segment_index
2564                    })
2565                {
2566                    let max_local_segment_index = changed_entries
2567                        .entry(shard_index)
2568                        .or_insert(local_segment_index);
2569                    *max_local_segment_index = (*max_local_segment_index).max(local_segment_index);
2570                }
2571            }
2572        }
2573
2574        let maybe_shard_max_local_segment_indices = if changed_entries.is_empty() {
2575            None
2576        } else {
2577            let mut storage_item = StorageItemSlice {
2578                entries: changed_entries
2579                    .iter()
2580                    .map(
2581                        |(&shard_index, &local_segment_index)| ShardMaxLocalSegmentIndex {
2582                            shard_index,
2583                            local_segment_index: Unaligned::from(local_segment_index),
2584                        },
2585                    )
2586                    .collect(),
2587            };
2588            // The rest of the last page is filled with the least recently written other entries,
2589            // such that every entry is eventually written again and older page groups can be
2590            // pruned without losing anything
2591            let other_entries = state
2592                .shard_max_local_segment_indices
2593                .write_order
2594                .iter()
2595                .filter(|shard_index| !changed_entries.contains_key(shard_index))
2596                .take(storage_item.num_free_entries_in_last_page())
2597                .map(|&shard_index| {
2598                    let max_local_segment_index = state
2599                        .shard_max_local_segment_indices
2600                        .max_local_segment_indices
2601                        .get(&shard_index)
2602                        .copied()
2603                        .expect(
2604                            "Shards are added to the write order together with their entries; qed",
2605                        );
2606
2607                    ShardMaxLocalSegmentIndex {
2608                        shard_index,
2609                        local_segment_index: Unaligned::from(max_local_segment_index),
2610                    }
2611                })
2612                .collect::<Vec<_>>();
2613            storage_item.entries.extend(other_entries);
2614
2615            Some(storage_item.entries)
2616        };
2617
2618        if let Some(entries) = &maybe_shard_max_local_segment_indices {
2619            state
2620                .shard_max_local_segment_indices
2621                .add_written_entries(entries);
2622        }
2623        state
2624            .super_segment_headers_cache
2625            .add_super_segment_headers(&super_segment_headers);
2626        let (scheduled_sender, scheduled_receiver) = oneshot::channel();
2627        permit.send(Task::SuperSegments {
2628            shard_max_local_segment_indices: maybe_shard_max_local_segment_indices,
2629            super_segment_headers,
2630            scheduled_sender,
2631        });
2632        drop(state);
2633
2634        if !self.inner.task_scheduled(scheduled_receiver).await {
2635            return Err(PersistSuperSegmentsError::Unavailable);
2636        }
2637
2638        Ok(true)
2639    }
2640}
2641
2642impl<Block, StorageBackend> ClientDatabase<Block, StorageBackend>
2643where
2644    Block: GenericOwnedBlock,
2645    StorageBackend: ClientDatabaseStorageBackend,
2646{
2647    /// Open the existing database.
2648    ///
2649    /// NOTE: The database needs to be formatted with [`Self::format()`] before it can be used.
2650    ///
2651    /// Opening replays storage items in the order they were written. Every block read at a new
2652    /// highest block number is handled like a new best block: forks are adjusted towards it, other
2653    /// blocks at block offset `block_confirmation_depth - 1` are pruned, then the block at block
2654    /// offset `block_confirmation_depth` is confirmed (see the block lifecycle in
2655    /// [`ClientDatabaseOptions`]). The best block after opening is the last block written at the
2656    /// highest stored block number. It may be behind or on a different fork than the best block
2657    /// before shutdown, the node re-syncs from there.
2658    ///
2659    /// A database that stores another chain or was opened with another block confirmation depth
2660    /// before is not opened, see the chain parameters of the database in the crate documentation.
2661    ///
2662    /// Returns the database with its worker, which the caller has to run with
2663    /// [`ClientDatabaseWorker::run()`], see the crate documentation.
2664    pub async fn open<GBB>(
2665        options: ClientDatabaseOptions<GBB, StorageBackend>,
2666    ) -> Result<(Self, ClientDatabaseWorker<Block, StorageBackend>), ClientDatabaseError>
2667    where
2668        StorageBackend: Clone,
2669        GBB: FnOnce() -> GenesisBlockBuilderResult<Block>,
2670    {
2671        let ClientDatabaseOptions {
2672            write_buffer_size,
2673            block_confirmation_depth,
2674            soft_confirmation_depth,
2675            max_fork_tips,
2676            max_fork_tip_distance,
2677            genesis_block_builder,
2678            storage_backend,
2679        } = options;
2680        let options = ClientDatabaseInnerOptions::new(
2681            block_confirmation_depth,
2682            soft_confirmation_depth,
2683            max_fork_tips,
2684            max_fork_tip_distance,
2685        )?;
2686
2687        let GenesisBlockBuilderResult {
2688            block: genesis_block,
2689            system_contract_states: genesis_system_contract_states,
2690        } = genesis_block_builder();
2691        let chain_parameters = StorageItemPermanentChainParameters {
2692            genesis_root: *genesis_block.header().header().root(),
2693            block_confirmation_depth,
2694        };
2695        let mut has_chain_parameters = false;
2696
2697        let mut replay = Replay {
2698            options: &options,
2699            state_data: StateData {
2700                fork_tips: VecDeque::new(),
2701                block_roots: HashMap::default(),
2702                blocks: VecDeque::new(),
2703            },
2704            segment_headers_cache: SegmentHeadersCache {
2705                segment_headers_cache: Vec::new(),
2706            },
2707            segment_header_pages: HeaderPages::default(),
2708            super_segment_headers_cache: SuperSegmentHeadersCache {
2709                super_segment_headers_cache: Vec::new(),
2710            },
2711            super_segment_header_pages: HeaderPages::default(),
2712            shard_max_local_segment_indices: ShardMaxLocalSegmentIndices::default(),
2713        };
2714
2715        let storage_item_handler = |storage_item| match storage_item {
2716            ReplayedStorageItem::Permanent(StorageItemHandlerArg {
2717                storage_item,
2718                page_offset,
2719                num_pages: _,
2720            }) => match storage_item {
2721                StorageItemPermanent::PageGroupHeader(_)
2722                | StorageItemPermanent::NextPageGroup(_) => {
2723                    unreachable!("Logs handle page group headers and next page group entries; qed")
2724                }
2725                StorageItemPermanent::ChainParameters(stored_chain_parameters) => {
2726                    chain_parameters.check_stored(&stored_chain_parameters)?;
2727                    has_chain_parameters = true;
2728                    Ok(())
2729                }
2730                StorageItemPermanent::SegmentHeaders(storage_item) => {
2731                    replay.add_segment_headers(storage_item, page_offset, PageGroupKind::Permanent)
2732                }
2733                StorageItemPermanent::SuperSegmentHeaders(storage_item) => replay
2734                    .add_super_segment_headers(storage_item, page_offset, PageGroupKind::Permanent),
2735            },
2736            ReplayedStorageItem::Temporary(StorageItemHandlerArg {
2737                storage_item,
2738                page_offset,
2739                num_pages,
2740            }) => {
2741                // The chain parameters are committed first, so they are checked before anything
2742                // else is replayed
2743                if !has_chain_parameters {
2744                    return Err(
2745                        ClientDatabaseError::TemporaryStorageItemBeforeChainParameters {
2746                            page_offset,
2747                        },
2748                    );
2749                }
2750
2751                match storage_item {
2752                    StorageItemTemporary::PageGroupHeader(_)
2753                    | StorageItemTemporary::NextPageGroup(_) => {
2754                        unreachable!(
2755                            "Logs handle page group headers and next page group entries; qed"
2756                        )
2757                    }
2758                    StorageItemTemporary::Commit(_) => {
2759                        unreachable!("Storage backend adapter handles commits; qed")
2760                    }
2761                    StorageItemTemporary::Block(storage_item) => {
2762                        replay.add_block(storage_item, page_offset, num_pages)
2763                    }
2764                    StorageItemTemporary::SegmentHeaders(storage_item) => replay
2765                        .add_segment_headers(storage_item, page_offset, PageGroupKind::Temporary),
2766                    StorageItemTemporary::SuperSegmentHeaders(storage_item) => replay
2767                        .add_super_segment_headers(
2768                            storage_item,
2769                            page_offset,
2770                            PageGroupKind::Temporary,
2771                        ),
2772                    StorageItemTemporary::ShardMaxLocalSegmentIndices(storage_item) => {
2773                        replay.add_shard_max_local_segment_indices(storage_item);
2774                        Ok(())
2775                    }
2776                }
2777            }
2778        };
2779
2780        let mut storage_backend_adapter = StorageBackendAdapter::open(
2781            write_buffer_size,
2782            storage_item_handler,
2783            storage_backend.clone(),
2784        )
2785        .await?;
2786        // A database without chain parameters is empty and starts with the genesis block below
2787        if !has_chain_parameters {
2788            storage_backend_adapter
2789                .write_storage_item(StorageItemPermanent::ChainParameters(chain_parameters))
2790                .await
2791                .map_err(|error| ClientDatabaseError::FailedToWriteChainParameters { error })?;
2792        }
2793        let Replay {
2794            options: _,
2795            mut state_data,
2796            segment_headers_cache,
2797            segment_header_pages,
2798            super_segment_headers_cache,
2799            super_segment_header_pages,
2800            shard_max_local_segment_indices,
2801        } = replay;
2802        let segment_headers_after_pages = segment_headers_cache
2803            .segment_headers_cache
2804            .get(segment_header_pages.num_headers..)
2805            .expect("Every header in replayed pages was added to the cache; qed")
2806            .to_vec();
2807        let super_segment_headers_after_pages = super_segment_headers_cache
2808            .super_segment_headers_cache
2809            .get(super_segment_header_pages.num_headers..)
2810            .expect("Every header in replayed pages was added to the cache; qed")
2811            .to_vec();
2812
2813        // NOTE: Confirmation is not stored, a deep reorg right after opening may revert blocks that
2814        // were confirmed before shutdown, consumers like the archiver then fail loudly, as intended
2815        if let Some(best_block) = state_data.blocks.front().and_then(|block_forks| {
2816            // The best block is the last block written at the highest block number, block forks
2817            // are in the order they were written in
2818            block_forks.last()
2819        }) {
2820            // Type inference is not working here for some reason
2821            let header: &Block::Header = best_block.header();
2822            let header = header.header();
2823            let block_number = header.prefix.number;
2824            let block_root = *header.root();
2825
2826            // Block forks are in the order they were written in, so all block offsets that may
2827            // have forks are adjusted
2828            if !state_data.adjust_ancestor_block_forks(
2829                block_root,
2830                AncestorBlockForksWalk::UpToBlockOffset {
2831                    max_block_offset: options.fork_pruning_block_offset(),
2832                },
2833            ) {
2834                return Err(ClientDatabaseError::FailedToAdjustAncestorBlockForks { block_number });
2835            }
2836
2837            // Store the best block as the first and only fork tip
2838            state_data.fork_tips.push_front(ForkTip {
2839                number: block_number,
2840                root: block_root,
2841            });
2842        } else {
2843            // If the database is empty, initialize everything with the genesis block
2844            let block_number = genesis_block.header().header().prefix.number;
2845            let block_root = chain_parameters.genesis_root;
2846
2847            state_data.fork_tips.push_front(ForkTip {
2848                number: block_number,
2849                root: block_root,
2850            });
2851            state_data.block_roots.insert(block_root, block_number);
2852            let beacon_chain_block_details =
2853                <dyn Any>::downcast_ref::<OwnedBeaconChainBlock>(&genesis_block)
2854                    .map(|block| BeaconChainBlockDetails::from_body(block.body.body()));
2855            state_data
2856                .blocks
2857                .push_front(smallvec![ClientDatabaseBlock::InMemory {
2858                    block: genesis_block,
2859                    block_details: BlockDetails {
2860                        system_contract_states: genesis_system_contract_states,
2861                        mmr_with_block: Arc::new({
2862                            let mut mmr = BlockMerkleMountainRange::new();
2863                            mmr.add_leaf(&block_root);
2864                            mmr
2865                        })
2866                    },
2867                    beacon_chain_block_details,
2868                }]);
2869        }
2870
2871        let state = Arc::new(AsyncRwLock::new(State {
2872            data: state_data,
2873            segment_headers_cache,
2874            super_segment_headers_cache,
2875            shard_max_local_segment_indices,
2876        }));
2877        let (task_sender, task_receiver) = mpsc::channel(1);
2878
2879        let worker = ClientDatabaseWorker::new(
2880            Arc::clone(&state),
2881            options.block_confirmation_depth,
2882            storage_backend_adapter,
2883            segment_headers_after_pages,
2884            super_segment_headers_after_pages,
2885            task_receiver,
2886        );
2887
2888        let inner = Inner {
2889            state,
2890            storage_backend,
2891            task_sender,
2892            options,
2893        };
2894
2895        Ok((
2896            Self {
2897                inner: Arc::new(inner),
2898            },
2899            worker,
2900        ))
2901    }
2902
2903    /// Format a new database
2904    pub async fn format(
2905        storage_backend: &StorageBackend,
2906        options: ClientDatabaseFormatOptions,
2907    ) -> Result<(), ClientDatabaseFormatError> {
2908        StorageBackendAdapter::format(storage_backend, options).await
2909    }
2910
2911    fn insert_first_block(state: &mut StateData<Block>, block: Block, block_details: BlockDetails) {
2912        // If the database is empty, initialize everything with the genesis block
2913        let header = block.header().header();
2914        let block_number = header.prefix.number;
2915        let block_root = *header.root();
2916
2917        state.fork_tips.clear();
2918        state.fork_tips.push_front(ForkTip {
2919            number: block_number,
2920            root: block_root,
2921        });
2922        state.block_roots.clear();
2923        state.block_roots.insert(block_root, block_number);
2924        state.blocks.clear();
2925        let beacon_chain_block_details = <dyn Any>::downcast_ref::<OwnedBeaconChainBlock>(&block)
2926            .map(|block| BeaconChainBlockDetails::from_body(block.body.body()));
2927        state
2928            .blocks
2929            .push_front(smallvec![ClientDatabaseBlock::InMemory {
2930                block,
2931                block_details,
2932                beacon_chain_block_details,
2933            }]);
2934    }
2935
2936    /// Insert `block` as the new best block and return blocks to write, see the block lifecycle in
2937    /// [`ClientDatabaseOptions`]
2938    fn insert_new_best_block(
2939        state: &mut State<Block>,
2940        options: &ClientDatabaseInnerOptions,
2941        block: Block,
2942        block_details: BlockDetails,
2943    ) -> Result<Vec<BlockToWrite>, PersistBlockError> {
2944        let header = block.header().header();
2945        let block_number = header.prefix.number;
2946        let block_root = *header.root();
2947        let parent_root = header.prefix.parent_root;
2948
2949        // Adjust the relative order of forks to ensure the first index always corresponds to
2950        // ancestors of the new best block
2951        if !state
2952            .data
2953            .adjust_ancestor_block_forks(parent_root, AncestorBlockForksWalk::UntilCanonical)
2954        {
2955            return Err(PersistBlockError::MissingParent);
2956        }
2957
2958        // Store new block in the state
2959        {
2960            for (index, fork_tip) in state.data.fork_tips.iter_mut().enumerate() {
2961                // Block's parent is no longer a fork tip, remove it
2962                if fork_tip.root == parent_root {
2963                    state.data.fork_tips.remove(index);
2964                    break;
2965                }
2966            }
2967
2968            state.data.fork_tips.push_front(ForkTip {
2969                number: block_number,
2970                root: block_root,
2971            });
2972            state.data.block_roots.insert(block_root, block_number);
2973            let beacon_chain_block_details =
2974                <dyn Any>::downcast_ref::<OwnedBeaconChainBlock>(&block)
2975                    .map(|block| BeaconChainBlockDetails::from_body(block.body.body()));
2976            state
2977                .data
2978                .blocks
2979                .push_front(smallvec![ClientDatabaseBlock::InMemory {
2980                    block,
2981                    block_details,
2982                    beacon_chain_block_details,
2983                }]);
2984        }
2985
2986        // The new best block shifted all block offsets by one, other blocks that reached the fork
2987        // pruning block offset could only become a part of the best chain with a reorg of
2988        // `block_confirmation_depth` blocks now (see the block lifecycle in
2989        // `ClientDatabaseOptions`)
2990        state
2991            .data
2992            .prune_non_canonical_blocks(options.fork_pruning_block_offset());
2993        state.data.confirm_canonical_block(block_number, options);
2994        state.data.prune_outdated_fork_tips(block_number, options);
2995
2996        let mut blocks_to_write = Vec::new();
2997        for block_offset in u64::from(options.soft_confirmation_depth) as usize.. {
2998            let Some(fork_blocks) = state.data.blocks.get_mut(block_offset) else {
2999                break;
3000            };
3001
3002            let len_before = blocks_to_write.len();
3003            for fork_block in fork_blocks.iter_mut() {
3004                replace_with_or_abort(fork_block, |fork_block| {
3005                    let ClientDatabaseBlock::InMemory {
3006                        block,
3007                        block_details,
3008                        beacon_chain_block_details,
3009                    } = fork_block
3010                    else {
3011                        return fork_block;
3012                    };
3013
3014                    blocks_to_write.push(BlockToWrite::new(&block, &block_details));
3015                    ClientDatabaseBlock::Writing {
3016                        block,
3017                        block_details,
3018                        beacon_chain_block_details,
3019                    }
3020                });
3021            }
3022
3023            if blocks_to_write.len() == len_before {
3024                break;
3025            }
3026        }
3027
3028        // Blocks are written from older to newer: the deepest block offset first and within each
3029        // block offset the canonical block at fork offset `0` last. The scan above stops at the
3030        // first block offset without blocks to write, so a block is never written before its
3031        // parent. `Self::open()` relies on this order.
3032        blocks_to_write.reverse();
3033
3034        // TODO: Prune blocks that are no longer necessary
3035        // TODO: Prune unused page groups here or elsewhere? Page groups that contain blocks whose
3036        //  block number is within `block_confirmation_depth` of the highest stored block number
3037        //  must not be freed, `Self::open()` needs them to prune forks and find the canonical
3038        //  blocks to confirm. Once older page groups are freed, block numbers below that window
3039        //  may only have forks that are not ancestors of the best block left, `Self::open()`
3040        //  currently confirms such a fork and needs to drop it instead. Add a test for this
3041        //  together with freeing, it also pins the bound of
3042        //  `AncestorBlockForksWalk::UpToBlockOffset`: an unbounded walk fails to find the
3043        //  canonical ancestor at such a block number. Freeing must also carry forward what
3044        //  permanent page groups don't hold, like headers after the last page and the highest
3045        //  local segment indices of shards.
3046
3047        Ok(blocks_to_write)
3048    }
3049}