-
Notifications
You must be signed in to change notification settings - Fork 64
Expand file tree
/
Copy pathcas_object_format.rs
More file actions
2354 lines (1934 loc) · 89.7 KB
/
cas_object_format.rs
File metadata and controls
2354 lines (1934 loc) · 89.7 KB
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
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use std::cmp::min;
use std::io::{Cursor, Read, Seek, SeekFrom, Write};
use std::mem::{size_of, size_of_val};
use anyhow::anyhow;
use bytes::Buf;
use deduplication::RawXorbData;
use deduplication::constants::TARGET_CHUNK_SIZE;
#[cfg(not(target_family = "wasm"))]
use futures::AsyncReadExt;
use mdb_shard::chunk_verification::range_hash_from_chunks;
use merklehash::{DataHash, MerkleHash};
use more_asserts::*;
use serde::Serialize;
use tracing::warn;
use utils::serialization_utils::*;
use xet_runtime::xet_config;
use crate::cas_chunk_format::{deserialize_chunk, serialize_chunk};
use crate::constants::XORB_BLOCK_SIZE;
use crate::error::CasObjectError;
use crate::{CASChunkHeader, CompressionScheme};
pub type CasObjectIdent = [u8; 7];
pub(crate) const CAS_OBJECT_FORMAT_IDENT: CasObjectIdent = [b'X', b'E', b'T', b'B', b'L', b'O', b'B'];
pub(crate) const CAS_OBJECT_FORMAT_VERSION_V0: u8 = 0;
pub(crate) const CAS_OBJECT_FORMAT_IDENT_HASHES: CasObjectIdent = [b'X', b'B', b'L', b'B', b'H', b'S', b'H'];
pub(crate) const CAS_OBJECT_FORMAT_IDENT_BOUNDARIES: CasObjectIdent = [b'X', b'B', b'L', b'B', b'B', b'N', b'D'];
pub(crate) const CAS_OBJECT_FORMAT_VERSION: u8 = 1;
pub(crate) const CAS_OBJECT_FORMAT_HASHES_VERSION: u8 = 0;
// This is 1 as we can test on the struct using this version field whether we have the unpacked boundary lengths
pub(crate) const CAS_OBJECT_FORMAT_BOUNDARIES_VERSION_NO_UNPACKED_INFO: u8 = 0;
pub(crate) const CAS_OBJECT_FORMAT_BOUNDARIES_VERSION: u8 = 1;
const _CAS_OBJECT_INFO_DEFAULT_LENGTH_V0: u32 = 60;
const CAS_OBJECT_INFO_DEFAULT_LENGTH: u32 = 92;
// Decide array preallocation size based on the declared size, to prevent an adversarial
// giant size that leads to OOM on allocation.
#[inline]
fn prealloc_num_chunks(declared_size: usize) -> usize {
let average_num_chunks_per_xorb: usize = *XORB_BLOCK_SIZE / *TARGET_CHUNK_SIZE;
// We add a bit buffer to the average size, hoping to reduce reallocation if
// the actual number of chunks exceeds AVERAGE_NUM_CHUNKS_PER_XORB.
declared_size.min(average_num_chunks_per_xorb * 9 / 8)
}
#[derive(Clone, PartialEq, Eq, Debug, Serialize)]
/// Info struct for [CasObject]. This is stored at the end of the XORB.
/// DO NOT USE in any new code
pub struct CasObjectInfoV0 {
/// CAS identifier: "XETBLOB"
pub ident: CasObjectIdent,
/// Format version, expected to be 0 right now.
pub version: u8,
/// 256-bits, 32-bytes, The CAS Hash of this Xorb.
pub cashash: MerkleHash,
/// Total number of chunks in the Xorb. Length of chunk_boundary_offsets & chunk_hashes vectors.
pub num_chunks: u32,
/// Byte offset marking the boundary of each chunk. Length of vector is num_chunks.
///
/// This vector only contains boundaries, so assumes the first chunk starts at offset 0.
/// The final entry in vector is the total length of the chunks.
/// See example below.
/// chunk[n] are bytes in [chunk_boundary_offsets[n-1], chunk_boundary_offsets[n])
/// ```
/// // ex. chunks: [ 0, 1, 2, 3 ]
/// // chunk_boundary_offsets: [ 100, 200, 300, 400]
/// ```
pub chunk_boundary_offsets: Vec<u32>,
/// Merklehash for each chunk stored in the Xorb. Length of vector is num_chunks.
pub chunk_hashes: Vec<MerkleHash>,
#[serde(skip)]
/// Unused 16-byte buffer to allow for future extensibility.
_buffer: [u8; 16],
}
impl Default for CasObjectInfoV0 {
fn default() -> Self {
CasObjectInfoV0 {
ident: CAS_OBJECT_FORMAT_IDENT,
version: CAS_OBJECT_FORMAT_VERSION_V0,
cashash: MerkleHash::default(),
num_chunks: 0,
chunk_boundary_offsets: Vec::new(),
chunk_hashes: Vec::new(),
_buffer: Default::default(),
}
}
}
impl CasObjectInfoV0 {
/// Serialize CasObjectInfoV0 to provided Writer.
///
/// Assumes caller has set position of Writer to appropriate location for serialization.
#[deprecated]
pub fn serialize<W: Write>(&self, writer: &mut W) -> Result<usize, CasObjectError> {
let mut total_bytes_written = 0;
// Helper function to write data and update the byte count
let mut write_bytes = |data: &[u8]| -> Result<(), CasObjectError> {
writer.write_all(data)?;
total_bytes_written += data.len();
Ok(())
};
// Write fixed-size fields, in order: ident, version, cashash, num_chunks
write_bytes(&self.ident)?;
write_bytes(&[self.version])?;
write_bytes(self.cashash.as_bytes())?;
write_bytes(&self.num_chunks.to_le_bytes())?;
// write variable field: chunk boundaries & hashes
for offset in &self.chunk_boundary_offsets {
write_bytes(&offset.to_le_bytes())?;
}
for hash in &self.chunk_hashes {
write_bytes(hash.as_bytes())?;
}
// write closing metadata
write_bytes(&self._buffer)?;
Ok(total_bytes_written)
}
/// Construct CasObjectInfoV0 object from Read.
///
/// Expects metadata struct is found at end of Reader, written out in struct order.
#[deprecated]
pub fn deserialize<R: Read>(reader: &mut R) -> Result<(Self, u32), CasObjectError> {
let mut total_bytes_read: u32 = 0;
// Helper function to read data and update the byte count
let mut read_bytes = |data: &mut [u8]| -> Result<(), CasObjectError> {
reader.read_exact(data)?;
total_bytes_read += data.len() as u32;
Ok(())
};
let mut ident = [0u8; 7];
read_bytes(&mut ident)?;
if ident != CAS_OBJECT_FORMAT_IDENT {
return Err(CasObjectError::FormatError(anyhow!("Xorb Invalid Ident")));
}
let mut version = [0u8; 1];
read_bytes(&mut version)?;
if version[0] != CAS_OBJECT_FORMAT_VERSION_V0 {
return Err(CasObjectError::FormatError(anyhow!("Xorb Invalid Format Version")));
}
let (s, bytes_read_v0) = Self::deserialize_v0(reader)?;
Ok((s, total_bytes_read + bytes_read_v0))
}
pub fn deserialize_v0<R: Read>(reader: &mut R) -> Result<(Self, u32), CasObjectError> {
let mut total_bytes_read: u32 = 0;
// Helper function to read data and update the byte count
let mut read_bytes = |data: &mut [u8]| -> Result<(), CasObjectError> {
reader.read_exact(data)?;
total_bytes_read += data.len() as u32;
Ok(())
};
let mut buf = [0u8; size_of::<MerkleHash>()];
read_bytes(&mut buf)?;
let cashash = MerkleHash::from(&buf);
let mut num_chunks = [0u8; size_of::<u32>()];
read_bytes(&mut num_chunks)?;
let num_chunks = u32::from_le_bytes(num_chunks);
let mut chunk_boundary_offsets = Vec::with_capacity(prealloc_num_chunks(num_chunks as usize));
for _ in 0..num_chunks {
let mut offset = [0u8; size_of::<u32>()];
read_bytes(&mut offset)?;
chunk_boundary_offsets.push(u32::from_le_bytes(offset));
}
let mut chunk_hashes = Vec::with_capacity(prealloc_num_chunks(num_chunks as usize));
for _ in 0..num_chunks {
let mut hash = [0u8; size_of::<MerkleHash>()];
read_bytes(&mut hash)?;
chunk_hashes.push(MerkleHash::from(&hash));
}
let mut _buffer = [0u8; 16];
read_bytes(&mut _buffer)?;
Ok((
CasObjectInfoV0 {
ident: CAS_OBJECT_FORMAT_IDENT,
version: CAS_OBJECT_FORMAT_VERSION_V0,
cashash,
num_chunks,
chunk_boundary_offsets,
chunk_hashes,
_buffer,
},
total_bytes_read,
))
}
/// Construct CasObjectInfo object from AsyncRead.
/// assumes that the ident and version have already been read and verified.
///
/// verifies that the length of the footer data matches the length field at the very end of the buffer
#[cfg(not(target_family = "wasm"))]
pub async fn deserialize_async<R: futures::io::AsyncRead + Unpin>(
reader: &mut R,
version: u8,
) -> Result<(Self, u32), CasObjectError> {
// already read 8 bytes (ident + version)
let mut total_bytes_read: u32 = (size_of::<CasObjectIdent>() + size_of::<u8>()) as u32;
// Helper function to read data and update the byte count
async fn read_bytes<R: futures::io::AsyncRead + Unpin>(
reader: &mut R,
total_bytes_read: &mut u32,
buf: &mut [u8],
) -> Result<(), CasObjectError> {
reader.read_exact(buf).await?;
*total_bytes_read += buf.len() as u32;
Ok(())
}
// notable difference from non-async version, we skip reading the ident and version
// these fields have been verified before.
let mut buf = [0u8; size_of::<MerkleHash>()];
read_bytes(reader, &mut total_bytes_read, &mut buf).await?;
let cashash = MerkleHash::from(&buf);
let mut num_chunks = [0u8; size_of::<u32>()];
read_bytes(reader, &mut total_bytes_read, &mut num_chunks).await?;
let num_chunks = u32::from_le_bytes(num_chunks);
let mut chunk_boundary_offsets = Vec::with_capacity(prealloc_num_chunks(num_chunks as usize));
for _ in 0..num_chunks {
let mut offset = [0u8; size_of::<u32>()];
read_bytes(reader, &mut total_bytes_read, &mut offset).await?;
chunk_boundary_offsets.push(u32::from_le_bytes(offset));
}
let mut chunk_hashes = Vec::with_capacity(prealloc_num_chunks(num_chunks as usize));
for _ in 0..num_chunks {
let mut hash = [0u8; size_of::<MerkleHash>()];
read_bytes(reader, &mut total_bytes_read, &mut hash).await?;
chunk_hashes.push(MerkleHash::from(&hash));
}
let mut _buffer = [0u8; 16];
read_bytes(reader, &mut total_bytes_read, &mut _buffer).await?;
Ok((
CasObjectInfoV0 {
ident: CAS_OBJECT_FORMAT_IDENT,
version,
cashash,
num_chunks,
chunk_boundary_offsets,
chunk_hashes,
_buffer,
},
total_bytes_read,
))
}
}
#[allow(clippy::empty_line_after_doc_comments)]
#[derive(Clone, PartialEq, Eq, Debug, Serialize)]
/// Info struct for [CasObject]. This is stored at the end of the XORB.
pub struct CasObjectInfoV1 {
/// CAS identifier: "XETBLOB"
pub ident: CasObjectIdent,
/// Format version, expected to be 1 right now.
pub version: u8,
/// 256-bits, 32-bytes, The CAS Hash of this Xorb.
pub cashash: MerkleHash,
///////////////////////////////////////////////////////////////////
/// The hashes section
/// CAS identifier: "XBLBHSH"
pub ident_hash_section: CasObjectIdent,
/// The version of the chunk hash section.
pub hashes_version: u8,
/// Total number of chunks in the Xorb. Duplicated here.
/// This only exists in the physical serialized layout.
// _num_chunks_2: u32,
/// Merklehash for each chunk stored in the Xorb. Length of vector is num_chunks.
pub chunk_hashes: Vec<MerkleHash>,
///////////////////////////////////////////////////////////////////
/// The boundaries and index metadata
/// The identity for the metadata section; should be "XBLBMDT"
pub ident_boundary_section: CasObjectIdent,
/// The version of the boundary section.
pub boundaries_version: u8,
/// Total number of chunks in the Xorb. Duplicated here.
/// This only exists in the physical serialized layout
// _num_chunks_3: u32,
/// Byte offset marking the boundary of each chunk in physical layout including chunk header.
/// Length of vector is num_chunks.
///
/// This vector only contains boundaries, so assumes the first chunk starts at offset 0.
/// The final entry in vector is the total length of the chunks.
/// See example below.
/// chunk[n] are bytes in [chunk_boundary_offsets[n-1], chunk_boundary_offsets[n])
/// ```
/// // ex. chunks: [ 0, 1, 2, 3 ]
/// // chunk_boundary_offsets: [ 100, 200, 300, 400]
/// ```
pub chunk_boundary_offsets: Vec<u32>,
/// The byte offsets marking the boundary of each chunk in uncompressed layout without header,
/// assuming that each chunk gets unzipped and concatenated.
/// Length of vector is num_chunks.
/// This permits range queries on the contents of the xorb. The uncompressed length of
/// chunk k can be determined by unpacked_chunk_offsets[k] - unpacked_chunk_offsets[k - 1].
pub unpacked_chunk_offsets: Vec<u32>,
/// Below this everything is fixed; these fields are in exactly the same place.
///
/// Total number of chunks in the Xorb. This is also duplicated in the serialization
/// at the start of each section.
pub num_chunks: u32,
// The number of bytes from the end of this footer to the start of the hashes section
pub hashes_section_offset_from_end: u32,
// The number of bytes from the end of this footer to the start of the boundaries section
pub boundary_section_offset_from_end: u32,
#[serde(skip)]
/// Unused 16-byte buffer to allow for future extensibility.
_buffer: [u8; 16],
}
impl Default for CasObjectInfoV1 {
fn default() -> Self {
let mut s = CasObjectInfoV1 {
ident: CAS_OBJECT_FORMAT_IDENT,
version: CAS_OBJECT_FORMAT_VERSION,
cashash: MerkleHash::default(),
ident_hash_section: CAS_OBJECT_FORMAT_IDENT_HASHES,
hashes_version: CAS_OBJECT_FORMAT_HASHES_VERSION,
chunk_hashes: Vec::new(),
ident_boundary_section: CAS_OBJECT_FORMAT_IDENT_BOUNDARIES,
boundaries_version: CAS_OBJECT_FORMAT_BOUNDARIES_VERSION,
chunk_boundary_offsets: Vec::new(),
unpacked_chunk_offsets: Vec::new(),
num_chunks: 0,
hashes_section_offset_from_end: 0,
boundary_section_offset_from_end: 0,
_buffer: Default::default(),
};
s.fill_in_boundary_offsets();
s
}
}
impl CasObjectInfoV1 {
pub fn serialized_length(&self) -> usize {
size_of::<CasObjectIdent>() * 3 // ident, ident_hash_section, ident_boundary_section
+ size_of::<u8>() * 3 // version, hashes_version, boundaries_version
+ size_of::<u32>() * 5 // num_chunks, hashes_section_offset_from_end, boundary_section_offset_from_end,
// chunk_boundary_offsets, unpacked_chunk_offsets
+ size_of::<MerkleHash>() * self.chunk_hashes.len() // chunk_hashes
+ size_of_val(&self._buffer) // _buffer
+ self.chunk_boundary_offsets.len() * size_of::<u32>() // chunk_boundary_offsets
+ self.unpacked_chunk_offsets.len() * size_of::<u32>() // unpacked_chunk_offsets
+ size_of::<MerkleHash>() // cashash
}
/// Serialize CasObjectInfoV1 to provided Writer.
///
/// Assumes caller has set position of Writer to appropriate location for serialization.
pub fn serialize<W: Write>(&self, writer: &mut W) -> Result<usize, CasObjectError> {
let mut counting_writer = countio::Counter::new(writer);
let w = &mut counting_writer;
//////////////////////////////////////////////////////////////////////////////////////////////
// First section (Calf). (Open to moving to another name.)
write_bytes(w, &self.ident)?;
write_u8(w, self.version)?;
write_hash(w, &self.cashash)?;
//////////////////////////////////////////////////////////////////////////////////////////////
// Hash section (Ankle)
// Write fixed-size fields, in order: ident, version
write_bytes(w, &self.ident_hash_section)?;
write_u8(w, self.hashes_version)?;
// Write number of chunks again.
write_u32(w, self.num_chunks)?;
if self.num_chunks as usize != self.chunk_hashes.len() {
debug_assert_eq!(self.num_chunks as usize, self.chunk_hashes.len());
return Err(CasObjectError::FormatError(anyhow!(
"Chunk hash vector not correct length on serialization. ({}, expected {})",
self.chunk_hashes.len(),
self.num_chunks
)));
}
for hash in &self.chunk_hashes {
write_hash(w, hash)?;
}
//////////////////////////////////////////////////////////////////////////////////////////////
// Boundary Section (Foot).
write_bytes(w, &self.ident_boundary_section)?;
write_u8(w, self.boundaries_version)?;
write_u32(w, self.num_chunks)?;
// write variable field: chunk boundaries
if self.num_chunks as usize != self.chunk_boundary_offsets.len() {
debug_assert_eq!(self.num_chunks as usize, self.chunk_boundary_offsets.len());
return Err(CasObjectError::FormatError(anyhow!(
"Chunk boundary offset vector not correct length on serialization. ({}, expected {})",
self.chunk_boundary_offsets.len(),
self.num_chunks
)));
}
write_u32s(w, &self.chunk_boundary_offsets)?;
// write variable field: unpacked chunk data offsets
if self.num_chunks as usize != self.unpacked_chunk_offsets.len() {
debug_assert_eq!(self.num_chunks as usize, self.unpacked_chunk_offsets.len());
return Err(CasObjectError::FormatError(anyhow!(
"Unpacked chunk offset vector not correct length on serialization. ({}, expected {})",
self.unpacked_chunk_offsets.len(),
self.num_chunks
)));
}
write_u32s(w, &self.unpacked_chunk_offsets)?;
//////////////////////////////////////////////////////////////////////////////////////////////
// Constant length end of footer (Toes).
// Write num_chunks here, though it's written out multiple places. Here as it applies all over
// the place.
write_u32(w, self.num_chunks)?;
write_u32(w, self.hashes_section_offset_from_end)?;
write_u32(w, self.boundary_section_offset_from_end)?;
// write closing metadata
write_bytes(w, &self._buffer)?;
Ok(w.writer_bytes())
}
/// Construct CasObjectInfo object from Reader + Seek.
///
/// Expects metadata struct is found at end of Reader, written out in struct order.
pub fn deserialize<R: Read>(reader: &mut R) -> Result<(Self, u32), CasObjectError> {
let mut counting_reader = countio::Counter::new(reader);
let r = &mut counting_reader;
let mut s = Self::default();
//////////////////////////////////////////////////////////////////////////////////////////////
// First section.
read_bytes(r, &mut s.ident)?;
if s.ident != CAS_OBJECT_FORMAT_IDENT {
return Err(CasObjectError::FormatError(anyhow!("Xorb Invalid Ident")));
}
s.version = read_u8(r)?;
if s.version == CAS_OBJECT_FORMAT_VERSION_V0 {
let (sv0, _) = CasObjectInfoV0::deserialize_v0(r)?;
// we don't have the missing info (unpacked_chunk_offsets), it's OK
return Ok((Self::from_v0(sv0), r.reader_bytes() as u32));
} else if s.version != CAS_OBJECT_FORMAT_VERSION {
return Err(CasObjectError::FormatError(anyhow!("Xorb Invalid Format Version")));
}
s.cashash = read_hash(r)?;
//////////////////////////////////////////////////////////////////////////////////////////////
// Hash section
let hash_section_begin_byte_offset = r.reader_bytes();
read_bytes(r, &mut s.ident_hash_section)?;
if s.ident_hash_section != CAS_OBJECT_FORMAT_IDENT_HASHES {
return Err(CasObjectError::FormatError(anyhow!("Xorb Invalid Ident for Hash Metadata Section")));
}
s.hashes_version = read_u8(r)?;
if s.hashes_version != CAS_OBJECT_FORMAT_HASHES_VERSION {
return Err(CasObjectError::FormatError(anyhow!("Xorb Invalid Format Version for Hash Metadata Section")));
}
let num_chunks_2 = read_u32(r)?;
// Read in the hashes.
s.chunk_hashes.reserve(prealloc_num_chunks(num_chunks_2 as usize));
for _ in 0..num_chunks_2 {
s.chunk_hashes.push(read_hash(r)?);
}
//////////////////////////////////////////////////////////////////////////////////////////////
// Boundary Section (Foot).
let boundary_section_begin_byte_offset = r.reader_bytes();
read_bytes(r, &mut s.ident_boundary_section)?;
if s.ident_boundary_section != CAS_OBJECT_FORMAT_IDENT_BOUNDARIES {
return Err(CasObjectError::FormatError(anyhow!("Xorb Invalid Ident for Boundary Metadata Section")));
}
s.boundaries_version = read_u8(r)?;
if s.boundaries_version != CAS_OBJECT_FORMAT_BOUNDARIES_VERSION {
return Err(CasObjectError::FormatError(anyhow!(
"Xorb Invalid Format Version for Boundaries Metadata Section"
)));
}
let num_chunks_3 = read_u32(r)?;
if num_chunks_2 != num_chunks_3 {
return Err(CasObjectError::FormatError(anyhow!(
"Xorb Invalid: inconsistent num_chunks between hashes and boundaries section."
)));
}
s.chunk_boundary_offsets.reserve(prealloc_num_chunks(num_chunks_3 as usize));
for _ in 0..num_chunks_3 {
s.chunk_boundary_offsets.push(read_u32(r)?);
}
s.unpacked_chunk_offsets.reserve(prealloc_num_chunks(num_chunks_3 as usize));
for _ in 0..num_chunks_3 {
s.unpacked_chunk_offsets.push(read_u32(r)?);
}
// Now the final parts here.
s.num_chunks = read_u32(r)?;
if s.num_chunks != num_chunks_2 {
return Err(CasObjectError::FormatError(anyhow!(
"Xorb Invalid: inconsistent num_chunks between metadata and hashes section."
)));
}
s.hashes_section_offset_from_end = read_u32(r)?;
s.boundary_section_offset_from_end = read_u32(r)?;
read_bytes(r, &mut s._buffer)?;
let end_byte_offset = r.reader_bytes();
if end_byte_offset - hash_section_begin_byte_offset != s.hashes_section_offset_from_end as usize {
return Err(CasObjectError::FormatError(anyhow!(
"Xorb Invalid: incorrect hashes_section_offset_from_end."
)));
}
if end_byte_offset - boundary_section_begin_byte_offset != s.boundary_section_offset_from_end as usize {
return Err(CasObjectError::FormatError(anyhow!(
"Xorb Invalid: incorrect boundary_section_offset_from_end."
)));
}
Ok((s, r.reader_bytes() as u32))
}
/// Construct CasObjectInfo object from Reader + Seek.
///
/// Expects metadata struct is found at end of Reader, written out in struct order.
pub fn deserialize_only_boundaries_section<R: Read + Seek>(reader: &mut R) -> Result<(Self, u32), CasObjectError> {
let mut s = Self::default();
// info_length + size of _buffer + size of u32 for offset field
let offset_to_boundary_section_offset =
size_of::<u32>() + size_of_val(&s._buffer) + size_of_val(&s.boundary_section_offset_from_end);
reader.seek(SeekFrom::End(-(offset_to_boundary_section_offset as i64)))?;
let mut boundary_section_offset_from_end = read_u32(reader)?;
// add 4 bytes to offset from info_length at the end
boundary_section_offset_from_end += size_of::<u32>() as u32;
reader.seek(SeekFrom::End(-(boundary_section_offset_from_end as i64)))?;
let mut counting_reader = countio::Counter::new(reader);
let r = &mut counting_reader;
//////////////////////////////////////////////////////////////////////////////////////////////
// Boundary Section (Foot).
read_bytes(r, &mut s.ident_boundary_section)?;
if s.ident_boundary_section != CAS_OBJECT_FORMAT_IDENT_BOUNDARIES {
return Err(CasObjectError::FormatError(anyhow!("Xorb Invalid Ident for Boundary Metadata Section")));
}
s.boundaries_version = read_u8(r)?;
if s.boundaries_version != CAS_OBJECT_FORMAT_BOUNDARIES_VERSION {
return Err(CasObjectError::FormatError(anyhow!(
"Xorb Invalid Format Version for Boundaries Metadata Section"
)));
}
let num_chunks_boundaries_section = read_u32(r)?;
s.chunk_boundary_offsets.resize(num_chunks_boundaries_section as usize, 0);
read_u32s(r, &mut s.chunk_boundary_offsets)?;
s.unpacked_chunk_offsets.resize(num_chunks_boundaries_section as usize, 0);
read_u32s(r, &mut s.unpacked_chunk_offsets)?;
// Now the final parts here.
s.num_chunks = read_u32(r)?;
if s.num_chunks != num_chunks_boundaries_section {
return Err(CasObjectError::FormatError(anyhow!(
"Xorb Invalid: inconsistent num_chunks between metadata and hashes section."
)));
}
s.hashes_section_offset_from_end = read_u32(r)?;
s.boundary_section_offset_from_end = read_u32(r)?;
read_bytes(r, &mut s._buffer)?;
let end_byte_offset = r.reader_bytes();
if end_byte_offset != s.boundary_section_offset_from_end as usize {
return Err(CasObjectError::FormatError(anyhow!(
"Xorb Invalid: incorrect boundary_section_offset_from_end."
)));
}
debug_assert!(s.chunk_hashes.is_empty());
Ok((s, r.reader_bytes() as u32))
}
#[cfg(not(target_family = "wasm"))]
pub async fn deserialize_async_v1<R: futures::io::AsyncRead + Unpin>(
reader: &mut R,
) -> Result<(Self, u32), CasObjectError> {
// already read 8 bytes (ident + version)
let total_bytes_read: u32 = (size_of::<CasObjectIdent>() + size_of::<u8>()) as u32;
let mut counting_reader = countio::Counter::new(reader);
let r = &mut counting_reader;
// ident and version have been read already above
let mut s = Self {
ident: CAS_OBJECT_FORMAT_IDENT,
version: CAS_OBJECT_FORMAT_VERSION,
cashash: read_hash_async(r).await?,
..Default::default()
};
//////////////////////////////////////////////////////////////////////////////////////////////
// Hash section
let hash_section_begin_byte_offset = r.reader_bytes();
read_bytes_async(r, &mut s.ident_hash_section).await?;
if s.ident_hash_section != CAS_OBJECT_FORMAT_IDENT_HASHES {
return Err(CasObjectError::FormatError(anyhow!("Xorb Invalid Ident for Hash Metadata Section")));
}
s.hashes_version = read_u8_async(r).await?;
if s.hashes_version != CAS_OBJECT_FORMAT_HASHES_VERSION {
return Err(CasObjectError::FormatError(anyhow!("Xorb Invalid Format Version for Hash Metadata Section")));
}
let num_chunks_2 = read_u32_async(r).await?;
// Read in the hashes.
s.chunk_hashes.reserve(prealloc_num_chunks(num_chunks_2 as usize));
for _ in 0..num_chunks_2 {
s.chunk_hashes.push(read_hash_async(r).await?);
}
//////////////////////////////////////////////////////////////////////////////////////////////
// Boundary Section (Foot).
let boundary_section_begin_byte_offset = r.reader_bytes();
read_bytes_async(r, &mut s.ident_boundary_section).await?;
if s.ident_boundary_section != CAS_OBJECT_FORMAT_IDENT_BOUNDARIES {
return Err(CasObjectError::FormatError(anyhow!("Xorb Invalid Ident for Boundary Metadata Section")));
}
s.boundaries_version = read_u8_async(r).await?;
if s.boundaries_version != CAS_OBJECT_FORMAT_BOUNDARIES_VERSION {
return Err(CasObjectError::FormatError(anyhow!(
"Xorb Invalid Format Version for Boundaries Metadata Section"
)));
}
let num_chunks_3 = read_u32_async(r).await?;
if num_chunks_2 != num_chunks_3 {
return Err(CasObjectError::FormatError(anyhow!(
"Xorb Invalid: inconsistent num_chunks between hashes and boundaries section."
)));
}
s.chunk_boundary_offsets.reserve(prealloc_num_chunks(num_chunks_3 as usize));
for _ in 0..num_chunks_3 {
s.chunk_boundary_offsets.push(read_u32_async(r).await?);
}
s.unpacked_chunk_offsets.reserve(prealloc_num_chunks(num_chunks_3 as usize));
for _ in 0..num_chunks_3 {
s.unpacked_chunk_offsets.push(read_u32_async(r).await?);
}
s.num_chunks = read_u32_async(r).await?;
if s.num_chunks != num_chunks_2 {
return Err(CasObjectError::FormatError(anyhow!(
"Xorb Invalid: inconsistent num_chunks between metadata and hashes section."
)));
}
s.hashes_section_offset_from_end = read_u32_async(r).await?;
s.boundary_section_offset_from_end = read_u32_async(r).await?;
read_bytes_async(r, &mut s._buffer).await?;
let end_byte_offset = r.reader_bytes();
if end_byte_offset - hash_section_begin_byte_offset != s.hashes_section_offset_from_end as usize {
return Err(CasObjectError::FormatError(anyhow!(
"Xorb Invalid: incorrect hashes_section_offset_from_end."
)));
}
if end_byte_offset - boundary_section_begin_byte_offset != s.boundary_section_offset_from_end as usize {
return Err(CasObjectError::FormatError(anyhow!(
"Xorb Invalid: incorrect boundary_section_offset_from_end."
)));
}
Ok((s, r.reader_bytes() as u32 + total_bytes_read))
}
/// Construct CasObjectInfo object from AsyncRead.
/// assumes that the ident and version have already been read and verified.
///
/// verifies that the length of the footer data matches the length field at the very end of the buffer
#[cfg(not(target_family = "wasm"))]
pub async fn deserialize_async<R: futures::io::AsyncRead + Unpin>(
reader: &mut R,
version: u8,
) -> Result<(Self, u32), CasObjectError> {
if version == 0 {
let (s, n) = CasObjectInfoV0::deserialize_async(reader, 0).await?;
// we don't have the missing info (unpacked_chunk_offsets), it's OK
Ok((Self::from_v0(s), n))
} else if version == 1 {
Self::deserialize_async_v1(reader).await
} else {
Err(CasObjectError::FormatError(anyhow!(
"Xorb Format Error: Version {version} not supported by this code version."
)))
}
}
pub fn from_v0(src: CasObjectInfoV0) -> Self {
// Fill in all the appropriate fields from the V0 version.
let mut s = Self {
ident: src.ident,
version: CAS_OBJECT_FORMAT_VERSION,
cashash: src.cashash,
ident_hash_section: CAS_OBJECT_FORMAT_IDENT_HASHES,
hashes_version: CAS_OBJECT_FORMAT_HASHES_VERSION,
chunk_hashes: src.chunk_hashes,
ident_boundary_section: CAS_OBJECT_FORMAT_IDENT_BOUNDARIES,
boundaries_version: CAS_OBJECT_FORMAT_BOUNDARIES_VERSION_NO_UNPACKED_INFO,
chunk_boundary_offsets: src.chunk_boundary_offsets,
unpacked_chunk_offsets: Vec::new(),
num_chunks: src.num_chunks,
hashes_section_offset_from_end: 0,
boundary_section_offset_from_end: 0,
_buffer: src._buffer,
};
s.fill_in_boundary_offsets();
s
}
pub fn from_v0_with_unpacked_chunk_offsets(src: CasObjectInfoV0, unpacked_chunk_offsets: Vec<u32>) -> Self {
if unpacked_chunk_offsets.len() != src.chunk_boundary_offsets.len() {
warn!(
"unpacked_chunk_offsets len ({}) does not match src chunk_boundary_offsets len ({})",
unpacked_chunk_offsets.len(),
src.chunk_boundary_offsets.len()
);
}
// Fill in all the appropriate fields from the V0 version.
let mut s = Self {
ident: src.ident,
version: 1,
cashash: src.cashash,
ident_hash_section: CAS_OBJECT_FORMAT_IDENT_HASHES,
hashes_version: CAS_OBJECT_FORMAT_HASHES_VERSION,
chunk_hashes: src.chunk_hashes,
ident_boundary_section: CAS_OBJECT_FORMAT_IDENT_BOUNDARIES,
boundaries_version: CAS_OBJECT_FORMAT_BOUNDARIES_VERSION,
chunk_boundary_offsets: src.chunk_boundary_offsets,
unpacked_chunk_offsets,
num_chunks: src.num_chunks,
hashes_section_offset_from_end: 0,
boundary_section_offset_from_end: 0,
_buffer: Default::default(),
};
s.fill_in_boundary_offsets();
s
}
pub fn fill_in_boundary_offsets(&mut self) {
self.boundary_section_offset_from_end = (size_of_val(&self.ident_boundary_section)
+ size_of_val(&self.boundaries_version)
+ size_of::<u32>() // num_chunks_3
+ self.chunk_boundary_offsets.len() * size_of::<u32>()
+ self.unpacked_chunk_offsets.len() * size_of::<u32>()
+ size_of_val(&self.num_chunks)
+ size_of_val(&self.hashes_section_offset_from_end)
+ size_of_val(&self.boundary_section_offset_from_end)
+ size_of_val(&self._buffer)) as u32;
self.hashes_section_offset_from_end = (size_of_val(&self.ident_hash_section)
+ size_of_val(&self.hashes_version)
+ size_of::<u32>() // num_chunks_2
+ self.chunk_hashes.len() * size_of::<MerkleHash>()) as u32
+ self.boundary_section_offset_from_end;
}
pub fn has_chunk_hashes(&self) -> bool {
!self.chunk_hashes.is_empty()
}
}
#[derive(Clone, PartialEq, Eq, Debug, Serialize)]
/// XORB: 16MB data block for storing chunks.
///
/// Has Info footer, and a set of functions that interact directly with XORB.
///
/// Physical layout of this object is as follows:
/// [START OF XORB]
/// <CHUNK 0>
/// <CHUNK 1>
/// <..>
/// <CHUNK N>
/// <CasObjectInfo>
/// CasObjectInfo length: u32
/// [END OF XORB]
pub struct CasObject {
/// CasObjectInfo block see [CasObjectInfo] for details.
pub info: CasObjectInfoV1,
/// Length of entire info block.
///
/// This is required to be at the end of the CasObject, so readers can read the
/// final 4 bytes and know the full length of the info block.
pub info_length: u32,
}
impl Default for CasObject {
fn default() -> Self {
Self {
info: Default::default(),
info_length: CAS_OBJECT_INFO_DEFAULT_LENGTH,
}
}
}
impl CasObject {
/// Deserializes only the info length field of the footer to tell the user how many bytes
/// make up the info portion of the xorb.
///
/// Assumes reader has at least size_of::<u32>() bytes, otherwise returns an error.
pub fn get_info_length<R: Read + Seek>(reader: &mut R) -> Result<u32, CasObjectError> {
// Go to end of Reader and get length, then jump back to it, and read sequentially
// read last 4 bytes to get length
reader.seek(SeekFrom::End(-(size_of::<u32>() as i64)))?;
let mut info_length = [0u8; 4];
reader.read_exact(&mut info_length)?;
let info_length = u32::from_le_bytes(info_length);
Ok(info_length)
}
/// Deserialize the CasObjectInfo struct, the metadata for this Xorb.
///
/// This allows the CasObject to be partially constructed, allowing for range reads inside the CasObject.
pub fn deserialize<R: Read + Seek>(reader: &mut R) -> Result<Self, CasObjectError> {
let info_length = Self::get_info_length(reader)?;
// now seek back that many bytes + size of length (u32) and read sequentially.
reader.seek(SeekFrom::End(-(size_of::<u32>() as i64 + info_length as i64)))?;
let (info, total_bytes_read) = CasObjectInfoV1::deserialize(reader)?;
// validate that info_length matches what we read off of header
if total_bytes_read != info_length {
return Err(CasObjectError::FormatError(anyhow!("Xorb Info Format Error")));
}
Ok(Self { info, info_length })
}
/// Construct CasObject object from AsyncRead.
/// assumes that the ident and version have already been read and verified.
#[cfg(not(target_family = "wasm"))]
pub async fn deserialize_async<R: futures::io::AsyncRead + Unpin>(
reader: &mut R,
version: u8,
) -> Result<Self, CasObjectError> {
let (info, total_bytes_read) = CasObjectInfoV1::deserialize_async(reader, version).await?;
let mut info_length_buf = [0u8; size_of::<u32>()];
// not using read_bytes since we do not want to count these bytes in total_bytes_read
// the info_length u32 is not counted in its value
reader.read_exact(&mut info_length_buf).await?;
let info_length = u32::from_le_bytes(info_length_buf);
if info_length != total_bytes_read {
return Err(CasObjectError::FormatError(anyhow!("Xorb Info Format Error")));
}
// verify we've read to the end
if reader.read(&mut [0u8; 8]).await? != 0 {
return Err(CasObjectError::FormatError(anyhow!(
"Xorb Reader has content past the end of serialized xorb"
)));
}
Ok(Self { info, info_length })
}
pub fn serialize_given_info<W: Write>(w: &mut W, info: CasObjectInfoV1) -> Result<(Self, usize), CasObjectError> {
let mut total_written_bytes: usize = 0;
let info_length = info.serialize(w)? as u32;
total_written_bytes += info_length as usize;
write_u32(w, info_length)?;
total_written_bytes += size_of::<u32>();
let cas_object = Self { info, info_length };
debug_assert_eq!(cas_object.info_length, info_length);
debug_assert_eq!(cas_object.info_length as usize, cas_object.info.serialized_length());
Ok((cas_object, total_written_bytes))
}
pub fn from_info(info: CasObjectInfoV1) -> Self {
let info_length = info.serialized_length() as u32;
Self { info, info_length }
}
/// Validate CasObject.