forked from WithAutonomi/ant-node
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommitment_state.rs
More file actions
1658 lines (1519 loc) · 71.5 KB
/
Copy pathcommitment_state.rs
File metadata and controls
1658 lines (1519 loc) · 71.5 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
//! Responder-side commitment builder + rotation state.
//!
//! Phase 2b of the v12 storage-bound audit design. Builds, signs, and
//! caches a [`StorageCommitment`] over the responder's currently-stored
//! key set; serves audit lookups by `expected_commitment_hash`; retains
//! the previous commitment across one rotation so an audit pinned to it
//! does not false-fail at the rotation boundary (v5/v12 §4 retention).
//!
//! Rotation strategy:
//!
//! - `rotate(new_built)` atomically replaces `current` with `new_built`
//! and demotes the prior `current` to `previous`. The prior
//! `previous` is dropped.
//! - `lookup(hash)` reads the in-memory map and returns an [`Arc`] to
//! the matching `BuiltCommitment`, keeping it alive for the audit
//! response regardless of subsequent rotation (mirrors the `ArcSwap`
//! semantics specified in v6 §2: an in-flight reader holding its
//! `Arc` is unaffected by a concurrent rotate).
//!
//! Retention is persisted across restart (ADR-0004 A1): [`ResponderCommitmentState::snapshot`]
//! captures the signed commitments + their key sets + gossip stamps, and
//! [`ResponderCommitmentState::restore`] reloads them and rebuilds each tree from
//! its persisted key set — so an honest restarted node can answer every pin that
//! is still inside its answerability window, and an unanswerable pin is provable
//! misbehaviour rather than an honest crash-restart. Trees are otherwise rebuilt
//! from `LmdbStorage` at the next rotation tick. Memory cost is bounded by
//! `2 × (key_count × ~64 bytes + signature_size)` — for 10k keys, ~1.3 MB.
use std::sync::Arc;
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use parking_lot::RwLock;
use saorsa_pqc::api::sig::MlDsaSecretKey;
use serde::{Deserialize, Serialize};
use crate::ant_protocol::XorName;
use crate::replication::commitment::{
commitment_hash, sign_commitment, verify_commitment_signature, CommitmentError, MerkleTree,
StorageCommitment,
};
/// Auditor-side per-peer commitment state.
///
/// Holds two things that together implement v10/v12 §2 step 5 and §6:
/// - `last_commitment`: the most recently received, verified, signed
/// commitment from this peer. `None` if we've evicted it (TTL,
/// sybil cap, peer-removed) or never received one.
/// - `commitment_capable`: a **sticky** boolean that flips to `true`
/// on the first successful gossip ingest and NEVER reverts. Used
/// by holder-eligibility (§6) and bootstrap-claim shield: a peer
/// that has at least once proven it speaks v12 is forever held to
/// that standard. Without stickiness, a peer could flip the flag
/// off by silencing its gossip and downgrade to the weaker legacy
/// audit path.
#[derive(Debug, Clone)]
pub struct PeerCommitmentRecord {
/// Last verified commitment, or `None` if evicted/expired. PRIVATE so it can
/// only be mutated through [`Self::set_commitment`] / [`Self::clear_commitment`],
/// which keep `cached_hash` in lockstep (codex#2 — a stray
/// `record.last_commitment = …` would otherwise stale the cached hash). Read
/// it via [`Self::last_commitment`].
last_commitment: Option<StorageCommitment>,
/// `commitment_hash(last_commitment)`, cached so the per-cycle verifier
/// snapshot doesn't re-serialize + re-hash every peer's ~5 KiB commitment
/// each verification round (§13). Kept in sync via [`Self::set_commitment`]
/// / [`Self::clear_commitment`]; `None` exactly when `last_commitment` is
/// `None`.
cached_hash: Option<[u8; 32]>,
/// Sticky: true once this peer has gossiped a valid commitment.
/// Set on ingest. Never set back to false except by full
/// `PeerRemoved` cleanup.
pub commitment_capable: bool,
/// When `last_commitment` was received. Used for TTL on the
/// commitment itself (independent of the `commitment_capable`
/// stickiness — losing the commitment via TTL doesn't make us
/// forget the peer ever spoke v12).
pub received_at: Instant,
/// Last time we performed an ML-DSA signature verify for this
/// peer's commitment. Used to enforce the §2 step 3 rate limit
/// (at most one sig verify per peer per 60s).
pub last_sig_verify_at: Instant,
}
impl PeerCommitmentRecord {
/// Construct from a freshly-verified commitment. `commitment_capable`
/// is set to `true` here and must remain so for the lifetime of the
/// record.
#[must_use]
pub fn from_verified(commitment: StorageCommitment, now: Instant) -> Self {
let cached_hash = commitment_hash(&commitment);
Self {
last_commitment: Some(commitment),
cached_hash,
commitment_capable: true,
received_at: now,
last_sig_verify_at: now,
}
}
/// Mark commitment-capable without storing a commitment (used when
/// we've TTL-expired the commitment itself but want to remember the
/// peer has spoken v12 before).
#[must_use]
pub fn capable_but_no_commitment(now: Instant) -> Self {
Self {
last_commitment: None,
cached_hash: None,
commitment_capable: true,
received_at: now,
last_sig_verify_at: now,
}
}
/// The stored commitment, if any. Read-only view of the private field.
#[must_use]
pub fn last_commitment(&self) -> Option<&StorageCommitment> {
self.last_commitment.as_ref()
}
/// The cached `commitment_hash` of the stored commitment (§13) — `None`
/// when no commitment is held. Avoids re-serializing/re-hashing on every
/// verifier snapshot.
#[must_use]
pub fn commitment_hash(&self) -> Option<[u8; 32]> {
self.cached_hash
}
/// Replace the stored commitment and refresh the cached hash together, so
/// the two never drift.
pub fn set_commitment(&mut self, commitment: StorageCommitment, now: Instant) {
self.cached_hash = commitment_hash(&commitment);
self.last_commitment = Some(commitment);
self.received_at = now;
}
/// Drop the stored commitment and its cached hash together.
pub fn clear_commitment(&mut self) {
self.last_commitment = None;
self.cached_hash = None;
}
}
/// A fully-built commitment: signed wire blob, cached hash, Merkle tree
/// for inclusion proofs, and a sorted leaf-index lookup for the auditor's
/// `leaf_index` field.
///
/// Held inside an [`Arc`] so audit responders can grab a reference and
/// build a reply without holding the [`ResponderCommitmentState`] read
/// lock for the duration of the response.
pub struct BuiltCommitment {
/// The signed wire blob.
commitment: StorageCommitment,
/// `commitment_hash(commitment)` — cached so audit lookups don't
/// re-serialize on every match.
cached_hash: [u8; 32],
/// The Merkle tree behind the commitment. `path_for(key)` produces the
/// inclusion proof and `key_index(key)` reconstructs a key's leaf index in
/// `O(log n)` — so no separate `sorted_keys` Vec is kept (it duplicated the
/// keys already in `tree.leaves`, §14).
tree: MerkleTree,
}
impl BuiltCommitment {
/// Build a commitment over `entries = [(key, bytes_hash), ...]` and
/// sign it with `secret_key`.
///
/// `entries` does not need to be sorted (the inner [`MerkleTree`]
/// sorts internally); `sender_peer_id` is bound into the signature
/// and the commitment.
///
/// # Errors
///
/// Returns the wrapped [`CommitmentError`] on empty key sets,
/// over-cap key counts, duplicates, or signing failures.
pub fn build(
entries: Vec<(XorName, [u8; 32])>,
sender_peer_id: &[u8; 32],
secret_key: &MlDsaSecretKey,
sender_public_key: &[u8],
) -> Result<Self, CommitmentError> {
let tree = MerkleTree::build(entries)?;
Self::build_from_tree(tree, sender_peer_id, secret_key, sender_public_key)
}
/// Sign and wrap an ALREADY-BUILT Merkle tree. Lets callers that already
/// built the tree (e.g. the rotation no-op-root check, §11) avoid rebuilding
/// it inside [`Self::build`].
///
/// # Errors
///
/// Propagates signing / serialization failures, identical to [`Self::build`].
pub fn build_from_tree(
tree: MerkleTree,
sender_peer_id: &[u8; 32],
secret_key: &MlDsaSecretKey,
sender_public_key: &[u8],
) -> Result<Self, CommitmentError> {
let root = tree.root();
let key_count = tree.key_count();
let signature = sign_commitment(
secret_key,
&root,
key_count,
sender_peer_id,
sender_public_key,
)?;
let commitment = StorageCommitment {
root,
key_count,
sender_peer_id: *sender_peer_id,
sender_public_key: sender_public_key.to_vec(),
signature,
};
// `commitment_hash` only returns None on a postcard serialization
// failure, which for our fixed-size commitment cannot occur in
// practice (ML-DSA-65 signature is 3293 bytes). If it ever
// somehow does, surface as a SignatureFailed so callers don't
// need a new error variant for an unreachable case.
let cached_hash = commitment_hash(&commitment).ok_or_else(|| {
CommitmentError::SignatureFailed("commitment serialization failed".to_string())
})?;
Ok(Self {
commitment,
cached_hash,
tree,
})
}
/// The signed wire blob.
#[must_use]
pub fn commitment(&self) -> &StorageCommitment {
&self.commitment
}
/// The cached commitment hash. Equal to
/// [`crate::replication::commitment::commitment_hash`]
/// `(self.commitment())`.
#[must_use]
pub fn hash(&self) -> [u8; 32] {
self.cached_hash
}
/// The Merkle tree behind this commitment.
///
/// Used by the subtree-audit responder to plan a proof (select the
/// nonce-determined branch and read its sibling cut-hashes).
#[must_use]
pub fn tree(&self) -> &MerkleTree {
&self.tree
}
/// Inclusion path + leaf index for `key`, if it is in this
/// commitment. Returns `None` if `key` is not committed.
#[must_use]
pub fn proof_for(&self, key: &XorName) -> Option<(Vec<[u8; 32]>, u32)> {
let idx = self.tree.key_index(key)?;
let path = self.tree.path_for(key)?;
// u32 cast safe because MerkleTree::build rejects > MAX_COMMITMENT_KEY_COUNT.
let leaf_index = u32::try_from(idx).unwrap_or(u32::MAX);
Some((path, leaf_index))
}
/// Whether `key` is committed in this tree. Allocation-free membership
/// check (binary search over the sorted leaf keys) — equivalent to
/// `proof_for(key).is_some()` but without building the inclusion path, for
/// hot callers (e.g. the pruner's `is_held` veto) that only need the
/// boolean.
#[must_use]
pub fn contains_key(&self, key: &XorName) -> bool {
self.tree.contains_key(key)
}
/// The committed leaf keys — the key set persisted so this commitment can be
/// rebuilt after a restart without re-reading chunks.
#[must_use]
pub fn leaf_keys(&self) -> Vec<XorName> {
self.tree.leaf_keys()
}
/// Reconstruct a `BuiltCommitment` from a persisted signed commitment and a
/// `tree` rebuilt from its leaf keys — WITHOUT re-signing, so the pin
/// (`commitment_hash`) is preserved exactly across a restart (ML-DSA
/// signatures are randomized, so re-signing would change the pin).
///
/// Returns `None` (never trusts the blob) unless the rebuilt tree matches the
/// signed `root` and `key_count` AND the embedded-key ML-DSA signature still
/// verifies — so a corrupted or forged persisted commitment is rejected.
#[must_use]
pub fn from_persisted(commitment: StorageCommitment, tree: MerkleTree) -> Option<Self> {
if tree.root() != commitment.root || tree.key_count() != commitment.key_count {
return None;
}
if !verify_commitment_signature(&commitment) {
return None;
}
let cached_hash = commitment_hash(&commitment)?;
Some(Self {
commitment,
cached_hash,
tree,
})
}
}
/// Expected steady-state count of retained recently-gossiped commitments (the
/// last ~two, plus the current one) — used only as an initial `Vec` capacity
/// hint. Retention itself is TTL-based (see [`GOSSIP_ANSWERABILITY_TTL`] and
/// [`prune_slots`]), NOT a hard count: a commitment stays answerable for the
/// full TTL after its last gossip regardless of how many rotations occur.
///
/// (A hard count cap was a flawed proxy — under a restart with a shifted
/// responsible range, an in-window root could be evicted by count before its
/// TTL, which after grace removal would be a false conviction.)
const RETAINED_GOSSIPED_COMMITMENTS: usize = 2;
/// Hard upper bound on retained gossip records — a pure memory backstop against
/// pathological churn (e.g. an implausibly fast rotation producing many distinct
/// in-window roots). At the 1 h rotation cadence and 3 h TTL only ~3 distinct
/// roots are ever in-window, so this is never hit in practice; it exists solely
/// so `recently_gossiped` cannot grow unbounded.
const MAX_RETAINED_GOSSIPED_SLOTS: usize = 16;
/// How long a gossiped commitment stays answerable after it was last put on the
/// wire. Retention (and therefore the pruner's `is_held` deletion veto) is
/// anchored to gossip emission, not to the rotation timer or to distinct-hash
/// churn: a commitment record expires this long after its last `mark_gossiped`,
/// even if the node keeps re-gossiping nothing new (the steady-state no-op
/// rotation case) or stops being responsible for all its keys.
///
/// Sized so it strictly dominates the longest realistic auditor pin lifetime —
/// well above the neighbor-sync gossip cadence and per-peer cooldown (≤1 h) —
/// while staying far below the prune hysteresis (days), so once a stale key
/// stops being gossiped the pruner reclaims it promptly. At
/// `RETAINED_GOSSIPED_COMMITMENTS = 2` this is `(2 + 1) ×` the 1 h rotation
/// interval = 3 h.
pub(crate) const GOSSIP_ANSWERABILITY_TTL: Duration = Duration::from_secs(3 * 3600);
/// Extra answerability margin applied ONLY when reloading retention after a
/// restart (ADR-0004 A1). A gossip-stamp refresh in the last persist window may
/// not have been flushed before an unclean restart, so a persisted deadline can
/// be slightly early. Adding this margin on reload guarantees an honest node
/// never *under*-retains across a restart (it may over-retain by the margin,
/// which is harmless — it only makes the responder answer a little longer, and a
/// data-deleter still fails the round-2 byte challenge). Sized well above the
/// persist interval + gossip cadence, far below the TTL.
const RESTART_STAMP_GRACE: Duration = Duration::from_secs(5 * 60);
/// One persisted retention slot (ADR-0004 A1): the signed commitment, its
/// committed key set (so the tree can be rebuilt without re-reading chunks), and
/// the wall-clock time its hash was last gossiped (`None` if never gossiped —
/// then it only survives reload while it is the current slot).
#[derive(Serialize, Deserialize)]
struct PersistedSlot {
commitment: StorageCommitment,
leaf_keys: Vec<XorName>,
/// Absolute wall-clock time (unix secs) at which this slot's answerability
/// expires. Storing the ABSOLUTE deadline (not the last-gossip time) makes
/// downtime count against the TTL: a node down past the deadline reloads the
/// slot as already expired. `None` if the slot was never gossiped — then it
/// survives reload only while it is the current slot.
expires_at_unix: Option<u64>,
}
/// Persisted-format version. Bump on any layout OR semantic change so an
/// incompatible on-disk snapshot is rejected (→ empty retention, which self-heals
/// via re-gossip) rather than silently misinterpreted (e.g. an old field read
/// under new semantics).
const RETENTION_FORMAT_VERSION: u32 = 1;
/// The persisted responder retention. Slots are newest-first; `has_current`
/// says whether `slots[0]` was the live advertised commitment.
#[derive(Serialize, Deserialize)]
pub struct PersistedRetention {
/// Format version (see [`RETENTION_FORMAT_VERSION`]); a mismatch is rejected.
version: u32,
slots: Vec<PersistedSlot>,
has_current: bool,
}
impl PersistedRetention {
/// Serialize for durable persistence (caller writes it atomically). `None`
/// on a serialization error, so the caller can refuse to overwrite the
/// durable file rather than truncate it.
#[must_use]
pub fn to_bytes(&self) -> Option<Vec<u8>> {
postcard::to_allocvec(self).ok()
}
/// Decode a persisted snapshot. `None` on a corrupt blob OR a version
/// mismatch — the caller then fails open LOCALLY (empty retention; the node
/// re-gossips a fresh root), which never grants a remote grace.
#[must_use]
pub fn from_bytes(bytes: &[u8]) -> Option<Self> {
let this: Self = postcard::from_bytes(bytes).ok()?;
(this.version == RETENTION_FORMAT_VERSION).then_some(this)
}
}
/// Responder retention state (ADR-0002).
///
/// Keeps the current (latest-rotated) commitment plus every commitment that was
/// recently gossiped and is still in-window (its `GOSSIP_ANSWERABILITY_TTL` has
/// not expired) — retention is TTL-based, not a fixed count. A
/// built-but-never-gossiped commitment is dropped on the next rotation unless
/// it gets gossiped. Rotation and gossip are the only paths that mutate this.
pub struct ResponderCommitmentState {
inner: RwLock<Inner>,
/// Test-only: `(pinned commitment hash, keys)` of each round-2
/// `SubtreeByteChallenge` this responder received. Lets an e2e test assert
/// that co-held sampled leaves are verified LOCALLY by the auditor (so this
/// responder receives NO byte challenge for them — the egress saving),
/// CORRELATED to a specific audited commitment (a freshly-rebuilt commitment
/// held by only one auditor pins uniquely to that auditor's audit). Never
/// read or written in production builds.
#[cfg(any(test, feature = "test-utils"))]
observed_byte_challenges: RwLock<Vec<([u8; 32], Vec<XorName>)>>,
}
/// A commitment hash that was emitted on the wire, with the monotonic instant at
/// which its answerability EXPIRES (`last_gossiped_at + GOSSIP_ANSWERABILITY_TTL`).
///
/// Storing the deadline rather than the last-gossip instant makes reload after a
/// restart robust: `restore` sets `expires_at = now + remaining` (pure addition),
/// so an OS reboot — where the monotonic clock resets and uptime can be far less
/// than the wall-clock age — cannot underflow and wrongly drop a still-in-window
/// root.
#[derive(Clone, Copy)]
struct GossipedAt {
hash: [u8; 32],
expires_at: Instant,
}
struct Inner {
/// Newest-first. When `has_current` is true, `slots[0]` is the current
/// (advertised) commitment; the rest — and, once retired, `slots[0]` too —
/// are retained only because their hash is still in `recently_gossiped` and
/// not yet expired.
slots: Vec<Arc<BuiltCommitment>>,
/// Whether `slots[0]` is the live, advertised current commitment. Set by
/// `rotate`; cleared by `retire_current` (and when the slot set empties).
/// When false, `current()` returns `None` — the node stops advertising and
/// re-gossiping the stale root, so it ages out by its gossip TTL — while
/// `lookup_by_hash` still answers any in-flight pin until then. This
/// decouples ADVERTISE (gossiped as current, refreshes the TTL) from ANSWER
/// (still resolvable during the TTL window).
has_current: bool,
/// Commitments recently emitted on the wire, newest-first, each stamped with
/// when it was last gossiped (in steady state the last ~two, but bounded by
/// the answerability TTL, not a fixed count). A commitment is retained iff it
/// is the live current one or its hash appears here with an unexpired stamp.
recently_gossiped: Vec<GossipedAt>,
}
impl Default for ResponderCommitmentState {
fn default() -> Self {
Self::new()
}
}
impl ResponderCommitmentState {
/// Empty state: no commitments yet. Audits before the first rotation
/// see `None` lookups and the auditor falls back to the legacy plain
/// digest path.
#[must_use]
pub fn new() -> Self {
Self {
inner: RwLock::new(Inner {
slots: Vec::with_capacity(RETAINED_GOSSIPED_COMMITMENTS + 1),
has_current: false,
recently_gossiped: Vec::with_capacity(RETAINED_GOSSIPED_COMMITMENTS),
}),
#[cfg(any(test, feature = "test-utils"))]
observed_byte_challenges: RwLock::new(Vec::new()),
}
}
/// Test-only: record an incoming round-2 byte challenge for `pin`.
#[cfg(any(test, feature = "test-utils"))]
pub fn record_byte_challenge(&self, pin: [u8; 32], keys: &[XorName]) {
self.observed_byte_challenges
.write()
.push((pin, keys.to_vec()));
}
/// Test-only: the distinct keys this responder has been asked to serve in
/// round-2 byte challenges pinned to `pin` since construction.
#[cfg(any(test, feature = "test-utils"))]
#[must_use]
pub fn byte_challenge_keys_for_pin(
&self,
pin: &[u8; 32],
) -> std::collections::BTreeSet<XorName> {
self.observed_byte_challenges
.read()
.iter()
.filter(|(p, _)| p == pin)
.flat_map(|(_, keys)| keys.iter().copied())
.collect()
}
/// Rotate: the freshly-rebuilt commitment becomes `current`. Slots that are
/// neither the new current nor among the last gossiped hashes are dropped
/// (a built-but-never-gossiped commitment does not linger).
pub fn rotate(&self, new_current: BuiltCommitment) {
let new_current = Arc::new(new_current);
let mut guard = self.inner.write();
guard.slots.insert(0, new_current);
guard.has_current = true;
prune_slots(&mut guard, Instant::now());
}
/// Retire the current commitment WITHOUT clearing retention: stop
/// advertising it (so `current()` returns `None`, the gossip-emit sites stop
/// re-emitting and re-stamping it, and it can age out by its gossip TTL),
/// while keeping it answerable via `lookup_by_hash` for any in-flight pin a
/// peer already formed — until that pin's gossip stamp expires.
///
/// Called when the node has no key it is still responsible for: it must no
/// longer claim to hold that data going forward, but must not strand a peer
/// mid-audit on a root it gossiped moments ago. A never-gossiped current is
/// simply dropped (nothing to stay answerable for).
pub fn retire_current(&self) {
let mut guard = self.inner.write();
guard.has_current = false;
prune_slots(&mut guard, Instant::now());
}
/// Record that `hash` was emitted on the wire (gossiped). Keeps every
/// in-window gossiped hash (unexpired `GOSSIP_ANSWERABILITY_TTL`) so the
/// matching commitments stay answerable (ADR-0002). Call at every gossip-emit site.
///
/// Re-gossiping a hash already present **refreshes** its answerability
/// deadline to now and moves it to the front: every time the node actually
/// puts a root on the wire — including re-emitting the current root in the
/// steady-state no-op-rotation case — its retention legitimately extends.
/// Conversely a root that stops being gossiped expires
/// `GOSSIP_ANSWERABILITY_TTL` after its last emission, which is what lets
/// an out-of-range key age out even when the no-op guard freezes the
/// committed key set.
pub fn mark_gossiped(&self, hash: [u8; 32]) {
let now = Instant::now();
let mut guard = self.inner.write();
mark_gossiped_locked(&mut guard, hash, now);
}
/// Atomically snapshot the current commitment to advertise AND mark it
/// gossiped, under a single lock. Returns the commitment to put on the wire,
/// or `None` if there is no live current (never rotated, or retired).
///
/// This is the ONLY correct way to gossip the current commitment: doing
/// `current()` then a separate `mark_gossiped()` is a TOCTOU — a concurrent
/// `retire_current`/`rotate` between the two could drop the slot, so the node
/// would emit a root the responder no longer retains (a peer pinning it would
/// get "unknown commitment hash" → false failure). Taking the snapshot and
/// the stamp in one critical section guarantees anything emitted is
/// simultaneously retained for its answerability TTL.
#[must_use]
pub fn current_for_gossip(&self) -> Option<Arc<BuiltCommitment>> {
let now = Instant::now();
let mut guard = self.inner.write();
if !guard.has_current {
return None;
}
let current = guard.slots.first().map(Arc::clone)?;
mark_gossiped_locked(&mut guard, current.cached_hash, now);
Some(current)
}
/// Atomically snapshot the current commitment to PIN IN A QUOTE and refresh
/// its answerability, under a single lock. Returns the live current
/// commitment, or `None` if there is no live current (never rotated, or
/// retired) — in which case the caller must quote the baseline with no pin.
///
/// ADR-0004 ("quoting is advertising"): issuing a quote that prices against
/// the current commitment must extend that commitment's answerability
/// exactly as gossiping it does, so a recently-quoted pin stays resolvable
/// for its TTL and a peer auditing it cannot false-fail an honest node.
/// This deliberately mirrors [`Self::current_for_gossip`]: same atomic
/// snapshot-and-stamp, same TOCTOU-free guarantee that anything a quote can
/// pin is simultaneously retained. It refreshes the CURRENT commitment only
/// — a retired or merely-retained-but-not-current commitment is never
/// returned here, so quote traffic can never keep a stale fat commitment
/// alive (it can only be answered, via `lookup_by_hash`, until its own
/// gossip/quote stamp lapses).
#[must_use]
pub fn current_for_quote(&self) -> Option<Arc<BuiltCommitment>> {
let now = Instant::now();
let mut guard = self.inner.write();
if !guard.has_current {
return None;
}
let current = guard.slots.first().map(Arc::clone)?;
mark_gossiped_locked(&mut guard, current.cached_hash, now);
Some(current)
}
/// Expire retention purely by the wall clock, without building, signing, or
/// rotating anything. Call once per rotation tick so a gossiped commitment's
/// answerability deadline advances even when the rotation no-op guard
/// returns early (unchanged committed set) or when the node has no
/// responsible keys to commit to. This is the time-driven half of the
/// retention contract — without it, a frozen `recently_gossiped` entry would
/// keep a stale key `is_held` forever.
pub fn age_out(&self) {
let mut guard = self.inner.write();
prune_slots(&mut guard, Instant::now());
}
/// Look up a commitment by its hash. Returns `Some(arc)` if `hash`
/// matches any retained slot. The returned `Arc` keeps the
/// [`BuiltCommitment`] alive for as long as the caller holds it,
/// even if a concurrent `rotate` ages it out of the retention buffer.
#[must_use]
pub fn lookup_by_hash(&self, hash: &[u8; 32]) -> Option<Arc<BuiltCommitment>> {
let guard = self.inner.read();
for c in &guard.slots {
if &c.cached_hash == hash {
return Some(Arc::clone(c));
}
}
None
}
/// Whether `key` is committed under any retained slot (the current
/// commitment plus any still-in-window gossiped ones) — i.e. whether a peer
/// could still pin a recently gossiped root and demand this key's bytes in a
/// round-2 byte challenge.
///
/// This is the SAME predicate the round-2 responder uses to decide a key is
/// "committed" (`handle_subtree_byte_challenge` calls `built.proof_for(key)`
/// on the pinned slot, which is committed iff `contains_key`), folded over
/// every retained slot. The pruner consults it before deleting an
/// out-of-range key, so "the pruner will not delete it" and "the responder
/// still owes an answer for it" are provably the same boolean and cannot
/// drift. `slots` holds at most `RETAINED_GOSSIPED_COMMITMENTS` + 1
/// commitments, and `contains_key` is an allocation-free binary search, so
/// this is a short, allocation-free read.
#[must_use]
pub fn is_held(&self, key: &XorName) -> bool {
self.inner.read().slots.iter().any(|c| c.contains_key(key))
}
/// Snapshot the current commitment to ADVERTISE, if any. Used by the gossip
/// piggyback path: emit `state.current()` on the next outbound
/// `NeighborSyncRequest`/`Response`. Returns `None` once the current
/// commitment has been retired (the node has no responsible keys), so the
/// node stops re-gossiping a stale root even though `lookup_by_hash` may
/// still answer it during its remaining TTL.
#[must_use]
pub fn current(&self) -> Option<Arc<BuiltCommitment>> {
let guard = self.inner.read();
if guard.has_current {
guard.slots.first().map(Arc::clone)
} else {
None
}
}
/// Number of commitment slots currently retained (the current commitment
/// plus any still-answerable recently-gossiped ones). Used only for the
/// v12 `commitment_rotated` event's `retained_slots` field; carries no
/// behavioural meaning.
#[must_use]
pub fn retained_slot_count(&self) -> usize {
self.inner.read().slots.len()
}
/// Drop every retained slot. Called when the local store has
/// transitioned to empty: keeping the previously-advertised
/// commitment alive would invite audit failures (we can no longer
/// answer for any of the keys we committed to), and would leave
/// remote auditors pinning a hash this node will never satisfy
/// again. After clearing, the gossip piggyback path will emit
/// `commitment: None` until a fresh rotation occurs.
///
/// This is the one sanctioned escape from the "callers MUST NOT
/// clear retention by any other mechanism" invariant — empty
/// storage means there is nothing to retain.
pub fn clear_all(&self) {
let mut guard = self.inner.write();
guard.slots.clear();
guard.has_current = false;
guard.recently_gossiped.clear();
}
/// Snapshot retention for durable persistence (ADR-0004 A1): each slot's
/// signed commitment + committed key set + wall-clock gossip stamp. Reloading
/// this after a restart makes every still-in-window pin answerable again, so
/// an unanswerable pin is provable misbehaviour, not an honest crash-restart.
#[must_use]
pub fn snapshot(&self) -> PersistedRetention {
let now_i = Instant::now();
let now_s = SystemTime::now();
let guard = self.inner.read();
let slots = guard
.slots
.iter()
.map(|c| {
let expires_at_unix = guard
.recently_gossiped
.iter()
.find(|g| g.hash == c.cached_hash)
.and_then(|g| {
// Persist the ABSOLUTE wall-clock deadline = now + remaining,
// so a restart accounts for downtime. Skip if already expired.
let remaining = g.expires_at.saturating_duration_since(now_i);
if remaining.is_zero() {
return None;
}
now_s
.checked_add(remaining)
.and_then(|w| w.duration_since(UNIX_EPOCH).ok())
.map(|d| d.as_secs())
});
PersistedSlot {
commitment: c.commitment().clone(),
leaf_keys: c.leaf_keys(),
expires_at_unix,
}
})
.collect();
PersistedRetention {
version: RETENTION_FORMAT_VERSION,
slots,
has_current: guard.has_current,
}
}
/// Reload retention from a persisted snapshot at startup (ADR-0004 A1).
/// Rebuilds each slot's tree from its persisted (content-addressed) key set,
/// verifies it against the signed root, converts wall-clock gossip stamps
/// back to the monotonic clock, drops corrupt or already-expired slots, and
/// enforces retention. Replaces any existing state.
pub fn restore(&self, persisted: &PersistedRetention) {
let now_i = Instant::now();
let now_s = SystemTime::now();
let mut guard = self.inner.write();
guard.slots.clear();
guard.recently_gossiped.clear();
guard.has_current = false;
// Track whether the FIRST persisted slot (the pre-restart current)
// restored successfully — `has_current` may only be honoured if it did,
// else a later slot would be wrongly promoted to current.
let mut first_slot_restored = false;
for (i, slot) in persisted.slots.iter().enumerate() {
let entries: Vec<_> = slot.leaf_keys.iter().map(|k| (*k, *k)).collect();
let Ok(tree) = MerkleTree::build(entries) else {
continue;
};
let Some(built) = BuiltCommitment::from_persisted(slot.commitment.clone(), tree) else {
continue;
};
let hash = built.cached_hash;
if i == 0 {
first_slot_restored = true;
}
guard.slots.push(Arc::new(built));
if let Some(exp_unix) = slot.expires_at_unix {
if let Some(expires_at) = wall_expiry_to_instant(exp_unix, now_s, now_i) {
guard
.recently_gossiped
.push(GossipedAt { hash, expires_at });
}
}
}
guard.has_current = persisted.has_current && first_slot_restored;
prune_slots(&mut guard, now_i);
}
}
/// Convert a persisted ABSOLUTE wall-clock expiry (unix secs) to a monotonic
/// [`Instant`] deadline, given the current wall-clock/monotonic pair. Returns
/// `None` if the deadline has already passed (downtime consumed the TTL). Uses
/// `now_i + remaining` (addition), so it never underflows across an OS reboot
/// where the monotonic clock has reset; `remaining` is clamped to the TTL so a
/// forward clock skew cannot over-extend answerability.
fn wall_expiry_to_instant(expires_unix: u64, now_s: SystemTime, now_i: Instant) -> Option<Instant> {
let expires_wall = UNIX_EPOCH.checked_add(Duration::from_secs(expires_unix))?;
// Apply RESTART_STAMP_GRACE to the persisted deadline BEFORE deciding expiry:
// the persisted deadline can be slightly early (a stamp refresh lost in the
// last persist window may have already carried the true deadline past the
// persisted one — even past `now`). Treating `persisted + grace` as the
// effective deadline means an honest node never under-retains across a
// restart. A slot only drops here if it expired MORE than the grace ago
// (genuine expiry — downtime still counts, minus the grace margin).
let effective_wall = expires_wall.checked_add(RESTART_STAMP_GRACE)?;
let remaining = effective_wall.duration_since(now_s).ok()?;
if remaining.is_zero() {
return None;
}
// Clamp so a forward wall-clock skew cannot over-extend beyond one TTL + grace.
now_i.checked_add(remaining.min(GOSSIP_ANSWERABILITY_TTL + RESTART_STAMP_GRACE))
}
/// ADR-0004: the responder commitment state is the quote generator's commitment
/// source. `current_binding_for_quote` snapshots the live current commitment's
/// `(key_count, pin)` and refreshes its answerability in one atomic step (via
/// [`ResponderCommitmentState::current_for_quote`]), so a quote that prices
/// against the current commitment keeps it answerable for its TTL.
impl crate::payment::quote::CommitmentSource for ResponderCommitmentState {
fn current_binding_for_quote(&self) -> Option<crate::payment::quote::QuoteBinding> {
self.current_for_quote()
.map(|built| crate::payment::quote::QuoteBinding {
key_count: built.commitment().key_count,
pin: built.hash(),
})
}
fn current_binding_snapshot(&self) -> Option<crate::payment::quote::QuoteBinding> {
// Read-only sibling of `current_binding_for_quote`: same live current
// commitment (via `current()`), but no gossip stamp — the price-floor
// consumer reads pricing state without extending answerability.
self.current()
.map(|built| crate::payment::quote::QuoteBinding {
key_count: built.commitment().key_count,
pin: built.hash(),
})
}
fn commitment_blob_for_pin(&self, pin: [u8; 32]) -> Option<Vec<u8>> {
// rmp-encode the `StorageCommitment` itself — the EXACT form the storer's
// `index_valid_sidecars` deserializes (`rmp_serde::from_slice::<StorageCommitment>`),
// so a sidecar shipped here resolves identically to one fetched via
// `GetCommitmentByPin`. Only retained pins resolve; a rotated-out pin
// yields `None` and the response simply carries no commitment.
let built = self.lookup_by_hash(&pin)?;
rmp_serde::to_vec(built.commitment()).ok()
}
}
/// Enforce retention as of `now`: first expire any gossip record older than
/// `GOSSIP_ANSWERABILITY_TTL`, then keep the live current slot (only while
/// `has_current`) and any slot whose hash is still among the unexpired
/// recently-gossiped hashes; drop the rest. Idempotent; preserves newest-first
/// order. This is the single place retention is enforced.
///
/// The current-slot exemption is conditional on `has_current`: once the current
/// commitment is retired (no responsible keys), `slots[0]` is no longer exempt
/// and ages out by its own gossip TTL exactly like any other retained slot —
/// the fix that stops a stale, continuously-re-gossiped current from pinning its
/// keys forever.
/// Stamp `hash` as gossiped at `now` (newest-first, de-duplicated, bounded to
/// `RETAINED_GOSSIPED_COMMITMENTS`) and re-run retention. Shared by
/// `mark_gossiped` and `current_for_gossip` so the snapshot-and-stamp can be one
/// critical section.
fn mark_gossiped_locked(inner: &mut Inner, hash: [u8; 32], now: Instant) {
inner.recently_gossiped.retain(|g| g.hash != hash);
inner.recently_gossiped.insert(
0,
GossipedAt {
hash,
expires_at: now + GOSSIP_ANSWERABILITY_TTL,
},
);
// Retention is TTL-based; truncation is only a memory backstop and must never
// drop an unexpired (still-in-window) record, so it caps at a value far above
// the number of roots that can be in-window at once.
inner
.recently_gossiped
.truncate(MAX_RETAINED_GOSSIPED_SLOTS);
prune_slots(inner, now);
}
fn prune_slots(inner: &mut Inner, now: Instant) {
// 1. TTL-expire gossip records first (the answerability anchor). A record
// whose answerability deadline has passed no longer keeps anything
// answerable, regardless of distinct-hash churn or rotation ticks.
inner.recently_gossiped.retain(|g| g.expires_at > now);
// 2. Keep the live current slot (only while has_current) + any slot still
// covered by an unexpired record. Snapshot the live hashes first to avoid
// borrowing `inner` twice (both collections are at most
// RETAINED_GOSSIPED_COMMITMENTS + 1 long).
let live: Vec<[u8; 32]> = inner.recently_gossiped.iter().map(|g| g.hash).collect();
let has_current = inner.has_current;
let mut idx = 0usize;
inner.slots.retain(|c| {
let keep = (has_current && idx == 0) || live.contains(&c.cached_hash);
idx += 1;
keep
});
// If nothing remains, there is no current slot to advertise.
if inner.slots.is_empty() {
inner.has_current = false;
}
}
// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------
#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
mod tests {
use super::*;
use crate::replication::commitment::{commitment_hash, leaf_hash, verify_path};
use saorsa_pqc::api::sig::ml_dsa_65;
fn key(byte: u8) -> XorName {
let mut k = [0u8; 32];
k[0] = byte;
k
}
fn bh(byte: u8) -> [u8; 32] {
[byte ^ 0x5A; 32]
}
fn keypair() -> (saorsa_pqc::api::sig::MlDsaPublicKey, MlDsaSecretKey) {
ml_dsa_65().generate_keypair().unwrap()
}
/// ADR-0004 A1: retention survives a restart. A snapshot → serialize →
/// deserialize → restore into a fresh state keeps the exact pre-restart pin
/// answerable (signature preserved, not re-signed) and its keys held — so an
/// honest restarted node is not falsely convicted once grace is removed.
#[test]
fn retention_survives_restart_via_snapshot_reload() {
let (pk, sk) = keypair();
let pk_bytes = pk.to_bytes();
// Content-addressed leaves (bytes_hash := key), matching production.
let entries: Vec<_> = (1..=5u8).map(|i| (key(i), key(i))).collect();
let built = BuiltCommitment::build(entries, &[0xAB; 32], &sk, &pk_bytes).unwrap();
let pin = built.hash();
let state = ResponderCommitmentState::new();
state.rotate(built);
state.mark_gossiped(pin);
assert!(state.lookup_by_hash(&pin).is_some());
assert!(state.is_held(&key(3)));
// "Restart": snapshot -> bytes -> reload into a fresh state.
let bytes = state.snapshot().to_bytes().expect("serialize");
let reloaded = PersistedRetention::from_bytes(&bytes).expect("deserialize");
let fresh = ResponderCommitmentState::new();
fresh.restore(&reloaded);
// The pre-restart pin is still answerable, with the SAME hash, and its
// committed keys are still held.
let got = fresh.lookup_by_hash(&pin).expect("pin survives restart");
assert_eq!(got.hash(), pin, "pin preserved (not re-signed)");
assert!(
fresh.is_held(&key(3)),
"committed key still held after restart"
);
}
/// A corrupt snapshot blob decodes to `None`, so the caller fails open with
/// empty retention rather than trusting garbage.
#[test]
fn corrupt_retention_snapshot_is_rejected() {
assert!(PersistedRetention::from_bytes(&[0xffu8; 9]).is_none());
}
/// A snapshot from an incompatible format version is rejected (→ empty
/// retention), not silently misdecoded.
#[test]
fn wrong_format_version_is_rejected() {
let entries: Vec<_> = (1..=3u8).map(|i| (key(i), key(i))).collect();
let (pk, sk) = keypair();
let built = BuiltCommitment::build(entries, &[9; 32], &sk, &pk.to_bytes()).unwrap();
let bad = PersistedRetention {
version: RETENTION_FORMAT_VERSION + 1,
slots: vec![PersistedSlot {
commitment: built.commitment().clone(),
leaf_keys: vec![key(1)],
expires_at_unix: None,
}],
has_current: true,
};
let bytes = bad.to_bytes().expect("serialize");
assert!(PersistedRetention::from_bytes(&bytes).is_none());
}
/// ADR-0004 A1 restart grace: a persisted deadline that is slightly in the
/// PAST (within `RESTART_STAMP_GRACE`, e.g. a stamp refresh lost in the last
/// persist window before an unclean restart) must still be answerable — an
/// honest node never under-retains across restart. A deadline older than the
/// grace is genuinely expired and dropped (downtime still counts).
#[test]
fn restore_grace_retains_slightly_stale_deadline_but_drops_expired() {
let (pk, sk) = keypair();
let pk_bytes = pk.to_bytes();
let entries: Vec<_> = (1..=3u8).map(|i| (key(i), key(i))).collect();
let built = BuiltCommitment::build(entries.clone(), &[0xCD; 32], &sk, &pk_bytes).unwrap();
let pin = built.hash();
let leaf_keys: Vec<_> = entries.iter().map(|(k, _)| *k).collect();
let now_unix = SystemTime::now()
.duration_since(UNIX_EPOCH)
.expect("after epoch")
.as_secs();
let make = |expires_at_unix: Option<u64>| PersistedRetention {
version: RETENTION_FORMAT_VERSION,
slots: vec![PersistedSlot {
commitment: built.commitment().clone(),
leaf_keys: leaf_keys.clone(),
expires_at_unix,
}],
has_current: false, // not current -> retention depends on the stamp