Skip to main content

subspace_archiving/
reconstructor.rs

1#[cfg(not(feature = "std"))]
2extern crate alloc;
3
4use crate::archiver::{Segment, SegmentItem};
5#[cfg(not(feature = "std"))]
6use alloc::string::String;
7#[cfg(not(feature = "std"))]
8use alloc::vec::Vec;
9use core::mem;
10use parity_scale_codec::Decode;
11use subspace_core_primitives::BlockNumber;
12use subspace_core_primitives::pieces::{Piece, RawRecord};
13use subspace_core_primitives::segments::{
14    ArchivedBlockProgress, ArchivedHistorySegment, LastArchivedBlock, RecordedHistorySegment,
15    SegmentHeader, SegmentIndex,
16};
17use subspace_erasure_coding::ErasureCoding;
18use subspace_kzg::Scalar;
19
20/// Reconstructor-related instantiation error
21#[derive(Debug, Clone, PartialEq, thiserror::Error)]
22pub enum ReconstructorError {
23    /// Error during data shards reconstruction
24    #[error("Error during data shards reconstruction: {0}")]
25    DataShardsReconstruction(String),
26    /// Segment size is not bigger than record size
27    #[error("Error during segment decoding: {0}")]
28    SegmentDecoding(parity_scale_codec::Error),
29    /// Incorrect segment order, each next segment must directly follow the previous one
30    #[error(
31        "Incorrect segment order, expected index {expected_segment_index}, actual \
32        {actual_segment_index}"
33    )]
34    IncorrectSegmentOrder {
35        expected_segment_index: SegmentIndex,
36        actual_segment_index: SegmentIndex,
37    },
38    /// Parent segment header is not the first item of the segment
39    #[error("Parent segment header is not the first item of the segment")]
40    UnexpectedParentSegmentHeader,
41    /// Segment index overflow, no segment can follow the segment with the maximum index
42    #[error("Segment index overflow, no segment can follow the segment with the maximum index")]
43    SegmentIndexOverflow,
44    /// Block number overflow
45    #[error("Block number overflow")]
46    BlockNumberOverflow,
47}
48
49/// Data structure that contains information reconstructed from given segment (potentially using
50/// information from segments that were added previously)
51#[derive(Debug, Default, Clone, Eq, PartialEq)]
52pub struct ReconstructedContents {
53    /// Segment header stored in a segment
54    pub segment_header: Option<SegmentHeader>,
55    /// Reconstructed encoded blocks with their block numbers
56    pub blocks: Vec<(BlockNumber, Vec<u8>)>,
57}
58
59/// Reconstructor helps to retrieve blocks from archived pieces.
60#[derive(Debug, Clone)]
61pub struct Reconstructor {
62    /// Erasure coding data structure
63    erasure_coding: ErasureCoding,
64    /// Index of last segment added to reconstructor
65    last_segment_index: Option<SegmentIndex>,
66    /// Partially reconstructed block waiting for more data, empty if there is none
67    partial_block: Vec<u8>,
68}
69
70impl Reconstructor {
71    /// Create a new instance
72    pub fn new(erasure_coding: ErasureCoding) -> Self {
73        Self {
74            erasure_coding,
75            last_segment_index: None,
76            partial_block: Vec::new(),
77        }
78    }
79
80    /// Given a set of pieces of a segment of the archived history (any half of all pieces are
81    /// required to be present, the rest will be recovered automatically due to use of erasure
82    /// coding if needed), reconstructs and returns the segment itself.
83    ///
84    /// Does not modify the internal state of the reconstructor.
85    pub fn reconstruct_segment(
86        &self,
87        segment_pieces: &[Option<Piece>],
88    ) -> Result<Segment, ReconstructorError> {
89        let mut segment_data = RecordedHistorySegment::new_boxed();
90
91        if !segment_pieces
92            .iter()
93            // Take each source shards here
94            .step_by(2)
95            .zip(segment_data.iter_mut())
96            .all(|(maybe_piece, raw_record)| {
97                if let Some(piece) = maybe_piece {
98                    piece
99                        .record()
100                        .to_raw_record_chunks()
101                        .zip(raw_record.iter_mut())
102                        .for_each(|(source, target)| {
103                            target.copy_from_slice(source);
104                        });
105                    true
106                } else {
107                    false
108                }
109            })
110        {
111            // If not all data pieces are available, need to reconstruct data shards using erasure
112            // coding.
113
114            // Scratch buffer to avoid re-allocation
115            let mut tmp_shards_scalars =
116                Vec::<Option<Scalar>>::with_capacity(ArchivedHistorySegment::NUM_PIECES);
117            // Iterate over the chunks of `ScalarBytes::SAFE_BYTES` bytes of all records
118            for record_offset in 0..RawRecord::NUM_CHUNKS {
119                // Collect chunks of each record at the same offset
120                for maybe_piece in segment_pieces.iter() {
121                    let maybe_scalar = maybe_piece
122                        .as_ref()
123                        .map(|piece| {
124                            piece
125                                .record()
126                                .get(record_offset)
127                                .expect("Statically guaranteed to exist in a piece; qed")
128                        })
129                        .map(Scalar::try_from)
130                        .transpose()
131                        .map_err(ReconstructorError::DataShardsReconstruction)?;
132
133                    tmp_shards_scalars.push(maybe_scalar);
134                }
135
136                self.erasure_coding
137                    .recover(&tmp_shards_scalars)
138                    .map_err(ReconstructorError::DataShardsReconstruction)?
139                    .into_iter()
140                    // Take each source shards here
141                    .step_by(2)
142                    .zip(segment_data.iter_mut().map(|raw_record| {
143                        raw_record
144                            .get_mut(record_offset)
145                            .expect("Statically guaranteed to exist in a piece; qed")
146                    }))
147                    .for_each(|(source_scalar, segment_data)| {
148                        segment_data.copy_from_slice(
149                            &source_scalar
150                                .try_to_safe_bytes()
151                                .expect("Source scalar has only safe bytes; qed"),
152                        );
153                    });
154
155                tmp_shards_scalars.clear();
156            }
157        }
158
159        let segment = Segment::decode(&mut AsRef::<[u8]>::as_ref(segment_data.as_ref()))
160            .map_err(ReconstructorError::SegmentDecoding)?;
161
162        Ok(segment)
163    }
164
165    /// Given a set of pieces of a segment of the archived history (any half of all pieces are
166    /// required to be present, the rest will be recovered automatically due to use of erasure
167    /// coding if needed), reconstructs and returns segment header and a list of encoded blocks with
168    /// corresponding block numbers.
169    ///
170    /// The reconstructor is consumed and returned together with reconstructed contents if the
171    /// segment was added successfully. It is possible to start with any segment, but when next
172    /// segment is pushed, it needs to follow the previous one or else error will be returned.
173    pub fn add_segment(
174        mut self,
175        segment_pieces: &[Option<Piece>],
176    ) -> Result<(Self, ReconstructedContents), ReconstructorError> {
177        let mut segment_items = self
178            .reconstruct_segment(segment_pieces)?
179            .into_items()
180            .into_iter()
181            .peekable();
182
183        let mut reconstructed_contents = ReconstructedContents::default();
184        let mut next_block_number: BlockNumber = 0;
185
186        // Only the first segment has no parent segment header, all other segments start with it
187        let segment_index = if let Some(&SegmentItem::ParentSegmentHeader(parent_segment_header)) =
188            segment_items.peek()
189        {
190            segment_items.next();
191
192            let LastArchivedBlock {
193                number,
194                archived_progress,
195            } = parent_segment_header.last_archived_block();
196
197            reconstructed_contents
198                .segment_header
199                .replace(parent_segment_header);
200
201            match archived_progress {
202                ArchivedBlockProgress::Complete => {
203                    // The last archived block ended exactly with the previous segment, so if its
204                    // beginning was reconstructed from previous segments, it is complete now
205                    if !self.partial_block.is_empty() {
206                        reconstructed_contents
207                            .blocks
208                            .push((number, mem::take(&mut self.partial_block)));
209                    }
210
211                    next_block_number = number
212                        .checked_add(1)
213                        .ok_or(ReconstructorError::BlockNumberOverflow)?;
214                }
215                ArchivedBlockProgress::Partial(_bytes) => {
216                    next_block_number = number;
217
218                    if self.partial_block.is_empty() {
219                        // Will not be able to recover full block, bump right away
220                        next_block_number = next_block_number
221                            .checked_add(1)
222                            .ok_or(ReconstructorError::BlockNumberOverflow)?;
223                    }
224                }
225            }
226
227            parent_segment_header
228                .segment_index()
229                .checked_add(SegmentIndex::ONE)
230                .ok_or(ReconstructorError::SegmentIndexOverflow)?
231        } else {
232            SegmentIndex::ZERO
233        };
234
235        if let Some(last_segment_index) = self.last_segment_index {
236            let expected_segment_index = last_segment_index
237                .checked_add(SegmentIndex::ONE)
238                .ok_or(ReconstructorError::SegmentIndexOverflow)?;
239
240            if segment_index != expected_segment_index {
241                return Err(ReconstructorError::IncorrectSegmentOrder {
242                    expected_segment_index,
243                    actual_segment_index: segment_index,
244                });
245            }
246        }
247
248        self.last_segment_index.replace(segment_index);
249
250        for segment_item in segment_items {
251            match segment_item {
252                SegmentItem::Padding => {
253                    // Doesn't contain anything
254                }
255                SegmentItem::Block { bytes, .. } => {
256                    if !self.partial_block.is_empty() {
257                        reconstructed_contents
258                            .blocks
259                            .push((next_block_number, mem::take(&mut self.partial_block)));
260
261                        next_block_number = next_block_number
262                            .checked_add(1)
263                            .ok_or(ReconstructorError::BlockNumberOverflow)?;
264                    }
265
266                    reconstructed_contents
267                        .blocks
268                        .push((next_block_number, bytes));
269
270                    next_block_number = next_block_number
271                        .checked_add(1)
272                        .ok_or(ReconstructorError::BlockNumberOverflow)?;
273                }
274                SegmentItem::BlockStart { bytes, .. } => {
275                    if !self.partial_block.is_empty() {
276                        reconstructed_contents
277                            .blocks
278                            .push((next_block_number, mem::take(&mut self.partial_block)));
279
280                        next_block_number = next_block_number
281                            .checked_add(1)
282                            .ok_or(ReconstructorError::BlockNumberOverflow)?;
283                    }
284
285                    self.partial_block = bytes;
286                }
287                SegmentItem::BlockContinuation { bytes, .. } => {
288                    if self.partial_block.is_empty() {
289                        // This is continuation from previous segment, we don't have the beginning
290                        // of the block to continue.
291                        continue;
292                    }
293
294                    self.partial_block.extend_from_slice(&bytes);
295                }
296                SegmentItem::ParentSegmentHeader(_) => {
297                    return Err(ReconstructorError::UnexpectedParentSegmentHeader);
298                }
299            }
300        }
301
302        Ok((self, reconstructed_contents))
303    }
304}