Skip to main content

subspace_archiving/
archiver.rs

1mod incremental_record_commitments;
2
3extern crate alloc;
4
5use crate::archiver::incremental_record_commitments::{
6    IncrementalRecordCommitmentsState, update_record_commitments,
7};
8use alloc::collections::VecDeque;
9#[cfg(not(feature = "std"))]
10use alloc::vec;
11#[cfg(not(feature = "std"))]
12use alloc::vec::Vec;
13use core::cmp::Ordering;
14use parity_scale_codec::{Compact, CompactLen, Decode, Encode, Input, Output};
15#[cfg(feature = "parallel")]
16use rayon::prelude::*;
17use subspace_core_primitives::hashes::{Blake3Hash, blake3_254_hash_to_scalar};
18use subspace_core_primitives::objects::{BlockObject, BlockObjectMapping, GlobalObject};
19use subspace_core_primitives::pieces::RawRecord;
20use subspace_core_primitives::segments::{
21    ArchivedBlockProgress, ArchivedHistorySegment, LastArchivedBlock, RecordedHistorySegment,
22    SegmentCommitment, SegmentHeader, SegmentIndex,
23};
24use subspace_core_primitives::{BlockNumber, ScalarBytes};
25use subspace_erasure_coding::ErasureCoding;
26use subspace_kzg::{Kzg, Scalar};
27
28const INITIAL_LAST_ARCHIVED_BLOCK: LastArchivedBlock = LastArchivedBlock {
29    number: 0,
30    // Special case for the genesis block.
31    //
32    // When we start archiving process with pre-genesis objects, we do not yet have any blocks
33    // archived, but `LastArchivedBlock` is required for `SegmentHeader`s to be produced, so
34    // `ArchivedBlockProgress::Partial(0)` indicates that we have archived 0 bytes of block `0` (see
35    // field above), meaning we did not in fact archive actual blocks yet.
36    archived_progress: ArchivedBlockProgress::Partial(0),
37};
38
39/// Segment is complete once its encoded size reaches this threshold.
40///
41/// `-2` because even the smallest segment item will take 2 bytes to encode, so it makes sense to
42/// stop earlier here.
43const SEGMENT_SIZE_THRESHOLD: usize = RecordedHistorySegment::SIZE - 2;
44
45/// Segment represents a collection of items stored in archival history of the Subspace blockchain
46#[derive(Debug, Clone, Eq, PartialEq)]
47pub enum Segment {
48    // V0 of the segment data structure
49    V0 {
50        /// Segment items
51        items: Vec<SegmentItem>,
52    },
53}
54
55impl Default for Segment {
56    fn default() -> Self {
57        Segment::V0 { items: Vec::new() }
58    }
59}
60
61impl Encode for Segment {
62    fn size_hint(&self) -> usize {
63        RecordedHistorySegment::SIZE
64    }
65
66    fn encode_to<O: Output + ?Sized>(&self, dest: &mut O) {
67        match self {
68            Segment::V0 { items } => Self::encode_v0_items_to(items, dest),
69        }
70    }
71}
72
73impl Decode for Segment {
74    fn decode<I: Input>(input: &mut I) -> Result<Self, parity_scale_codec::Error> {
75        let variant = input
76            .read_byte()
77            .map_err(|e| e.chain("Could not decode `Segment`, failed to read variant byte"))?;
78        match variant {
79            0 => {
80                let mut items = Vec::new();
81                loop {
82                    match input.remaining_len()? {
83                        Some(0) => {
84                            break;
85                        }
86                        Some(_) => {
87                            // Processing continues below
88                        }
89                        None => {
90                            return Err(
91                                "Source doesn't report remaining length, decoding not possible"
92                                    .into(),
93                            );
94                        }
95                    }
96
97                    match SegmentItem::decode(input) {
98                        Ok(item) => {
99                            items.push(item);
100                        }
101                        Err(error) => {
102                            return Err(error.chain("Could not decode `Segment::V0::items`"));
103                        }
104                    }
105                }
106
107                Ok(Segment::V0 { items })
108            }
109            _ => Err("Could not decode `Segment`, variant doesn't exist".into()),
110        }
111    }
112}
113
114impl Segment {
115    fn push_item(&mut self, segment_item: SegmentItem) {
116        let Self::V0 { items } = self;
117        items.push(segment_item);
118    }
119
120    pub fn items(&self) -> &[SegmentItem] {
121        match self {
122            Segment::V0 { items } => items,
123        }
124    }
125
126    pub(crate) fn items_mut(&mut self) -> &mut Vec<SegmentItem> {
127        match self {
128            Segment::V0 { items } => items,
129        }
130    }
131
132    pub fn into_items(self) -> Vec<SegmentItem> {
133        match self {
134            Segment::V0 { items } => items,
135        }
136    }
137
138    /// Encode items as if they were in [`Segment::V0`] without collecting them into one
139    pub(crate) fn encode_v0_items_to<'a, Items, O>(items: Items, dest: &mut O)
140    where
141        Items: IntoIterator<Item = &'a SegmentItem>,
142        O: Output + ?Sized,
143    {
144        dest.push_byte(0);
145        for item in items {
146            item.encode_to(dest);
147        }
148    }
149}
150
151/// Kinds of items that are contained within a segment
152#[derive(Debug, Clone, Eq, PartialEq, Encode, Decode)]
153pub enum SegmentItem {
154    /// Special dummy enum variant only used as an implementation detail for padding purposes
155    #[codec(index = 0)]
156    Padding,
157    /// Contains full block inside
158    #[codec(index = 1)]
159    Block {
160        /// Block bytes
161        bytes: Vec<u8>,
162        /// This is a convenience implementation detail and will not be available on decoding
163        #[doc(hidden)]
164        #[codec(skip)]
165        object_mapping: BlockObjectMapping,
166    },
167    /// Contains the beginning of the block inside, remainder will be found in subsequent segments
168    #[codec(index = 2)]
169    BlockStart {
170        /// Block bytes
171        bytes: Vec<u8>,
172        /// This is a convenience implementation detail and will not be available on decoding
173        #[doc(hidden)]
174        #[codec(skip)]
175        object_mapping: BlockObjectMapping,
176    },
177    /// Continuation of the partial block spilled over into the next segment
178    #[codec(index = 3)]
179    BlockContinuation {
180        /// Block bytes
181        bytes: Vec<u8>,
182        /// This is a convenience implementation detail and will not be available on decoding
183        #[doc(hidden)]
184        #[codec(skip)]
185        object_mapping: BlockObjectMapping,
186    },
187    /// Segment header of the parent
188    #[codec(index = 4)]
189    ParentSegmentHeader(SegmentHeader),
190}
191
192/// Newly archived segment as a combination of segment header and corresponding archived history
193/// segment containing pieces
194#[derive(Debug, Clone, Eq, PartialEq)]
195pub struct NewArchivedSegment {
196    /// Segment header
197    pub segment_header: SegmentHeader,
198    /// Segment of archived history containing pieces
199    pub pieces: ArchivedHistorySegment,
200}
201
202/// The outcome of adding a block to the archiver.
203#[derive(Debug, Clone, Eq, PartialEq)]
204pub struct ArchiveBlockOutcome {
205    /// The new segments archived after adding the block.
206    /// There can be zero or more segments created after each block.
207    pub archived_segments: Vec<NewArchivedSegment>,
208
209    /// The new object mappings for those segments.
210    /// There can be zero or more mappings created after each block.
211    pub object_mapping: Vec<GlobalObject>,
212}
213
214/// Archiver instantiation error
215#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, thiserror::Error)]
216pub enum ArchiverInstantiationError {
217    /// Invalid last archived block, its size is the same as the encoded block
218    /// (so it should have been completely archived, not partially archived)
219    #[error("Invalid last archived block, its size {0} bytes is the same as the encoded block")]
220    InvalidLastArchivedBlock(u32),
221    /// Invalid block, its size is smaller than the already archived number of bytes
222    #[error(
223        "Invalid block, its size {block_bytes} bytes is smaller than the already archived block \
224        {archived_block_bytes} bytes"
225    )]
226    InvalidBlockSmallSize {
227        /// Full block size
228        block_bytes: u32,
229        /// Already archived portion of the block
230        archived_block_bytes: u32,
231    },
232}
233
234/// Buffer of segment items that keeps track of their total encoded size and which items had their
235/// object mappings produced already
236#[derive(Debug, Default, Clone)]
237struct SegmentItemsBuffer {
238    items: VecDeque<SegmentItem>,
239    /// Total encoded size of all items
240    encoded_size: usize,
241    /// Number of items at the beginning of the buffer that had their object mappings produced
242    num_mapped_items: usize,
243    /// Total encoded size of items that had their object mappings produced
244    mapped_encoded_size: usize,
245}
246
247impl SegmentItemsBuffer {
248    fn len(&self) -> usize {
249        self.items.len()
250    }
251
252    fn iter(&self) -> impl Iterator<Item = &SegmentItem> {
253        self.items.iter()
254    }
255
256    fn push_back(&mut self, item: SegmentItem) {
257        self.encoded_size += item.encoded_size();
258        self.items.push_back(item);
259    }
260
261    fn push_front(&mut self, item: SegmentItem) {
262        self.encoded_size += item.encoded_size();
263        self.items.push_front(item);
264        // New item may have object mappings and shifts offsets of all other items, so all items are
265        // considered unmapped (items that were mapped before have no object mappings left anyway)
266        self.num_mapped_items = 0;
267        self.mapped_encoded_size = 0;
268    }
269
270    fn pop_front(&mut self) -> Option<SegmentItem> {
271        let item = self.items.pop_front()?;
272        let item_encoded_size = item.encoded_size();
273        self.encoded_size = self
274            .encoded_size
275            .checked_sub(item_encoded_size)
276            .expect("Item size was added to the total when the item was inserted; qed");
277        if self.num_mapped_items > 0 {
278            self.num_mapped_items -= 1;
279            self.mapped_encoded_size = self
280                .mapped_encoded_size
281                .checked_sub(item_encoded_size)
282                .expect("Mapped item size was added to the mapped total; qed");
283        }
284        Some(item)
285    }
286
287    /// Returns items that didn't have their object mappings produced yet along with the offset of
288    /// the first of them from the beginning of the buffer.
289    ///
290    /// Returned items are considered mapped afterwards, so object mappings must be produced for
291    /// them. Only fields that are not encoded (like object mappings) may be modified, otherwise the
292    /// total encoded size will be wrong.
293    fn take_unmapped_items(&mut self) -> (usize, impl Iterator<Item = &mut SegmentItem>) {
294        let offset = self.mapped_encoded_size;
295        let first_unmapped_item = self.num_mapped_items;
296
297        self.num_mapped_items = self.items.len();
298        self.mapped_encoded_size = self.encoded_size;
299
300        (offset, self.items.range_mut(first_unmapped_item..))
301    }
302}
303
304/// Block archiver for Subspace blockchain.
305///
306/// It takes new confirmed (at `K` depth) blocks and concatenates them into a buffer, buffer is
307/// sliced into segments of [`RecordedHistorySegment::SIZE`] size, segments are sliced into source
308/// records of [`RawRecord::SIZE`], records are erasure coded, committed to with [`Kzg`], then
309/// commitments with witnesses are appended and records become pieces that are returned alongside
310/// corresponding segment header header.
311///
312/// ## Panics
313/// Panics when operating on blocks, whose length doesn't fit into u32 (should never be the case in
314/// blockchain context anyway).
315#[derive(Debug, Clone)]
316pub struct Archiver {
317    /// Buffer containing blocks and other buffered items that are pending to be included into the
318    /// next segment
319    buffer: SegmentItemsBuffer,
320    /// Intermediate record commitments that are built incrementally as above buffer fills up.
321    incremental_record_commitments: IncrementalRecordCommitmentsState,
322    /// Erasure coding data structure
323    erasure_coding: ErasureCoding,
324    /// KZG instance
325    kzg: Kzg,
326    /// An index of the current segment
327    segment_index: SegmentIndex,
328    /// Hash of the segment header of the previous segment
329    prev_segment_header_hash: Blake3Hash,
330    /// Last archived block
331    last_archived_block: LastArchivedBlock,
332}
333
334impl Archiver {
335    /// Create a new instance
336    pub fn new(kzg: Kzg, erasure_coding: ErasureCoding) -> Self {
337        Self {
338            buffer: SegmentItemsBuffer::default(),
339            incremental_record_commitments: IncrementalRecordCommitmentsState::with_capacity(
340                RecordedHistorySegment::NUM_RAW_RECORDS,
341            ),
342            erasure_coding,
343            kzg,
344            segment_index: SegmentIndex::ZERO,
345            prev_segment_header_hash: Blake3Hash::default(),
346            last_archived_block: INITIAL_LAST_ARCHIVED_BLOCK,
347        }
348    }
349
350    /// Create a new instance of the archiver with initial state in case of restart.
351    ///
352    /// `block` corresponds to `last_archived_block` and will be processed according to its state.
353    pub fn with_initial_state(
354        kzg: Kzg,
355        erasure_coding: ErasureCoding,
356        segment_header: SegmentHeader,
357        encoded_block: &[u8],
358        mut object_mapping: BlockObjectMapping,
359    ) -> Result<Self, ArchiverInstantiationError> {
360        let mut archiver = Self::new(kzg, erasure_coding);
361
362        archiver.segment_index = segment_header.segment_index() + SegmentIndex::ONE;
363        archiver.prev_segment_header_hash = segment_header.hash();
364        archiver.last_archived_block = segment_header.last_archived_block();
365
366        // The first thing in the buffer should be segment header
367        archiver
368            .buffer
369            .push_back(SegmentItem::ParentSegmentHeader(segment_header));
370
371        if let Some(archived_block_bytes) = archiver.last_archived_block.partial_archived() {
372            let encoded_block_bytes = u32::try_from(encoded_block.len())
373                .expect("Blocks length is never bigger than u32; qed");
374
375            match encoded_block_bytes.cmp(&archived_block_bytes) {
376                Ordering::Less => {
377                    return Err(ArchiverInstantiationError::InvalidBlockSmallSize {
378                        block_bytes: encoded_block_bytes,
379                        archived_block_bytes,
380                    });
381                }
382                Ordering::Equal => {
383                    return Err(ArchiverInstantiationError::InvalidLastArchivedBlock(
384                        encoded_block_bytes,
385                    ));
386                }
387                Ordering::Greater => {
388                    // Take part of the encoded block that wasn't archived yet and push to the
389                    // buffer as a block continuation
390                    object_mapping
391                        .objects_mut()
392                        .retain_mut(|block_object: &mut BlockObject| {
393                            if block_object.offset >= archived_block_bytes {
394                                block_object.offset -= archived_block_bytes;
395                                true
396                            } else {
397                                false
398                            }
399                        });
400                    archiver.buffer.push_back(SegmentItem::BlockContinuation {
401                        bytes: encoded_block[(archived_block_bytes as usize)..].to_vec(),
402                        object_mapping,
403                    });
404                }
405            }
406        }
407
408        Ok(archiver)
409    }
410
411    /// Get last archived block if there was any
412    pub fn last_archived_block_number(&self) -> Option<BlockNumber> {
413        if self.last_archived_block != INITIAL_LAST_ARCHIVED_BLOCK {
414            Some(self.last_archived_block.number)
415        } else {
416            None
417        }
418    }
419
420    /// Adds new block to internal buffer, potentially producing pieces, segment headers, and
421    /// object mappings.
422    ///
423    /// Incremental archiving can be enabled if amortized block addition cost is preferred over
424    /// throughput.
425    pub fn add_block(
426        &mut self,
427        bytes: Vec<u8>,
428        object_mapping: BlockObjectMapping,
429        incremental: bool,
430    ) -> ArchiveBlockOutcome {
431        // Append new block to the buffer
432        self.buffer.push_back(SegmentItem::Block {
433            bytes,
434            object_mapping,
435        });
436
437        let mut archived_segments = Vec::new();
438        let mut object_mapping = Vec::new();
439
440        // Add completed segments and their mappings for this block.
441        while let Some(mut segment) = self.produce_segment(incremental) {
442            // Produce any segment mappings that haven't already been produced.
443            object_mapping.extend(Self::produce_object_mappings(
444                self.segment_index,
445                Segment::default().encoded_size(),
446                segment.items_mut().iter_mut(),
447            ));
448            archived_segments.push(self.produce_archived_segment(segment));
449        }
450
451        // Produce any next segment buffer mappings that haven't already been produced.
452        object_mapping.extend(self.produce_next_segment_mappings());
453
454        ArchiveBlockOutcome {
455            archived_segments,
456            object_mapping,
457        }
458    }
459
460    /// Try to slice buffer contents into segments if there is enough data, producing one segment at
461    /// a time
462    fn produce_segment(&mut self, incremental: bool) -> Option<Segment> {
463        let mut segment_size = Segment::default().encoded_size();
464        let buffered_segment_size = segment_size + self.buffer.encoded_size;
465
466        // Not enough data for a segment yet
467        if buffered_segment_size < SEGMENT_SIZE_THRESHOLD {
468            let existing_commitments = self.incremental_record_commitments.len();
469            let bytes_committed_to = existing_commitments * RawRecord::SIZE;
470            // Run incremental archiver only when there is at least two records to archive,
471            // otherwise we're wasting CPU cycles encoding segment over and over again
472            if incremental && buffered_segment_size - bytes_committed_to >= RawRecord::SIZE * 2 {
473                update_record_commitments(
474                    &mut self.incremental_record_commitments,
475                    self.buffer.iter(),
476                    &self.kzg,
477                );
478            }
479
480            return None;
481        }
482
483        let mut segment = Segment::V0 {
484            items: Vec::with_capacity(self.buffer.len()),
485        };
486
487        let mut last_archived_block = self.last_archived_block;
488
489        while segment_size < SEGMENT_SIZE_THRESHOLD {
490            let segment_item = self.buffer.pop_front().expect(
491                "Buffered items are large enough to fill a segment, which is checked above; qed",
492            );
493
494            let segment_item_encoded_size = segment_item.encoded_size();
495            segment_size += segment_item_encoded_size;
496
497            // Check if there would be enough data collected with above segment item inserted
498            if segment_size >= RecordedHistorySegment::SIZE {
499                // Check if there is an excess of data that should be spilled over into the next
500                // segment
501                let spill_over = segment_size - RecordedHistorySegment::SIZE;
502
503                // Due to compact vector length encoding in scale codec, spill over might happen to
504                // be the same or even bigger than the inserted segment item bytes, in which case
505                // last segment item insertion needs to be skipped to avoid out of range panic when
506                // trying to cut segment item internal bytes.
507                let inner_bytes_size = match &segment_item {
508                    SegmentItem::Padding => {
509                        unreachable!("Buffer never contains SegmentItem::Padding; qed");
510                    }
511                    SegmentItem::Block { bytes, .. } => bytes.len(),
512                    SegmentItem::BlockStart { .. } => {
513                        unreachable!("Buffer never contains SegmentItem::BlockStart; qed");
514                    }
515                    SegmentItem::BlockContinuation { bytes, .. } => bytes.len(),
516                    SegmentItem::ParentSegmentHeader(_) => {
517                        unreachable!(
518                            "SegmentItem::SegmentHeader is always the first element in the buffer \
519                            and fits into the segment; qed",
520                        );
521                    }
522                };
523
524                if spill_over > inner_bytes_size {
525                    self.buffer.push_front(segment_item);
526                    segment_size -= segment_item_encoded_size;
527                    break;
528                }
529            }
530
531            match &segment_item {
532                SegmentItem::Padding => {
533                    unreachable!("Buffer never contains SegmentItem::Padding; qed");
534                }
535                SegmentItem::Block { .. } => {
536                    // Skip block number increase in case of the very first block
537                    if last_archived_block != INITIAL_LAST_ARCHIVED_BLOCK {
538                        // Increase archived block number and assume the whole block was
539                        // archived
540                        last_archived_block.number += 1;
541                    }
542                    last_archived_block.set_complete();
543                }
544                SegmentItem::BlockStart { .. } => {
545                    unreachable!("Buffer never contains SegmentItem::BlockStart; qed");
546                }
547                SegmentItem::BlockContinuation { bytes, .. } => {
548                    // Same block, but assume for now that the whole block was archived, but
549                    // also store the number of bytes as opposed to `None`, we'll transform
550                    // it into `None` if needed later
551                    let archived_bytes = last_archived_block.partial_archived().expect(
552                        "Block continuation implies that there are some bytes \
553                            archived already; qed",
554                    );
555                    last_archived_block.set_partial_archived(
556                        archived_bytes
557                            + u32::try_from(bytes.len())
558                                .expect("Blocks length is never bigger than u32; qed"),
559                    );
560                }
561                SegmentItem::ParentSegmentHeader(_) => {
562                    // We are not interested in segment header here
563                }
564            }
565
566            segment.push_item(segment_item);
567        }
568
569        // Check if there is an excess of data that should be spilled over into the next segment
570        let spill_over = segment_size.saturating_sub(RecordedHistorySegment::SIZE);
571
572        if spill_over > 0 {
573            let items = segment.items_mut();
574            let segment_item = items
575                .pop()
576                .expect("Segment over segment size always has at least one item; qed");
577
578            let segment_item = match segment_item {
579                SegmentItem::Padding => {
580                    unreachable!("Buffer never contains SegmentItem::Padding; qed");
581                }
582                SegmentItem::Block {
583                    mut bytes,
584                    mut object_mapping,
585                } => {
586                    let split_point = bytes.len() - spill_over;
587                    let continuation_bytes = bytes[split_point..].to_vec();
588
589                    bytes.truncate(split_point);
590
591                    let continuation_object_mapping = BlockObjectMapping::V0 {
592                        objects: object_mapping
593                            .objects_mut()
594                            .extract_if(.., |block_object: &mut BlockObject| {
595                                if block_object.offset >= split_point as u32 {
596                                    block_object.offset -= split_point as u32;
597                                    true
598                                } else {
599                                    false
600                                }
601                            })
602                            .collect(),
603                    };
604
605                    // Update last archived block to include partial archiving info
606                    last_archived_block.set_partial_archived(
607                        u32::try_from(bytes.len())
608                            .expect("Blocks length is never bigger than u32; qed"),
609                    );
610
611                    // Push continuation element back into the buffer where removed segment item was
612                    self.buffer.push_front(SegmentItem::BlockContinuation {
613                        bytes: continuation_bytes,
614                        object_mapping: continuation_object_mapping,
615                    });
616
617                    SegmentItem::BlockStart {
618                        bytes,
619                        object_mapping,
620                    }
621                }
622                SegmentItem::BlockStart { .. } => {
623                    unreachable!("Buffer never contains SegmentItem::BlockStart; qed");
624                }
625                SegmentItem::BlockContinuation {
626                    mut bytes,
627                    mut object_mapping,
628                } => {
629                    let split_point = bytes.len() - spill_over;
630                    let continuation_bytes = bytes[split_point..].to_vec();
631
632                    bytes.truncate(split_point);
633
634                    let continuation_object_mapping = BlockObjectMapping::V0 {
635                        objects: object_mapping
636                            .objects_mut()
637                            .extract_if(.., |block_object: &mut BlockObject| {
638                                if block_object.offset >= split_point as u32 {
639                                    block_object.offset -= split_point as u32;
640                                    true
641                                } else {
642                                    false
643                                }
644                            })
645                            .collect(),
646                    };
647
648                    // Above code assumed that block was archived fully, now remove spilled-over
649                    // bytes from the size
650                    let archived_bytes = last_archived_block.partial_archived().expect(
651                        "Block continuation implies that there are some bytes archived \
652                        already; qed",
653                    );
654                    last_archived_block.set_partial_archived(
655                        archived_bytes
656                            - u32::try_from(spill_over)
657                                .expect("Blocks length is never bigger than u32; qed"),
658                    );
659
660                    // Push continuation element back into the buffer where removed segment item was
661                    self.buffer.push_front(SegmentItem::BlockContinuation {
662                        bytes: continuation_bytes,
663                        object_mapping: continuation_object_mapping,
664                    });
665
666                    SegmentItem::BlockContinuation {
667                        bytes,
668                        object_mapping,
669                    }
670                }
671                SegmentItem::ParentSegmentHeader(_) => {
672                    unreachable!(
673                        "SegmentItem::SegmentHeader is always the first element in the buffer and \
674                        fits into the segment; qed",
675                    );
676                }
677            };
678
679            // Push back shortened segment item
680            items.push(segment_item);
681        } else {
682            // Above code added bytes length even though it was assumed that all continuation bytes
683            // fit into the segment, now we need to tweak that
684            last_archived_block.set_complete();
685        }
686
687        self.last_archived_block = last_archived_block;
688
689        Some(segment)
690    }
691
692    /// Produce object mappings for the buffered items for the next segment. Then remove the
693    /// mappings in those items.
694    ///
695    /// Must only be called after all complete segments for a block have been produced. Before
696    /// that, the buffer can contain a `BlockContinuation` which spans multiple segments.
697    fn produce_next_segment_mappings(&mut self) -> Vec<GlobalObject> {
698        // Usually this is just the block that was just added, avoiding iteration over the whole
699        // buffer is important for performance when there are many small blocks
700        let (offset, unmapped_items) = self.buffer.take_unmapped_items();
701
702        Self::produce_object_mappings(
703            self.segment_index,
704            Segment::default().encoded_size() + offset,
705            unmapped_items,
706        )
707    }
708
709    /// Produce object mappings for `items` in `segment_index`, where the first item starts at
710    /// `base_offset_in_segment`. Then remove the mappings from those items.
711    ///
712    /// This method can be called on a `Segment`’s items, or on the `Archiver`'s internal buffer.
713    fn produce_object_mappings<'a, Items>(
714        segment_index: SegmentIndex,
715        mut base_offset_in_segment: usize,
716        items: Items,
717    ) -> Vec<GlobalObject>
718    where
719        Items: Iterator<Item = &'a mut SegmentItem>,
720    {
721        let source_piece_indexes = &segment_index.segment_piece_indexes_source_first()
722            [..RecordedHistorySegment::NUM_RAW_RECORDS];
723
724        let mut corrected_object_mapping = Vec::new();
725        for segment_item in items {
726            match segment_item {
727                SegmentItem::Padding => {
728                    unreachable!(
729                        "Segment during archiving never contains SegmentItem::Padding; qed"
730                    );
731                }
732                SegmentItem::Block {
733                    bytes,
734                    object_mapping,
735                }
736                | SegmentItem::BlockStart {
737                    bytes,
738                    object_mapping,
739                }
740                | SegmentItem::BlockContinuation {
741                    bytes,
742                    object_mapping,
743                } => {
744                    for block_object in object_mapping.objects_mut().drain(..) {
745                        // `+1` corresponds to `SegmentItem::X {}` enum variant encoding
746                        let offset_in_segment = base_offset_in_segment
747                            + 1
748                            + Compact::compact_len(&(bytes.len() as u32))
749                            + block_object.offset as usize;
750                        let raw_piece_offset = (offset_in_segment % RawRecord::SIZE)
751                            .try_into()
752                            .expect("Offset within piece should always fit in 32-bit integer; qed");
753                        corrected_object_mapping.push(GlobalObject {
754                            hash: block_object.hash,
755                            piece_index: source_piece_indexes[offset_in_segment / RawRecord::SIZE],
756                            offset: raw_piece_offset,
757                        });
758                    }
759                }
760                SegmentItem::ParentSegmentHeader(_) => {
761                    // Ignore, no object mappings here
762                }
763            }
764
765            base_offset_in_segment += segment_item.encoded_size();
766        }
767
768        corrected_object_mapping
769    }
770
771    /// Take segment as an input, apply necessary transformations and produce archived segment
772    fn produce_archived_segment(&mut self, segment: Segment) -> NewArchivedSegment {
773        let mut pieces = {
774            // Serialize segment into concatenation of raw records
775            let mut raw_record_shards = Vec::<u8>::with_capacity(RecordedHistorySegment::SIZE);
776            segment.encode_to(&mut raw_record_shards);
777            // Segment might require some padding (see [`Self::produce_segment`] for details)
778            raw_record_shards.resize(raw_record_shards.capacity(), 0);
779
780            // Segment is quite big and no longer necessary
781            drop(segment);
782
783            let mut pieces = ArchivedHistorySegment::default();
784
785            // Scratch buffer to avoid re-allocation
786            let mut tmp_source_shards_scalars =
787                Vec::<Scalar>::with_capacity(RecordedHistorySegment::NUM_RAW_RECORDS);
788            // Iterate over the chunks of `ScalarBytes::SAFE_BYTES` bytes of all records
789            for record_offset in 0..RawRecord::NUM_CHUNKS {
790                // Collect chunks of each record at the same offset
791                raw_record_shards
792                    .as_chunks::<{ RawRecord::SIZE }>()
793                    .0
794                    .iter()
795                    .map(|record_bytes| {
796                        record_bytes
797                            .as_chunks::<{ ScalarBytes::SAFE_BYTES }>()
798                            .0
799                            .get(record_offset)
800                            .expect("Statically known to exist in a record; qed")
801                    })
802                    .map(Scalar::from)
803                    .collect_into(&mut tmp_source_shards_scalars);
804
805                // Extend to obtain corresponding parity shards
806                let parity_shards = self
807                    .erasure_coding
808                    .extend(&tmp_source_shards_scalars)
809                    .expect(
810                        "Erasure coding instance is deliberately configured to support this \
811                        input; qed",
812                    );
813
814                let interleaved_input_chunks = tmp_source_shards_scalars
815                    .drain(..)
816                    .zip(parity_shards)
817                    .flat_map(|(a, b)| [a, b]);
818                let output_chunks = pieces.iter_mut().map(|piece| {
819                    piece
820                        .record_mut()
821                        .get_mut(record_offset)
822                        .expect("Statically known to exist in a record; qed")
823                });
824
825                interleaved_input_chunks
826                    .zip(output_chunks)
827                    .for_each(|(input, output)| output.copy_from_slice(&input.to_bytes()));
828            }
829
830            pieces
831        };
832
833        let existing_commitments = self.incremental_record_commitments.len();
834        // Add commitments for pieces that were not created incrementally
835        {
836            #[cfg(not(feature = "parallel"))]
837            let source_pieces = pieces.source();
838            #[cfg(feature = "parallel")]
839            let source_pieces = pieces.par_source();
840
841            let iter = source_pieces.skip(existing_commitments).map(|piece| {
842                let record_chunks = piece.record().iter().map(|scalar_bytes| {
843                    Scalar::try_from(scalar_bytes).expect(
844                        "Source pieces were just created and are guaranteed to contain \
845                            valid scalars; qed",
846                    )
847                });
848
849                let number_of_chunks = record_chunks.len();
850                let mut scalars = Vec::with_capacity(number_of_chunks.next_power_of_two());
851
852                record_chunks.collect_into(&mut scalars);
853
854                // Number of scalars for KZG must be a power of two elements
855                scalars.resize(scalars.capacity(), Scalar::default());
856
857                let polynomial = self
858                    .kzg
859                    .poly(&scalars)
860                    .expect("KZG instance must be configured to support this many scalars; qed");
861                self.kzg
862                    .commit(&polynomial)
863                    .expect("KZG instance must be configured to support this many scalars; qed")
864            });
865
866            #[cfg(not(feature = "parallel"))]
867            iter.collect_into(&mut *self.incremental_record_commitments);
868            // TODO: `collect_into_vec()`, unfortunately, truncates input, which is not what we want
869            //  can be unified when https://github.com/rayon-rs/rayon/issues/1039 is resolved
870            #[cfg(feature = "parallel")]
871            self.incremental_record_commitments.par_extend(iter);
872        }
873        // Collect hashes to commitments from all records
874        let record_commitments = self
875            .erasure_coding
876            .extend_commitments(&self.incremental_record_commitments)
877            .expect(
878                "Erasure coding instance is deliberately configured to support this input; qed",
879            );
880        self.incremental_record_commitments.clear();
881
882        let polynomial = self
883            .kzg
884            .poly(
885                &record_commitments
886                    .iter()
887                    .map(|commitment| {
888                        Scalar::try_from(blake3_254_hash_to_scalar(&commitment.to_bytes()))
889                            .expect("Create correctly by dedicated hash function; qed")
890                    })
891                    .collect::<Vec<_>>(),
892            )
893            .expect("Internally produced values must never fail; qed");
894
895        let segment_commitment = SegmentCommitment::from(
896            self.kzg
897                .commit(&polynomial)
898                .expect("Internally produced values must never fail; qed"),
899        );
900
901        // Create witness for every record and write it to corresponding piece.
902        pieces
903            .iter_mut()
904            .zip(record_commitments)
905            .enumerate()
906            .for_each(|(position, (piece, commitment))| {
907                let commitment_bytes = commitment.to_bytes();
908                let (_record, commitment, witness) = piece.split_mut();
909                commitment.copy_from_slice(&commitment_bytes);
910                // TODO: Consider batch witness creation for improved performance
911                witness.copy_from_slice(
912                    &self
913                        .kzg
914                        .create_witness(
915                            &polynomial,
916                            ArchivedHistorySegment::NUM_PIECES,
917                            position as u32,
918                        )
919                        .expect("Position is statically known to be valid; qed")
920                        .to_bytes(),
921                );
922            });
923
924        // Now produce segment header
925        let segment_header = SegmentHeader::V0 {
926            segment_index: self.segment_index,
927            segment_commitment,
928            prev_segment_header_hash: self.prev_segment_header_hash,
929            last_archived_block: self.last_archived_block,
930        };
931
932        // Update state
933        self.segment_index += SegmentIndex::ONE;
934        self.prev_segment_header_hash = segment_header.hash();
935
936        // Add segment header to the beginning of the buffer to be the first thing included in the
937        // next segment
938        self.buffer
939            .push_front(SegmentItem::ParentSegmentHeader(segment_header));
940
941        NewArchivedSegment {
942            segment_header,
943            pieces: pieces.to_shared(),
944        }
945    }
946}