Skip to main content

ab_archiving/
piece_reconstructor.rs

1use ab_core_primitives::pieces::{
2    InnerPiece, Piece, PieceHeader, PiecePosition, Record, RecordChunksRoot, RecordProof,
3    SegmentProof,
4};
5use ab_core_primitives::segments::{
6    ArchivedHistorySegment, LocalSegmentIndex, RecordedHistorySegment, SegmentRoot,
7};
8use ab_core_primitives::shard::ShardIndex;
9use ab_erasure_coding::{ErasureCoding, ErasureCodingError, ShardsPresent};
10use ab_merkle_tree::blake3::BalancedMerkleTree;
11#[cfg(feature = "parallel")]
12use rayon::prelude::*;
13
14/// Reconstructor-related instantiation error
15#[derive(Debug, Clone, PartialEq, thiserror::Error)]
16pub enum ReconstructorError {
17    /// Segment size is not bigger than record size
18    #[error("Error during data shards reconstruction: {0}")]
19    DataShardsReconstruction(#[from] ErasureCodingError),
20    /// Not enough shards
21    #[error("Not enough shards: {num_shards}")]
22    NotEnoughShards { num_shards: usize },
23}
24
25struct SharedPieceDetails {
26    shard_index: ShardIndex,
27    local_segment_index: LocalSegmentIndex,
28    segment_root: SegmentRoot,
29    segment_proof: SegmentProof,
30}
31
32/// Piece reconstructor helps to reconstruct missing pieces.
33#[derive(Debug, Clone)]
34pub struct PiecesReconstructor {
35    /// Erasure coding data structure
36    erasure_coding: ErasureCoding,
37}
38
39impl PiecesReconstructor {
40    /// Create a new instance
41    pub fn new(erasure_coding: ErasureCoding) -> Self {
42        Self { erasure_coding }
43    }
44
45    fn reconstruct_shards(
46        &self,
47        input_pieces: &[Option<Piece>],
48    ) -> Result<ArchivedHistorySegment, ReconstructorError> {
49        if input_pieces.len() < ArchivedHistorySegment::NUM_PIECES {
50            return Err(ReconstructorError::NotEnoughShards {
51                num_shards: input_pieces.len(),
52            });
53        }
54        let mut reconstructed_pieces = ArchivedHistorySegment::default();
55
56        let shared_piece_details =
57            input_pieces
58                .iter()
59                .flatten()
60                .next()
61                .map(|input_piece| SharedPieceDetails {
62                    shard_index: input_piece.header.shard_index.as_inner(),
63                    local_segment_index: input_piece.header.local_segment_index.as_inner(),
64                    segment_root: input_piece.header.segment_root,
65                    segment_proof: input_piece.header.segment_proof,
66                });
67        {
68            let (source_input_pieces, parity_input_pieces) =
69                input_pieces.split_at(RecordedHistorySegment::NUM_RAW_RECORDS);
70            let (source_reconstructed_pieces, parity_reconstructed_pieces) =
71                reconstructed_pieces.split_at_mut(RecordedHistorySegment::NUM_RAW_RECORDS);
72
73            let mut present = ShardsPresent::none();
74
75            for (index, (maybe_input_piece, output_piece)) in source_input_pieces
76                .iter()
77                .zip(source_reconstructed_pieces.iter_mut())
78                .enumerate()
79            {
80                if let Some(input_piece) = maybe_input_piece {
81                    // Fancy way to insert value to avoid going through stack (if naive
82                    // dereferencing is used) and potentially causing stack overflow as the result
83                    output_piece.record.copy_from_slice(&*input_piece.record);
84                    present.source.set(index);
85                }
86            }
87
88            for (index, (maybe_input_piece, output_piece)) in parity_input_pieces
89                .iter()
90                .zip(parity_reconstructed_pieces.iter_mut())
91                .enumerate()
92            {
93                if let Some(input_piece) = maybe_input_piece {
94                    output_piece.record.copy_from_slice(&*input_piece.record);
95                    present.parity.set(index);
96                }
97            }
98
99            let (source_records, parity_records) = reconstructed_pieces.split_records_mut();
100
101            #[cfg(not(feature = "parallel"))]
102            let recover_all = ErasureCoding::recover_all_scattered;
103            #[cfg(feature = "parallel")]
104            let recover_all = ErasureCoding::par_recover_all_scattered;
105
106            recover_all(
107                &self.erasure_coding,
108                source_records,
109                parity_records,
110                &present,
111            )?;
112        }
113        let SharedPieceDetails {
114            shard_index,
115            local_segment_index,
116            segment_root,
117            segment_proof,
118        } = shared_piece_details.expect(
119            "Successful recovery means at least one source or parity piece was present; qed",
120        );
121
122        let mut record_roots = [[0; _]; ArchivedHistorySegment::NUM_PIECES];
123        {
124            // `parity_chunks` is only used for deriving a root and is fully overwritten by erasure
125            // coding, so it is reused between pieces.
126            let process_piece = |parity_chunks: &mut Record,
127                                 piece: &mut InnerPiece,
128                                 maybe_input_piece: &Option<Piece>,
129                                 output_record_root: &mut [u8; _]| {
130                let (record_root, parity_chunks_root) = if let Some(input_piece) = maybe_input_piece
131                {
132                    (
133                        *input_piece.record_root(),
134                        *input_piece.header.parity_chunks_root,
135                    )
136                } else {
137                    self.erasure_coding.extend(&piece.record, parity_chunks)?;
138
139                    let source_chunks_root = *piece.record.source_chunks_root();
140                    let parity_chunks_root = BalancedMerkleTree::compute_root_only(parity_chunks);
141
142                    let record_root =
143                        BalancedMerkleTree::new(&[source_chunks_root, parity_chunks_root]).root();
144
145                    (record_root, parity_chunks_root)
146                };
147
148                piece.header.parity_chunks_root = RecordChunksRoot::from(parity_chunks_root);
149                *output_record_root = record_root;
150
151                Ok::<_, ReconstructorError>(())
152            };
153
154            #[cfg(not(feature = "parallel"))]
155            {
156                let mut parity_chunks = Record::new_boxed();
157                reconstructed_pieces
158                    .iter_mut()
159                    .zip(input_pieces)
160                    .zip(&mut record_roots)
161                    .try_for_each(|((piece, maybe_input_piece), output_record_root)| {
162                        process_piece(
163                            &mut parity_chunks,
164                            piece,
165                            maybe_input_piece,
166                            output_record_root,
167                        )
168                    })?;
169            }
170            #[cfg(feature = "parallel")]
171            reconstructed_pieces
172                .par_iter_mut()
173                .zip_eq(input_pieces)
174                .zip_eq(&mut record_roots)
175                .try_for_each_init(
176                    Record::new_boxed,
177                    |parity_chunks, ((piece, maybe_input_piece), output_record_root)| {
178                        process_piece(parity_chunks, piece, maybe_input_piece, output_record_root)
179                    },
180                )?;
181        }
182
183        let segment_merkle_tree = BalancedMerkleTree::new_boxed(&record_roots);
184
185        reconstructed_pieces
186            .iter_mut()
187            .zip(segment_merkle_tree.all_proofs())
188            .for_each(|(piece, record_proof)| {
189                piece.header = PieceHeader {
190                    shard_index: shard_index.into(),
191                    local_segment_index: local_segment_index.into(),
192                    segment_root,
193                    segment_proof,
194                    parity_chunks_root: piece.header.parity_chunks_root,
195                    record_proof: RecordProof::from(record_proof),
196                };
197            });
198
199        Ok(reconstructed_pieces)
200    }
201
202    /// Returns all the pieces for a segment using a given set of pieces of a segment of the
203    /// archived history.
204    ///
205    /// Any half of all pieces are required to be present, the rest will be recovered automatically
206    /// due to use of erasure coding if needed.
207    pub fn reconstruct_segment(
208        &self,
209        segment_pieces: &[Option<Piece>],
210    ) -> Result<ArchivedHistorySegment, ReconstructorError> {
211        let pieces = self.reconstruct_shards(segment_pieces)?;
212
213        Ok(pieces.to_shared())
214    }
215
216    /// Returns the missing piece for a segment using given set of pieces of a segment of the
217    /// archived history (any half of all pieces are required to be present).
218    pub fn reconstruct_piece(
219        &self,
220        segment_pieces: &[Option<Piece>],
221        piece_position: PiecePosition,
222    ) -> Result<Piece, ReconstructorError> {
223        // TODO: Early exit if position already exists and doesn't need reconstruction
224        // TODO: It is now inefficient to recover all shards if only one piece is needed, especially
225        //  source piece
226        let pieces = self.reconstruct_shards(segment_pieces)?;
227
228        Ok(Piece::from(&pieces[piece_position]))
229    }
230}