Skip to main content

ab_client_archiving/
task.rs

1//! Segment archiving task.
2//!
3//! Implements archiving process in that converts blockchain history (blocks) into archived history
4//! (segments and pieces).
5//!
6//! The main entry point here is [`create_segment_archiver_task`] that will create a task, which
7//! while driven will perform the archiving itself.
8//!
9//! Archiving itself will also wait for acknowledgement by various subscribers before proceeding,
10//! which includes farmer subscription, in case of reference implementation via RPC.
11//!
12//! All segment headers of the archived segments are available to other parts of the protocol that
13//! need to know what the correct archival history of the blockchain looks like through
14//! [`ChainInfo`]. For example, it is used during node sync and farmer plotting to verify pieces of
15//! archival history received from other network participants. Future segment header might also be
16//! already known in the case of Snap sync.
17//!
18//! [`encode_block`] and [`decode_block`] are symmetric encoding/decoding functions turning
19//! Blocks into bytes and back.
20
21#[cfg(test)]
22mod tests;
23
24use ab_aligned_buffer::SharedAlignedBuffer;
25use ab_archiving::archiver::{Archiver, ArchiverInstantiationError, NewArchivedSegment};
26use ab_client_api::{ChainInfo, ChainInfoWrite, PersistSegmentHeadersError, ReadBlockError};
27use ab_client_consensus_common::{BlockImportingNotification, ConsensusConstants};
28use ab_core_primitives::block::body::owned::GenericOwnedBlockBody;
29use ab_core_primitives::block::header::GenericBlockHeader;
30use ab_core_primitives::block::header::owned::GenericOwnedBlockHeader;
31use ab_core_primitives::block::owned::GenericOwnedBlock;
32use ab_core_primitives::block::{BlockNumber, BlockRoot, GenericBlock};
33use ab_core_primitives::segments::{LocalSegmentIndex, RecordedHistorySegment, SegmentHeader};
34use ab_core_primitives::shard::RealShardKind;
35use ab_erasure_coding::ErasureCoding;
36use bytesize::ByteSize;
37use chacha20::ChaCha8Rng;
38use chacha20::rand_core::{Rng, SeedableRng};
39use futures::channel::mpsc;
40use futures::prelude::*;
41use std::time::Duration;
42use tracing::{debug, info, trace, warn};
43use triomphe::Arc;
44
45/// Do not wait for acknowledgements beyond this time limit
46const ACKNOWLEDGEMENT_TIMEOUT: Duration = Duration::from_mins(2);
47
48/// Notification with a new archived segment that was just archived
49#[derive(Debug)]
50pub struct ArchivedSegmentNotification {
51    /// Archived segment.
52    pub archived_segment: Arc<NewArchivedSegment>,
53    /// Sender that signified the fact of receiving an archived segment by farmer.
54    ///
55    /// This must be used to send a message, or else the block import pipeline will get stuck.
56    pub acknowledgement_sender: mpsc::Sender<()>,
57}
58
59async fn find_last_archived_block<Block, CI>(
60    chain_info: &CI,
61    best_block_number_to_archive: BlockNumber,
62    best_block_root: &BlockRoot,
63) -> Option<(SegmentHeader, Block)>
64where
65    Block: GenericOwnedBlock,
66    CI: ChainInfo<Block>,
67{
68    let max_local_segment_index = chain_info.last_segment_header()?.index.as_inner();
69
70    for segment_header in (LocalSegmentIndex::ZERO..=max_local_segment_index)
71        .rev()
72        .filter_map(|segment_index| chain_info.get_segment_header(segment_index))
73    {
74        let last_archived_block_number = segment_header.last_archived_block.number();
75
76        if last_archived_block_number > best_block_number_to_archive {
77            // Last archived block in segment header is too high for the current state of the chain
78            // (segment headers store may know about more blocks in existence than is currently
79            // imported)
80            continue;
81        }
82
83        let Some(last_archived_block_header) =
84            chain_info.ancestor_header(last_archived_block_number, best_block_root)
85        else {
86            // This block number is not in our chain yet (segment headers store may know about more
87            // blocks in existence than is currently imported)
88            continue;
89        };
90
91        let last_archived_block_root = &*last_archived_block_header.root();
92
93        let Ok(last_archived_block) = chain_info.block(last_archived_block_root).await else {
94            // Block might have been pruned between ancestor search and disk read
95            continue;
96        };
97
98        return Some((segment_header, last_archived_block));
99    }
100
101    None
102}
103
104/// Encode block for archiving purposes
105pub fn encode_block<Block>(block: &Block) -> Vec<u8>
106where
107    Block: GenericOwnedBlock,
108{
109    let is_beacon_chain_genesis_block = Block::Block::SHARD_KIND == RealShardKind::BeaconChain
110        && block.header().header().prefix.number == BlockNumber::ZERO;
111    let header_buffer = block.header().buffer();
112    let body_buffer = block.body().buffer();
113
114    // TODO: Extra allocation here is unfortunate, would be nice to avoid it
115    let mut encoded_block = Vec::with_capacity(if is_beacon_chain_genesis_block {
116        RecordedHistorySegment::SIZE
117    } else {
118        size_of::<u32>() * 2 + header_buffer.len() as usize + body_buffer.len() as usize
119    });
120
121    encoded_block.extend_from_slice(&header_buffer.len().to_le_bytes());
122    encoded_block.extend_from_slice(&body_buffer.len().to_le_bytes());
123    encoded_block.extend_from_slice(header_buffer);
124    encoded_block.extend_from_slice(body_buffer);
125
126    let encoded_block_length = encoded_block.len();
127    if is_beacon_chain_genesis_block && encoded_block_length < RecordedHistorySegment::SIZE {
128        // Encoding of the genesis block is extended with extra data such that the very first
129        // archived segment can be produced right away, bootstrapping the farming process.
130        //
131        // Note: we add it to the end of the encoded block, so during decoding it'll actually be
132        // ignored even though it is technically present in encoded form.
133        encoded_block.resize(RecordedHistorySegment::SIZE, 0);
134        let mut rng = ChaCha8Rng::from_seed(*block.header().header().result.state_root);
135        rng.fill_bytes(&mut encoded_block[encoded_block_length..]);
136    }
137
138    encoded_block
139}
140
141/// Symmetrical to [`encode_block()`], used to decode previously encoded blocks
142pub fn decode_block<Block>(mut encoded_block: &[u8]) -> Option<Block>
143where
144    Block: GenericOwnedBlock,
145{
146    let header_length;
147    (header_length, encoded_block) = encoded_block.split_first_chunk::<{ size_of::<u32>() }>()?;
148    let header_length = u32::from_le_bytes(*header_length);
149    let body_length;
150    (body_length, encoded_block) = encoded_block.split_first_chunk::<{ size_of::<u32>() }>()?;
151    let body_length = u32::from_le_bytes(*body_length);
152
153    let header_buffer = encoded_block.split_off(..header_length as usize)?;
154    let body_buffer = encoded_block.split_off(..body_length as usize)?;
155
156    let header_buffer = SharedAlignedBuffer::from_bytes(header_buffer);
157    let body_buffer = SharedAlignedBuffer::from_bytes(body_buffer);
158
159    Block::from_buffers(header_buffer, body_buffer).ok()
160}
161
162/// Segment archiver task error
163#[derive(Debug, thiserror::Error)]
164pub enum SegmentArchiverTaskError {
165    /// Archiver instantiation error
166    #[error("Archiver instantiation error: {error}")]
167    Instantiation {
168        /// Low-level error
169        #[from]
170        error: ArchiverInstantiationError,
171    },
172    /// Failed to persist a new segment header
173    #[error("Failed to persist a new segment header: {error}")]
174    PersistSegmentHeaders {
175        /// Low-level error
176        #[from]
177        error: PersistSegmentHeadersError,
178    },
179    /// Block that must be archived is missing in the chain
180    #[error("Block {block_number} that must be archived is missing in the chain")]
181    BlockMissing {
182        /// Block number
183        block_number: BlockNumber,
184    },
185    /// Failed to read a block that must be archived
186    #[error("Failed to read block {block_number} that must be archived: {error}")]
187    ReadBlock {
188        /// Block number
189        block_number: BlockNumber,
190        /// Low-level error
191        error: ReadBlockError,
192    },
193    /// Encoded block is too large to archive
194    #[error("Encoded block {block_number} is too large to archive: {size} bytes")]
195    BlockTooLarge {
196        /// Block number
197        block_number: BlockNumber,
198        /// Encoded block size in bytes
199        size: usize,
200    },
201    /// Attempt to switch to a different fork beyond archiving depth
202    #[error(
203        "Attempt to switch to a different fork beyond archiving depth: parent block root \
204        {parent_block_root}, best archived block root {best_archived_block_root}"
205    )]
206    ArchivingReorg {
207        /// Parent block root
208        parent_block_root: BlockRoot,
209        /// Best archived block root
210        best_archived_block_root: BlockRoot,
211    },
212    /// Re-initialization left a gap before the block to archive
213    #[error(
214        "Re-initialization left a gap before the block to archive (best archived block number \
215        {best_archived_block_number}, block number to archive {block_number_to_archive}, block \
216        about to be imported {importing_block_number})"
217    )]
218    BlockGap {
219        /// Best archived block number
220        best_archived_block_number: BlockNumber,
221        /// Block number to archive
222        block_number_to_archive: BlockNumber,
223        /// Importing block number
224        importing_block_number: BlockNumber,
225    },
226}
227
228struct InitializedArchiver {
229    archiver: Archiver,
230    best_archived_block: (BlockRoot, BlockNumber),
231}
232
233async fn initialize_archiver<Block, CI>(
234    chain_info: &CI,
235    block_confirmation_depth: BlockNumber,
236    erasure_coding: ErasureCoding,
237) -> Result<InitializedArchiver, SegmentArchiverTaskError>
238where
239    Block: GenericOwnedBlock,
240    CI: ChainInfoWrite<Block>,
241{
242    let best_block_header = chain_info.best_header();
243    let best_block_root = *best_block_header.root();
244    let best_block_number: BlockNumber = best_block_header.header().prefix.number;
245
246    let mut best_block_to_archive = best_block_number.saturating_sub(block_confirmation_depth);
247
248    if (best_block_to_archive..best_block_number).any(|block_number| {
249        chain_info
250            .ancestor_header(block_number, &best_block_root)
251            .is_none()
252    }) {
253        // If there are blocks missing headers between best block to archive and best block of the
254        // blockchain it means newer block was inserted by Snap sync and as such is by definition
255        // valid, so we can simply assume that is our best block to archive instead
256        best_block_to_archive = best_block_number;
257    }
258
259    let maybe_last_archived_block =
260        find_last_archived_block(chain_info, best_block_to_archive, &best_block_root).await;
261
262    let have_last_segment_header = maybe_last_archived_block.is_some();
263    let mut best_archived_block = None::<(BlockRoot, BlockNumber)>;
264
265    let mut archiver =
266        if let Some((last_segment_header, last_archived_block)) = maybe_last_archived_block {
267            // Continuing from existing initial state
268            let last_archived_block_number = last_segment_header.last_archived_block.number;
269            info!(
270                %last_archived_block_number,
271                "Resuming archiver from last archived block",
272            );
273
274            let last_archived_block_header = last_archived_block.header().header();
275            // Set initial value, this is needed in case only genesis block was archived and there
276            // is nothing else available
277            best_archived_block.replace((
278                *last_archived_block_header.root(),
279                last_archived_block_header.prefix.number,
280            ));
281
282            let last_archived_block_encoded = encode_block(&last_archived_block);
283
284            Archiver::with_initial_state(
285                best_block_header.header().prefix.shard_index,
286                erasure_coding,
287                last_segment_header,
288                &last_archived_block_encoded,
289                Vec::new(),
290            )?
291        } else {
292            info!("Starting archiving from genesis");
293
294            Archiver::new(
295                best_block_header.header().prefix.shard_index,
296                erasure_coding,
297            )
298        };
299
300    // Process blocks since last fully archived block up to
301    // `best_block_number - block_confirmation_depth`
302    {
303        let blocks_to_archive_from = archiver
304            .last_archived_block_number()
305            .map_or_default(|n| n + BlockNumber::ONE);
306        let blocks_to_archive_to = best_block_number
307            .checked_sub(block_confirmation_depth)
308            .filter(|&blocks_to_archive_to| blocks_to_archive_to >= blocks_to_archive_from)
309            .or({
310                if have_last_segment_header {
311                    None
312                } else {
313                    // If not continuation, archive genesis block
314                    Some(BlockNumber::ZERO)
315                }
316            });
317
318        if let Some(blocks_to_archive_to) = blocks_to_archive_to {
319            info!(
320                "Archiving already produced blocks {}..={}",
321                blocks_to_archive_from, blocks_to_archive_to,
322            );
323
324            for block_number_to_archive in blocks_to_archive_from..=blocks_to_archive_to {
325                // Blocks are missing if segment headers don't match the chain, for example when
326                // Snap sync didn't store them first (see `create_segment_archiver_task()`)
327                let header = chain_info
328                    .ancestor_header(block_number_to_archive, &best_block_root)
329                    .ok_or(SegmentArchiverTaskError::BlockMissing {
330                        block_number: block_number_to_archive,
331                    })?;
332
333                let block = chain_info.block(&header.root()).await.map_err(|error| {
334                    SegmentArchiverTaskError::ReadBlock {
335                        block_number: block_number_to_archive,
336                        error,
337                    }
338                })?;
339
340                let encoded_block = encode_block(&block);
341
342                debug!(
343                    "Encoded block {} has size of {}",
344                    block_number_to_archive,
345                    ByteSize::b(encoded_block.len() as u64).display().iec(),
346                );
347
348                let encoded_block_size = encoded_block.len();
349                let block_outcome = archiver.add_block(encoded_block, Vec::new()).ok_or(
350                    SegmentArchiverTaskError::BlockTooLarge {
351                        block_number: block_number_to_archive,
352                        size: encoded_block_size,
353                    },
354                )?;
355                let new_segment_headers: Vec<SegmentHeader> = block_outcome
356                    .archived_segments
357                    .iter()
358                    .map(|archived_segment| archived_segment.segment_header)
359                    .collect();
360
361                if !new_segment_headers.is_empty() {
362                    chain_info
363                        .persist_segment_headers(new_segment_headers)
364                        .await?;
365                }
366
367                if block_number_to_archive == blocks_to_archive_to {
368                    best_archived_block.replace((*header.root(), block_number_to_archive));
369                }
370            }
371        }
372    }
373
374    Ok(InitializedArchiver {
375        archiver,
376        best_archived_block: best_archived_block
377            .expect("Must always set if there is no logical error; qed"),
378    })
379}
380
381// TODO: Public API for re-archiving of blocks with ability to produce object mappings
382/// Create a segment archiver task.
383///
384/// Archiver task will listen for importing blocks and archive confirmed blocks, producing pieces
385/// and segment headers. It produces local segments initially, which after confirmation by the
386/// beacon chain will be updated with the necessary proof and given a global segment index.
387///
388/// NOTE: Archiver is doing blocking operations and must run in a dedicated task.
389///
390/// Archiver is only able to move forward and doesn't support reorgs. Upon restart, it will check
391/// segments in [`ChainInfo`] and chain history to reconstruct the "current" state it was in before
392/// the last shutdown and continue incrementally archiving blockchain history from there.
393///
394/// Archiving is triggered by block importing notification (`block_importing_notification_receiver`)
395/// and tries to archive the block that the block being imported confirms (see
396/// [`ConsensusConstants::block_confirmation_depth`]). Block importing will then wait for archiver
397/// to acknowledge processing, which is necessary for ensuring that when a child of the block being
398/// imported is imported, the newly archived segment is already available deterministically.
399///
400/// Once a new segment is archived, a notification (`archived_segment_notification_sender`) will be
401/// sent and archiver will be paused until all receivers have provided an acknowledgement for it (or
402/// a very generous timeout has passed). After a restart, a segment that was already announced can
403/// be announced again: blocks that the database didn't write to disk yet (above its
404/// `soft_confirmation_depth`) are lost and imported again, and the blocks they confirm are archived
405/// again.
406///
407/// Snap sync must store all known segment headers before any block is imported, and a block that it
408/// inserts directly, without its ancestors, must be the last archived block of one of those
409/// segments. Re-initialization then resumes archiving from the latest of those segments whose last
410/// archived block is in the chain.
411pub async fn create_segment_archiver_task<Block, CI>(
412    chain_info: CI,
413    mut block_importing_notification_receiver: mpsc::Receiver<BlockImportingNotification>,
414    mut archived_segment_notification_sender: mpsc::Sender<ArchivedSegmentNotification>,
415    consensus_constants: ConsensusConstants,
416    erasure_coding: ErasureCoding,
417) -> Result<
418    impl Future<Output = Result<(), SegmentArchiverTaskError>> + Send + 'static,
419    SegmentArchiverTaskError,
420>
421where
422    Block: GenericOwnedBlock,
423    CI: ChainInfoWrite<Block> + 'static,
424{
425    let maybe_archiver = if chain_info.last_segment_header().is_none() {
426        let initialize_archiver_fut = initialize_archiver(
427            &chain_info,
428            consensus_constants.block_confirmation_depth,
429            erasure_coding.clone(),
430        );
431        Some(initialize_archiver_fut.await?)
432    } else {
433        None
434    };
435
436    Ok(async move {
437        let archiver = if let Some(archiver) = maybe_archiver {
438            archiver
439        } else {
440            let initialize_archiver_fut = initialize_archiver(
441                &chain_info,
442                consensus_constants.block_confirmation_depth,
443                erasure_coding.clone(),
444            );
445            initialize_archiver_fut.await?
446        };
447
448        let InitializedArchiver {
449            mut archiver,
450            best_archived_block,
451        } = archiver;
452        let (mut best_archived_block_root, mut best_archived_block_number) = best_archived_block;
453
454        while let Some(block_importing_notification) =
455            block_importing_notification_receiver.next().await
456        {
457            let importing_block_number = block_importing_notification.block_number;
458            let Some(block_number_to_archive) =
459                importing_block_number.checked_sub(consensus_constants.block_confirmation_depth)
460            else {
461                // Too early to archive blocks
462                continue;
463            };
464
465            // There is no segment header yet when the genesis block doesn't fill a segment, which
466            // is the case on intermediate and leaf shards
467            let maybe_last_archived_block_number = chain_info
468                .last_segment_header()
469                .map(|last_segment_header| last_segment_header.last_archived_block.number());
470            trace!(
471                %importing_block_number,
472                %block_number_to_archive,
473                %best_archived_block_number,
474                last_archived_block_number = ?maybe_last_archived_block_number,
475                "Checking if block needs to be skipped"
476            );
477
478            // Skip archived blocks
479            let skip_last_archived_blocks =
480                maybe_last_archived_block_number.is_some_and(|last_archived_block_number| {
481                    last_archived_block_number > block_number_to_archive
482                });
483            if best_archived_block_number >= block_number_to_archive || skip_last_archived_blocks {
484                // This block was already archived, skip
485                debug!(
486                    %importing_block_number,
487                    %block_number_to_archive,
488                    %best_archived_block_number,
489                    last_archived_block_number = ?maybe_last_archived_block_number,
490                    "Skipping already archived block",
491                );
492                continue;
493            }
494
495            let best_block_root = chain_info.best_root();
496
497            // The best archived block is behind the block to archive when Snap sync inserted a
498            // block directly, or when blocks below the last archived block of the last stored
499            // segment were skipped above (after a restart that lost blocks, for example).
500            // Re-initialize the archiver from stored segments and the chain (see
501            // `create_segment_archiver_task()`).
502            if best_archived_block_number + BlockNumber::ONE != block_number_to_archive {
503                let initialize_archiver_fut = initialize_archiver(
504                    &chain_info,
505                    consensus_constants.block_confirmation_depth,
506                    erasure_coding.clone(),
507                );
508                InitializedArchiver {
509                    archiver,
510                    best_archived_block: (best_archived_block_root, best_archived_block_number),
511                } = initialize_archiver_fut.await?;
512
513                if best_archived_block_number + BlockNumber::ONE == block_number_to_archive {
514                    // As expected, can archive this block
515                } else if best_archived_block_number >= block_number_to_archive {
516                    // This block was already archived, skip
517                    continue;
518                } else {
519                    // Re-initialization leaves the best archived block at
520                    // `best_block_number - block_confirmation_depth` or higher, and the best block
521                    // it reads is the parent of the block being imported, so there can't be a gap
522                    // here unless there is a logic error elsewhere. A block that Snap sync inserts
523                    // directly is found archived, since its segment header is stored first.
524                    return Err(SegmentArchiverTaskError::BlockGap {
525                        best_archived_block_number,
526                        block_number_to_archive,
527                        importing_block_number,
528                    });
529                }
530            }
531
532            (best_archived_block_root, best_archived_block_number) = archive_block(
533                &mut archiver,
534                &chain_info,
535                &mut archived_segment_notification_sender,
536                best_archived_block_root,
537                block_number_to_archive,
538                &best_block_root,
539            )
540            .await?;
541        }
542
543        Ok(())
544    })
545}
546
547/// Tries to archive `block_number` and returns new (or old if not changed) best archived block
548async fn archive_block<Block, CI>(
549    archiver: &mut Archiver,
550    chain_info: &CI,
551    archived_segment_notification_sender: &mut mpsc::Sender<ArchivedSegmentNotification>,
552    best_archived_block_root: BlockRoot,
553    block_number_to_archive: BlockNumber,
554    best_block_root: &BlockRoot,
555) -> Result<(BlockRoot, BlockNumber), SegmentArchiverTaskError>
556where
557    Block: GenericOwnedBlock,
558    CI: ChainInfoWrite<Block>,
559{
560    let header = chain_info
561        .ancestor_header(block_number_to_archive, best_block_root)
562        .ok_or(SegmentArchiverTaskError::BlockMissing {
563            block_number: block_number_to_archive,
564        })?;
565
566    let parent_block_root = header.header().prefix.parent_root;
567    if parent_block_root != best_archived_block_root {
568        return Err(SegmentArchiverTaskError::ArchivingReorg {
569            parent_block_root,
570            best_archived_block_root,
571        });
572    }
573
574    let block_root_to_archive = *header.root();
575
576    let block = chain_info
577        .block(&block_root_to_archive)
578        .await
579        .map_err(|error| SegmentArchiverTaskError::ReadBlock {
580            block_number: block_number_to_archive,
581            error,
582        })?;
583
584    debug!("Archiving block {block_number_to_archive} ({block_root_to_archive})");
585
586    let encoded_block = encode_block(&block);
587    debug!(
588        "Encoded block {block_number_to_archive} has size of {}",
589        ByteSize::b(encoded_block.len() as u64).display().iec(),
590    );
591
592    let encoded_block_size = encoded_block.len();
593    let block_outcome = archiver.add_block(encoded_block, Vec::new()).ok_or(
594        SegmentArchiverTaskError::BlockTooLarge {
595            block_number: block_number_to_archive,
596            size: encoded_block_size,
597        },
598    )?;
599    for archived_segment in block_outcome.archived_segments {
600        let segment_header = archived_segment.segment_header;
601
602        chain_info
603            .persist_segment_headers(vec![segment_header])
604            .await?;
605
606        send_archived_segment_notification(archived_segment_notification_sender, archived_segment)
607            .await;
608    }
609
610    Ok((block_root_to_archive, block_number_to_archive))
611}
612
613async fn send_archived_segment_notification(
614    archived_segment_notification_sender: &mut mpsc::Sender<ArchivedSegmentNotification>,
615    archived_segment: NewArchivedSegment,
616) {
617    let segment_index = archived_segment.segment_header.index;
618    let (acknowledgement_sender, mut acknowledgement_receiver) = mpsc::channel(1);
619    // Keep `archived_segment` around until all acknowledgements are received since some receivers
620    // might use weak references
621    let archived_segment = Arc::new(archived_segment);
622    let archived_segment_notification = ArchivedSegmentNotification {
623        archived_segment: Arc::clone(&archived_segment),
624        acknowledgement_sender,
625    };
626
627    if let Err(error) = archived_segment_notification_sender
628        .send(archived_segment_notification)
629        .await
630    {
631        warn!(
632            %error,
633            "Failed to send archived segment notification"
634        );
635    }
636
637    let wait_fut = async {
638        while acknowledgement_receiver.next().await.is_some() {
639            debug!(
640                "Archived segment notification acknowledged: {}",
641                segment_index
642            );
643        }
644    };
645
646    if tokio::time::timeout(ACKNOWLEDGEMENT_TIMEOUT, wait_fut)
647        .await
648        .is_err()
649    {
650        warn!(
651            "Archived segment notification was not acknowledged and reached timeout, continue \
652            regardless"
653        );
654    }
655}