Skip to main content

subspace_farmer_components/
sector.rs

1//! Sector-related data structures
2//!
3//! Sectors and corresponding metadata created by functions in [`plotting`](crate::plotting) module
4//! have a specific structure, represented by data structured in this module.
5//!
6//! It is typically not needed to construct these data structures explicitly outside of this crate,
7//! instead they will be returned as a result of certain operations (like plotting).
8
9use bitvec::prelude::*;
10use parity_scale_codec::{Decode, Encode};
11use rayon::prelude::*;
12use std::mem::{ManuallyDrop, MaybeUninit};
13use std::ops::{Deref, DerefMut};
14use std::{mem, slice};
15use subspace_core_primitives::checksum::Blake3Checksummed;
16use subspace_core_primitives::hashes::{Blake3Hash, blake3_hash};
17use subspace_core_primitives::pieces::{PieceOffset, Record, RecordCommitment, RecordWitness};
18use subspace_core_primitives::sectors::{SBucket, SectorIndex};
19use subspace_core_primitives::segments::{HistorySize, SegmentIndex};
20use thiserror::Error;
21use tracing::debug;
22
23/// Size of the part of the plot containing record chunks (s-buckets).
24///
25/// Total size of the plot can be computed with [`sector_size()`].
26#[inline]
27pub const fn sector_record_chunks_size(pieces_in_sector: u16) -> usize {
28    pieces_in_sector as usize * Record::SIZE
29}
30
31/// Size of the part of the plot containing record metadata.
32///
33/// Total size of the plot can be computed with [`sector_size()`].
34#[inline]
35pub const fn sector_record_metadata_size(pieces_in_sector: u16) -> usize {
36    pieces_in_sector as usize * RecordMetadata::encoded_size()
37}
38
39/// Exact sector plot size (sector contents map, record chunks, record metadata).
40///
41/// NOTE: Each sector also has corresponding fixed size metadata whose size can be obtained with
42/// [`SectorMetadataChecksummed::encoded_size()`], size of the record chunks (s-buckets) with
43/// [`sector_record_chunks_size()`] and size of record commitments and witnesses with
44/// [`sector_record_metadata_size()`]. This function just combines those three together for
45/// convenience.
46#[inline]
47pub const fn sector_size(pieces_in_sector: u16) -> usize {
48    sector_record_chunks_size(pieces_in_sector)
49        + sector_record_metadata_size(pieces_in_sector)
50        + SectorContentsMap::encoded_size(pieces_in_sector)
51        + Blake3Hash::SIZE
52}
53
54/// Metadata of the plotted sector
55#[derive(Debug, Encode, Decode, Clone)]
56pub struct SectorMetadata {
57    /// Sector index
58    pub sector_index: SectorIndex,
59    /// Number of pieces stored in this sector
60    pub pieces_in_sector: u16,
61    /// S-bucket sizes in a sector
62    pub s_bucket_sizes: Box<[u16; Record::NUM_S_BUCKETS]>,
63    /// Size of the blockchain history at time of sector creation
64    pub history_size: HistorySize,
65}
66
67impl SectorMetadata {
68    /// Returns offsets of each s-bucket relatively to the beginning of the sector (in chunks)
69    pub fn s_bucket_offsets(&self) -> Box<[u32; Record::NUM_S_BUCKETS]> {
70        let s_bucket_offsets = self
71            .s_bucket_sizes
72            .iter()
73            .map({
74                let mut base_offset = 0;
75
76                move |s_bucket_size| {
77                    let offset = base_offset;
78                    base_offset += u32::from(*s_bucket_size);
79                    offset
80                }
81            })
82            .collect::<Box<_>>();
83
84        assert_eq!(s_bucket_offsets.len(), Record::NUM_S_BUCKETS);
85        let mut s_bucket_offsets = ManuallyDrop::new(s_bucket_offsets);
86        // SAFETY: Original memory is not dropped, number of elements checked above
87        unsafe { Box::from_raw(s_bucket_offsets.as_mut_ptr() as *mut [u32; Record::NUM_S_BUCKETS]) }
88    }
89}
90
91/// Same as [`SectorMetadata`], but with checksums verified during SCALE encoding/decoding
92#[derive(Debug, Clone, Encode, Decode)]
93pub struct SectorMetadataChecksummed(Blake3Checksummed<SectorMetadata>);
94
95impl From<SectorMetadata> for SectorMetadataChecksummed {
96    #[inline]
97    fn from(value: SectorMetadata) -> Self {
98        Self(Blake3Checksummed(value))
99    }
100}
101
102impl Deref for SectorMetadataChecksummed {
103    type Target = SectorMetadata;
104
105    #[inline]
106    fn deref(&self) -> &Self::Target {
107        &self.0.0
108    }
109}
110
111impl DerefMut for SectorMetadataChecksummed {
112    #[inline]
113    fn deref_mut(&mut self) -> &mut Self::Target {
114        &mut self.0.0
115    }
116}
117
118impl SectorMetadataChecksummed {
119    /// Size of encoded checksummed sector metadata.
120    ///
121    /// For sector plot size use [`sector_size()`].
122    #[inline]
123    pub fn encoded_size() -> usize {
124        let default = SectorMetadataChecksummed::from(SectorMetadata {
125            sector_index: 0,
126            pieces_in_sector: 0,
127            // TODO: Should have been just `::new()`, but https://github.com/rust-lang/rust/issues/53827
128            // SAFETY: Data structure filled with zeroes is a valid invariant
129            s_bucket_sizes: unsafe { Box::new_zeroed().assume_init() },
130            history_size: HistorySize::from(SegmentIndex::ZERO),
131        });
132
133        default.encoded_size()
134    }
135}
136
137/// Commitment and witness corresponding to the same record
138#[derive(Debug, Default, Clone, Encode, Decode)]
139pub(crate) struct RecordMetadata {
140    /// Record commitment
141    pub(crate) commitment: RecordCommitment,
142    /// Record witness
143    pub(crate) witness: RecordWitness,
144    /// Checksum (hash) of the whole piece
145    pub(crate) piece_checksum: Blake3Hash,
146}
147
148impl RecordMetadata {
149    pub(crate) const fn encoded_size() -> usize {
150        RecordWitness::SIZE + RecordCommitment::SIZE + Blake3Hash::SIZE
151    }
152}
153
154/// Raw sector before it is transformed and written to plot, used during plotting
155#[derive(Debug, Clone)]
156pub(crate) struct RawSector {
157    /// List of records, likely downloaded from the network
158    pub(crate) records: Vec<Record>,
159    /// Metadata (commitment and witness) corresponding to the same record
160    pub(crate) metadata: Vec<RecordMetadata>,
161}
162
163impl RawSector {
164    /// Create new raw sector with internal vectors being allocated and filled with default values
165    pub(crate) fn new(pieces_in_sector: u16) -> Self {
166        Self {
167            records: Record::new_zero_vec(usize::from(pieces_in_sector)),
168            metadata: vec![RecordMetadata::default(); usize::from(pieces_in_sector)],
169        }
170    }
171}
172
173// Bit array containing space for bits equal to the number of s-buckets in a record
174type SingleRecordBitArray = BitArray<[u8; Record::NUM_S_BUCKETS / u8::BITS as usize]>;
175
176const SINGLE_RECORD_BIT_ARRAY_SIZE: usize = mem::size_of::<SingleRecordBitArray>();
177
178// TODO: I really tried to avoid `count_ones()`, but wasn't able to with safe Rust due to lifetimes
179/// Wrapper data structure that allows to iterate mutably over encoded chunks bitfields, while
180/// maintaining up-to-date number of encoded chunks
181///
182/// ## Panics
183/// Panics on drop if too many chunks are encoded
184#[derive(Debug)]
185pub struct EncodedChunksUsed<'a> {
186    encoded_record_chunks_used: &'a mut SingleRecordBitArray,
187    num_encoded_record_chunks: &'a mut SBucket,
188    potentially_updated: bool,
189}
190
191impl Drop for EncodedChunksUsed<'_> {
192    fn drop(&mut self) {
193        if self.potentially_updated {
194            let num_encoded_record_chunks = self.encoded_record_chunks_used.count_ones();
195            assert!(num_encoded_record_chunks <= SBucket::MAX.into());
196            *self.num_encoded_record_chunks = SBucket::try_from(num_encoded_record_chunks)
197                .expect("Checked with explicit assert above; qed");
198        }
199    }
200}
201
202impl EncodedChunksUsed<'_> {
203    /// Produces an iterator over encoded chunks bitfields.
204    pub fn iter(&self) -> impl ExactSizeIterator<Item = impl Deref<Target = bool> + '_> + '_ {
205        self.encoded_record_chunks_used.iter()
206    }
207
208    /// Produces a mutable iterator over encoded chunks bitfields.
209    pub fn iter_mut(
210        &mut self,
211    ) -> impl ExactSizeIterator<Item = impl DerefMut<Target = bool> + '_> + '_ {
212        self.potentially_updated = true;
213        self.encoded_record_chunks_used.iter_mut()
214    }
215}
216
217/// Error happening when trying to create [`SectorContentsMap`] from bytes
218#[derive(Debug, Error, Copy, Clone, Eq, PartialEq)]
219pub enum SectorContentsMapFromBytesError {
220    /// Invalid bytes length
221    #[error("Invalid bytes length, expected {expected}, actual {actual}")]
222    InvalidBytesLength {
223        /// Expected length
224        expected: usize,
225        /// Actual length
226        actual: usize,
227    },
228    /// Invalid number of encoded record chunks
229    #[error("Invalid number of encoded record chunks: {actual}")]
230    InvalidEncodedRecordChunks {
231        /// Actual number of encoded record chunks
232        actual: usize,
233        /// Max supported
234        max: usize,
235    },
236    /// Checksum mismatch
237    #[error("Checksum mismatch")]
238    ChecksumMismatch,
239}
240
241/// Error happening when trying to encode [`SectorContentsMap`] into bytes
242#[derive(Debug, Error, Copy, Clone, Eq, PartialEq)]
243pub enum SectorContentsMapEncodeIntoError {
244    /// Invalid bytes length
245    #[error("Invalid bytes length, expected {expected}, actual {actual}")]
246    InvalidBytesLength {
247        /// Expected length
248        expected: usize,
249        /// Actual length
250        actual: usize,
251    },
252}
253
254/// Error happening when trying to create [`SectorContentsMap`] from bytes
255#[derive(Debug, Error, Copy, Clone, Eq, PartialEq)]
256pub enum SectorContentsMapIterationError {
257    /// S-bucket provided is out of range
258    #[error("S-bucket provided {provided} is out of range, max {max}")]
259    SBucketOutOfRange {
260        /// Provided s-bucket
261        provided: usize,
262        /// Max s-bucket
263        max: usize,
264    },
265}
266
267/// Map of sector contents.
268///
269/// Abstraction on top of bitfields that allow making sense of sector contents that contains both
270/// encoded (meaning erasure coded and encoded with existing PoSpace quality) and unencoded chunks
271/// (just erasure coded) used at the same time both in records (before writing to plot) and
272/// s-buckets (written into the plot) format
273#[derive(Debug, Clone, Eq, PartialEq)]
274pub struct SectorContentsMap {
275    /// Number of encoded chunks used in each record.
276    ///
277    /// This is technically redundant, but allows to drastically decrease amount of work in
278    /// [`Self::iter_s_bucket_records()`] and other places, which become unusably slow otherwise.
279    num_encoded_record_chunks: Vec<SBucket>,
280    /// Bitfields for each record, each bit is `true` if encoded chunk at corresponding position was
281    /// used
282    encoded_record_chunks_used: Vec<SingleRecordBitArray>,
283}
284
285impl SectorContentsMap {
286    /// Create new sector contents map initialized with zeroes to store data for `pieces_in_sector`
287    /// records
288    pub fn new(pieces_in_sector: u16) -> Self {
289        Self {
290            num_encoded_record_chunks: vec![SBucket::default(); usize::from(pieces_in_sector)],
291            encoded_record_chunks_used: vec![
292                SingleRecordBitArray::default();
293                usize::from(pieces_in_sector)
294            ],
295        }
296    }
297
298    /// Reconstruct sector contents map from bytes.
299    ///
300    /// Returns error if length of the vector doesn't match [`Self::encoded_size()`] for
301    /// `pieces_in_sector`.
302    pub fn from_bytes(
303        bytes: &[u8],
304        pieces_in_sector: u16,
305    ) -> Result<Self, SectorContentsMapFromBytesError> {
306        if bytes.len() != Self::encoded_size(pieces_in_sector) {
307            return Err(SectorContentsMapFromBytesError::InvalidBytesLength {
308                expected: Self::encoded_size(pieces_in_sector),
309                actual: bytes.len(),
310            });
311        }
312
313        let (single_records_bit_arrays, expected_checksum) =
314            bytes.split_at(bytes.len() - Blake3Hash::SIZE);
315        // Verify checksum
316        let actual_checksum = blake3_hash(single_records_bit_arrays);
317        if *actual_checksum != *expected_checksum {
318            debug!(
319                actual_checksum = %hex::encode(actual_checksum),
320                expected_checksum = %hex::encode(expected_checksum),
321                "Hash doesn't match, corrupted bytes"
322            );
323
324            return Err(SectorContentsMapFromBytesError::ChecksumMismatch);
325        }
326
327        // Length was checked above, so there is no remainder
328        let encoded_record_chunks_used = single_records_bit_arrays
329            .as_chunks::<{ SINGLE_RECORD_BIT_ARRAY_SIZE }>()
330            .0
331            .iter()
332            .copied()
333            .map(SingleRecordBitArray::new)
334            .collect::<Vec<_>>();
335
336        let num_encoded_record_chunks = encoded_record_chunks_used
337            .iter()
338            .map(|encoded_record_chunks_used| {
339                let num_encoded_record_chunks = encoded_record_chunks_used.count_ones();
340                if num_encoded_record_chunks > Record::NUM_CHUNKS {
341                    return Err(
342                        SectorContentsMapFromBytesError::InvalidEncodedRecordChunks {
343                            actual: num_encoded_record_chunks,
344                            max: Record::NUM_CHUNKS,
345                        },
346                    );
347                }
348                Ok(SBucket::try_from(num_encoded_record_chunks).expect("Verified above; qed"))
349            })
350            .collect::<Result<Vec<_>, _>>()?;
351
352        Ok(Self {
353            num_encoded_record_chunks,
354            encoded_record_chunks_used,
355        })
356    }
357
358    /// Size of sector contents map when encoded and stored in the plot for specified number of
359    /// pieces in sector
360    pub const fn encoded_size(pieces_in_sector: u16) -> usize {
361        SINGLE_RECORD_BIT_ARRAY_SIZE * pieces_in_sector as usize + Blake3Hash::SIZE
362    }
363
364    /// Encode internal contents into `output`, which doesn't need to be initialized.
365    ///
366    /// Returns `output` that is now fully initialized.
367    pub fn encode_into<'a>(
368        &self,
369        output: &'a mut [MaybeUninit<u8>],
370    ) -> Result<&'a mut [u8], SectorContentsMapEncodeIntoError> {
371        if output.len() != Self::encoded_size(self.encoded_record_chunks_used.len() as u16) {
372            return Err(SectorContentsMapEncodeIntoError::InvalidBytesLength {
373                expected: Self::encoded_size(self.encoded_record_chunks_used.len() as u16),
374                actual: output.len(),
375            });
376        }
377
378        let slice = self.encoded_record_chunks_used.as_slice();
379        // SAFETY: `BitArray` is a transparent data structure containing array of bytes
380        let slice = unsafe {
381            slice::from_raw_parts(
382                slice.as_ptr() as *const u8,
383                slice.len() * SINGLE_RECORD_BIT_ARRAY_SIZE,
384            )
385        };
386
387        // Write data and checksum
388        let (data_output, checksum_output) = output.split_at_mut(slice.len());
389        data_output.write_copy_of_slice(slice);
390        checksum_output.write_copy_of_slice(blake3_hash(slice).as_ref());
391
392        // SAFETY: Data and checksum together cover the whole `output`, both were initialized above
393        Ok(unsafe { output.assume_init_mut() })
394    }
395
396    /// Number of encoded chunks in each record
397    pub fn num_encoded_record_chunks(&self) -> &[SBucket] {
398        &self.num_encoded_record_chunks
399    }
400
401    /// Iterate over individual record bitfields
402    pub fn iter_record_bitfields(&self) -> &[SingleRecordBitArray] {
403        &self.encoded_record_chunks_used
404    }
405
406    /// Iterate mutably over individual record bitfields
407    pub fn iter_record_bitfields_mut(
408        &mut self,
409    ) -> impl ExactSizeIterator<Item = EncodedChunksUsed<'_>> + '_ {
410        self.encoded_record_chunks_used
411            .iter_mut()
412            .zip(&mut self.num_encoded_record_chunks)
413            .map(
414                |(encoded_record_chunks_used, num_encoded_record_chunks)| EncodedChunksUsed {
415                    encoded_record_chunks_used,
416                    num_encoded_record_chunks,
417                    potentially_updated: false,
418                },
419            )
420    }
421
422    /// Returns sizes of each s-bucket
423    pub fn s_bucket_sizes(&self) -> Box<[u16; Record::NUM_S_BUCKETS]> {
424        // Rayon doesn't support iteration over custom types yet
425        let s_bucket_sizes = (u16::from(SBucket::ZERO)..=u16::from(SBucket::MAX))
426            .into_par_iter()
427            .map(SBucket::from)
428            .map(|s_bucket| {
429                self.iter_s_bucket_records(s_bucket)
430                    .expect("S-bucket guaranteed to be in range; qed")
431                    .count() as u16
432            })
433            .collect::<Box<_>>();
434
435        assert_eq!(s_bucket_sizes.len(), Record::NUM_S_BUCKETS);
436        let mut s_bucket_sizes = ManuallyDrop::new(s_bucket_sizes);
437        // SAFETY: Original memory is not dropped, number of elements checked above
438        unsafe { Box::from_raw(s_bucket_sizes.as_mut_ptr() as *mut [u16; Record::NUM_S_BUCKETS]) }
439    }
440
441    /// Creates an iterator of `(s_bucket, encoded_chunk_used, chunk_location)`, where `s_bucket` is
442    /// position of the chunk in the erasure coded record, `encoded_chunk_used` indicates whether it
443    /// was encoded and `chunk_location` is the offset of the chunk in the plot (across all
444    /// s-buckets).
445    pub fn iter_record_chunk_to_plot(
446        &self,
447        piece_offset: PieceOffset,
448    ) -> impl Iterator<Item = (SBucket, bool, usize)> + '_ {
449        // Iterate over all s-buckets
450        (SBucket::ZERO..=SBucket::MAX)
451            // In each s-bucket map all records used
452            .flat_map(|s_bucket| {
453                self.iter_s_bucket_records(s_bucket)
454                    .expect("S-bucket guaranteed to be in range; qed")
455                    .map(move |(current_piece_offset, encoded_chunk_used)| {
456                        (s_bucket, current_piece_offset, encoded_chunk_used)
457                    })
458            })
459            // We've got contents of all s-buckets in a flat iterator, enumerating them so it is
460            // possible to find in the plot later if desired
461            .enumerate()
462            // Everything about the piece offset we care about
463            .filter_map(
464                move |(chunk_location, (s_bucket, current_piece_offset, encoded_chunk_used))| {
465                    // In case record for `piece_offset` is found, return necessary information
466                    (current_piece_offset == piece_offset).then_some((
467                        s_bucket,
468                        encoded_chunk_used,
469                        chunk_location,
470                    ))
471                },
472            )
473            // Tiny optimization in case we have found chunks for all records already
474            .take(Record::NUM_CHUNKS)
475    }
476
477    /// Creates an iterator of `Option<(chunk_offset, encoded_chunk_used)>`, where each entry
478    /// corresponds s-bucket/position of the chunk in the erasure coded record, `encoded_chunk_used`
479    /// indicates whether it was encoded and `chunk_offset` is the offset of the chunk in the
480    /// corresponding s-bucket.
481    ///
482    /// Similar to `Self::iter_record_chunk_to_plot()`, but runs in parallel, returns entries for
483    /// all s-buckets and offsets are within corresponding s-buckets rather than the whole plot.
484    pub fn par_iter_record_chunk_to_plot(
485        &self,
486        piece_offset: PieceOffset,
487    ) -> impl IndexedParallelIterator<Item = Option<(usize, bool)>> + '_ {
488        let piece_offset = usize::from(piece_offset);
489        (u16::from(SBucket::ZERO)..=u16::from(SBucket::MAX))
490            .into_par_iter()
491            .map(SBucket::from)
492            // In each s-bucket map all records used
493            .map(move |s_bucket| {
494                let encoded_chunk_used = record_has_s_bucket_chunk(
495                    s_bucket.into(),
496                    &self.encoded_record_chunks_used[piece_offset],
497                    usize::from(self.num_encoded_record_chunks[piece_offset]),
498                )?;
499
500                // How many other record chunks we have in s-bucket before piece offset we care
501                // about
502                let chunk_offset = self
503                    .encoded_record_chunks_used
504                    .iter()
505                    .zip(&self.num_encoded_record_chunks)
506                    .take(piece_offset)
507                    .filter(move |(record_bitfields, num_encoded_record_chunks)| {
508                        record_has_s_bucket_chunk(
509                            s_bucket.into(),
510                            record_bitfields,
511                            usize::from(**num_encoded_record_chunks),
512                        )
513                        .is_some()
514                    })
515                    .count();
516
517                Some((chunk_offset, encoded_chunk_used))
518            })
519    }
520
521    /// Creates an iterator of `(piece_offset, encoded_chunk_used)`, where `piece_offset`
522    /// corresponds to the record to which chunk belongs and `encoded_chunk_used` indicates whether
523    /// it was encoded.
524    ///
525    /// Returns error if `s_bucket` is outside of [`Record::NUM_S_BUCKETS`] range.
526    pub fn iter_s_bucket_records(
527        &self,
528        s_bucket: SBucket,
529    ) -> Result<impl Iterator<Item = (PieceOffset, bool)> + '_, SectorContentsMapIterationError>
530    {
531        let s_bucket = usize::from(s_bucket);
532
533        if s_bucket >= Record::NUM_S_BUCKETS {
534            return Err(SectorContentsMapIterationError::SBucketOutOfRange {
535                provided: s_bucket,
536                max: Record::NUM_S_BUCKETS,
537            });
538        }
539
540        Ok((PieceOffset::ZERO..)
541            .zip(
542                self.encoded_record_chunks_used
543                    .iter()
544                    .zip(&self.num_encoded_record_chunks),
545            )
546            .filter_map(
547                move |(piece_offset, (record_bitfields, num_encoded_record_chunks))| {
548                    let encoded_chunk_used = record_has_s_bucket_chunk(
549                        s_bucket,
550                        record_bitfields,
551                        usize::from(*num_encoded_record_chunks),
552                    )?;
553
554                    Some((piece_offset, encoded_chunk_used))
555                },
556            ))
557    }
558
559    /// Iterate over chunks of s-bucket indicating if encoded chunk is used at corresponding
560    /// position
561    ///
562    /// ## Panics
563    /// Panics if `s_bucket` is outside of [`Record::NUM_S_BUCKETS`] range.
564    pub fn iter_s_bucket_encoded_record_chunks_used(
565        &self,
566        s_bucket: SBucket,
567    ) -> Result<impl Iterator<Item = bool> + '_, SectorContentsMapIterationError> {
568        let s_bucket = usize::from(s_bucket);
569
570        if s_bucket >= Record::NUM_S_BUCKETS {
571            return Err(SectorContentsMapIterationError::SBucketOutOfRange {
572                provided: s_bucket,
573                max: Record::NUM_S_BUCKETS,
574            });
575        }
576
577        Ok(self
578            .encoded_record_chunks_used
579            .iter()
580            .map(move |record_bitfields| record_bitfields[s_bucket]))
581    }
582}
583
584/// Checks if record has corresponding s-bucket chunk, returns `Some(true)` if yes and chunk is
585/// encoded, `Some(false)` if yes and chunk is not encoded, `None` if chunk at corresponding
586/// s-bucket is not found.
587fn record_has_s_bucket_chunk(
588    s_bucket: usize,
589    record_bitfields: &SingleRecordBitArray,
590    num_encoded_record_chunks: usize,
591) -> Option<bool> {
592    if record_bitfields[s_bucket] {
593        // Bit is explicitly set to `true`, easy case
594        Some(true)
595    } else if num_encoded_record_chunks == Record::NUM_CHUNKS {
596        None
597    } else {
598        // Count how many encoded chunks we have before current offset
599        let encoded_before = record_bitfields[..s_bucket].count_ones();
600        let unencoded_before = s_bucket - encoded_before;
601        // And how many unencoded we have total and how many before current offset
602        // (we know that total number of used chunks is always `Record::NUM_CHUNKS`)
603        let unencoded_total = Record::NUM_CHUNKS.saturating_sub(num_encoded_record_chunks);
604
605        if unencoded_before < unencoded_total {
606            // Have not seen all unencoded chunks before current offset yet, hence
607            // current offset qualifies
608            Some(false)
609        } else {
610            None
611        }
612    }
613}