Repository navigation
Expand file tree
/
Copy pathbao.js
More file actions
2564 lines (2200 loc) · 73.2 KB
/
Copy pathbao.js
File metadata and controls
2564 lines (2200 loc) · 73.2 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
/**
* Bao - Verified Streaming for BLAKE3
*
* Implements the Bao tree construction primitives for verified streaming.
* Based on the official Bao specification.
*
* @see https://github.com/oconnor663/bao/blob/master/docs/spec.md
*/
const blake3 = require('./blake3.js');
const pool = require('./buffer-pool.js');
// Import from blake3.js
const { IV, BLOCK_LEN, CHUNK_LEN, _compress: compress } = blake3;
// BLAKE3 domain separation flags
const CHUNK_START = 1;
const CHUNK_END = 2;
const PARENT = 4;
const ROOT = 8;
/**
* Convert a Uint32Array to a Uint8Array (little-endian)
* @param {Uint32Array} words - Input words
* @param {Uint8Array} [out] - Optional output buffer (if not provided, allocates new)
* @returns {Uint8Array} Output bytes
*/
function wordsToBytes(words, out) {
const bytes = out || new Uint8Array(words.length * 4);
for (let i = 0; i < words.length; i++) {
bytes[i * 4] = words[i] & 0xff;
bytes[i * 4 + 1] = (words[i] >> 8) & 0xff;
bytes[i * 4 + 2] = (words[i] >> 16) & 0xff;
bytes[i * 4 + 3] = (words[i] >> 24) & 0xff;
}
return bytes;
}
// Reusable Uint32Array buffers for chunkCV/parentCV to reduce allocations
const _blockWords = new Uint32Array(16);
const _cvOut = new Uint32Array(8);
const _cvTemp = new Uint32Array(8);
/**
* Fast byte-to-word conversion using DataView for aligned reads.
* @param {Uint8Array} chunkBytes - Source bytes
* @param {number} blockStart - Start offset in source
* @param {number} blockLen - Number of bytes to load
* @param {Uint32Array} blockWords - Destination words (must be cleared)
*/
function loadBlockFast(chunkBytes, blockStart, blockLen, blockWords) {
// Clear the block words first
blockWords.fill(0);
// Handle empty block
if (blockLen === 0) return;
// Check for detached buffer
if (chunkBytes.buffer && chunkBytes.buffer.byteLength === 0) {
throw new Error('Cannot load from detached ArrayBuffer');
}
// Bounds check
if (blockStart + blockLen > chunkBytes.length) {
throw new Error('Block extends beyond buffer bounds');
}
// Use DataView for efficient 32-bit reads (little-endian)
const alignedLen = blockLen & ~3; // Round down to 4-byte boundary
if (alignedLen > 0 && chunkBytes.buffer !== undefined) {
// Has underlying ArrayBuffer - use DataView for aligned portion
const view = new DataView(chunkBytes.buffer, chunkBytes.byteOffset + blockStart, alignedLen);
for (let i = 0; i < alignedLen; i += 4) {
blockWords[i >> 2] = view.getUint32(i, true); // little-endian
}
} else if (alignedLen > 0) {
// Fallback for non-TypedArray
for (let i = 0; i < alignedLen; i += 4) {
blockWords[i >> 2] = chunkBytes[blockStart + i] |
(chunkBytes[blockStart + i + 1] << 8) |
(chunkBytes[blockStart + i + 2] << 16) |
(chunkBytes[blockStart + i + 3] << 24);
}
}
// Handle remaining 1-3 bytes
for (let i = alignedLen; i < blockLen; i++) {
blockWords[i >> 2] |= chunkBytes[blockStart + i] << ((i & 3) * 8);
}
}
/**
* Compute the chaining value (CV) for a chunk.
*
* @param {Uint8Array} chunkBytes - The chunk data (0 to 1024 bytes)
* @param {number} chunkIndex - The chunk counter (0-indexed)
* @param {boolean} isRoot - Whether this is the root node
* @returns {Uint8Array} 32-byte chaining value
*/
function chunkCV(chunkBytes, chunkIndex, isRoot) {
// Initialize CV with IV
_cvTemp.set(IV);
let cv = _cvTemp;
const chunkLen = chunkBytes.length;
const numBlocks = chunkLen === 0 ? 1 : Math.ceil(chunkLen / BLOCK_LEN);
for (let blockIdx = 0; blockIdx < numBlocks; blockIdx++) {
const blockStart = blockIdx * BLOCK_LEN;
const blockEnd = Math.min(blockStart + BLOCK_LEN, chunkLen);
const blockLen = blockEnd - blockStart;
// Build block words using fast DataView approach
loadBlockFast(chunkBytes, blockStart, blockLen, _blockWords);
// Determine flags
let flags = 0;
const isFirstBlock = blockIdx === 0;
const isLastBlock = blockIdx === numBlocks - 1;
if (isFirstBlock) flags |= CHUNK_START;
if (isLastBlock) flags |= CHUNK_END;
if (isLastBlock && isRoot) flags |= ROOT;
// Compress into reusable buffer
compress(cv, 0, _blockWords, 0, _cvOut, 0, true, chunkIndex, blockLen, flags);
// Swap buffers for next iteration
const temp = cv;
cv = _cvOut;
if (blockIdx < numBlocks - 1) {
// Need to preserve cv for next iteration
_cvTemp.set(_cvOut);
cv = _cvTemp;
}
}
// Return a new Uint8Array (must allocate for return value)
return wordsToBytes(cv);
}
// Reusable buffers for parentCV
const _parentBlockWords = new Uint32Array(16);
const _parentOut = new Uint32Array(8);
/**
* Compute the chaining value for a parent node.
*
* @param {Uint8Array} leftCV - Left child's 32-byte CV
* @param {Uint8Array} rightCV - Right child's 32-byte CV
* @param {boolean} isRoot - Whether this is the root node
* @returns {Uint8Array} 32-byte chaining value
*/
function parentCV(leftCV, rightCV, isRoot) {
// Build block from concatenated CVs (64 bytes = 16 words)
// Clear and reuse buffer
_parentBlockWords.fill(0);
// Left CV -> words 0-7
for (let i = 0; i < 32; i++) {
_parentBlockWords[i >> 2] |= leftCV[i] << ((i & 3) * 8);
}
// Right CV -> words 8-15
for (let i = 0; i < 32; i++) {
_parentBlockWords[8 + (i >> 2)] |= rightCV[i] << ((i & 3) * 8);
}
// Flags: always PARENT, optionally ROOT
let flags = PARENT;
if (isRoot) flags |= ROOT;
// Compress with IV as input CV, counter = 0, blockLen = 64
compress(IV, 0, _parentBlockWords, 0, _parentOut, 0, true, 0, BLOCK_LEN, flags);
return wordsToBytes(_parentOut);
}
/**
* Calculate the left subtree size for a given parent length.
*
* The left subtree contains the largest power-of-two number of chunks
* that leaves at least 1 byte for the right subtree.
*
* @param {number} parentLen - Total length of the parent's content
* @returns {number} Size of the left subtree in bytes
*/
function leftLen(parentLen) {
// Exact translation from Python reference:
// available_chunks = (parent_len - 1) // CHUNK_SIZE
// power_of_two_chunks = 2 ** (available_chunks.bit_length() - 1)
// return CHUNK_SIZE * power_of_two_chunks
const availableChunks = Math.floor((parentLen - 1) / CHUNK_LEN);
// bit_length() in Python = number of bits needed to represent the number
// For JavaScript: Math.floor(Math.log2(n)) + 1 for n > 0
const bitLength = availableChunks > 0 ? Math.floor(Math.log2(availableChunks)) + 1 : 0;
const powerOfTwoChunks = Math.pow(2, bitLength - 1);
return CHUNK_LEN * powerOfTwoChunks;
}
/**
* Count the number of chunks for a given content length.
* Empty content still counts as 1 chunk.
*
* @param {number} contentLen - Content length in bytes
* @returns {number} Number of chunks
*/
function countChunks(contentLen) {
if (contentLen === 0) return 1;
return Math.ceil(contentLen / CHUNK_LEN);
}
/**
* Calculate the size of an encoded subtree (parent nodes only, for outboard).
* A subtree of N chunks always has N-1 parent nodes.
*
* @param {number} contentLen - Content length in bytes
* @param {boolean} outboard - If true, only count parent nodes (no chunk data)
* @returns {number} Encoded size in bytes
*/
function encodedSubtreeSize(contentLen, outboard = false) {
const numChunks = countChunks(contentLen);
const parentsSize = (numChunks - 1) * 64; // Each parent is 64 bytes (2 CVs)
return outboard ? parentsSize : parentsSize + contentLen;
}
// ============================================
// BAO ENCODING
// ============================================
const HEADER_SIZE = 8;
/**
* Encode content length as 8-byte little-endian.
*
* @param {number} contentLen - Content length
* @returns {Uint8Array} 8-byte little-endian length
*/
function encodeLen(contentLen) {
const bytes = new Uint8Array(HEADER_SIZE);
// JavaScript can safely represent integers up to 2^53-1
// For a proper 64-bit LE encoding:
let n = contentLen;
for (let i = 0; i < 8; i++) {
bytes[i] = n & 0xff;
n = Math.floor(n / 256);
}
return bytes;
}
/**
* Decode 8-byte little-endian length.
*
* @param {Uint8Array} bytes - 8-byte buffer
* @returns {number} Decoded length
*/
function decodeLen(bytes) {
let n = 0;
let mult = 1;
for (let i = 0; i < 8; i++) {
n += bytes[i] * mult;
mult *= 256;
}
return n;
}
/**
* Encode data in Bao format (optimized single-allocation version).
*
* Format: [8-byte length LE] + [pre-order tree nodes]
* Pre-order: parent node, then left subtree, then right subtree
*
* @param {Uint8Array} buf - Input data
* @param {boolean} outboard - If true, omit chunk data (outboard format)
* @returns {{ encoded: Uint8Array, hash: Uint8Array }} Encoded data and root hash
*/
function baoEncode(buf, outboard = false) {
if (typeof buf === 'string') {
buf = new TextEncoder().encode(buf);
}
if (!(buf instanceof Uint8Array)) {
buf = new Uint8Array(buf);
}
// Pre-calculate total output size for single allocation
const totalSize = HEADER_SIZE + encodedSubtreeSize(buf.length, outboard);
const output = new Uint8Array(totalSize);
// Write header
let n = buf.length;
for (let i = 0; i < 8; i++) {
output[i] = n & 0xff;
n = Math.floor(n / 256);
}
let writePos = HEADER_SIZE;
let chunkIndex = 0;
/**
* Recursive encoding function that writes directly to output buffer.
*
* @param {Uint8Array} data - Data segment to encode
* @param {boolean} isRoot - Whether this is the root node
* @returns {Uint8Array} Chaining value (32 bytes)
*/
function encodeRecurse(data, isRoot) {
if (data.length <= CHUNK_LEN) {
// Leaf node: single chunk
const cv = chunkCV(data, chunkIndex, isRoot);
if (!outboard) {
output.set(data, writePos);
writePos += data.length;
}
chunkIndex++;
return cv;
}
// Interior node: split into left and right subtrees
const lLen = leftLen(data.length);
// Reserve space for parent node (64 bytes) at current position
const parentPos = writePos;
writePos += 64;
// Recursively encode left and right (neither is root)
const leftCV = encodeRecurse(data.subarray(0, lLen), false);
const rightCV = encodeRecurse(data.subarray(lLen), false);
// Write parent node at reserved position
output.set(leftCV, parentPos);
output.set(rightCV, parentPos + 32);
// Compute and return parent CV
return parentCV(leftCV, rightCV, isRoot);
}
// Encode the tree (root finalization at top level)
const rootHash = encodeRecurse(buf, true);
return { encoded: output, hash: rootHash };
}
// ============================================
// BAO DECODING
// ============================================
const HASH_SIZE = 32;
const PARENT_SIZE = 64;
/**
* Compare two byte arrays in constant time.
*
* @param {Uint8Array} a - First array
* @param {Uint8Array} b - Second array
* @returns {boolean} True if equal
*/
function constantTimeEqual(a, b) {
if (a.length !== b.length) return false;
let diff = 0;
for (let i = 0; i < a.length; i++) {
diff |= a[i] ^ b[i];
}
return diff === 0;
}
/**
* Verify a chunk's CV matches the expected value.
*
* @param {Uint8Array} expectedCV - Expected 32-byte CV
* @param {Uint8Array} chunkBytes - Chunk data
* @param {number} chunkIndex - Chunk counter
* @param {boolean} isRoot - Whether this is the root
* @throws {Error} If verification fails
*/
function verifyChunk(expectedCV, chunkBytes, chunkIndex, isRoot) {
const actualCV = chunkCV(chunkBytes, chunkIndex, isRoot);
if (!constantTimeEqual(expectedCV, actualCV)) {
throw new Error(`Chunk ${chunkIndex} verification failed: hash mismatch`);
}
}
/**
* Verify a parent node's CV matches the expected value.
*
* @param {Uint8Array} expectedCV - Expected 32-byte CV
* @param {Uint8Array} parentBytes - 64-byte parent node (left_cv + right_cv)
* @param {boolean} isRoot - Whether this is the root
* @throws {Error} If verification fails
*/
function verifyParent(expectedCV, parentBytes, isRoot) {
const leftCV = parentBytes.subarray(0, HASH_SIZE);
const rightCV = parentBytes.subarray(HASH_SIZE, PARENT_SIZE);
const actualCV = parentCV(leftCV, rightCV, isRoot);
if (!constantTimeEqual(expectedCV, actualCV)) {
throw new Error('Parent node verification failed: hash mismatch');
}
}
/**
* Decode and verify a Bao-encoded stream.
*
* @param {Uint8Array} encoded - Combined Bao encoding (header + tree + chunks)
* @param {Uint8Array} rootHash - Expected 32-byte root hash
* @param {Uint8Array} [outboardData] - Optional original data for outboard mode
* @returns {Uint8Array} Decoded and verified data
* @throws {Error} If verification fails
*/
function baoDecode(encoded, rootHash, outboardData = null) {
if (encoded.length < HEADER_SIZE) {
throw new Error('Encoded data too short: missing header');
}
// Parse length header
const contentLen = decodeLen(encoded.subarray(0, HEADER_SIZE));
// For outboard mode, we need the original data
const isOutboard = outboardData !== null;
if (isOutboard && outboardData.length !== contentLen) {
throw new Error(`Outboard data length mismatch: expected ${contentLen}, got ${outboardData.length}`);
}
// Validate root hash length
if (rootHash.length !== HASH_SIZE) {
throw new Error(`Root hash must be ${HASH_SIZE} bytes`);
}
// Output buffer
const output = new Uint8Array(contentLen);
let outputPos = 0;
// Reading positions
let treePos = HEADER_SIZE; // Position in tree/parent nodes
let dataPos = 0; // Position in outboard data (if applicable)
let chunkIndex = 0;
/**
* Recursive decode function.
*
* @param {Uint8Array} subtreeCV - Expected CV for this subtree
* @param {number} subtreeLen - Length of content in this subtree
* @param {boolean} isRoot - Whether this is the root node
*/
function decodeRecurse(subtreeCV, subtreeLen, isRoot) {
if (subtreeLen <= CHUNK_LEN) {
// Leaf node: read and verify chunk
let chunk;
if (isOutboard) {
chunk = outboardData.subarray(dataPos, dataPos + subtreeLen);
dataPos += subtreeLen;
} else {
chunk = encoded.subarray(treePos, treePos + subtreeLen);
treePos += subtreeLen;
}
// Verify we got the expected amount of data
if (chunk.length !== subtreeLen) {
throw new Error(`Truncated chunk: expected ${subtreeLen} bytes, got ${chunk.length}`);
}
verifyChunk(subtreeCV, chunk, chunkIndex, isRoot);
chunkIndex++;
// Copy to output
output.set(chunk, outputPos);
outputPos += subtreeLen;
} else {
// Interior node: read parent, verify, and recurse
const parent = encoded.subarray(treePos, treePos + PARENT_SIZE);
treePos += PARENT_SIZE;
verifyParent(subtreeCV, parent, isRoot);
const leftCV = parent.subarray(0, HASH_SIZE);
const rightCV = parent.subarray(HASH_SIZE, PARENT_SIZE);
const lLen = leftLen(subtreeLen);
// Recurse into left and right subtrees (neither is root)
decodeRecurse(leftCV, lLen, false);
decodeRecurse(rightCV, subtreeLen - lLen, false);
}
}
// Start decoding from root
decodeRecurse(rootHash, contentLen, true);
return output;
}
// ============================================
// BAO SLICING
// ============================================
/**
* Extract a slice from a Bao encoding.
*
* The slice contains only the parent nodes and chunks needed to verify
* the requested byte range. This is always a combined-format slice
* (chunks are included inline).
*
* @param {Uint8Array} encoded - Combined Bao encoding
* @param {number} sliceStart - Start byte offset
* @param {number} sliceLen - Number of bytes to include
* @param {Uint8Array} [outboardData] - Original data for outboard mode
* @returns {Uint8Array} Slice encoding
*/
function baoSlice(encoded, sliceStart, sliceLen, outboardData = null) {
if (encoded.length < HEADER_SIZE) {
throw new Error('Encoded data too short: missing header');
}
const contentLen = decodeLen(encoded.subarray(0, HEADER_SIZE));
const isOutboard = outboardData !== null;
// Validate outboard data length
if (isOutboard && outboardData.length !== contentLen) {
throw new Error(`Outboard data length mismatch: expected ${contentLen}, got ${outboardData.length}`);
}
// Normalize slice parameters (per spec)
if (sliceLen === 0) {
sliceLen = 1;
}
let sliceEnd = sliceStart + sliceLen;
// If sliceStart is past EOF, adjust to include final chunk
if (sliceStart >= contentLen) {
sliceStart = contentLen > 0 ? contentLen - 1 : 0;
sliceEnd = sliceStart + 1;
}
// Collect output chunks
const outputParts = [];
outputParts.push(encoded.subarray(0, HEADER_SIZE)); // Header
// Reading positions
let treePos = HEADER_SIZE;
let dataPos = 0;
/**
* Recursive slice extraction.
*
* @param {number} subtreeStart - Start byte of this subtree in content
* @param {number} subtreeLen - Length of content in this subtree
*/
function sliceRecurse(subtreeStart, subtreeLen) {
const subtreeEnd = subtreeStart + subtreeLen;
if (subtreeEnd <= sliceStart) {
// Subtree is entirely before slice - skip it
const parentNodesSize = encodedSubtreeSize(subtreeLen, true);
treePos += parentNodesSize;
if (!isOutboard) {
treePos += subtreeLen;
}
dataPos += subtreeLen;
} else if (sliceEnd <= subtreeStart) {
// Subtree is entirely after slice - skip it (don't even read)
// Nothing to do
} else if (subtreeLen <= CHUNK_LEN) {
// Chunk overlaps with slice - include it
let chunk;
if (isOutboard) {
chunk = outboardData.subarray(dataPos, dataPos + subtreeLen);
} else {
chunk = encoded.subarray(treePos, treePos + subtreeLen);
treePos += subtreeLen;
}
dataPos += subtreeLen;
outputParts.push(chunk);
} else {
// Parent node - include it and recurse
const parent = encoded.subarray(treePos, treePos + PARENT_SIZE);
treePos += PARENT_SIZE;
outputParts.push(parent);
const lLen = leftLen(subtreeLen);
sliceRecurse(subtreeStart, lLen);
sliceRecurse(subtreeStart + lLen, subtreeLen - lLen);
}
}
sliceRecurse(0, contentLen);
// Concatenate all parts
const totalLen = outputParts.reduce((sum, part) => sum + part.length, 0);
const result = new Uint8Array(totalLen);
let offset = 0;
for (const part of outputParts) {
result.set(part, offset);
offset += part.length;
}
return result;
}
/**
* Decode and verify a Bao slice.
*
* @param {Uint8Array} slice - Slice encoding
* @param {Uint8Array} rootHash - Expected 32-byte root hash
* @param {number} sliceStart - Start byte offset of the slice
* @param {number} sliceLen - Number of bytes in the slice
* @returns {Uint8Array} Decoded and verified slice data
* @throws {Error} If verification fails
*/
function baoDecodeSlice(slice, rootHash, sliceStart, sliceLen) {
if (slice.length < HEADER_SIZE) {
throw new Error('Slice too short: missing header');
}
if (rootHash.length !== HASH_SIZE) {
throw new Error(`Root hash must be ${HASH_SIZE} bytes`);
}
const contentLen = decodeLen(slice.subarray(0, HEADER_SIZE));
// Normalize parameters (per spec)
let skipOutput = false;
if (sliceLen === 0) {
sliceLen = 1;
skipOutput = true;
}
let sliceEnd = sliceStart + sliceLen;
// If sliceStart is past EOF, adjust to verify final chunk but skip output
if (sliceStart >= contentLen) {
sliceStart = contentLen > 0 ? contentLen - 1 : 0;
sliceEnd = sliceStart + 1;
skipOutput = true;
}
// Calculate output size
const outputStart = Math.max(0, sliceStart);
const outputEnd = Math.min(contentLen, sliceEnd);
const outputLen = skipOutput ? 0 : Math.max(0, outputEnd - outputStart);
const output = new Uint8Array(outputLen);
let outputPos = 0;
let slicePos = HEADER_SIZE;
/**
* Recursive slice decoding.
*
* @param {number} subtreeStart - Start byte of this subtree in content
* @param {number} subtreeLen - Length of content in this subtree
* @param {Uint8Array} subtreeCV - Expected CV for this subtree
* @param {boolean} isRoot - Whether this is the root node
*/
function decodeSliceRecurse(subtreeStart, subtreeLen, subtreeCV, isRoot) {
const subtreeEnd = subtreeStart + subtreeLen;
if (subtreeEnd <= sliceStart && contentLen > 0) {
// Subtree is before slice - skip (not in slice encoding)
return;
}
if (sliceEnd <= subtreeStart && contentLen > 0) {
// Subtree is after slice - skip (not in slice encoding)
return;
}
if (subtreeLen <= CHUNK_LEN) {
// Chunk - read, verify, and output overlapping portion
const chunk = slice.subarray(slicePos, slicePos + subtreeLen);
slicePos += subtreeLen;
const chunkIndex = Math.floor(subtreeStart / CHUNK_LEN);
verifyChunk(subtreeCV, chunk, chunkIndex, isRoot);
if (!skipOutput) {
// Calculate which part of this chunk to output
const chunkStart = Math.max(0, Math.min(subtreeLen, sliceStart - subtreeStart));
const chunkEnd = Math.max(0, Math.min(subtreeLen, sliceEnd - subtreeStart));
const chunkSlice = chunk.subarray(chunkStart, chunkEnd);
output.set(chunkSlice, outputPos);
outputPos += chunkSlice.length;
}
} else {
// Parent node - read, verify, and recurse
const parent = slice.subarray(slicePos, slicePos + PARENT_SIZE);
slicePos += PARENT_SIZE;
verifyParent(subtreeCV, parent, isRoot);
const leftCV = parent.subarray(0, HASH_SIZE);
const rightCV = parent.subarray(HASH_SIZE, PARENT_SIZE);
const lLen = leftLen(subtreeLen);
decodeSliceRecurse(subtreeStart, lLen, leftCV, false);
decodeSliceRecurse(subtreeStart + lLen, subtreeLen - lLen, rightCV, false);
}
}
decodeSliceRecurse(0, contentLen, rootHash, true);
return output;
}
// ============================================
// STREAMING BAO ENCODER
// ============================================
/**
* Streaming Bao encoder with optimized memory usage.
*
* - Outboard mode: O(n) memory but only 32 bytes per chunk (stores CVs only)
* - Combined mode: O(n) memory (must store full chunks)
*
* Computes chunk CVs incrementally as data arrives.
*/
class BaoEncoder {
/**
* Create a streaming Bao encoder.
*
* @param {boolean} outboard - If true, produce outboard format (no chunk data)
*/
constructor(outboard = false) {
this.outboard = outboard;
this.totalLen = 0;
this.pendingData = [];
this.pendingLen = 0;
// For outboard mode: store only chunk CVs (32 bytes each)
// For combined mode: store full chunk data
this.chunkCVs = []; // Used in outboard mode
this.chunkData = []; // Used in combined mode
this.chunkIndex = 0;
// Cache finalize result for idempotency
this._finalResult = null;
}
/**
* Write data to the encoder.
*
* @param {Uint8Array|string} data - Data to write
* @returns {BaoEncoder} this (for chaining)
*/
write(data) {
if (typeof data === 'string') {
data = new TextEncoder().encode(data);
}
if (!(data instanceof Uint8Array)) {
data = new Uint8Array(data);
}
if (data.length === 0) return this;
this.totalLen += data.length;
// Add to pending buffer
this.pendingData.push(data);
this.pendingLen += data.length;
// Process complete chunks
while (this.pendingLen >= CHUNK_LEN) {
const chunk = this._extractChunk(CHUNK_LEN);
this._processChunk(chunk);
}
return this;
}
/**
* Extract a chunk of specified size from pending data.
*/
_extractChunk(size) {
if (this.pendingData.length === 1 && this.pendingData[0].length >= size) {
const first = this.pendingData[0];
const result = new Uint8Array(first.subarray(0, size));
if (first.length === size) {
this.pendingData.shift();
} else {
this.pendingData[0] = first.subarray(size);
}
this.pendingLen -= size;
return result;
}
const result = new Uint8Array(size);
let resultPos = 0;
while (resultPos < size && this.pendingData.length > 0) {
const first = this.pendingData[0];
const needed = size - resultPos;
if (first.length <= needed) {
result.set(first, resultPos);
resultPos += first.length;
this.pendingData.shift();
} else {
result.set(first.subarray(0, needed), resultPos);
this.pendingData[0] = first.subarray(needed);
resultPos += needed;
}
}
this.pendingLen -= size;
return result;
}
/**
* Process a complete chunk.
*/
_processChunk(chunk) {
// Compute chunk CV (not root - determined at finalize)
const cv = chunkCV(chunk, this.chunkIndex, false);
this.chunkIndex++;
if (this.outboard) {
this.chunkCVs.push(cv); // Store 32-byte CV only
} else {
this.chunkCVs.push(cv); // Store CV for tree building
this.chunkData.push(chunk); // Store full chunk
}
}
/**
* Finalize the encoding and return the result.
* This method is idempotent - calling it multiple times returns the same result.
*
* @returns {{ encoded: Uint8Array, hash: Uint8Array }}
*/
finalize() {
// Return cached result if already finalized
if (this._finalResult) {
return this._finalResult;
}
// Handle remaining pending data as final chunk
if (this.pendingLen > 0 || this.chunkIndex === 0) {
const finalChunk = this.pendingLen > 0
? this._extractChunk(this.pendingLen)
: new Uint8Array(0);
// Single chunk case: it's the root
if (this.chunkIndex === 0) {
const rootHash = chunkCV(finalChunk, 0, true);
const header = encodeLen(this.totalLen);
if (this.outboard) {
this._finalResult = { encoded: header, hash: rootHash };
return this._finalResult;
} else {
const encoded = new Uint8Array(HEADER_SIZE + finalChunk.length);
encoded.set(header, 0);
encoded.set(finalChunk, HEADER_SIZE);
this._finalResult = { encoded, hash: rootHash };
return this._finalResult;
}
}
// Multiple chunks: process final chunk
const cv = chunkCV(finalChunk, this.chunkIndex, false);
this.chunkIndex++;
this.chunkCVs.push(cv);
if (!this.outboard) {
this.chunkData.push(finalChunk);
}
}
// Build tree from chunk CVs
if (this.outboard) {
this._finalResult = this._buildOutboardFromCVs();
} else {
this._finalResult = this._buildCombinedFromCVs();
}
return this._finalResult;
}
/**
* Build outboard encoding from stored chunk CVs.
* Memory efficient: only stores 32 bytes per chunk.
*/
_buildOutboardFromCVs() {
const numChunks = this.chunkCVs.length;
if (numChunks === 1) {
// Recompute with isRoot=true (the stored CV used isRoot=false)
const header = encodeLen(this.totalLen);
// For single chunk, the CV should have been computed with isRoot=true
// But we stored it with isRoot=false, so we need the original chunk...
// Actually, this case is handled in finalize() above, so we shouldn't get here
return { encoded: header, hash: this.chunkCVs[0] };
}
const numParents = numChunks - 1;
const outputSize = HEADER_SIZE + numParents * 64;
const output = new Uint8Array(outputSize);
// Write header
let n = this.totalLen;
for (let i = 0; i < 8; i++) {
output[i] = n & 0xff;
n = Math.floor(n / 256);
}
let writePos = HEADER_SIZE;
// Memoize subtree CV computations
const cvCache = new Map();
const getSubtreeCV = (startIdx, count) => {
if (count === 1) return this.chunkCVs[startIdx];
const key = `${startIdx}:${count}`;
if (cvCache.has(key)) return cvCache.get(key);
const leftCount = 1 << Math.floor(Math.log2(count - 1));
const leftCV = getSubtreeCV(startIdx, leftCount);
const rightCV = getSubtreeCV(startIdx + leftCount, count - leftCount);
const cv = parentCV(leftCV, rightCV, false);
cvCache.set(key, cv);
return cv;
};
// Write tree in pre-order
const writeTree = (startIdx, count, isRoot) => {
if (count === 1) {
return this.chunkCVs[startIdx];
}
const leftCount = 1 << Math.floor(Math.log2(count - 1));
const rightCount = count - leftCount;
const leftCV = getSubtreeCV(startIdx, leftCount);
const rightCV = getSubtreeCV(startIdx + leftCount, rightCount);
// Pre-order: write parent node first
output.set(leftCV, writePos);
output.set(rightCV, writePos + 32);
writePos += 64;
// Then recurse into subtrees
writeTree(startIdx, leftCount, false);
writeTree(startIdx + leftCount, rightCount, false);
return parentCV(leftCV, rightCV, isRoot);
};
const rootHash = writeTree(0, numChunks, true);
return { encoded: output, hash: rootHash };
}
/**
* Build combined encoding from stored chunks and CVs.
*/
_buildCombinedFromCVs() {
const numChunks = this.chunkCVs.length;
// Calculate output size
const numParents = Math.max(0, numChunks - 1);
const outputSize = HEADER_SIZE + numParents * 64 + this.totalLen;
const output = new Uint8Array(outputSize);
// Write header
let n = this.totalLen;
for (let i = 0; i < 8; i++) {
output[i] = n & 0xff;
n = Math.floor(n / 256);
}
let writePos = HEADER_SIZE;
let chunkWriteIdx = 0;
// Memoize subtree CV computations
const cvCache = new Map();
const getSubtreeCV = (startIdx, count) => {
if (count === 1) return this.chunkCVs[startIdx];
const key = `${startIdx}:${count}`;
if (cvCache.has(key)) return cvCache.get(key);
const leftCount = 1 << Math.floor(Math.log2(count - 1));
const leftCV = getSubtreeCV(startIdx, leftCount);
const rightCV = getSubtreeCV(startIdx + leftCount, count - leftCount);
const cv = parentCV(leftCV, rightCV, false);
cvCache.set(key, cv);
return cv;
};
// Write tree in pre-order (combined mode includes chunk data)
const writeTree = (startIdx, count, isRoot) => {
if (count === 1) {
// Leaf: write chunk data
output.set(this.chunkData[chunkWriteIdx], writePos);
writePos += this.chunkData[chunkWriteIdx].length;
chunkWriteIdx++;
return this.chunkCVs[startIdx];
}
const leftCount = 1 << Math.floor(Math.log2(count - 1));