1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
use crate::{
RepairingChunkSet,
chunk::{self, ProofCarryingChunk},
chunkset::{self, ChunkSet},
consts::{DECDS_BINCODE_CONFIG, DECDS_NUM_ERASURE_CODED_SHARES},
errors::DecdsError,
merkle_tree::MerkleTree,
};
use blake3;
use rayon::prelude::*;
use serde::{Deserialize, Serialize};
use std::{collections::HashMap, ops::RangeBounds, usize};
/// Represents the header of a `Blob`, containing essential metadata about the blob's
/// structure and cryptographic commitments. This is essentially what is used during
/// validity checking and repairing of erasure-coded chunks.
#[derive(Clone, Serialize, Deserialize, Debug, PartialEq)]
pub struct BlobHeader {
byte_length: usize,
num_chunksets: usize,
digest: blake3::Hash,
root_commitment: blake3::Hash,
chunkset_root_commitments: Vec<blake3::Hash>,
}
impl BlobHeader {
/// Returns the original byte length of the blob data before padding.
pub fn get_blob_size(&self) -> usize {
self.byte_length
}
/// Returns the total number of chunksets that comprise the blob.
pub fn get_num_chunksets(&self) -> usize {
self.num_chunksets
}
/// Returns the total number of erasure-coded chunks across all chunksets in the blob.
pub fn get_num_chunks(&self) -> usize {
self.get_num_chunksets() * chunkset::ChunkSet::NUM_ERASURE_CODED_CHUNKS
}
/// Returns the BLAKE3 digest of the original, unpadded blob data.
pub fn get_blob_digest(&self) -> blake3::Hash {
self.digest
}
/// Returns the Merkle root commitment of the entire blob.
///
/// This commitment is derived from the Merkle tree of all chunksets in the blob.
pub fn get_root_commitment(&self) -> blake3::Hash {
self.root_commitment
}
/// Returns the Merkle root commitment of a specific chunkset within the blob.
///
/// # Arguments
///
/// * `chunkset_id` - The ID of the chunkset whose commitment is to be retrieved.
///
/// # Returns
///
/// Returns a `Result` which is:
/// - `Ok(blake3::Hash)` containing the root commitment of the specified chunkset if successful.
/// - `Err(DecdsError::InvalidChunksetId)` if `chunkset_id` is out of bounds.
pub fn get_chunkset_commitment(&self, chunkset_id: usize) -> Result<blake3::Hash, DecdsError> {
self.chunkset_root_commitments
.get(chunkset_id)
.and_then(|&v| Some(v))
.ok_or(DecdsError::InvalidChunksetId(chunkset_id, self.get_num_chunksets()))
}
/// Calculates the effective byte length of a specific chunkset within the blob.
/// This accounts for the last chunkset potentially being smaller than `ChunkSet::BYTE_LENGTH`.
///
/// # Arguments
///
/// * `chunkset_id` - The ID of the chunkset whose size is to be determined.
///
/// # Returns
///
/// Returns a `Result` which is:
/// - `Ok(usize)` containing the effective byte length of the chunkset if successful.
/// - `Err(DecdsError::InvalidChunksetId)` if `chunkset_id` is out of bounds.
pub fn get_chunkset_size(&self, chunkset_id: usize) -> Result<usize, DecdsError> {
if chunkset_id < self.get_num_chunksets() {
let from = chunkset_id * ChunkSet::BYTE_LENGTH;
let to = (from + ChunkSet::BYTE_LENGTH).min(self.get_blob_size());
let effective_len = to - from;
Ok(effective_len)
} else {
Err(DecdsError::InvalidChunksetId(chunkset_id, self.get_num_chunksets()))
}
}
/// Returns the full byte range `[start, end)` of a specific chunkset as it would appear
/// in the zero-padded blob data.
///
/// # Arguments
///
/// * `chunkset_id` - The ID of the chunkset whose byte range is to be retrieved.
///
/// # Returns
///
/// Returns a `Result` which is:
/// - `Ok((usize, usize))` containing a tuple `[start_byte_idx, end_byte_idx)` if successful.
/// - `Err(DecdsError::InvalidChunksetId)` if `chunkset_id` is out of bounds.
pub fn get_byte_range_for_chunkset(&self, chunkset_id: usize) -> Result<(usize, usize), DecdsError> {
if chunkset_id < self.get_num_chunksets() {
let from = chunkset_id * ChunkSet::BYTE_LENGTH;
let to = (from + ChunkSet::BYTE_LENGTH).min(self.get_blob_size());
Ok((from, to))
} else {
Err(DecdsError::InvalidChunksetId(chunkset_id, self.get_num_chunksets()))
}
}
/// Determines the IDs of all chunksets that overlap with a given byte range within the blob.
///
/// # Arguments
///
/// * `byte_range` - A range `impl RangeBounds<usize>` specifying the byte range.
///
/// # Returns
///
/// Returns a `Result` which is:
/// - `Ok(Vec<usize>)` containing a vector of chunkset IDs if successful.
/// - `Err(DecdsError::InvalidStartBound)` if the start bound of the range is not valid.
/// - `Err(DecdsError::InvalidEndBound)` if the end bound of the range is not valid (e.g., 0 for an `Excluded` bound or `usize::MAX`).
/// - `Err(DecdsError::InvalidChunksetId)` if the calculated `end_chunkset_id` is out of bounds.
pub fn get_chunkset_ids_for_byte_range(&self, byte_range: impl RangeBounds<usize>) -> Result<Vec<usize>, DecdsError> {
let start = match byte_range.start_bound() {
std::ops::Bound::Unbounded => 0,
std::ops::Bound::Included(&x) => x,
_ => return Err(DecdsError::InvalidStartBound),
};
let end = match byte_range.end_bound() {
std::ops::Bound::Included(&x) => x,
std::ops::Bound::Excluded(&x) => {
if x == 0 {
return Err(DecdsError::InvalidEndBound(x));
}
x - 1
}
_ => return Err(DecdsError::InvalidEndBound(usize::MAX)),
};
let start_chunkset_id = start / ChunkSet::BYTE_LENGTH;
let end_chunkset_id = end / ChunkSet::BYTE_LENGTH;
if end_chunkset_id >= self.get_num_chunksets() {
return Err(DecdsError::InvalidChunksetId(end_chunkset_id, self.get_num_chunksets()));
}
Ok((start_chunkset_id..=end_chunkset_id).collect())
}
/// Serializes the `BlobHeader` into a vector of bytes using `bincode`.
///
/// # Returns
///
/// Returns a `Result` which is:
/// - `Ok(Vec<u8>)` containing the serialized bytes if successful.
/// - `Err(DecdsError::BlobHeaderSerializationFailed)` if `bincode` serialization fails.
pub fn to_bytes(&self) -> Result<Vec<u8>, DecdsError> {
bincode::serde::encode_to_vec(self, DECDS_BINCODE_CONFIG).map_err(|err| DecdsError::BlobHeaderSerializationFailed(err.to_string()))
}
/// Deserializes a `BlobHeader` from a byte slice using `bincode`.
///
/// # Arguments
///
/// * `bytes` - The byte slice from which to deserialize the header.
///
/// # Returns
///
/// Returns a `Result` which is:
/// - `Ok((Self, usize))` containing the deserialized `BlobHeader` and the number of bytes read if successful.
/// - `Err(DecdsError::BlobHeaderDeserializationFailed)` if `bincode` deserialization fails, or if the number
/// of chunksets in the header does not match the number of root commitments.
pub fn from_bytes(bytes: &[u8]) -> Result<(Self, usize), DecdsError> {
match bincode::serde::decode_from_slice::<BlobHeader, bincode::config::Configuration>(bytes, DECDS_BINCODE_CONFIG) {
Ok((header, n)) => {
if header.num_chunksets != header.chunkset_root_commitments.len() {
return Err(DecdsError::BlobHeaderDeserializationFailed(
"number of chunksets and root commitments do not match".to_string(),
));
}
Ok((header, n))
}
Err(err) => Err(DecdsError::BlobHeaderDeserializationFailed(err.to_string())),
}
}
/// Validates a `ProofCarryingChunk` against the `BlobHeader`'s commitments.
///
/// This checks if the chunk is correctly included in the blob (via blob root commitment)
/// and its respective chunkset (via chunkset root commitment).
///
/// # Arguments
///
/// * `chunk` - A reference to the `ProofCarryingChunk` to validate.
///
/// # Returns
///
/// Returns `true` if the chunk is valid and its proofs are consistent with the blob header, `false` otherwise.
pub fn validate_chunk(&self, chunk: &chunk::ProofCarryingChunk) -> bool {
chunk.validate_inclusion_in_blob(self.root_commitment)
&& (chunk.get_chunkset_id() < self.num_chunksets)
&& chunk.validate_inclusion_in_chunkset(self.chunkset_root_commitments[chunk.get_chunkset_id()])
}
}
/// Represents a complete, erasure-coded blob of data, consisting of a `BlobHeader` and a collection of `ChunkSet`s,
/// each of which are holding 16 erasure-coded proof-of-inclusion carrying chunks.
pub struct Blob {
header: BlobHeader,
body: Vec<chunkset::ChunkSet>,
}
impl Blob {
/// Creates a new `Blob` from raw byte data.
///
/// This involves:
/// 1. Calculating the blob's digest and padding its length to a multiple of `ChunkSet::BYTE_LENGTH`.
/// 2. Dividing the data into `ChunkSet`s and erasure-coding them individually.
/// 3. Building a Merkle tree over the chunksets' root commitments to create the blob's root commitment.
/// 4. Appending blob-level Merkle proofs to each chunk within the chunksets.
///
/// # Arguments
///
/// * `data` - The raw `Vec<u8>` representing the blob's content.
///
/// # Returns
///
/// Returns a `Result` which is:
/// - `Ok(Self)` containing the newly created `Blob` if successful.
/// - `Err(DecdsError::EmptyDataForBlob)` if the input `data` is empty.
/// - Other `DecdsError` types may be returned from underlying `ChunkSet::new` or `MerkleTree::new` calls.
pub fn new(mut data: Vec<u8>) -> Result<Self, DecdsError> {
if data.is_empty() {
return Err(DecdsError::EmptyDataForBlob);
}
let blob_digest = blake3::hash(&data);
let blob_length = data.len();
let num_chunksets = blob_length.div_ceil(chunkset::ChunkSet::BYTE_LENGTH);
let zero_padded_blob_len = num_chunksets * chunkset::ChunkSet::BYTE_LENGTH;
data.resize(zero_padded_blob_len, 0);
let mut chunksets = (0..num_chunksets)
.into_par_iter()
.map(|chunkset_id| {
let offset = chunkset_id * chunkset::ChunkSet::BYTE_LENGTH;
let till = offset + chunkset::ChunkSet::BYTE_LENGTH;
unsafe { chunkset::ChunkSet::new(chunkset_id, data[offset..till].to_vec()).unwrap_unchecked() }
})
.collect::<Vec<chunkset::ChunkSet>>();
let merkle_leaves = chunksets.iter().map(|chunkset| chunkset.get_root_commitment()).collect::<Vec<blake3::Hash>>();
let merkle_tree = MerkleTree::new(merkle_leaves)?;
let commitment = merkle_tree.get_root_commitment();
chunksets.par_iter_mut().enumerate().for_each(|(chunkset_idx, chunkset)| {
let blob_proof = unsafe { merkle_tree.generate_proof(chunkset_idx).unwrap_unchecked() };
chunkset.append_blob_inclusion_proof(&blob_proof);
});
Ok(Blob {
header: BlobHeader {
byte_length: blob_length,
num_chunksets,
digest: blob_digest,
root_commitment: commitment,
chunkset_root_commitments: chunksets.iter().map(|chunkset| chunkset.get_root_commitment()).collect(),
},
body: chunksets,
})
}
/// Returns a reference to the `BlobHeader` of this blob.
pub fn get_blob_header(&self) -> &BlobHeader {
&self.header
}
/// Retrieves a specific "share" (a collection of erasure-coded chunks, one from each chunkset)
/// based on the `share_id`.
///
/// Each share represents a vertical slice through the blob's chunksets.
///
/// # Arguments
///
/// * `share_id` - The ID of the share to retrieve (`0` to `DECDS_NUM_ERASURE_CODED_SHARES - 1`).
///
/// # Returns
///
/// Returns a `Result` which is:
/// - `Ok(Vec<ProofCarryingChunk>)` containing a vector of proof-carrying chunks for the requested share.
/// - `Err(DecdsError::InvalidErasureCodedShareId)` if `share_id` is out of bounds.
pub fn get_share(&self, share_id: usize) -> Result<Vec<ProofCarryingChunk>, DecdsError> {
if share_id >= DECDS_NUM_ERASURE_CODED_SHARES {
return Err(DecdsError::InvalidErasureCodedShareId(share_id));
}
Ok((0..self.header.num_chunksets)
.map(|chunkset_id| unsafe {
let chunkset = &self.body[chunkset_id];
chunkset.get_chunk(share_id).unwrap_unchecked().clone()
})
.collect::<Vec<ProofCarryingChunk>>())
}
}
/// Represents a blob that is in the process of being incrementally repaired or reconstructed
/// from received `ProofCarryingChunk`s.
pub struct RepairingBlob {
header: BlobHeader,
body: HashMap<usize, Option<chunkset::RepairingChunkSet>>,
}
impl RepairingBlob {
/// Creates a new `RepairingBlob` instance from a `BlobHeader`.
///
/// This initializes an empty `RepairingChunkSet` for each chunkset indicated in the header,
/// ready to receive chunks for repair.
///
/// # Arguments
///
/// * `header` - The `BlobHeader` of the blob to be repaired. This header provides the necessary
/// metadata, including chunkset commitments, for the repair process.
///
/// # Returns
///
/// A new `RepairingBlob` instance, prepared to accept chunks for reconstruction.
pub fn new(header: BlobHeader) -> Self {
RepairingBlob {
body: HashMap::from_iter((0..header.get_num_chunksets()).map(|chunkset_id| {
(
chunkset_id,
Some(RepairingChunkSet::new(chunkset_id, unsafe {
header.get_chunkset_commitment(chunkset_id).unwrap_unchecked()
})),
)
})),
header: header,
}
}
/// Adds a `ProofCarryingChunk` to the appropriate `RepairingChunkSet` within the blob.
///
/// This method first validates the chunk's inclusion using the blob header, then attempts
/// to add it to the relevant chunkset's decoder.
///
/// # Arguments
///
/// * `chunk` - A reference to the `ProofCarryingChunk` to add.
///
/// # Returns
///
/// Returns a `Result` which is:
/// - `Ok(())` if the chunk is successfully added.
/// - `Err(DecdsError::InvalidChunksetId)` if the chunk's `chunkset_id` does not exist in this blob.
/// - `Err(DecdsError::ChunksetAlreadyRepaired)` if the target chunkset has already been repaired.
/// - `Err(DecdsError::InvalidProofInChunk)` if the chunk's proof of inclusion in the blob or chunkset is invalid.
/// - `Err(DecdsError::ChunksetReadyToRepair)` if the chunkset is already ready to repair (and thus cannot accept more chunks).
/// - Other `DecdsError` types may be returned from `RepairingChunkSet::add_chunk_unvalidated`.
pub fn add_chunk(&mut self, chunk: &chunk::ProofCarryingChunk) -> Result<(), DecdsError> {
let chunkset_id = chunk.get_chunkset_id();
match self
.body
.get_mut(&chunkset_id)
.ok_or(DecdsError::InvalidChunksetId(chunkset_id, self.header.get_num_chunksets()))?
{
Some(chunkset) => {
if self.header.validate_chunk(chunk) {
if !chunkset.is_ready_to_repair() {
chunkset.add_chunk_unvalidated(chunk)
} else {
Err(DecdsError::ChunksetReadyToRepair(chunkset_id))
}
} else {
Err(DecdsError::InvalidProofInChunk(chunkset_id))
}
}
None => Err(DecdsError::ChunksetAlreadyRepaired(chunkset_id)),
}
}
/// Checks if a specific chunkset within the blob is ready to be repaired (reconstructed).
///
/// # Arguments
///
/// * `chunkset_id` - The ID of the chunkset to check.
///
/// # Returns
///
/// Returns a `Result` which is:
/// - `Ok(bool)`: `true` if the chunkset is ready for repair, `false` otherwise.
/// - `Err(DecdsError::InvalidChunksetId)` if `chunkset_id` is out of bounds.
pub fn is_chunkset_ready_to_repair(&self, chunkset_id: usize) -> Result<bool, DecdsError> {
Ok(self
.body
.get(&chunkset_id)
.ok_or(DecdsError::InvalidChunksetId(chunkset_id, self.header.get_num_chunksets()))?
.as_ref()
.is_some_and(|x| x.is_ready_to_repair()))
}
/// Checks if a specific chunkset within the blob has already been successfully repaired.
///
/// # Arguments
///
/// * `chunkset_id` - The ID of the chunkset to check.
///
/// # Returns
///
/// Returns a `Result` which is:
/// - `Ok(bool)`: `true` if the chunkset has already been repaired, `false` otherwise.
/// - `Err(DecdsError::InvalidChunksetId)` if `chunkset_id` is out of bounds.
pub fn is_chunkset_already_repaired(&self, chunkset_id: usize) -> Result<bool, DecdsError> {
Ok(self
.body
.get(&chunkset_id)
.ok_or(DecdsError::InvalidChunksetId(chunkset_id, self.header.get_num_chunksets()))?
.is_none())
}
/// Retrieves the repaired (reconstructed) data for a specific chunkset.
/// This method consumes the `RepairingChunkSet` for the given ID once successful,
/// as the data is fully reconstructed.
///
/// # Arguments
///
/// * `chunkset_id` - The ID of the chunkset to retrieve repaired data for.
///
/// # Returns
///
/// Returns a `Result` which is:
/// - `Ok(Vec<u8>)` containing the repaired chunkset data if successful.
/// - `Err(DecdsError::ChunksetAlreadyRepaired)` if the chunkset has already been repaired and retrieved.
/// - `Err(DecdsError::ChunksetNotYetReadyToRepair)` if not enough chunks have been added to repair the chunkset.
/// - `Err(DecdsError::InvalidChunksetId)` if `chunkset_id` is out of bounds.
/// - `Err(DecdsError::ChunksetRepairingFailed)` if an error occurs during the underlying chunkset repair process.
pub fn get_repaired_chunkset(&mut self, chunkset_id: usize) -> Result<Vec<u8>, DecdsError> {
self.is_chunkset_already_repaired(chunkset_id).and_then(|yes| {
if yes {
Err(DecdsError::ChunksetAlreadyRepaired(chunkset_id))
} else {
self.is_chunkset_ready_to_repair(chunkset_id).and_then(|yes| unsafe {
if yes {
self.body
.insert(chunkset_id, None)
.unwrap_unchecked()
.unwrap_unchecked()
.repair()
.map(|mut repaired| {
repaired.truncate(self.header.get_chunkset_size(chunkset_id).unwrap_unchecked());
repaired
})
} else {
Err(DecdsError::ChunksetNotYetReadyToRepair(chunkset_id))
}
})
}
})
}
}
#[cfg(test)]
mod tests {
use crate::{BlobHeader, ProofCarryingChunk, RepairingBlob, blob::Blob, chunkset::ChunkSet, consts, errors::DecdsError};
use blake3;
use rand::Rng;
#[test]
fn prop_test_blob_preparation_and_commitment_works() {
const NUM_TEST_ITERATIONS: usize = 10;
const MIN_BLOB_DATA_BYTE_LEN: usize = 1usize;
const MAX_BLOB_DATA_BYTE_LEN: usize = 1usize << 30;
let mut rng = rand::rng();
(0..NUM_TEST_ITERATIONS).for_each(|_| {
let blob_byte_len = rng.random_range(MIN_BLOB_DATA_BYTE_LEN..=MAX_BLOB_DATA_BYTE_LEN);
let blob_data = (0..blob_byte_len).map(|_| rng.random()).collect::<Vec<u8>>();
let blob = Blob::new(blob_data).expect("Must be able to prepare blob");
let blob_header = blob.get_blob_header();
assert!(
(0..consts::DECDS_NUM_ERASURE_CODED_SHARES)
.flat_map(|share_id| blob.get_share(share_id).expect("Must be able to get erasure coded shares"))
.all(|share| blob_header.validate_chunk(&share))
);
});
}
#[test]
fn test_get_chunkset_commitment() {
let mut rng = rand::rng();
let blob_byte_len = (ChunkSet::BYTE_LENGTH * 2) + (ChunkSet::BYTE_LENGTH / 2);
let blob_data = (0..blob_byte_len).map(|_| rng.random()).collect::<Vec<u8>>();
let blob = Blob::new(blob_data).unwrap();
let header = blob.get_blob_header();
// Valid chunkset ID
let commitment = header.get_chunkset_commitment(0);
assert!(commitment.is_ok());
let commitment = header.get_chunkset_commitment(1);
assert!(commitment.is_ok());
// Invalid chunkset ID
let err = header.get_chunkset_commitment(header.get_num_chunksets());
assert_eq!(err, Err(DecdsError::InvalidChunksetId(header.get_num_chunksets(), header.get_num_chunksets())));
}
#[test]
fn test_get_chunkset_size() {
let mut rng = rand::rng();
// Blob size: 2.5 chunksets -> 2 full, 1 half
let blob_byte_len = (ChunkSet::BYTE_LENGTH * 2) + (ChunkSet::BYTE_LENGTH / 2);
let blob_data = (0..blob_byte_len).map(|_| rng.random()).collect::<Vec<u8>>();
let blob = Blob::new(blob_data).unwrap();
let header = blob.get_blob_header();
// Full chunkset
assert_eq!(header.get_chunkset_size(0).unwrap(), ChunkSet::BYTE_LENGTH);
assert_eq!(header.get_chunkset_size(1).unwrap(), ChunkSet::BYTE_LENGTH);
// Partial chunkset
assert_eq!(header.get_chunkset_size(2).unwrap(), ChunkSet::BYTE_LENGTH / 2);
// Invalid chunkset ID
assert_eq!(
header.get_chunkset_size(header.get_num_chunksets()).unwrap_err(),
DecdsError::InvalidChunksetId(header.get_num_chunksets(), header.get_num_chunksets())
);
}
#[test]
fn test_get_byte_range_for_chunkset() {
let mut rng = rand::rng();
let blob_byte_len = (ChunkSet::BYTE_LENGTH * 2) + (ChunkSet::BYTE_LENGTH / 2);
let blob_data = (0..blob_byte_len).map(|_| rng.random()).collect::<Vec<u8>>();
let blob = Blob::new(blob_data).unwrap();
let header = blob.get_blob_header();
// First chunkset
assert_eq!(header.get_byte_range_for_chunkset(0).unwrap(), (0, ChunkSet::BYTE_LENGTH));
// Second chunkset
assert_eq!(
header.get_byte_range_for_chunkset(1).unwrap(),
(ChunkSet::BYTE_LENGTH, ChunkSet::BYTE_LENGTH * 2)
);
// Last (partial) chunkset
assert_eq!(header.get_byte_range_for_chunkset(2).unwrap(), (ChunkSet::BYTE_LENGTH * 2, blob_byte_len));
// Invalid chunkset ID
assert_eq!(
header.get_byte_range_for_chunkset(header.get_num_chunksets()).unwrap_err(),
DecdsError::InvalidChunksetId(header.get_num_chunksets(), header.get_num_chunksets())
);
}
#[test]
fn test_get_chunkset_ids_for_byte_range() {
let mut rng = rand::rng();
let blob_byte_len = (ChunkSet::BYTE_LENGTH * 2) + (ChunkSet::BYTE_LENGTH / 2);
let blob_data = (0..blob_byte_len).map(|_| rng.random()).collect::<Vec<u8>>();
let blob = Blob::new(blob_data).unwrap();
let header = blob.get_blob_header();
// Range within a single chunkset
assert_eq!(header.get_chunkset_ids_for_byte_range(0..10).unwrap(), vec![0]);
assert_eq!(
header
.get_chunkset_ids_for_byte_range(ChunkSet::BYTE_LENGTH + 10..ChunkSet::BYTE_LENGTH + 20)
.unwrap(),
vec![1]
);
// Range spanning multiple chunksets
assert_eq!(
header.get_chunkset_ids_for_byte_range(10..(ChunkSet::BYTE_LENGTH * 1 + 10)).unwrap(),
vec![0, 1]
);
assert_eq!(header.get_chunkset_ids_for_byte_range(10..blob_byte_len).unwrap(), vec![0, 1, 2]);
// Range exactly matching chunkset boundaries
assert_eq!(header.get_chunkset_ids_for_byte_range(0..ChunkSet::BYTE_LENGTH).unwrap(), vec![0]);
assert_eq!(header.get_chunkset_ids_for_byte_range(0..=(ChunkSet::BYTE_LENGTH - 1)).unwrap(), vec![0]);
// Edge cases for bounds
assert_eq!(header.get_chunkset_ids_for_byte_range(0..0).unwrap_err(), DecdsError::InvalidEndBound(0));
assert_eq!(header.get_chunkset_ids_for_byte_range(0..=0).unwrap(), vec![0]); // Covers first byte of first chunkset
// Invalid end bound (range beyond blob size)
let end_beyond_blob = header.get_blob_size() + ChunkSet::BYTE_LENGTH;
let expected_end_chunkset_id = end_beyond_blob.saturating_sub(1) / ChunkSet::BYTE_LENGTH;
assert_eq!(
header.get_chunkset_ids_for_byte_range(0..end_beyond_blob).unwrap_err(),
DecdsError::InvalidChunksetId(expected_end_chunkset_id, header.get_num_chunksets())
);
// Test for `InvalidEndBound(usize::MAX)` for unbounded ranges
assert_eq!(header.get_chunkset_ids_for_byte_range(..).unwrap_err(), DecdsError::InvalidEndBound(usize::MAX));
assert_eq!(
header.get_chunkset_ids_for_byte_range(0..).unwrap_err(),
DecdsError::InvalidEndBound(usize::MAX)
);
}
#[test]
fn test_blob_header_serialization_deserialization() {
let mut rng = rand::rng();
let blob_byte_len = ChunkSet::BYTE_LENGTH * 3;
let blob_data = (0..blob_byte_len).map(|_| rng.random()).collect::<Vec<u8>>();
let blob = Blob::new(blob_data).unwrap();
let original_header = blob.get_blob_header().clone();
let serialized_header = original_header.to_bytes().expect("Header serialization failed");
let (deserialized_header, bytes_read) = BlobHeader::from_bytes(&serialized_header).expect("Header deserialization failed");
assert_eq!(original_header, deserialized_header);
assert_eq!(serialized_header.len(), bytes_read);
// Test deserialization failure with lesser bytes
assert!(BlobHeader::from_bytes(&serialized_header[..(serialized_header.len() / 2)]).is_err());
}
#[test]
fn test_blob_new_empty_data() {
assert_eq!(Blob::new(Vec::new()).err(), Some(DecdsError::EmptyDataForBlob));
}
#[test]
fn test_blob_get_share_invalid_id() {
let mut rng = rand::rng();
let blob_data: Vec<u8> = (0..(ChunkSet::BYTE_LENGTH * 2)).map(|_| rng.random()).collect();
let blob = Blob::new(blob_data).unwrap();
// Test with an invalid share ID (out of bounds)
let invalid_share_id = consts::DECDS_NUM_ERASURE_CODED_SHARES;
assert_eq!(
blob.get_share(invalid_share_id).unwrap_err(),
DecdsError::InvalidErasureCodedShareId(invalid_share_id)
);
// Test with a very large invalid share ID
let large_invalid_share_id = consts::DECDS_NUM_ERASURE_CODED_SHARES + 100;
assert_eq!(
blob.get_share(large_invalid_share_id).unwrap_err(),
DecdsError::InvalidErasureCodedShareId(large_invalid_share_id)
);
}
#[test]
fn test_repairing_blob_new() {
let mut rng = rand::rng();
let blob_data: Vec<u8> = (0..(ChunkSet::BYTE_LENGTH * 2 + ChunkSet::BYTE_LENGTH / 2)).map(|_| rng.random()).collect();
let blob = Blob::new(blob_data).unwrap();
let header = blob.get_blob_header().clone();
let repairer = RepairingBlob::new(header.clone());
assert_eq!(repairer.header.get_blob_size(), header.get_blob_size());
assert_eq!(repairer.header.get_num_chunksets(), header.get_num_chunksets());
assert_eq!(repairer.body.len(), header.get_num_chunksets());
for i in 0..header.get_num_chunksets() {
assert!(repairer.body.get(&i).unwrap().is_some());
assert!(!repairer.is_chunkset_ready_to_repair(i).unwrap());
assert!(!repairer.is_chunkset_already_repaired(i).unwrap());
}
}
#[test]
fn test_repairing_blob_add_chunk() {
let mut rng = rand::rng();
let blob_data: Vec<u8> = (0..(ChunkSet::BYTE_LENGTH * 2)).map(|_| rng.random()).collect(); // Two full chunksets
let blob = Blob::new(blob_data).unwrap();
let blob_header = blob.get_blob_header().clone();
let mut repairer = RepairingBlob::new(blob_header.clone());
let all_chunks: Vec<ProofCarryingChunk> = (0..consts::DECDS_NUM_ERASURE_CODED_SHARES)
.flat_map(|share_id| blob.get_share(share_id).unwrap())
.collect();
// Test valid chunk addition
let chunk_to_add = &all_chunks[0];
assert!(repairer.add_chunk(chunk_to_add).is_ok());
// Simulate an invalid chunk proof by creating a new header with a different root commitment
let mut invalid_header = blob_header.clone();
invalid_header.root_commitment = blake3::hash(b"fake_root_commitment");
let mut repairer_invalid_header = RepairingBlob::new(invalid_header);
assert_eq!(
repairer_invalid_header.add_chunk(chunk_to_add).unwrap_err(),
DecdsError::InvalidProofInChunk(chunk_to_add.get_chunkset_id())
);
// Add enough chunks to make a chunkset ready for repair
let mut repairer_ready = RepairingBlob::new(blob_header.clone());
let chunkset_id = all_chunks[0].get_chunkset_id();
for chunk in &all_chunks {
if chunk.get_chunkset_id() == chunkset_id {
repairer_ready.add_chunk(chunk).unwrap();
if repairer_ready.is_chunkset_ready_to_repair(chunkset_id).unwrap() {
break;
}
}
}
assert!(repairer_ready.is_chunkset_ready_to_repair(chunkset_id).unwrap());
// Try adding another chunk to a chunkset already ready for repair
let extra_chunk = &all_chunks
.iter()
.find(|c| c.get_chunkset_id() == chunkset_id && c.get_global_chunk_id() != all_chunks[0].get_global_chunk_id())
.unwrap();
assert_eq!(
repairer_ready.add_chunk(extra_chunk).unwrap_err(),
DecdsError::ChunksetReadyToRepair(chunkset_id)
);
// Repair the chunkset, then try adding a chunk to it
repairer_ready.get_repaired_chunkset(chunkset_id).unwrap();
assert!(!repairer_ready.is_chunkset_ready_to_repair(chunkset_id).unwrap());
assert!(repairer_ready.is_chunkset_already_repaired(chunkset_id).unwrap());
assert_eq!(
repairer_ready.add_chunk(chunk_to_add).unwrap_err(),
DecdsError::ChunksetAlreadyRepaired(chunkset_id)
);
}
#[test]
fn test_repairing_blob_get_repaired_chunkset() {
let mut rng = rand::rng();
let blob_data: Vec<u8> = (0..(ChunkSet::BYTE_LENGTH * 2 + ChunkSet::BYTE_LENGTH / 2)).map(|_| rng.random()).collect();
let blob = Blob::new(blob_data.clone()).unwrap();
let blob_header = blob.get_blob_header().clone();
let mut repairer = RepairingBlob::new(blob_header.clone());
let all_chunks: Vec<ProofCarryingChunk> = (0..consts::DECDS_NUM_ERASURE_CODED_SHARES)
.flat_map(|share_id| blob.get_share(share_id).unwrap())
.collect();
// Test `ChunksetNotYetReadyToRepair`
let chunkset_id_0 = 0;
assert_eq!(
repairer.get_repaired_chunkset(chunkset_id_0).unwrap_err(),
DecdsError::ChunksetNotYetReadyToRepair(chunkset_id_0)
);
// Add enough chunks for the first chunkset
for chunk in &all_chunks {
if chunk.get_chunkset_id() == chunkset_id_0 {
repairer.add_chunk(chunk).unwrap();
if repairer.is_chunkset_ready_to_repair(chunkset_id_0).unwrap() {
break;
}
}
}
assert!(repairer.is_chunkset_ready_to_repair(chunkset_id_0).unwrap());
// Test successful repair
let repaired_data_0 = repairer.get_repaired_chunkset(chunkset_id_0).unwrap();
let expected_data_0 = blob_data[0..ChunkSet::BYTE_LENGTH].to_vec();
assert_eq!(repaired_data_0, expected_data_0);
assert!(repairer.is_chunkset_already_repaired(chunkset_id_0).unwrap());
// Test `ChunksetAlreadyRepaired`
assert_eq!(
repairer.get_repaired_chunkset(chunkset_id_0).unwrap_err(),
DecdsError::ChunksetAlreadyRepaired(chunkset_id_0)
);
// Test for a partial last chunkset
let chunkset_id_2 = 2;
for chunk in &all_chunks {
if chunk.get_chunkset_id() == chunkset_id_2 {
repairer.add_chunk(chunk).unwrap();
if repairer.is_chunkset_ready_to_repair(chunkset_id_2).unwrap() {
break;
}
}
}
assert!(repairer.is_chunkset_ready_to_repair(chunkset_id_2).unwrap());
let repaired_data_2 = repairer.get_repaired_chunkset(chunkset_id_2).unwrap();
let expected_data_2 = blob_data[ChunkSet::BYTE_LENGTH * 2..].to_vec();
assert_eq!(repaired_data_2, expected_data_2);
// Test invalid chunkset ID
let invalid_chunkset_id = blob_header.get_num_chunksets();
assert_eq!(
repairer.get_repaired_chunkset(invalid_chunkset_id).unwrap_err(),
DecdsError::InvalidChunksetId(invalid_chunkset_id, blob_header.get_num_chunksets())
);
}
}