-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsharded_diff.txt
More file actions
821 lines (814 loc) · 74.9 KB
/
Copy pathsharded_diff.txt
File metadata and controls
821 lines (814 loc) · 74.9 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
diff --git a/crates/fula-crypto/src/sharded_hamt_forest.rs b/crates/fula-crypto/src/sharded_hamt_forest.rs
index 6351850..146bca5 100644
--- a/crates/fula-crypto/src/sharded_hamt_forest.rs
+++ b/crates/fula-crypto/src/sharded_hamt_forest.rs
@@ -38,6 +38,7 @@ use crate::private_forest::{
use crate::subtree_keys::EncryptedSubtreeDek;
use crate::wnfs_hamt::{BlobBackend, V7NodeStore};
use crate::{CryptoError, Result};
+use cid::Cid;
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, HashMap, VecDeque};
use std::sync::Arc;
@@ -77,10 +78,31 @@ pub enum HamtEntry {
// to postcard-serialize as the HAMT value type. Conversion happens only at
// the `upsert_file` / `get_file` boundaries.
+/// Wire format for a HAMT leaf entry.
+///
+/// **Wire-version compatibility (walkable-v8 plan, section W.3.2 / W.9.1b).**
+/// Variant tags are part of the on-disk contract:
+///
+/// | Variant | Tag | Introduced | Read by | Written by |
+/// |-----------|-----|------------|-----------|---------------|
+/// | `File` | 0 | v7 | v7+, v8+ | v7+ |
+/// | `Dir` | 1 | v7 | v7+, v8+ | v7+ |
+/// | `FileV2` | 2 | v8 | v8+ | v8+ (W.9.3) |
+///
+/// A v7-only deserializer fails on tag `2` with postcard's "unknown variant"
+/// error — the intended forward-incompatibility boundary. Mirrors
+/// `PointerWire::LinkV2` (W.9.1a). For W.9.1b the writer never emits
+/// variant 2 (W.9.3 wires the actual CID-stamping); production HAMT leaves
+/// stay byte-identical to v7 on encode, preserving the load-bearing
+/// backward-compat property: `From<HamtEntry> for HamtEntryWire` produces
+/// byte-identical output for `ForestFileEntry { storage_cid: None, .. }`
+/// as it did before W.9.1b. See test
+/// `hamt_entry_wire_from_forest_file_entry_with_none_cid_emits_legacy_variant`.
#[derive(Clone, Debug, Serialize, Deserialize)]
enum HamtEntryWire {
File(FileEntryWire),
Dir(DirEntryWire),
+ FileV2(FileEntryWireV2),
}
#[derive(Clone, Debug, Serialize, Deserialize)]
@@ -94,15 +116,75 @@ struct FileEntryWire {
content_hash: Option<String>,
user_metadata: BTreeMap<String, String>,
encrypted: bool,
- /// Minimum blob-format version for this entry (H-2). `0` = legacy,
- /// `4` = written under AAD-bound v4 encryption and requires the
- /// download path to reject lower advertised versions. `#[serde(default)]`
- /// keeps wire compatibility with pre-H-2 shard blobs that lack the
- /// field — postcard's strict decoder will fail without this attribute.
+ /// Minimum blob-format version for this entry (audit finding H-2).
+ /// `0` = legacy (allowed pre-H-2), `4` = written under AAD-bound v4
+ /// encryption (download path rejects lower advertised versions).
+ ///
+ /// AUDIT NOTE (task #42, 2026-05-08): the `#[serde(default)]` here is
+ /// operationally dead. Postcard 1.x does NOT honor `serde(default)` for
+ /// missing trailing struct fields — it errors with
+ /// `DeserializeUnexpectedEnd` (verified empirically during W.9.1b, which
+ /// is why `FileEntryWireV2` was added as an enum-variant rather than
+ /// appending `storage_cid` to this struct). The reason this attribute
+ /// has never broken production is timing: `min_version` landed in
+ /// commit `13139c7` on 2026-04-19 17:41Z, and the earliest tag containing
+ /// `sharded_hamt_forest.rs` is v0.3.0 dated 2026-04-21 — i.e. no tagged
+ /// release ever shipped this struct without `min_version`. The 40h
+ /// window between `dd126cf` (file introduced) and `13139c7` saw no
+ /// release; any shards persisted from `main` HEAD inside that window
+ /// (internal/staging only) are not decodable today, accepted.
+ ///
+ /// CONTRAST: `ForestFileEntry::min_version` at `private_forest.rs:140-146`
+ /// is JSON-encoded, and `serde_json` DOES honor `serde(default)` for
+ /// trailing fields — that comment is correct. Only the postcard surface
+ /// (this struct) has the misleading-`serde(default)` issue.
+ ///
+ /// To extend `FileEntryWire` with a future optional field, follow the
+ /// W.9.1b pattern: add a new variant to `HamtEntryWire` (cf. `FileV2`).
+ /// Do NOT append a field with `serde(default)` and assume backward-compat.
#[serde(default)]
min_version: u8,
}
+/// Walkable-v8 (W.9.1b) variant of [`FileEntryWire`].
+///
+/// Mirrors `FileEntryWire` field-for-field PLUS a `storage_cid: Option<Cid>`
+/// hint for the encrypted chunk/object blob. Selected by [`HamtEntryWire`]'s
+/// variant tag dispatch (variant 2 = `FileV2`), NOT by appending a field to
+/// `FileEntryWire` — postcard 1.x does not honor `#[serde(default)]` for
+/// missing trailing struct fields (it errors with `DeserializeUnexpectedEnd`
+/// rather than substituting the default), so struct field-append is unsafe
+/// for backward compatibility. Enum-variant dispatch is the only postcard-safe
+/// pattern; this mirrors `PointerWire::LinkV2` in `wnfs_hamt::pointer` (W.9.1a).
+///
+/// Until W.9.3 wires the writer to capture chunk CIDs from S3BlobBackend's
+/// PUT response, the writer continues to emit [`HamtEntryWire::File`]
+/// (variant 0). `FileEntryWireV2` is type plumbing only at this stage.
+#[derive(Clone, Debug, Serialize, Deserialize)]
+struct FileEntryWireV2 {
+ path: String,
+ storage_key: String,
+ size: u64,
+ content_type: Option<String>,
+ created_at: i64,
+ modified_at: i64,
+ content_hash: Option<String>,
+ user_metadata: BTreeMap<String, String>,
+ encrypted: bool,
+ /// No `#[serde(default)]` here: `FileEntryWireV2` is the W.9.1b-introduced
+ /// variant and was never emitted without `min_version`. Postcard does not
+ /// honor `serde(default)` on missing trailing fields anyway (see the
+ /// audit note on `FileEntryWire::min_version`); leaving it off makes
+ /// the postcard contract explicit — every field of every variant is
+ /// required at the wire level, no exceptions.
+ min_version: u8,
+ /// CID hint for the encrypted chunk/object blob, populated from master's
+ /// PUT-response ETag. `Some(_)` here is the trigger for emitting variant
+ /// 2 (`FileV2`) on the wire; `None` falls back to legacy variant 0
+ /// (`File`) so that v7 SDKs can still read the leaf.
+ storage_cid: Option<Cid>,
+}
+
#[derive(Clone, Debug, Serialize, Deserialize)]
struct DirEntryWire {
path: String,
@@ -142,6 +224,44 @@ impl From<FileEntryWire> for ForestFileEntry {
user_metadata: w.user_metadata.into_iter().collect::<HashMap<_, _>>(),
encrypted: w.encrypted,
min_version: w.min_version,
+ // Legacy wire never carried a CID hint.
+ storage_cid: None,
+ }
+ }
+}
+
+impl From<ForestFileEntry> for FileEntryWireV2 {
+ fn from(e: ForestFileEntry) -> Self {
+ Self {
+ path: e.path,
+ storage_key: e.storage_key,
+ size: e.size,
+ content_type: e.content_type,
+ created_at: e.created_at,
+ modified_at: e.modified_at,
+ content_hash: e.content_hash,
+ user_metadata: e.user_metadata.into_iter().collect(),
+ encrypted: e.encrypted,
+ min_version: e.min_version,
+ storage_cid: e.storage_cid,
+ }
+ }
+}
+
+impl From<FileEntryWireV2> for ForestFileEntry {
+ fn from(w: FileEntryWireV2) -> Self {
+ Self {
+ path: w.path,
+ storage_key: w.storage_key,
+ size: w.size,
+ content_type: w.content_type,
+ created_at: w.created_at,
+ modified_at: w.modified_at,
+ content_hash: w.content_hash,
+ user_metadata: w.user_metadata.into_iter().collect::<HashMap<_, _>>(),
+ encrypted: w.encrypted,
+ min_version: w.min_version,
+ storage_cid: w.storage_cid,
}
}
}
@@ -175,6 +295,20 @@ impl From<DirEntryWire> for ForestDirectoryEntry {
impl From<HamtEntry> for HamtEntryWire {
fn from(e: HamtEntry) -> Self {
match e {
+ // Walkable-v8 (W.9.1b) writer dispatch: files with a stamped
+ // `storage_cid` emit variant 2 (`FileV2`); files without
+ // continue to emit variant 0 (`File`) byte-identically to v7.
+ //
+ // For W.9.1b foundational scope the upstream call sites do NOT
+ // populate `storage_cid` — that's W.9.3's writer integration —
+ // so this dispatch always falls through to the legacy variant
+ // in production today. The load-bearing property: existing v7
+ // SDKs reading buckets written by post-W.9.1b SDKs see
+ // byte-identical wire bytes until W.9.3 ships, preserving
+ // backward compat throughout the SDK adoption window.
+ HamtEntry::File(f) if f.storage_cid.is_some() => {
+ HamtEntryWire::FileV2(f.into())
+ }
HamtEntry::File(f) => HamtEntryWire::File(f.into()),
HamtEntry::Dir(d) => HamtEntryWire::Dir(d.into()),
}
@@ -186,6 +320,7 @@ impl From<HamtEntryWire> for HamtEntry {
match w {
HamtEntryWire::File(f) => HamtEntry::File(f.into()),
HamtEntryWire::Dir(d) => HamtEntry::Dir(d.into()),
+ HamtEntryWire::FileV2(f) => HamtEntry::File(f.into()),
}
}
}
@@ -514,7 +649,7 @@ impl ShardedHamtPrivateForest {
}
self.manifest.root.page_index.insert(
page_id,
- crate::private_forest::PageRef { etag, seq },
+ crate::private_forest::PageRef { etag, seq, cid: None },
);
}
@@ -1643,7 +1778,19 @@ impl ShardedHamtPrivateForest {
backend.clone(),
);
- let new_root = {
+ // Walkable-v8 (W.9.3): we surface BOTH the storage_key (used
+ // by master-S3 reads + the conditional-PUT story) AND the
+ // master-attested CID (used by W.9.4's offline gateway race).
+ // `cid` is `Some` only when the BlobBackend's `put` returned
+ // one (i.e. master S3 with `walkable_v8_writer_enabled = true`
+ // and a verified ETag); `None` for in-memory test backends,
+ // for writes under the v0.5 default-off mode, or when the
+ // master-attested CID failed self-verify against
+ // `BLAKE3(ciphertext)`. The two are stamped together so a
+ // future flush that doesn't change this shard preserves the
+ // pair atomically (next-flush logic only updates a shard's
+ // `root` + `root_cid` when its dirty flag is set).
+ let (new_root, new_root_cid) = {
let guard = self.loaded_shards[idx].read().await;
match &*guard {
LoadedShard::NotLoaded => {
@@ -1652,18 +1799,21 @@ impl ShardedHamtPrivateForest {
idx
)));
}
- LoadedShard::LoadedEmpty => None,
+ LoadedShard::LoadedEmpty => (None, None),
LoadedShard::Loaded(node) => {
if node.is_empty() {
- None
+ (None, None)
} else {
- Some(node.store(&store).await?)
+ let result = node.store(&store).await?;
+ (Some(result.storage_key), result.cid)
}
}
}
};
- self.manifest.shard_mut(idx).root = new_root;
+ let shard = self.manifest.shard_mut(idx);
+ shard.root = new_root;
+ shard.root_cid = new_root_cid;
self.dirty_shards[idx] = false;
}
self.manifest.touch();
@@ -1698,6 +1848,7 @@ mod tests {
user_metadata: Default::default(),
encrypted: true,
min_version: 0,
+ storage_cid: None,
}
}
@@ -2538,4 +2689,557 @@ mod tests {
}
assert_eq!(seen.len(), total, "paginated walk must see every match");
}
+
+ // ========================================================================
+ // Walkable-v8 wire format tests (W.9.1b)
+ //
+ // The v8 chunk-CID hint goes through `HamtEntryWire`'s **enum-variant
+ // dispatch** (mirrors `PointerWire::LinkV2` in `wnfs_hamt::pointer`),
+ // NOT through field-append on `FileEntryWire`. This is the only
+ // postcard-safe approach: postcard 1.x does not honor `#[serde(default)]`
+ // for missing trailing struct fields (it errors with
+ // `DeserializeUnexpectedEnd` rather than substituting the default), so
+ // a struct field-append would break backward compat for every existing
+ // HAMT leaf the day W.9.3 ships. Enum-variant dispatch keeps v7 leaves
+ // byte-identical (variant tag 0 = `File`) while letting v8 writers emit
+ // `FileV2` (variant tag 2) when a CID hint is available.
+ //
+ // Pinned properties (mirror `pointer.rs::walkable_v8_wire_tests`):
+ // 1. `HamtEntryWire::FileV2` round-trips through postcard losslessly.
+ // 2. The `FileV2` variant index is the postcard tag `2` —
+ // the value an old (v7-only) deserializer doesn't recognize.
+ // 3. A v7-only deserializer (`LegacyHamtEntryWire` with only File +
+ // Dir variants) errors cleanly on a v8-format `FileV2` blob.
+ // 4. The v8 deserializer reads a v7-format `File` blob unchanged
+ // (legacy data written pre-W.9.1b round-trips fine).
+ // 5. **Load-bearing backward-compat**: `From<HamtEntry> for
+ // HamtEntryWire` produces byte-identical output for a
+ // `ForestFileEntry { storage_cid: None, .. }` as it did before
+ // W.9.1b. Without this property, every existing v7 SDK reader
+ // would break the day post-W.9.1b code lands.
+ // ========================================================================
+
+ fn walkable_v8_test_cid(seed: u8) -> cid::Cid {
+ let digest = [seed; 32];
+ let mh = cid::multihash::Multihash::<64>::wrap(0x1e, &digest)
+ .expect("BLAKE3 multihash wrap");
+ cid::Cid::new_v1(0x55, mh)
+ }
+
+ fn fixture_forest_file_entry(path: &str, storage_cid: Option<cid::Cid>) -> ForestFileEntry {
+ ForestFileEntry {
+ path: path.to_string(),
+ storage_key: format!("Qm{}", hex::encode(blake3::hash(path.as_bytes()).as_bytes())),
+ size: 1024,
+ content_type: Some("text/plain".to_string()),
+ created_at: 1,
+ modified_at: 2,
+ content_hash: Some("blake3:...".to_string()),
+ user_metadata: HashMap::new(),
+ encrypted: true,
+ min_version: 4,
+ storage_cid,
+ }
+ }
+
+ #[test]
+ fn hamt_entry_wire_file_legacy_round_trips_via_postcard_variant_0() {
+ let entry = fixture_forest_file_entry("/legacy.bin", None);
+ let wire: HamtEntryWire = HamtEntry::File(entry.clone()).into();
+ let encoded = postcard::to_allocvec(&wire).expect("encode");
+ // Legacy variant must be `File` (tag 0). Postcard writes the variant
+ // index as the leading byte for small tags.
+ assert_eq!(encoded[0], 0, "legacy File variant must be index 0");
+ let decoded: HamtEntryWire = postcard::from_bytes(&encoded).expect("decode");
+ match decoded {
+ HamtEntryWire::File(_) => {}
+ other => panic!("expected File variant, got {:?}", other),
+ }
+ }
+
+ #[test]
+ fn hamt_entry_wire_file_v2_round_trips_via_postcard_variant_2() {
+ let cid = walkable_v8_test_cid(0xAB);
+ let entry = fixture_forest_file_entry("/v8.bin", Some(cid));
+ let wire: HamtEntryWire = HamtEntry::File(entry.clone()).into();
+ let encoded = postcard::to_allocvec(&wire).expect("encode");
+ // FileV2 must be variant 2 — this is the load-bearing
+ // forward-incompat dispatch byte. v7-only HamtEntryWire decoders
+ // (only File=0, Dir=1) error cleanly on tag 2.
+ assert_eq!(
+ encoded[0], 2,
+ "FileV2 must be variant 2 in the wire format — do not change this. \
+ A v7-only HamtEntryWire deserializer relies on tag 2 being \
+ unknown to surface a typed error rather than corrupting state."
+ );
+ let decoded: HamtEntryWire = postcard::from_bytes(&encoded).expect("decode");
+ match decoded {
+ HamtEntryWire::FileV2(f2) => {
+ assert_eq!(f2.storage_cid, Some(cid));
+ assert_eq!(f2.path, "/v8.bin");
+ assert_eq!(f2.min_version, 4);
+ }
+ other => panic!("expected FileV2 variant, got {:?}", other),
+ }
+ }
+
+ #[test]
+ fn hamt_entry_wire_from_forest_file_entry_with_none_cid_emits_legacy_variant() {
+ // LOAD-BEARING BACKWARD-COMPAT (W.4.3 hard-constraint #1).
+ //
+ // For W.9.1b's foundational scope the writer NEVER stamps a CID
+ // (W.9.3 wires that). All production writes have
+ // `storage_cid = None` and MUST emit variant 0 (`File`) byte-
+ // identically to v7 so that v7 SDKs continue reading the bucket
+ // through the entire SDK-adoption window. If this dispatch ever
+ // accidentally picks variant 2 for a None CID, every existing v7
+ // reader breaks the day post-W.9.1b code lands.
+ let entry = fixture_forest_file_entry("/no-cid.bin", None);
+ let wire_v8: HamtEntryWire = HamtEntry::File(entry.clone()).into();
+ let v8_bytes = postcard::to_allocvec(&wire_v8).expect("encode v8");
+ assert_eq!(
+ v8_bytes[0], 0,
+ "ForestFileEntry with storage_cid=None MUST emit variant 0 (File), \
+ NOT variant 2 (FileV2). Otherwise v7 SDKs break."
+ );
+
+ // And the bytes must match exactly what an SDK without W.9.1b
+ // changes would have emitted. Construct that simulated-legacy emit
+ // by going `HamtEntry → HamtEntryWire::File(FileEntryWire)`
+ // explicitly, encode, and compare.
+ let wire_legacy_explicit = HamtEntryWire::File(FileEntryWire {
+ path: "/no-cid.bin".to_string(),
+ storage_key: format!(
+ "Qm{}",
+ hex::encode(blake3::hash("/no-cid.bin".as_bytes()).as_bytes())
+ ),
+ size: 1024,
+ content_type: Some("text/plain".to_string()),
+ created_at: 1,
+ modified_at: 2,
+ content_hash: Some("blake3:...".to_string()),
+ user_metadata: BTreeMap::new(),
+ encrypted: true,
+ min_version: 4,
+ });
+ let legacy_bytes =
+ postcard::to_allocvec(&wire_legacy_explicit).expect("encode legacy");
+ assert_eq!(
+ v8_bytes, legacy_bytes,
+ "v8 SDK emit for None-CID entry must be byte-identical to v7 emit"
+ );
+ }
+
+ /// A v7-only enum (only File + Dir variants) — simulates a v0.5-or-earlier
+ /// SDK that has never been recompiled to know about `FileV2`. Reading a
+ /// v8-format `FileV2` blob into this enum must produce a typed error.
+ #[derive(Debug, Serialize, Deserialize)]
+ enum LegacyHamtEntryWire {
+ File(FileEntryWire),
+ Dir(DirEntryWire),
+ }
+
+ #[test]
+ fn legacy_v7_decoder_errors_on_v8_file_v2_blob() {
+ let cid = walkable_v8_test_cid(0xCD);
+ let entry = fixture_forest_file_entry("/forward-incompat.bin", Some(cid));
+ let wire_v8: HamtEntryWire = HamtEntry::File(entry).into();
+ let encoded = postcard::to_allocvec(&wire_v8).expect("encode v8");
+ // Sanity check: the FileV2 dispatch fired and we have a variant-2
+ // blob to feed to the legacy decoder.
+ assert_eq!(encoded[0], 2, "fixture must produce v8 FileV2 blob");
+
+ let result: std::result::Result<LegacyHamtEntryWire, _> =
+ postcard::from_bytes(&encoded);
+ assert!(
+ result.is_err(),
+ "v7-only HamtEntryWire deserializer must error on v8 FileV2 blob \
+ (forward-incompatibility boundary), got {:?}",
+ result
+ );
+ }
+
+ #[test]
+ fn v8_decoder_reads_legacy_v7_file_blob() {
+ // A v7 SDK encoded a `File(FileEntryWire)` blob. A v8 SDK reading
+ // the same bucket must decode it identically — no upgrade-on-read,
+ // legacy data stays accessible until the user happens to write to
+ // it (W.4.2: lazy migration on next write).
+ let v7_blob = LegacyHamtEntryWire::File(FileEntryWire {
+ path: "/v7.bin".to_string(),
+ storage_key: "QmV7".to_string(),
+ size: 100,
+ content_type: None,
+ created_at: 0,
+ modified_at: 0,
+ content_hash: None,
+ user_metadata: BTreeMap::new(),
+ encrypted: true,
+ min_version: 4,
+ });
+ let encoded = postcard::to_allocvec(&v7_blob).expect("encode v7");
+ assert_eq!(encoded[0], 0, "v7 File blob must use variant 0");
+
+ let decoded: HamtEntryWire = postcard::from_bytes(&encoded)
+ .expect("v8 decoder must read v7 File blob");
+ match decoded {
+ HamtEntryWire::File(f) => {
+ assert_eq!(f.path, "/v7.bin");
+ assert_eq!(f.storage_key, "QmV7");
+ assert_eq!(f.min_version, 4);
+ }
+ other => panic!("expected File variant, got {:?}", other),
+ }
+ }
+
+ #[test]
+ fn forest_file_entry_to_file_entry_wire_v2_preserves_storage_cid_both_directions() {
+ // The two-way conversion at the FileEntryWireV2 boundary preserves
+ // every field including storage_cid. Mirrors the round-trip pattern
+ // in `pointer.rs::walkable_v8_wire_tests::child_ptr_stored_v2_full_pipeline_roundtrip`.
+ let cid = walkable_v8_test_cid(0x42);
+ let original = fixture_forest_file_entry("/x.bin", Some(cid));
+
+ let wire: FileEntryWireV2 = original.clone().into();
+ assert_eq!(wire.storage_cid, Some(cid));
+ assert_eq!(wire.storage_key, original.storage_key);
+ assert_eq!(wire.path, "/x.bin");
+
+ let recovered: ForestFileEntry = wire.into();
+ assert_eq!(recovered.storage_cid, Some(cid));
+ assert_eq!(recovered.path, original.path);
+ assert_eq!(recovered.encrypted, true);
+ assert_eq!(recovered.min_version, 4);
+ }
+
+ #[test]
+ fn file_entry_wire_legacy_to_forest_file_entry_yields_none_storage_cid() {
+ // The legacy `FileEntryWire` (no storage_cid) → `ForestFileEntry`
+ // conversion produces `storage_cid = None`. This is what fires when
+ // a v8 SDK reads a v7-format `HamtEntryWire::File` leaf — the
+ // backward-compat path through `From<FileEntryWire> for ForestFileEntry`.
+ let wire = FileEntryWire {
+ path: "/legacy.bin".to_string(),
+ storage_key: "QmLegacy".to_string(),
+ size: 42,
+ content_type: None,
+ created_at: 0,
+ modified_at: 0,
+ content_hash: None,
+ user_metadata: BTreeMap::new(),
+ encrypted: true,
+ min_version: 4,
+ };
+ let entry: ForestFileEntry = wire.into();
+ assert_eq!(entry.storage_cid, None);
+ assert_eq!(entry.path, "/legacy.bin");
+ assert_eq!(entry.storage_key, "QmLegacy");
+ }
+
+ // ========================================================================
+ // Walkable-v8 writer integration tests (W.9.3)
+ //
+ // These tests pin the END-TO-END writer wiring: a v8-aware backend
+ // surfaces a CID in `BlobPutResult.cid`, the HAMT cascade in
+ // `node.rs`/`pointer.rs`/`sharded_hamt_forest.rs` propagates it
+ // through `NodePutResult`, and the manifest's per-shard `root_cid`
+ // gets stamped. A v8 reader (W.9.4) will then walk via those CIDs.
+ //
+ // Without these tests the W.9.3 wiring could silently regress —
+ // the unit tests in `pointer.rs` and `private_forest.rs` cover
+ // each layer in isolation, but only the integration test here
+ // exercises the full v8 cascade against a real HAMT.
+ // ========================================================================
+
+ /// In-memory backend that emulates master S3's walkable-v8 contract:
+ /// every PUT records `BLAKE3(ciphertext)` raw-codec as the returned
+ /// CID. Real master computes this via kubo's `block/put?cid-codec=
+ /// raw&mhtype=blake3` (see `crates/fula-cli/src/handlers/object.rs:
+ /// 103-137`); this fake implements the same contract so the SDK
+ /// can be tested end-to-end without a wiremock harness.
+ ///
+ /// Captures every PUT (`path -> ciphertext`) so the test can later
+ /// assert the parent's pointer plaintext references each child
+ /// with the correct CID.
+ struct CidCapturingBackend {
+ objects: std::sync::Mutex<std::collections::HashMap<String, Vec<u8>>>,
+ }
+
+ impl CidCapturingBackend {
+ fn new() -> Self {
+ Self {
+ objects: std::sync::Mutex::new(std::collections::HashMap::new()),
+ }
+ }
+
+ fn get_sync(&self, path: &str) -> Option<Vec<u8>> {
+ self.objects.lock().unwrap().get(path).cloned()
+ }
+
+ /// Build the same v1 raw-codec BLAKE3-multihash CID master would
+ /// emit on PUT for these bytes. This is the contract every
+ /// walkable-v8-enabled BlobBackend exposes: `cid.to_string()` is
+ /// what master returns in the ETag header.
+ fn cid_for(bytes: &[u8]) -> cid::Cid {
+ let h = blake3::hash(bytes);
+ let mh = cid::multihash::Multihash::<64>::wrap(0x1e, h.as_bytes())
+ .expect("blake3 multihash wrap");
+ cid::Cid::new_v1(0x55, mh)
+ }
+ }
+
+ #[async_trait::async_trait]
+ impl crate::wnfs_hamt::v7_store::BlobBackend for CidCapturingBackend {
+ async fn get(&self, path: &str) -> Result<Vec<u8>> {
+ self.objects
+ .lock()
+ .unwrap()
+ .get(path)
+ .cloned()
+ .ok_or_else(|| {
+ crate::CryptoError::Hamt(format!("v8 fake: object not found: {}", path))
+ })
+ }
+
+ async fn put(
+ &self,
+ path: &str,
+ bytes: Vec<u8>,
+ ) -> Result<crate::wnfs_hamt::v7_store::BlobPutResult> {
+ let cid = Self::cid_for(&bytes);
+ self.objects
+ .lock()
+ .unwrap()
+ .insert(path.to_string(), bytes);
+ Ok(crate::wnfs_hamt::v7_store::BlobPutResult { cid: Some(cid) })
+ }
+ }
+
+ #[tokio::test]
+ async fn walkable_v8_writer_e2e_stamps_shard_root_cid_matching_ciphertext_hash() {
+ // Goal: end-to-end check that when the BlobBackend returns a
+ // CID for every PUT (= walkable-v8-enabled writer), the flush
+ // stamps `manifest.shards[i].root_cid` to a value that matches
+ // BLAKE3(ciphertext) of the actual stored bytes. Failure here
+ // would mean either:
+ // - sharded_hamt_forest's flush_dirty doesn't propagate the
+ // CID into root_cid (regressing W.9.3-C), OR
+ // - the BlobPutResult plumbing through NodePutResult drops
+ // the CID somewhere (regressing W.9.2's seam).
+ let backend = std::sync::Arc::new(CidCapturingBackend::new());
+ let mut forest = ShardedHamtPrivateForest::new("bucket-w8", test_dek(), 16);
+
+ // Spread enough entries that at least one shard ends up with a
+ // populated root. 256 keys with 16 shards is ~16 entries per
+ // shard on average — well past the singleton-bucket threshold.
+ for i in 0..32u64 {
+ forest
+ .upsert_file(
+ file_entry(&format!("/v8/file-{:03}.bin", i), i),
+ &backend,
+ )
+ .await
+ .unwrap();
+ }
+
+ // Flush. After this the manifest should carry root_cid hints on
+ // every populated shard.
+ let manifest = forest.flush_dirty(&backend).await.unwrap().clone();
+
+ // Find populated shards. With CidCapturingBackend, every shard
+ // that flushed a non-empty root MUST also carry a Some(cid).
+ let mut populated_count = 0usize;
+ for (_idx, shard) in manifest.shards_iter().enumerate() {
+ if shard.root.is_some() {
+ populated_count += 1;
+ assert!(
+ shard.root_cid.is_some(),
+ "walkable-v8 writer wired: every populated shard must \
+ have its root_cid stamped (W.9.3 — sharded_hamt_forest::\
+ flush_dirty propagates BlobPutResult.cid into root_cid)"
+ );
+ } else {
+ assert!(
+ shard.root_cid.is_none(),
+ "empty shard must not carry a stale root_cid hint"
+ );
+ }
+ }
+ assert!(
+ populated_count > 0,
+ "test setup invalid: no shard got populated"
+ );
+ }
+
+ #[tokio::test]
+ async fn walkable_v8_writer_e2e_internal_node_pointers_use_link_v2() {
+ // Goal: end-to-end check that internal HAMT nodes (parents of
+ // mutated children) emit `PointerWire::LinkV2` on their child
+ // pointers when the BlobBackend returns CIDs. Loads the shard
+ // root's plaintext from the backend, decrypts, and decodes the
+ // wire form; asserts at least one `LinkV2` variant appears in
+ // a parent that has a mutated subtree.
+ //
+ // This test exercises the load-bearing assertion of W.9.3-C:
+ // the InMemory arm at pointer.rs:243 emits LinkV2 when
+ // result.cid is Some. Without it the wire format would still
+ // be all-`Link`, breaking offline walks.
+ use crate::wnfs_hamt::store::HamtNodeStore;
+ let backend = std::sync::Arc::new(CidCapturingBackend::new());
+ let mut forest = ShardedHamtPrivateForest::new("bucket-w8b", test_dek(), 16);
+
+ // Enough entries to force at least one shard to grow past a
+ // single-leaf bucket and produce internal nodes.
+ for i in 0..64u64 {
+ forest
+ .upsert_file(
+ file_entry(&format!("/deep/{:03}.bin", i), i),
+ &backend,
+ )
+ .await
+ .unwrap();
+ }
+ let manifest = forest.flush_dirty(&backend).await.unwrap().clone();
+
+ // Find a populated shard whose root has at least one child
+ // pointer (indicating an internal node exists in the cascade).
+ let mut found_link_v2 = false;
+ for (idx, shard) in manifest.shards_iter().enumerate() {
+ if shard.root.is_none() {
+ continue;
+ }
+ // Decrypt the root node and inspect its wire form. Use the
+ // same V7NodeStore the writer used so AAD matches.
+ let store = crate::wnfs_hamt::v7_store::V7NodeStore::new(
+ "bucket-w8b",
+ idx as u16,
+ manifest.shard_salt().to_vec(),
+ test_dek(),
+ backend.clone(),
+ );
+ let plaintext = store
+ .get_node(&shard.root.unwrap())
+ .await
+ .expect("root node must decrypt under the writer's DEK");
+
+ // `plaintext` is `postcard(NodeWire { bitmask, pointers })`.
+ // Decode and walk the pointers list looking for `LinkV2`.
+ #[derive(serde::Deserialize)]
+ struct NodeWireInspect<K, V> {
+ #[allow(dead_code)]
+ bitmask: u16,
+ pointers: Vec<crate::wnfs_hamt::pointer::PointerWire<K, V>>,
+ }
+ let wire: NodeWireInspect<Vec<u8>, HamtEntryWire> =
+ postcard::from_bytes(&plaintext).expect("decode root wire");
+ for ptr in &wire.pointers {
+ if let crate::wnfs_hamt::pointer::PointerWire::LinkV2 { storage_key, cid } =
+ ptr
+ {
+ found_link_v2 = true;
+ // Belt-and-suspenders: the CID embedded in the
+ // pointer should match BLAKE3 of the child's stored
+ // ciphertext at this storage_key path.
+ let child_path = format!(
+ "{}{}",
+ crate::wnfs_hamt::v7_store::V7_NODE_PREFIX,
+ hex::encode(storage_key)
+ );
+ let child_bytes = backend
+ .get_sync(&child_path)
+ .expect("child blob must be persisted");
+ let recomputed = CidCapturingBackend::cid_for(&child_bytes);
+ assert_eq!(
+ *cid, recomputed,
+ "LinkV2.cid in parent's pointer plaintext must equal \
+ BLAKE3(child's ciphertext) — without this guarantee, \
+ W.9.4's gateway-race walker would fetch the wrong \
+ bytes for this child"
+ );
+ }
+ }
+ // First populated shard with parent pointers is enough.
+ if found_link_v2 {
+ break;
+ }
+ }
+ assert!(
+ found_link_v2,
+ "no LinkV2 variant found in any flushed shard root — the writer \
+ cascade either short-circuited (every shard has only a single-leaf \
+ bucket) or pointer.rs's InMemory arm is regressing back to legacy \
+ Link. Try increasing the entry count for this test, or check \
+ pointer.rs:to_wire."
+ );
+ }
+
+ #[tokio::test]
+ async fn walkable_v8_writer_e2e_in_memory_backend_keeps_link_legacy() {
+ // Negative control: with the default `InMemoryBackend` (which
+ // returns BlobPutResult::none()), the writer cascade MUST emit
+ // legacy `Link` only — no `LinkV2`. This pins the v0.5-default
+ // backwards-compat: when the writer flag is off (or the backend
+ // doesn't surface CIDs), the wire format is byte-identical to
+ // the pre-walkable-v8 v7 form.
+ use crate::wnfs_hamt::store::HamtNodeStore;
+ let backend = std::sync::Arc::new(InMemoryBackend::new());
+ let mut forest = ShardedHamtPrivateForest::new("bucket-w8c", test_dek(), 16);
+
+ for i in 0..64u64 {
+ forest
+ .upsert_file(
+ file_entry(&format!("/d/{:03}.bin", i), i),
+ &backend,
+ )
+ .await
+ .unwrap();
+ }
+ let manifest = forest.flush_dirty(&backend).await.unwrap().clone();
+
+ // Every populated shard's root_cid MUST be None — the backend
+ // returned no CID hints.
+ for shard in manifest.shards_iter() {
+ assert!(
+ shard.root_cid.is_none(),
+ "InMemoryBackend returns BlobPutResult::none() — root_cid \
+ must stay None, otherwise the writer is fabricating CIDs"
+ );
+ }
+
+ // Decode any populated shard's root plaintext and assert no
+ // `LinkV2` variant appears in any pointer.
+ for (idx, shard) in manifest.shards_iter().enumerate() {
+ if shard.root.is_none() {
+ continue;
+ }
+ let store = crate::wnfs_hamt::v7_store::V7NodeStore::new(
+ "bucket-w8c",
+ idx as u16,
+ manifest.shard_salt().to_vec(),
+ test_dek(),
+ backend.clone(),
+ );
+ let plaintext = store.get_node(&shard.root.unwrap()).await.unwrap();
+ #[derive(serde::Deserialize)]
+ struct NodeWireInspect<K, V> {
+ #[allow(dead_code)]
+ bitmask: u16,
+ pointers: Vec<crate::wnfs_hamt::pointer::PointerWire<K, V>>,
+ }
+ let wire: NodeWireInspect<Vec<u8>, HamtEntryWire> =
+ postcard::from_bytes(&plaintext).unwrap();
+ for ptr in &wire.pointers {
+ assert!(
+ !matches!(
+ ptr,
+ crate::wnfs_hamt::pointer::PointerWire::LinkV2 { .. }
+ ),
+ "InMemoryBackend returns no CIDs — wire MUST stay all-Link, \
+ but found a LinkV2 in shard {}'s root pointers. Writer is \
+ fabricating CIDs.",
+ idx
+ );
+ }
+ }
+ }
}