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
//! The CID-addressed node store seam — [`get`](NodeStoreExt::get)/[`put`](NodeStoreExt::put) by [`ContentId`], with a
//! verified read path the extension-trait implementation establishes.
//!
//! # Why this exists
//!
//! Every Merkle structure built on this crate resolves its child/parent links
//! the same way: a [`ContentId`] goes in, and **hash-verified bytes come out**
//! (identity-preserving *typed* reads additionally establish canonical
//! representation — see [`get`](NodeStoreExt::get) vs
//! [`get_node`](NodeStoreExt::get_node)). This module is that one narrow seam. A
//! structure never owns storage; it traverses a [`NodeStore`], so **a root CID
//! plus a store fully determines the structure** — hand someone the root id and
//! *any* store holding the bytes, and they can reconstruct the whole structure and
//! prove every node on the way down.
//!
//! Three properties make the seam trustworthy:
//!
//! 1. **Traversal is uniform.** All structures resolve links through this one
//! trait — not N private storage conventions that diverge on exactly the
//! thing that must stay uniform.
//! 2. **The verified path cannot be *re-implemented*.** Tampering happens in the
//! backend (disk corruption, a hostile peer, a buggy cache). The verified
//! [`get`](NodeStoreExt::get) lives in [`NodeStoreExt`], a blanket-implemented
//! extension trait sealed by coherence: a backend implements only the raw
//! [`get_unverified`](NodeStore::get_unverified) fetch and cannot supply a
//! different body for the verified methods. **Caveat — this is not the same as
//! "unskippable".** Rust prefers *inherent* methods in method-call resolution,
//! so a concrete backend that defines its own inherent `fn get` will have
//! ordinary `store.get(&id)` resolve to *that*, not the trait method. Code that
//! must not be bypassed should hold a [`VerifiedStore`] (which exposes only the
//! verified operations) or call `NodeStoreExt::get(store, id)` via UFCS.
//! 3. **Storage is replaceable.** Identity comes from the frozen CID profile,
//! never from where bytes live: swapping the backend (memory today; disk and
//! network as follow-ups) can never change any node's id.
//!
//! # The laws (proof obligations)
//!
//! Law minimalism: three laws, each naming a **property** — the algorithm is
//! pinned by the frozen v1 CID profile, which already self-describes codec +
//! hash, so the laws never name a hash function:
//!
//! - **PO-STORE-1A (put derives the address) \[proof target: Lean, deferred\]** —
//! the **seam theorem** is [`put_node`](NodeStoreExt::put_node)`(n)` returns
//! `Address(n.canonical_form())` (equivalently [`put`](NodeStoreExt::put)`(b)`
//! returns [`ContentId::from_canonical_bytes`]`(b)`). This is **sealed**: the id
//! is derived in the blanket-implemented extension, and the backend's only write
//! op ([`insert`](NodeStore::insert)) receives an unforgeable [`AddressedBytes`]
//! whose id it *cannot* have chosen — so a backend cannot influence the id [`put`](NodeStoreExt::put)
//! returns, nor be handed bytes that do not derive their key. Addressing is a pure
//! function of content. The corollary `put_node(n) == n.content_id()` holds
//! **only for a lawful [`ContentAddressable`]** — one whose (overridable)
//! [`content_id`](crate::ContentAddressable::content_id) honors `content_id() == Address(canonical_form())`; the seam
//! cannot prove it for an arbitrary impl and does not rely on it ([`put_node`](NodeStoreExt::put_node) uses
//! the strict [`put_checked`](NodeStoreExt::put_checked), so a non-canonical
//! [`canonical_form`](crate::ContentAddressable::canonical_form) is a write-time error, not a mis-stamped id). (What a backend
//! does *with* a well-formed pair — file it correctly, durably, without disturbing
//! another entry — is PO-STORE-1B, not this law.)
//! - **PO-STORE-1B (backend acknowledgement) \[proof target: TLA+, a backend law, deferred\]** — that
//! [`insert`](NodeStore::insert) returned `Ok` means only that the backend
//! *accepted* the mapping under its documented durability/visibility contract.
//! The blanket impl CANNOT prove the bytes were stored, stored under that id,
//! readable later, or that no other mapping was disturbed: a backend that drops
//! every write and returns `Ok(())` satisfies 1A (the returned id is still
//! correct) while storing nothing. 1B is therefore a *backend* obligation, not a
//! seam guarantee — [`MemoryStore`] discharges it (in-memory, immediate); a
//! disk/network backend discharges it per its own model, surfacing failures
//! through [`StoreError::Backend`].
//! - **PO-STORE-2 (verify-on-read soundness) \[proof target: Lean, deferred\]** — for **any** backend
//! [`get_unverified`](NodeStore::get_unverified), including an adversarial one,
//! [`NodeStoreExt::get`]`(id)` returns `Ok(b)` only if
//! `from_canonical_bytes(b) == id` (byte-addressed: `b` hashes to `id`; it does
//! *not* assert `b` is canonical — see [`get`](NodeStoreExt::get) and the
//! identity-preserving [`get_node`](NodeStoreExt::get_node)). Corruption or
//! substitution surfaces as [`ContentError::VerificationFailed`], never as wrong
//! bytes. This holds for arbitrary backends because [`get`](NodeStoreExt::get) is blanket-implemented
//! and sealed by coherence.
//! - **PO-STORE-3 (grow-only monotonicity, fail-closed) \[proof target: TLA+, a backend law, deferred\]** —
//! a *conforming* backend's `id → bytes` map only grows and a mapping is never
//! rebound: re-inserting the *same* bytes is idempotent, and *different* bytes
//! under a live id **fail closed** with [`StoreError::Collision`], leaving state
//! unchanged. Like PO-STORE-1B this is a **backend** obligation, NOT a seam
//! theorem: [`AddressedBytes`] proves only that the pair handed to a backend is
//! address-consistent — it cannot stop an arbitrary backend from deleting or
//! overwriting an *unrelated* mapping, so the blanket seam / [`VerifiedStore`] do
//! not establish grow-only for arbitrary backends. [`MemoryStore`] **discharges**
//! it (its occupied-different branch fails closed without mutation; the law never
//! leans on hash injectivity). This is the invariant a future GC/eviction design
//! must consciously renegotiate, which is why deletion is a non-goal here.
//!
//! The `[proof target: …]` tags mark **deferred** obligations — the mechanized
//! Lean/TLA+ artifacts are NOT yet shipped (a follow-up stands up a forced-collision
//! TLA+ model + Lean read/insert laws). What ships today is the design plus
//! executable counterparts in `tests/store.rs` for *most* of the laws. The one
//! exception is PO-STORE-3's `Collision` branch (divergent bytes under a live id):
//! because [`AddressedBytes`] always derives a real BLAKE3 id, that branch is only
//! reachable via a genuine hash collision, so it has **no** executable Rust
//! counterpart — it is the deferred forced-collision TLA+ model's job (tracked as a
//! follow-up issue), not something `tests/store.rs` exercises.
//!
//! # ⚠️ EXPERIMENTAL — default-off feature, API NON-FROZEN
//!
//! This module is gated behind the default-**off** `unstable-store` cargo feature, and
//! its trait API is **NOT frozen**: signatures may change without a breaking-
//! change ceremony until the catalog stabilizes (epic #30's release ladder).
//! The seam defines **no new wire bytes of its own** — it stores bytes whose
//! layout is owned elsewhere (canonical dag-cbor when written through the typed
//! [`put_node`](NodeStoreExt::put_node) / [`put_checked`](NodeStoreExt::put_checked) doors; the raw [`put`](NodeStoreExt::put) is unchecked) — so nothing here is added to
//! `tests/vectors.json` (the frozen cross-language parity gate deliberately
//! excludes experimental surfaces).
//!
//! # Example
//!
//! ```
//! use content_addressable::store::{MemoryStore, NodeStoreExt as _};
//! use content_addressable::{canonical, ContentAddressable, ContentError};
//! use serde::{Deserialize, Serialize};
//!
//! #[derive(Debug, PartialEq, Serialize, Deserialize)]
//! struct Record {
//! name: String,
//! }
//!
//! impl ContentAddressable for Record {
//! fn canonical_form(&self) -> Result<Vec<u8>, ContentError> {
//! canonical::to_canonical_dagcbor(self)
//! }
//! }
//!
//! let mut store = MemoryStore::new();
//! let record = Record { name: "alpha".into() };
//!
//! // The seam derives the address from the content (PO-STORE-1)...
//! let id = store.put_node(&record).unwrap();
//! assert_eq!(id, record.content_id().unwrap());
//!
//! // ...and the identity-preserving read hands back exactly what the id names.
//! let back: Record = store.get_node(&id).unwrap();
//! assert_eq!(back, record);
//! ```
//!
//! With the `unstable-merkle` feature also enabled, a whole [`MerkleNode`] DAG is
//! reconstructible from its root id the same way — see `tests/store.rs` (the
//! seam's whole test suite lives there, separated from source) for the
//! traversal pattern and the laws' executable counterparts.
//!
//! [`MerkleNode`]: crate::merkle::MerkleNode
use Entry;
use BTreeMap;
use DeserializeOwned;
use cratecanonical;
use crateContentId;
use crateContentError;
use crate;
/// Store-layer errors.
///
/// Deliberately a **separate enum**, not new variants on the frozen
/// [`ContentError`] (freeze minimally — the frozen surface is untouched):
/// `NotFound` and backend failures are store concerns, while every
/// content-integrity failure is carried verbatim in the
/// [`Content`](StoreError::Content) variant so callers can still match on the
/// exact [`ContentError`] mode (verification, decoding, non-canonical, …).
///
/// `#[non_exhaustive]` because the API is experimental: further variants (e.g.
/// batching) may arrive additively. The [`Backend`](StoreError::Backend) variant a
/// fallible disk/network store needs is already present.
/// An **address-consistent** byte slice: bytes paired with the id they derive —
/// the only thing a [`NodeStore::insert`] can be handed.
///
/// It witnesses exactly one relationship — `id() == from_canonical_bytes(bytes())`
/// — and deliberately **not** canonicality. The id comes from the *unchecked*
/// [`ContentId::from_canonical_bytes`], and [`NodeStoreExt::put`] accepts any byte
/// slice, so `bytes()` may be non-canonical dag-cbor (validate ingest with
/// [`put_checked`](NodeStoreExt::put_checked); establish typed identity with
/// [`get_node`](NodeStoreExt::get_node)). A backend author must NOT infer
/// canonicality from this type.
///
/// The pair is unforgeable: the field is private and the constructor is
/// crate-internal, so *only the sealed seam* mints one (from bytes it hashes). An
/// external caller cannot construct a mismatched `(id, bytes)` pair, so a backend
/// can never be poisoned with bytes that do not derive their key. This moves
/// PO-STORE-1A's sealing from "the seam promises to derive the id" to "a backend
/// cannot even be handed a wrong one".
///
/// The unforgeability is compiler-enforced — neither of these builds downstream:
///
/// ```compile_fail
/// # use content_addressable::store::AddressedBytes;
/// // the id-deriving constructor is crate-internal:
/// let _ = AddressedBytes::new(b"anything");
/// ```
///
/// ```compile_fail
/// # use content_addressable::{ContentId, store::AddressedBytes};
/// // the fields are private, so a mismatched literal cannot be built either:
/// let _ = AddressedBytes { id: ContentId::from_canonical_bytes(b"a"), bytes: b"b" };
/// ```
/// The raw [`NodeStore`] operation a [`StoreError::Backend`] failure occurred in —
/// so a backend error names what it was doing.
/// The narrow seam every structure traverses: raw fetch and store of bytes, keyed
/// by [`ContentId`] (canonicality is the typed doors' concern, not this raw seam's).
///
/// Backends implement **only** these two operations. The verified operations —
/// the ones structures actually call — live in [`NodeStoreExt`], which is
/// blanket-implemented and cannot be overridden, so verify-on-read
/// (PO-STORE-2) holds no matter who wrote the backend.
///
/// The trait is dyn-compatible on purpose: structures can hold
/// `&S where S: NodeStore + ?Sized` or `Box<dyn NodeStore>`, and the blanket
/// [`NodeStoreExt`] impl covers the `dyn` form too.
/// The operations structures actually call: verified reads and
/// identity-deriving writes over any [`NodeStore`].
///
/// Blanket-implemented for every `NodeStore` and **sealed by coherence**: the
/// blanket impl below is necessarily the *only* impl (any other would overlap
/// it), so no backend can supply its own body for these methods. Identity —
/// both deriving it on write ([`put`](Self::put)) and checking it on read
/// ([`get`](Self::get)) — lives here, never in a backend, so PO-STORE-1 and
/// PO-STORE-2 hold for arbitrary, even adversarial, backends. (A *provided*
/// trait method would not do: implementors can override those.)
///
/// The typed doors [`get_node`](Self::get_node) /
/// [`decode_verified_bytes`](Self::decode_verified_bytes) / [`put_node`](Self::put_node)
/// are generic methods here rather than free functions: [`NodeStore`] itself
/// stays object-safe (its two methods are non-generic), and `dyn NodeStore`
/// still receives every method on this trait through the blanket impl — a
/// generic method on an extension trait costs no object-safety on the base.
// Forwarding impls so the verified surface composes with the advertised dynamic and
// borrowed forms: `VerifiedStore::new(Box::<dyn NodeStore>::new(..))` and
// `VerifiedStore::new(&mut backend)` both need `B: NodeStore`. (Method calls already
// worked through deref; wrapping a backend in the facade needs the trait itself.)
/// The in-memory reference backend: a grow-only `id → bytes` map.
///
/// This is the test substrate every structure issue builds on, and a real
/// backend for ephemeral use. It is **grow-only** (PO-STORE-3): there is no
/// deletion — a future GC/eviction design must renegotiate that law
/// explicitly, elsewhere.
///
/// Derives `PartialEq`/`Eq` so tests can assert store-state equivalence (e.g.
/// insertion-order independence) directly.
/// A verified facade over any [`NodeStore`] backend: it exposes **only** the
/// verified operations, each dispatched to [`NodeStoreExt`] by fully-qualified
/// syntax, so a backend's own inherent method of the same name can never intercept
/// the call.
///
/// The blanket [`NodeStoreExt`] impl is sealed — a backend cannot *replace the
/// trait implementation*. But that is not the same as "unskippable": ordinary
/// `store.get(&id)` on a concrete type resolves to an inherent `fn get` if the type
/// defines one, because Rust prefers inherent methods in method-call resolution.
/// Code that must not be bypassed should therefore hold a `VerifiedStore<B>` (or
/// call `NodeStoreExt::get(store, id)` via UFCS) rather than a bare `B: NodeStore`
/// on which `.get(..)` might resolve to something unverified.