Skip to main content

hyprstream_pds/
at9p_duplicity.rs

1//! B2 (#886): KERI-style **duplicity detection** — the `duplicity-check` layer
2//! that wraps B1's [`validate_successor`] (#885) — and B3 (#887): the
3//! empty/exhausted `next_key_commitments` **commitment-lifecycle semantics**.
4//!
5//! B1 answers "is this candidate an authorized successor of *this one*
6//! predecessor?" purely and locally. That is necessary but **not sufficient**
7//! for `did:at9p` trust: an attacker holding stolen pre-committed keys, or an
8//! equivocating identity holder, can mint a *second, individually-valid*
9//! successor that diverges from the honest chain (design #879 §7.2, threats
10//! A7/A12). B1 accepts each fork in isolation; only a client that remembers what
11//! it already accepted can tell they are a fork.
12//!
13//! # The watermark (R6 — the #879 BLOCKING-finding remediation)
14//!
15//! This layer persists, **per DID**, a high-watermark of exactly the pair design
16//! #879 §7.2/R6 mandates:
17//!
18//! > `(epoch, H512(accepted record))` — the epoch **and** the accepted record
19//! > digest, never the bare epoch.
20//!
21//! A bare-epoch watermark is the exact bug the BLOCKING review found: an
22//! attacker's `epoch N+1` exceeds a naive watermark `N` while silently replacing
23//! the honest key state, and "accept the max epoch" would *actively select the
24//! attacker's fork*. Carrying the digest makes divergence detectable and makes
25//! max-epoch selection impossible by construction:
26//!
27//! * a candidate that advances the chain **must chain through the persisted
28//!   watermark digest** (its `predecessor` must be the watermark head) — a
29//!   higher-epoch record that chains through a *different* head is a fork, not
30//!   progress ([`DuplicityKind::HigherEpochFork`]);
31//! * a candidate at `epoch == watermark.epoch` with a **different** digest is a
32//!   same-epoch fork ([`DuplicityKind::SameEpochFork`]);
33//! * any candidate at `epoch < watermark.epoch` is a branch reaching an
34//!   already-passed epoch ([`DuplicityKind::BelowWatermarkFork`]) — we hold only
35//!   the high-watermark, not full history, so a record below it is never
36//!   preferred and never silently dropped: it fails closed.
37//!
38//! Every one of those is **duplicity: hard fail-closed for that DID plus an
39//! operator alarm** — never a mere "lower-epoch reject", never a fork selection.
40//! The watermark advances **only** on a non-divergent, honestly-anchored
41//! successor. Non-advancing verdicts are classified from the candidate's own
42//! digest/epoch without running B1 (see [`DuplicityKind`] on why the alarm is an
43//! *unauthenticated* divergence indication).
44//!
45//! # B3 (#887): empty / exhausted commitment semantics
46//!
47//! `next_key_commitments` governs whether an identity can *ever* rotate again:
48//!
49//! * **Empty at genesis = declared-immutable identity.** Legal and useful (design
50//!   §7.1): the chain is frozen at genesis by construction and no update-record is
51//!   ever a valid successor. B1 already enforces this ([`SuccessorError::
52//!   ImmutableIdentity`]); here it is formalized as a **terminal watermark** —
53//!   [`Watermark::terminal`] is set the moment such a state is recorded, and this
54//!   layer refuses to admit any successor against a terminal watermark without
55//!   even re-running B1.
56//! * **A rotation to empty commitments = exhausted / frozen-forever.** A holder
57//!   MAY publish a final rotation whose new capsule commits to *no* further keys.
58//!   That final rotation is accepted (it is a valid successor of its predecessor);
59//!   the resulting state is terminal, and the identity is frozen at that epoch
60//!   forever. This is a **feature, not an error** (design §7.1): there is no
61//!   recovery path, because a recovery path is a backdoor.
62//!
63//! Both collapse onto the same terminal-watermark mechanism: an identity whose
64//! accepted head pre-commits to nothing admits no successor, ever.
65//!
66//! # B4 (#888): durable alarm routing
67//!
68//! This layer only *raises* the duplicity signal, as a typed [`DuplicityAlarm`]
69//! delivered to a pluggable [`DuplicityAlarmSink`]. [`WalDuplicityAlarmSink`]
70//! provides the production route: an fsync-on-write, **hybrid-signed**,
71//! hash-chained journal with a **signed** head checkpoint, plus a structured
72//! operator alarm through tracing / OTel. Detection and response remain
73//! decoupled; callers that intentionally do not need durable routing may still
74//! select [`NoopAlarmSink`] explicitly.
75//!
76//! ## Tamper-evidence (issue #888 acceptance: "durably recorded, tamper-evident")
77//!
78//! Every WAL entry AND the head checkpoint are signed with the **same pinned
79//! hybrid composite** (EdDSA + ML-DSA-65) the at9p record path and the S7
80//! `mac::audit` store use ([`hyprstream_crypto::cose_sign::sign_composite`],
81//! `require_pq = true`). This is what makes the "tamper-evident" claim true
82//! against a **local writer that does not hold the signing key**:
83//!
84//! * altering any entry breaks its BLAKE3 chain link *and* its signature;
85//! * rewriting the WAL to a shorter/forged valid chain is impossible without
86//!   forging every replaced entry's hybrid signature;
87//! * truncating the tail leaves the earlier entries individually valid, but the
88//!   **signed** checkpoint still anchors the true head — and the checkpoint
89//!   cannot be rolled back to the truncated head without forging *its* hybrid
90//!   signature.
91//!
92//! **Residual limit (honest, mirrors `WalAuditStore` in `mac::audit`):** the
93//! checkpoint is a *local* anchor. An attacker who can delete BOTH the journal
94//! and the checkpoint entirely re-baselines to an empty log — total erasure is
95//! not distinguishable from "no alarms yet" without an *off-host* anchor
96//! (replicating the signed head to a second host / OTel). That off-host anchor
97//! is deliberately out of scope here. What this store *does* guarantee: no
98//! tampering, reordering, middle-deletion, or tail-truncation goes undetected
99//! unless the attacker also holds the node's audit signing key.
100//!
101//! ## Wiring (finding remediation)
102//!
103//! Because [`WalDuplicityAlarmSink::open`] requires the node's signing keys, the
104//! durable route is a real construction path
105//! ([`DuplicityGuard::with_durable_alarm`]), not a latent option: a production
106//! guard built that way routes every real [`DuplicityGuard::admit_successor`]
107//! detection to the signed, durable sink by construction. The `NoopAlarmSink`
108//! default ([`DuplicityGuard::new`]) is the **explicit test / opt-out** path,
109//! never the accidental production one. (The live mesh PEP that *drives*
110//! `admit_successor` in the running daemon is a separate epic step and is not
111//! claimed live here.)
112//!
113//! # Persistence seam (#886/#1004)
114//!
115//! [`WatermarkStore`] persists the complete accepted head/body together with
116//! its watermark and terminal state. [`InMemoryWatermarkStore`] supports unit
117//! tests; the running PDS implements the same contract with one synchronous
118//! atomic RocksDB value, so recovery cannot pair a new watermark with an old
119//! body (or vice versa).
120
121use std::collections::HashMap;
122use std::fs::{File, OpenOptions};
123use std::io::{Read, Write};
124use std::path::{Path, PathBuf};
125use std::sync::Arc;
126
127use ed25519_dalek::{SigningKey, VerifyingKey};
128use parking_lot::Mutex;
129
130use hyprstream_crypto::cose_sign::{sign_composite, verify_composite};
131use hyprstream_crypto::pq::{
132    ml_dsa_sk_to_vk_bytes, ml_dsa_vk_from_bytes, MlDsaSigningKey, MlDsaVerifyingKey,
133};
134
135use crate::at9p::{h512, Capsule, CapsuleBody, UpdateRecord, H512_LEN};
136use crate::at9p_chain::{validate_successor, ChainState, SuccessorError};
137use crate::at9p_gate::VerifiedCapsule;
138
139/// The persistent per-DID duplicity high-watermark: design #879 §7.2/R6's
140/// `(epoch, H512(accepted record))` pair, plus the terminal flag that carries
141/// B3 (#887) commitment-lifecycle state.
142///
143/// Storing the digest (not just the epoch) is the whole point of the
144/// remediation: it is what lets [`DuplicityGuard`] tell an honest continuation
145/// from a divergent fork and makes max-epoch fork selection impossible.
146#[derive(Clone, Copy, Debug, Eq, PartialEq)]
147pub struct Watermark {
148    /// Highest accepted epoch for this DID.
149    pub epoch: u64,
150    /// `H512` over the canonical bytes of the record accepted at [`Watermark::
151    /// epoch`] — the digest half of the R6 pair. A successor advancing the chain
152    /// must echo this in its `prev_record_digest`; a divergent digest at
153    /// `epoch <= this.epoch` is duplicity.
154    pub record_digest: [u8; H512_LEN],
155    /// `true` iff the accepted head pre-commits to **no** next keys — a
156    /// declared-immutable (empty at genesis) or exhausted (rotated-to-empty)
157    /// identity (B3, #887). A terminal watermark admits no successor, ever.
158    pub terminal: bool,
159}
160
161impl Watermark {
162    /// Project the watermark a freshly-accepted [`ChainState`] represents. The
163    /// state is terminal iff it pre-commits to nothing (B3).
164    fn from_state(state: &ChainState) -> Self {
165        Self {
166            epoch: state.epoch,
167            record_digest: state.record_digest,
168            terminal: state.next_key_commitments.is_empty(),
169        }
170    }
171}
172
173/// Provenance of the durable accepted head. This identifies which verified
174/// record supplies [`AcceptedAt9pState::current`] without claiming live key
175/// possession, endpoint reachability, admission, or global latest consensus.
176#[derive(Clone, Debug, Eq, PartialEq)]
177pub enum AcceptedAt9pProvenance {
178    /// The complete GATE-verified immutable genesis capsule is the head.
179    Genesis { cid512: String },
180    /// A pinned-hybrid signed successor accepted against the prior durable head.
181    Update { prev_record_digest: [u8; H512_LEN] },
182}
183
184/// Complete record retained as the accepted head.
185#[derive(Clone, Debug, Eq, PartialEq)]
186pub enum AcceptedAt9pHead {
187    Genesis(Capsule),
188    Update(UpdateRecord),
189}
190
191/// Typed, re-verifiable current `did:at9p` state exposed to identity-bound
192/// resolver/admission consumers.
193///
194/// `current` carries the current authorized signing keys, services, aliases,
195/// and commitments. Service entries remain signed claims to validate and try;
196/// this type deliberately carries no liveness, reach, possession, selection,
197/// or admission verdict.
198#[derive(Clone, Debug, Eq, PartialEq)]
199pub struct AcceptedAt9pState {
200    pub subject_cid512: String,
201    pub did: String,
202    pub epoch: u64,
203    pub head_digest: [u8; H512_LEN],
204    pub terminal: bool,
205    pub current: CapsuleBody,
206    /// Successor expiry. Genesis has no update expiry.
207    pub expires_at: Option<String>,
208    pub provenance: AcceptedAt9pProvenance,
209    head: AcceptedAt9pHead,
210}
211
212impl AcceptedAt9pState {
213    /// Construct the initial durable state only from the unforgeable GATE
214    /// witness. There is no caller/config seed constructor.
215    pub fn from_verified_genesis(verified: &VerifiedCapsule) -> anyhow::Result<Self> {
216        let capsule = verified.capsule().clone();
217        let chain = ChainState::genesis(&capsule)?;
218        anyhow::ensure!(
219            chain.subject_cid512 == verified.cid512(),
220            "verified genesis subject/cid mismatch"
221        );
222        Ok(Self {
223            subject_cid512: chain.subject_cid512.clone(),
224            did: verified.did(),
225            epoch: 0,
226            head_digest: chain.record_digest,
227            terminal: chain.next_key_commitments.is_empty(),
228            current: capsule.body.clone(),
229            expires_at: None,
230            provenance: AcceptedAt9pProvenance::Genesis {
231                cid512: chain.subject_cid512,
232            },
233            head: AcceptedAt9pHead::Genesis(capsule),
234        })
235    }
236
237    fn from_accepted_update(record: UpdateRecord) -> Self {
238        let chain = ChainState::from_validated_update(&record);
239        Self {
240            subject_cid512: chain.subject_cid512.clone(),
241            did: format!(
242                "{}{}",
243                crate::at9p_gate::DID_AT9P_PREFIX,
244                chain.subject_cid512
245            ),
246            epoch: chain.epoch,
247            head_digest: chain.record_digest,
248            terminal: chain.next_key_commitments.is_empty(),
249            current: record.new_capsule_body.clone(),
250            expires_at: Some(record.expires_at.clone()),
251            provenance: AcceptedAt9pProvenance::Update {
252                prev_record_digest: record.prev_record_digest,
253            },
254            head: AcceptedAt9pHead::Update(record),
255        }
256    }
257
258    /// Rebuild a stored genesis through the complete GATE pipeline.
259    pub fn from_persisted_genesis(bytes: &[u8]) -> anyhow::Result<Self> {
260        let capsule = Capsule::from_dag_cbor(bytes)?;
261        let cid512 = capsule.cid512()?;
262        let verified = crate::at9p_gate::verify_genesis_capsule(&cid512, bytes)
263            .map_err(|e| anyhow::anyhow!("persisted genesis GATE rejected: {e}"))?;
264        Self::from_verified_genesis(&verified)
265    }
266
267    /// Rebuild a successor previously committed by the accepted-state owner.
268    /// Canonical/schema validation is repeated and all derived watermark fields
269    /// are recomputed from the retained bytes.
270    pub fn from_persisted_update(bytes: &[u8]) -> anyhow::Result<Self> {
271        let record = UpdateRecord::from_dag_cbor(bytes)?;
272        // `subjectKeys` is a published set (#1188 / #1183): the record was signed
273        // by one of the revealed keys, not necessarily position 0. Re-verify by
274        // trying each published subject key and accepting the record iff its
275        // composite verifies under one of them — the "try each candidate" rule
276        // for a set with no wire-level selector. (Authorization-by-pre-commitment
277        // was already enforced when this record was first accepted through
278        // `validate_successor`; here we only re-confirm the retained bytes carry
279        // an intact signature by a published key.)
280        let mut last_err = None;
281        let verified = record.new_capsule_body.subject_keys.iter().any(|signer| {
282            match crate::at9p_sign::verify_update_record(&record, signer) {
283                Ok(()) => true,
284                Err(e) => {
285                    last_err = Some(e);
286                    false
287                }
288            }
289        });
290        anyhow::ensure!(
291            verified,
292            "persisted update signature rejected: {}",
293            last_err
294                .map(|e| e.to_string())
295                .unwrap_or_else(|| "no published subject key verified the record".to_owned())
296        );
297        Ok(Self::from_accepted_update(record))
298    }
299
300    /// Fail closed if the accepted update has expired at `now`. Genesis has no
301    /// successor expiry and remains current until a successor is accepted.
302    pub fn ensure_fresh(&self, now: &str) -> anyhow::Result<()> {
303        if let Some(expires_at) = &self.expires_at {
304            anyhow::ensure!(
305                crate::at9p_chain::datetime_before(now, expires_at)?,
306                "accepted did:at9p state expired at {expires_at} (now {now})"
307            );
308        }
309        Ok(())
310    }
311
312    pub fn watermark(&self) -> Watermark {
313        Watermark {
314            epoch: self.epoch,
315            record_digest: self.head_digest,
316            terminal: self.terminal,
317        }
318    }
319
320    /// Complete canonical head record for durable re-verification/recovery.
321    pub fn head(&self) -> &AcceptedAt9pHead {
322        &self.head
323    }
324
325    fn predecessor(&self) -> PredecessorRecord<'_> {
326        match &self.head {
327            AcceptedAt9pHead::Genesis(capsule) => PredecessorRecord::Genesis(capsule),
328            AcceptedAt9pHead::Update(record) => PredecessorRecord::Update(record),
329        }
330    }
331}
332
333/// The predecessor head the guard derives from its durable accepted state — a
334/// genesis [`Capsule`] (epoch 0) or an [`UpdateRecord`] (epoch ≥ 1). This is
335/// private so callers cannot supply predecessor authority.
336///
337/// # Why a record, not a [`ChainState`] (#961)
338///
339/// This is the **provenance boundary** for at9p key-rotation assurance. A
340/// [`ChainState`] is a plaintext struct: nothing relates its `record_digest` to
341/// its `next_key_commitments`, and B1's signer-authorization gate keys off the
342/// latter. The B2 watermark persists only `(epoch, H512(record))` — by design
343/// (R6) — so across a restart or a network-fed head, *only the digest survives*.
344/// A guard that accepted a caller-supplied `ChainState` and checked merely
345/// `predecessor.record_digest == watermark.record_digest` would trust
346/// `next_key_commitments` that are unverified against that digest: an attacker
347/// who knows the honest digest `D1` can fabricate
348/// `ChainState{record_digest:D1, next_key_commitments:[commit(K_evil)]}`, sign
349/// an epoch-2 record with `K_evil`, and pass every B1 gate — authorizing a key
350/// the real head never pre-committed. (Caller-supplied state as an authoritative
351/// PDP input is forbidden by the CLAUDE.md MAC rule; this is that rule applied
352/// to the chain layer.)
353///
354/// The guard therefore refuses any caller-supplied `ChainState`. It takes the
355/// predecessor **record**, recomputes `H512` over the record's canonical bytes,
356/// and anchors it against [`Watermark::record_digest`] *before* deriving the
357/// authoritative `ChainState`. A record that does not hash to the watermark
358/// cannot have its fields trusted: the `next_key_commitments` B1 keys off are
359/// thus proven to belong to the anchored head (a preimage attack on BLAKE3-512,
360/// not a caller lie). This is the structural enforcement of the
361/// [`admit_successor`](DuplicityGuard::admit_successor) contract that #959
362/// documented as an interim measure.
363#[derive(Clone, Copy, Debug)]
364enum PredecessorRecord<'a> {
365    /// The genesis capsule — the epoch-0 head. Presented when the watermark sits
366    /// at genesis. The caller MUST have already GATE-verified it (self-signature
367    /// and `H512(bytes) == cid512`); the guard re-anchors it against the
368    /// persisted genesis watermark here.
369    Genesis(&'a Capsule),
370    /// A previously-accepted update-record — the head at epoch ≥ 1. The guard
371    /// re-anchors it against the persisted watermark before trusting it.
372    Update(&'a UpdateRecord),
373}
374
375impl PredecessorRecord<'_> {
376    /// `H512` over the predecessor's canonical bytes — **recomputed**, never read
377    /// from a field — so the anchor compares the record's true digest against
378    /// [`Watermark::record_digest`]. This is the whole point of #961: the value
379    /// the watermark pins is verified to describe *these* bytes.
380    fn record_digest(&self) -> [u8; H512_LEN] {
381        match self {
382            PredecessorRecord::Genesis(cap) => h512(&cap.encode_value()),
383            PredecessorRecord::Update(rec) => h512(&rec.encode_value()),
384        }
385    }
386
387    /// Derive the authoritative [`ChainState`] from the record's own fields.
388    /// Only meaningful AFTER the guard has anchored
389    /// [`record_digest`](Self::record_digest) against the watermark: the
390    /// `next_key_commitments` carried by the returned state are the record's,
391    /// never a caller's claim.
392    fn derive_chain_state(&self) -> anyhow::Result<ChainState> {
393        match self {
394            PredecessorRecord::Genesis(cap) => ChainState::genesis(cap),
395            PredecessorRecord::Update(rec) => Ok(ChainState::from_validated_update(rec)),
396        }
397    }
398}
399
400/// Persistence seam for the complete accepted state and its per-DID duplicity
401/// watermark (#886/#1004).
402///
403/// Keyed by `subject_cid512` (the genesis cid that names the identity). The
404/// in-memory [`InMemoryWatermarkStore`] is provided for tests; the daemon/PDS
405/// supplies the durable atomic implementation.
406///
407/// Implementations must be safe for concurrent use (`Send + Sync`) and MUST
408/// serialize [`conditional_advance`](WatermarkStore::conditional_advance)
409/// across every guard sharing the store. A guard-local lock is only an
410/// optimization: the durable store is the authority and the conditional write
411/// is the security boundary.
412pub trait WatermarkStore: Send + Sync {
413    /// Load the complete accepted state. Implementations must re-verify that
414    /// the retained head bytes derive the returned watermark fields.
415    fn get(&self, subject_cid512: &str) -> anyhow::Result<Option<AcceptedAt9pState>>;
416
417    /// Advance from exactly `expected` to `state` as one atomic durable commit.
418    /// `None` means the identity must still be unseeded. There is deliberately
419    /// no unconditional public write API.
420    fn conditional_advance(
421        &self,
422        expected: Option<Watermark>,
423        state: &AcceptedAt9pState,
424    ) -> anyhow::Result<ConditionalAdvance>;
425}
426
427impl<T: WatermarkStore + ?Sized> WatermarkStore for Arc<T> {
428    fn get(&self, subject_cid512: &str) -> anyhow::Result<Option<AcceptedAt9pState>> {
429        (**self).get(subject_cid512)
430    }
431
432    fn conditional_advance(
433        &self,
434        expected: Option<Watermark>,
435        state: &AcceptedAt9pState,
436    ) -> anyhow::Result<ConditionalAdvance> {
437        (**self).conditional_advance(expected, state)
438    }
439}
440
441#[derive(Clone, Debug, Eq, PartialEq)]
442pub enum ConditionalAdvance {
443    Committed,
444    Conflict(Box<AcceptedAt9pState>),
445}
446
447/// In-memory [`WatermarkStore`] — a `Mutex<HashMap<..>>`. Suitable for tests and
448/// single-process use; **not** durable across restarts. Production wires this
449/// trait to the signed, checkpointed RocksDB store owned by the PDS service.
450#[derive(Default)]
451pub struct InMemoryWatermarkStore {
452    marks: Mutex<HashMap<String, AcceptedAt9pState>>,
453}
454
455impl InMemoryWatermarkStore {
456    pub fn new() -> Self {
457        Self::default()
458    }
459}
460
461impl WatermarkStore for InMemoryWatermarkStore {
462    fn get(&self, subject_cid512: &str) -> anyhow::Result<Option<AcceptedAt9pState>> {
463        Ok(self.marks.lock().get(subject_cid512).cloned())
464    }
465
466    fn conditional_advance(
467        &self,
468        expected: Option<Watermark>,
469        state: &AcceptedAt9pState,
470    ) -> anyhow::Result<ConditionalAdvance> {
471        let mut marks = self.marks.lock();
472        let current = marks.get(&state.subject_cid512).cloned();
473        if current.as_ref().map(AcceptedAt9pState::watermark) != expected {
474            return current.map_or_else(
475                || anyhow::bail!("conditional advance expected an existing head, but none exists"),
476                |current| Ok(ConditionalAdvance::Conflict(Box::new(current))),
477            );
478        }
479        marks.insert(state.subject_cid512.clone(), state.clone());
480        Ok(ConditionalAdvance::Committed)
481    }
482}
483
484/// Which of the three fork shapes tripped duplicity detection. B4 (#888) can use
485/// this to grade the operator response; all three are equally fail-closed here.
486///
487/// # Authentication of the divergent record (#961)
488///
489/// These verdicts are classified from the candidate's **own** epoch and
490/// recomputed `H512` against the persisted watermark — B1 is deliberately NOT
491/// run first. It cannot be: validating a candidate at `epoch <= watermark.epoch`
492/// needs its committing predecessor (the accepted record at `epoch - 1`), which
493/// R6 watermark-only persistence does not retain, and re-accepting a
494/// caller-supplied predecessor for that purpose is exactly the forgeable input
495/// #961 removed (the pre-#961 "B1-valid" property was validated against a
496/// caller-forged `ChainState`, i.e. hollow). A duplicity verdict is therefore an
497/// **unauthenticated divergence indication** — evidence that *something*
498/// presented a record diverging from the accepted history, not proof the
499/// identity holder signed it. The admission decision itself is unaffected
500/// (fail-closed either way); alarm consumers (B4/#888) must treat alarms as
501/// pointers for investigation, not as attributable equivocation proof.
502#[derive(Clone, Copy, Debug, Eq, PartialEq)]
503pub enum DuplicityKind {
504    /// A record at `epoch == watermark.epoch` with a **different** record digest
505    /// than the one accepted at that epoch — an equivocation indication (two
506    /// records at the same epoch).
507    SameEpochFork,
508    /// A record at `epoch < watermark.epoch`: a branch reaching an epoch the
509    /// client has already passed. We hold only the high-watermark, so this is
510    /// never preferred over it and never silently dropped — it fails closed.
511    BelowWatermarkFork,
512    /// A record at `epoch > watermark.epoch` that chains through a
513    /// predecessor other than the watermark head — a higher-epoch record on the
514    /// attacker's fork rather than the client's accepted history (design #879
515    /// §7.2, the "never select max epoch" case). Caught at the advance-path
516    /// anchor (#961): the presented predecessor record does not hash to the
517    /// watermark, so the candidate's higher epoch cannot chain through the
518    /// accepted head — and B1 never runs against the foreign head's commitments.
519    HigherEpochFork,
520}
521
522/// A typed duplicity signal handed to the [`DuplicityAlarmSink`]. Carries both
523/// sides of the divergence (the persisted watermark and the divergent record) so
524/// the routing layer (B4, #888) has everything it needs to audit or notify
525/// without re-deriving state.
526#[derive(Clone, Debug)]
527pub struct DuplicityAlarm {
528    /// The self-certifying DID subject whose chain forked.
529    pub subject_cid512: String,
530    /// Which fork shape was detected.
531    pub kind: DuplicityKind,
532    /// Epoch of the persisted, honestly-accepted watermark.
533    pub watermark_epoch: u64,
534    /// Digest of the persisted, honestly-accepted watermark record.
535    pub watermark_digest: [u8; H512_LEN],
536    /// Epoch of the divergent record. NOT authenticated — see [`DuplicityKind`]'s
537    /// "Authentication of the divergent record" note.
538    pub divergent_epoch: u64,
539    /// Recomputed `H512` of the divergent record's canonical bytes. NOT
540    /// authenticated — see [`DuplicityKind`].
541    pub divergent_digest: [u8; H512_LEN],
542}
543
544/// Sink for [`DuplicityAlarm`]s (B4/#888 seam). Detection raises; **routing** the
545/// signal to the S7 audit store and/or an operator notification path is B4's
546/// job. The guard has already committed to rejecting before this is called;
547/// durable implementations may synchronously fsync so returning from admission
548/// means the alarm is crash-durable.
549pub trait DuplicityAlarmSink: Send + Sync {
550    /// Handle a raised duplicity alarm. Called exactly once per detected fork,
551    /// after the guard has committed to failing closed.
552    fn raise(&self, alarm: &DuplicityAlarm);
553}
554
555const ALARM_WAL_MAGIC: &[u8; 8] = b"AT9PALM2";
556const ALARM_FIXED_PAYLOAD_LEN: usize = 1 + 8 + H512_LEN + 8 + H512_LEN;
557
558/// AAD binding for a per-entry signature. Distinct from
559/// [`ALARM_CHECKPOINT_AAD`] so an entry signature can never be replayed as a
560/// checkpoint signature (and vice-versa).
561const ALARM_ENTRY_AAD: &[u8] = b"at9p-duplicity-alarm-entry/1";
562/// AAD binding for the signed head-anchor checkpoint.
563const ALARM_CHECKPOINT_AAD: &[u8] = b"at9p-duplicity-alarm-checkpoint/1";
564
565/// Durable, tamper-evident B4 duplicity-alarm sink.
566///
567/// Each alarm is appended to a length-delimited WAL, linked to the previous
568/// entry by BLAKE3 (`entry_hash = BLAKE3(prev_hash || payload)`), **and signed**
569/// with the pinned hybrid composite (EdDSA + ML-DSA-65). `raise` returns only
570/// after `sync_all`, so a successfully recorded alarm survives a crash. Opening
571/// an existing WAL verifies every link AND every signature and refuses a
572/// truncated, forged, or modified journal (see the module-level tamper-evidence
573/// section for the exact guarantee and its residual limit). The same call emits
574/// a structured `ERROR` event on the `hyprstream.at9p.duplicity` target, which
575/// reaches stderr and OTLP through the process tracing subscriber and is
576/// therefore visible to operators.
577pub struct WalDuplicityAlarmSink {
578    path: PathBuf,
579    checkpoint_path: PathBuf,
580    ed_sk: SigningKey,
581    pq_sk: MlDsaSigningKey,
582    state: Mutex<AlarmWalState>,
583}
584
585struct AlarmWalState {
586    file: File,
587    head: [u8; 32],
588}
589
590impl WalDuplicityAlarmSink {
591    /// Open (or create) an alarm WAL, verifying its complete hash chain and
592    /// every entry/checkpoint signature before accepting new records. A corrupt,
593    /// forged, or truncated journal fails closed at startup.
594    ///
595    /// `ed_sk` / `pq_sk` are the node's audit signing keys (the same pinned
596    /// hybrid pair the at9p record path uses). Requiring them here is what makes
597    /// the durable route a real, signed construction path rather than an
598    /// unauthenticated sidecar.
599    ///
600    /// # Crash-window recovery
601    ///
602    /// A crash between an entry's WAL `fsync` and its checkpoint persist leaves
603    /// the WAL exactly **one entry ahead** of the checkpoint. That is a valid,
604    /// recoverable state: `open` accepts an exact checkpoint match **or** a
605    /// verified one-entry lag (the durable WAL head is authoritative), then
606    /// advances the checkpoint to the WAL head. Any larger divergence — or a
607    /// checkpoint that names a head the WAL does not reach — fails closed as
608    /// truncation/tamper.
609    pub fn open(
610        path: impl AsRef<Path>,
611        ed_sk: SigningKey,
612        pq_sk: MlDsaSigningKey,
613    ) -> anyhow::Result<Self> {
614        let path = path.as_ref().to_path_buf();
615        let checkpoint_path = path.with_extension("checkpoint");
616        if let Some(parent) = path.parent() {
617            std::fs::create_dir_all(parent)?;
618        }
619        let (ed_vk, pq_vk) = alarm_verifying_keys(&ed_sk, &pq_sk)?;
620
621        let mut file = OpenOptions::new()
622            .create(true)
623            .read(true)
624            .append(true)
625            .open(&path)?;
626        let mut bytes = Vec::new();
627        file.read_to_end(&mut bytes)?;
628        // Verify every hash link AND every hybrid signature; also recover the
629        // head just before the last entry so a one-entry WAL-ahead lag (crash
630        // window) can be distinguished from real truncation/tamper.
631        let (head, prev_head) = verify_alarm_wal(&bytes, &ed_vk, &pq_vk)?;
632
633        if let Some((cp_head, cp_sig)) = read_alarm_checkpoint(&checkpoint_path)? {
634            // The checkpoint's own signature must verify — a forged or rolled-back
635            // checkpoint (e.g. re-pointed at a truncated head) is rejected offline.
636            verify_composite(
637                &cp_sig,
638                &ed_vk,
639                Some(&pq_vk),
640                &cp_head,
641                ALARM_CHECKPOINT_AAD,
642                true,
643            )
644            .map_err(|e| {
645                anyhow::anyhow!(
646                    "duplicity alarm checkpoint signature invalid (tamper/rollback): {e}"
647                )
648            })?;
649
650            let exact = cp_head == head;
651            // One-entry WAL-ahead lag: the checkpoint names the head as of before
652            // the last (durable) append. Valid crash-window state, not tamper.
653            let one_entry_lag = head != prev_head && cp_head == prev_head;
654            anyhow::ensure!(
655                exact || one_entry_lag,
656                "duplicity alarm WAL does not match its durable checkpoint (possible truncation/tamper)"
657            );
658        }
659
660        if bytes.is_empty() {
661            file.write_all(ALARM_WAL_MAGIC)?;
662            file.sync_all()?;
663        }
664        // (Re-)anchor the checkpoint at the authoritative WAL head. This both
665        // baselines a fresh log and advances a checkpoint that lagged the WAL by
666        // one entry after a crash — the WAL fsync already made that entry durable.
667        write_alarm_checkpoint(&checkpoint_path, &head, &ed_sk, &pq_sk)?;
668        Ok(Self {
669            path,
670            checkpoint_path,
671            ed_sk,
672            pq_sk,
673            state: Mutex::new(AlarmWalState { file, head }),
674        })
675    }
676
677    /// Location of the durable journal (operator diagnostics).
678    pub fn path(&self) -> &Path {
679        &self.path
680    }
681
682    fn record(&self, alarm: &DuplicityAlarm) -> anyhow::Result<()> {
683        let payload = encode_alarm(alarm)?;
684        let mut state = self.state.lock();
685        let previous = state.head;
686        let mut hasher = blake3::Hasher::new();
687        hasher.update(&previous);
688        hasher.update(&payload);
689        let entry_hash = *hasher.finalize().as_bytes();
690
691        // Sign the entry BEFORE any write, so a signer failure leaves the WAL
692        // untouched (no partial/unsigned entry ever reaches disk). Pinned hybrid:
693        // ML-DSA-65 is mandatory (require_pq on verify), so pass Some(pq_sk).
694        let signature =
695            sign_composite(&self.ed_sk, Some(&self.pq_sk), &entry_hash, ALARM_ENTRY_AAD)
696                .map_err(|e| anyhow::anyhow!("duplicity alarm entry signing failed: {e}"))?;
697
698        state
699            .file
700            .write_all(&(payload.len() as u32).to_be_bytes())?;
701        state.file.write_all(&previous)?;
702        state.file.write_all(&payload)?;
703        state.file.write_all(&entry_hash)?;
704        state
705            .file
706            .write_all(&(signature.len() as u32).to_be_bytes())?;
707        state.file.write_all(&signature)?;
708        state.file.sync_all()?;
709        // The alarm is now durable in the WAL. Advance the in-memory head BEFORE
710        // persisting the checkpoint: if the checkpoint write fails or the process
711        // crashes here, the next append still chains correctly from `entry_hash`
712        // (no corruption), and `open` recovers the one-entry lag.
713        state.head = entry_hash;
714
715        // Best-effort checkpoint advance. A failure here does NOT lose the alarm
716        // (it is durable above) and does NOT corrupt the chain; it only leaves the
717        // checkpoint one entry behind, which `open` treats as a valid crash-window
718        // lag and repairs. Surface it so operators can notice a failing anchor.
719        if let Err(e) =
720            write_alarm_checkpoint(&self.checkpoint_path, &entry_hash, &self.ed_sk, &self.pq_sk)
721        {
722            tracing::warn!(
723                target: "hyprstream.at9p.duplicity",
724                error = %e,
725                "duplicity alarm checkpoint persist failed; WAL entry is durable and self-recovers on reopen"
726            );
727        }
728        Ok(())
729    }
730}
731
732/// Derive the verifying keys for the pinned hybrid audit signature from the
733/// signing keys held by the sink.
734fn alarm_verifying_keys(
735    ed_sk: &SigningKey,
736    pq_sk: &MlDsaSigningKey,
737) -> anyhow::Result<(VerifyingKey, MlDsaVerifyingKey)> {
738    let ed_vk = ed_sk.verifying_key();
739    let pq_vk = ml_dsa_vk_from_bytes(&ml_dsa_sk_to_vk_bytes(pq_sk))
740        .map_err(|e| anyhow::anyhow!("deriving ML-DSA-65 audit verifying key failed: {e}"))?;
741    Ok((ed_vk, pq_vk))
742}
743
744/// Write the signed head-anchor checkpoint atomically (temp + rename + parent
745/// `fsync`). Layout: `head(32) || signature`. The signature is over `head` under
746/// [`ALARM_CHECKPOINT_AAD`], so it cannot be a replayed entry signature and a
747/// local writer without the key cannot re-point it at a truncated head.
748fn write_alarm_checkpoint(
749    path: &Path,
750    head: &[u8; 32],
751    ed_sk: &SigningKey,
752    pq_sk: &MlDsaSigningKey,
753) -> anyhow::Result<()> {
754    let signature = sign_composite(ed_sk, Some(pq_sk), head, ALARM_CHECKPOINT_AAD)
755        .map_err(|e| anyhow::anyhow!("duplicity alarm checkpoint signing failed: {e}"))?;
756    let mut buf = Vec::with_capacity(head.len() + signature.len());
757    buf.extend_from_slice(head);
758    buf.extend_from_slice(&signature);
759
760    let temporary = path.with_extension("checkpoint.tmp");
761    let mut file = File::create(&temporary)?;
762    file.write_all(&buf)?;
763    file.sync_all()?;
764    std::fs::rename(&temporary, path)?;
765    // fsync the parent directory so the rename is durable — otherwise a crash can
766    // lose the checkpoint entry and re-baseline the log on the next open.
767    if let Some(parent) = path.parent() {
768        if let Ok(dir) = File::open(parent) {
769            let _ = dir.sync_all();
770        }
771    }
772    Ok(())
773}
774
775/// Read a signed checkpoint file, returning `(head, signature)` or `None` if it
776/// does not exist. A file too short to hold a 32-byte head is treated as corrupt.
777fn read_alarm_checkpoint(path: &Path) -> anyhow::Result<Option<([u8; 32], Vec<u8>)>> {
778    if !path.exists() {
779        return Ok(None);
780    }
781    let bytes = std::fs::read(path)?;
782    anyhow::ensure!(
783        bytes.len() > 32,
784        "duplicity alarm checkpoint is truncated (missing head or signature)"
785    );
786    let mut head = [0u8; 32];
787    head.copy_from_slice(&bytes[..32]);
788    Ok(Some((head, bytes[32..].to_vec())))
789}
790
791impl DuplicityAlarmSink for WalDuplicityAlarmSink {
792    fn raise(&self, alarm: &DuplicityAlarm) {
793        let result = self.record(alarm);
794        tracing::error!(
795            target: "hyprstream.at9p.duplicity",
796            subject_cid512 = %alarm.subject_cid512,
797            kind = ?alarm.kind,
798            watermark_epoch = alarm.watermark_epoch,
799            watermark_digest = %hex_digest(&alarm.watermark_digest),
800            divergent_epoch = alarm.divergent_epoch,
801            divergent_digest = %hex_digest(&alarm.divergent_digest),
802            durable = result.is_ok(),
803            error = result.as_ref().err().map(ToString::to_string).as_deref().unwrap_or(""),
804            "did:at9p duplicity detected; identity remains fail-closed"
805        );
806    }
807}
808
809fn encode_alarm(alarm: &DuplicityAlarm) -> anyhow::Result<Vec<u8>> {
810    let subject = alarm.subject_cid512.as_bytes();
811    anyhow::ensure!(
812        subject.len() <= u16::MAX as usize,
813        "at9p subject exceeds WAL limit"
814    );
815    let mut out = Vec::with_capacity(2 + subject.len() + ALARM_FIXED_PAYLOAD_LEN);
816    out.extend_from_slice(&(subject.len() as u16).to_be_bytes());
817    out.extend_from_slice(subject);
818    out.push(match alarm.kind {
819        DuplicityKind::SameEpochFork => 0,
820        DuplicityKind::BelowWatermarkFork => 1,
821        DuplicityKind::HigherEpochFork => 2,
822    });
823    out.extend_from_slice(&alarm.watermark_epoch.to_be_bytes());
824    out.extend_from_slice(&alarm.watermark_digest);
825    out.extend_from_slice(&alarm.divergent_epoch.to_be_bytes());
826    out.extend_from_slice(&alarm.divergent_digest);
827    Ok(out)
828}
829
830/// Verify the whole alarm WAL end-to-end: the magic header, every hash-chain
831/// link, every entry's stored `entry_hash`, and every entry's **hybrid
832/// signature**. Returns `(head, prev_head)` where `head` is the final chain head
833/// and `prev_head` is the head as of just before the last entry (equal to `head`
834/// for an empty log) — the caller uses `prev_head` to recognise a legitimate
835/// one-entry WAL-ahead-of-checkpoint crash-window lag.
836fn verify_alarm_wal(
837    bytes: &[u8],
838    ed_vk: &VerifyingKey,
839    pq_vk: &MlDsaVerifyingKey,
840) -> anyhow::Result<([u8; 32], [u8; 32])> {
841    if bytes.is_empty() {
842        return Ok(([0; 32], [0; 32]));
843    }
844    anyhow::ensure!(
845        bytes.starts_with(ALARM_WAL_MAGIC),
846        "invalid duplicity alarm WAL header"
847    );
848    let mut cursor = ALARM_WAL_MAGIC.len();
849    let mut head = [0; 32];
850    let mut prev_head = [0; 32];
851    while cursor < bytes.len() {
852        anyhow::ensure!(
853            bytes.len() - cursor >= 4 + 32,
854            "truncated duplicity alarm WAL entry"
855        );
856        let len = u32::from_be_bytes(bytes[cursor..cursor + 4].try_into()?) as usize;
857        cursor += 4;
858        let previous: [u8; 32] = bytes[cursor..cursor + 32].try_into()?;
859        cursor += 32;
860        anyhow::ensure!(previous == head, "duplicity alarm WAL hash-chain break");
861        anyhow::ensure!(
862            bytes.len() - cursor >= len + 32 + 4,
863            "truncated duplicity alarm WAL payload"
864        );
865        let payload = &bytes[cursor..cursor + len];
866        cursor += len;
867        let stored: [u8; 32] = bytes[cursor..cursor + 32].try_into()?;
868        cursor += 32;
869        let mut hasher = blake3::Hasher::new();
870        hasher.update(&head);
871        hasher.update(payload);
872        let expected = *hasher.finalize().as_bytes();
873        anyhow::ensure!(
874            stored == expected,
875            "duplicity alarm WAL entry hash mismatch"
876        );
877        let sig_len = u32::from_be_bytes(bytes[cursor..cursor + 4].try_into()?) as usize;
878        cursor += 4;
879        anyhow::ensure!(
880            bytes.len() - cursor >= sig_len,
881            "truncated duplicity alarm WAL signature"
882        );
883        let signature = &bytes[cursor..cursor + sig_len];
884        cursor += sig_len;
885        // Authenticity: a rewritten/forged entry cannot produce a valid hybrid
886        // signature over its (recomputed) entry_hash without the node's key.
887        verify_composite(
888            signature,
889            ed_vk,
890            Some(pq_vk),
891            &stored,
892            ALARM_ENTRY_AAD,
893            true,
894        )
895        .map_err(|e| anyhow::anyhow!("duplicity alarm WAL entry signature invalid: {e}"))?;
896        prev_head = head;
897        head = stored;
898    }
899    Ok((head, prev_head))
900}
901
902fn hex_digest(digest: &[u8; H512_LEN]) -> String {
903    const HEX: &[u8; 16] = b"0123456789abcdef";
904    let mut out = String::with_capacity(H512_LEN * 2);
905    for byte in digest {
906        out.push(HEX[(byte >> 4) as usize] as char);
907        out.push(HEX[(byte & 0xf) as usize] as char);
908    }
909    out
910}
911
912/// Explicit no-op sink for tests or deployments that route alarms elsewhere.
913/// Detection still fails closed, but this sink provides no durable/operator
914/// signal; production callers should use [`WalDuplicityAlarmSink`].
915#[derive(Clone, Copy, Debug, Default)]
916pub struct NoopAlarmSink;
917
918impl DuplicityAlarmSink for NoopAlarmSink {
919    fn raise(&self, _alarm: &DuplicityAlarm) {}
920}
921
922/// Outcome of admitting a candidate successor through the duplicity guard.
923#[derive(Clone, Debug, Eq, PartialEq)]
924pub enum Admission {
925    /// Honest forward progress: the watermark advanced to `state`, a new highest
926    /// epoch that chains through the previous watermark head.
927    Advanced(ChainState),
928    /// The candidate is byte-identical (same epoch, same digest) to the record
929    /// already at the watermark — idempotent re-presentation, watermark
930    /// unchanged, no alarm.
931    AlreadyKnown,
932    /// Advanced to a **terminal** state (B3, #887): the accepted head pre-commits
933    /// to no further keys, so the identity is frozen at `state.epoch` forever. No
934    /// successor will ever be admitted after this.
935    Frozen(ChainState),
936}
937
938/// Why an admission failed. Every variant fails closed.
939#[derive(Debug)]
940#[non_exhaustive]
941pub enum AdmissionError {
942    /// B1's [`validate_successor`] rejected the candidate against the supplied
943    /// predecessor — it is not an authorized successor at all (propagated
944    /// unchanged so callers can match the specific gate).
945    Successor(SuccessorError),
946    /// Duplicity: the candidate is individually B1-valid but diverges from the
947    /// persisted watermark. Fail-closed; the [`DuplicityAlarm`] has already been
948    /// raised on the sink. Boxed to keep the happy-path `Result` small.
949    Duplicity(Box<DuplicityAlarm>),
950    /// The identity's watermark is terminal (declared-immutable or exhausted, B3
951    /// #887): no successor is admissible, by design. B1 is not even consulted.
952    FrozenIdentity {
953        /// The terminal epoch the identity is frozen at.
954        epoch: u64,
955    },
956    /// The guard was asked to admit a successor for a DID it has never seen (no
957    /// seeded watermark). Callers must [`DuplicityGuard::seed_genesis`] from a
958    /// GATE-verified genesis capsule first; admitting against an unknown baseline
959    /// is refused fail-closed rather than trusting an unanchored predecessor.
960    NotSeeded {
961        /// The DID whose watermark is missing.
962        subject_cid512: String,
963    },
964    /// The watermark for this DID already exists and must not be re-seeded
965    /// (anti-rollback, FIX in #959): `seed_genesis` refuses to overwrite an
966    /// already-advanced (`epoch > 0`) or different-genesis anchor so a stray /
967    /// hostile re-seed cannot roll the anchor backward.
968    AlreadySeeded {
969        /// The DID whose watermark already exists.
970        subject_cid512: String,
971        /// Epoch of the existing watermark that refused the re-seed.
972        existing_epoch: u64,
973    },
974    /// The durable accepted predecessor is an update whose validity window has
975    /// elapsed. An expired head cannot authorize a later rotation.
976    AcceptedHeadNotFresh(anyhow::Error),
977    /// The underlying [`WatermarkStore`] failed (I/O, poisoned lock). Fail-closed:
978    /// a watermark that cannot be read or written is treated as blocking, never
979    /// bypassed.
980    Store(anyhow::Error),
981    /// The presented predecessor record was anchored (its `H512` matches the
982    /// watermark) but could not be projected to a [`ChainState`] — e.g. a
983    /// genesis capsule whose cid512 does not parse. An anchored record that
984    /// nonetheless fails to decode is an internal inconsistency; fail-closed
985    /// rather than trust a partially-derived state.
986    MalformedPredecessor(anyhow::Error),
987}
988
989impl std::fmt::Display for AdmissionError {
990    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
991        match self {
992            Self::Successor(err) => write!(f, "duplicity guard: successor-check failed: {err}"),
993            Self::Duplicity(alarm) => write!(
994                f,
995                "duplicity guard: DUPLICITY ({:?}) — divergent record at epoch {} against watermark epoch {}",
996                alarm.kind, alarm.divergent_epoch, alarm.watermark_epoch
997            ),
998            Self::FrozenIdentity { epoch } => write!(
999                f,
1000                "duplicity guard: identity is frozen at epoch {epoch} (declared-immutable or exhausted); no successor is admissible"
1001            ),
1002            Self::NotSeeded { subject_cid512 } => write!(
1003                f,
1004                "duplicity guard: no watermark seeded for {subject_cid512:?}; seed the genesis state first"
1005            ),
1006            Self::AlreadySeeded {
1007                subject_cid512,
1008                existing_epoch,
1009            } => write!(
1010                f,
1011                "duplicity guard: watermark for {subject_cid512:?} already exists at epoch {existing_epoch}; refusing re-seed (anti-rollback)"
1012            ),
1013            Self::Store(err) => write!(f, "duplicity guard: watermark store error: {err}"),
1014            Self::AcceptedHeadNotFresh(err) => {
1015                write!(f, "duplicity guard: accepted predecessor is not fresh: {err}")
1016            }
1017            Self::MalformedPredecessor(err) => {
1018                write!(f, "duplicity guard: anchored predecessor did not decode: {err}")
1019            }
1020        }
1021    }
1022}
1023
1024impl std::error::Error for AdmissionError {
1025    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
1026        match self {
1027            Self::Successor(err) => Some(err),
1028            Self::Store(err)
1029            | Self::AcceptedHeadNotFresh(err)
1030            | Self::MalformedPredecessor(err) => Some(err.as_ref()),
1031            _ => None,
1032        }
1033    }
1034}
1035
1036/// The duplicity-detecting wrapper around B1 (#886, R6) with B3 (#887)
1037/// commitment-lifecycle semantics folded in.
1038///
1039/// Holds the [`WatermarkStore`] (persistence seam) and the [`DuplicityAlarmSink`]
1040/// (B4/#888 routing seam). Usage:
1041///
1042/// 1. Verify a genesis capsule externally (GATE 1/2), build its [`ChainState`]
1043///    ([`ChainState::genesis`]), and [`seed_genesis`](Self::seed_genesis) it.
1044/// 2. For each candidate update-record, resolve its predecessor state and call
1045///    [`admit_successor`](Self::admit_successor). B1 runs first; the watermark
1046///    reconciliation runs second and can only ever *reject* a B1-valid record
1047///    (duplicity) or *advance* on honest progress — never select a fork.
1048pub struct DuplicityGuard<S: WatermarkStore, A: DuplicityAlarmSink> {
1049    store: S,
1050    alarm: A,
1051    /// Per-DID optimization locks for calls through this guard instance. The
1052    /// store-owned conditional advance is authoritative across guards.
1053    admit_locks: Mutex<HashMap<String, Arc<Mutex<()>>>>,
1054}
1055
1056impl<S: WatermarkStore> DuplicityGuard<S, NoopAlarmSink> {
1057    /// Build a guard whose alarm routing is **explicitly disabled** — the test /
1058    /// opt-out path. This installs [`NoopAlarmSink`], so a real detection is
1059    /// classified and fail-closed but produces **no durable, tamper-evident
1060    /// record**. Production MUST NOT use this: build the guard with
1061    /// [`with_durable_alarm`](DuplicityGuard::with_durable_alarm) (the signed WAL
1062    /// route) or [`with_alarm`](Self::with_alarm) with an equivalent durable
1063    /// sink, so callers opt *out* of durable routing deliberately rather than
1064    /// keeping it off by accident.
1065    pub fn new(store: S) -> Self {
1066        Self {
1067            store,
1068            alarm: NoopAlarmSink,
1069            admit_locks: Mutex::new(HashMap::new()),
1070        }
1071    }
1072}
1073
1074impl<S: WatermarkStore> DuplicityGuard<S, WalDuplicityAlarmSink> {
1075    /// The **production** construction path: build a guard that routes every
1076    /// [`admit_successor`](Self::admit_successor) duplicity detection to a
1077    /// durable, hybrid-signed, tamper-evident [`WalDuplicityAlarmSink`] at
1078    /// `wal_path`, signed with the node's audit keys (`ed_sk` / `pq_sk`).
1079    ///
1080    /// Opening the sink verifies (or baselines) the existing journal, so a
1081    /// corrupt/forged/truncated log fails closed before the guard is usable. Use
1082    /// this — not [`new`](Self::new) — anywhere a real `did:at9p` chain is
1083    /// admitted, so a fork is always durably recorded and surfaced to an operator
1084    /// (issue #888 acceptance).
1085    pub fn with_durable_alarm(
1086        store: S,
1087        wal_path: impl AsRef<Path>,
1088        ed_sk: SigningKey,
1089        pq_sk: MlDsaSigningKey,
1090    ) -> anyhow::Result<Self> {
1091        let alarm = WalDuplicityAlarmSink::open(wal_path, ed_sk, pq_sk)?;
1092        Ok(Self::with_alarm(store, alarm))
1093    }
1094}
1095
1096impl<S: WatermarkStore, A: DuplicityAlarmSink> DuplicityGuard<S, A> {
1097    /// Build a guard with an explicit alarm sink (the B4/#888 routing seam).
1098    pub fn with_alarm(store: S, alarm: A) -> Self {
1099        Self {
1100            store,
1101            alarm,
1102            admit_locks: Mutex::new(HashMap::new()),
1103        }
1104    }
1105
1106    /// Run `f` while holding the per-DID admission lock, so concurrent
1107    /// `admit_successor` / `seed_genesis` calls for the same DID serialize
1108    /// their read-modify-write. The outer map lock is released as soon as the
1109    /// per-DID [`Arc<Mutex<()>>`] is cloned out; only the inner lock is held
1110    /// for the duration of `f`. (Closure-scoped rather than returning a guard
1111    /// because the guard borrows the inner `Mutex`, which the `Arc` owns —
1112    /// keeping both in this frame for `f`'s lifetime is the only sound way to
1113    /// hand the lock across the whole RMW.)
1114    fn with_admission_lock<R>(&self, subject_cid512: &str, f: impl FnOnce() -> R) -> R {
1115        let lock = {
1116            let mut map = self.admit_locks.lock();
1117            map.entry(subject_cid512.to_owned())
1118                .or_insert_with(|| Arc::new(Mutex::new(())))
1119                .clone()
1120        };
1121        let _guard = lock.lock();
1122        f()
1123    }
1124
1125    /// Seed complete accepted state for a DID from its unforgeable
1126    /// [`VerifiedCapsule`] GATE witness (epoch 0).
1127    ///
1128    /// **Anti-rollback (FIX in #959):** refuses to overwrite a watermark that
1129    /// is already-advanced (`epoch > 0`) or that anchors a *different* genesis
1130    /// digest — a stray or hostile re-seed must never move the anti-rollback
1131    /// anchor backward. The only overwrite permitted is an idempotent re-seed
1132    /// of the exact same genesis (epoch 0, identical `record_digest`), which is
1133    /// a no-op success. The per-DID admission lock is held across the
1134    /// read-then-conditional-advance so this check is race-free against a
1135    /// concurrent `admit_successor`.
1136    ///
1137    /// If the genesis pre-commits to no next keys, the seeded watermark is
1138    /// **terminal** immediately — a declared-immutable identity (B3, #887).
1139    /// Callers must seed only from a genesis they have themselves verified
1140    /// (`H512(bytes) == cid512` + self-signature).
1141    pub fn seed_genesis(&self, genesis: &VerifiedCapsule) -> Result<(), AdmissionError> {
1142        let accepted = AcceptedAt9pState::from_verified_genesis(genesis)
1143            .map_err(AdmissionError::MalformedPredecessor)?;
1144        let subject = &accepted.subject_cid512;
1145        self.with_admission_lock(subject, || {
1146            loop {
1147                if let Some(existing) = self.store.get(subject).map_err(AdmissionError::Store)? {
1148                    // Idempotent re-seed of the exact same genesis is a no-op success.
1149                    if existing.epoch == 0 && existing.head_digest == accepted.head_digest {
1150                        return Ok(());
1151                    }
1152                    // Anything else — an already-advanced watermark, or a different
1153                    // genesis — is the anti-rollback anchor; refuse rather than let a
1154                    // re-seed clobber it.
1155                    return Err(AdmissionError::AlreadySeeded {
1156                        subject_cid512: subject.clone(),
1157                        existing_epoch: existing.epoch,
1158                    });
1159                }
1160                match self
1161                    .store
1162                    .conditional_advance(None, &accepted)
1163                    .map_err(AdmissionError::Store)?
1164                {
1165                    ConditionalAdvance::Committed => return Ok(()),
1166                    ConditionalAdvance::Conflict(_) => continue,
1167                }
1168            }
1169        })
1170    }
1171
1172    /// The current persisted watermark for a DID, or `None` if unseeded.
1173    pub fn watermark(&self, subject_cid512: &str) -> Result<Option<Watermark>, AdmissionError> {
1174        self.store
1175            .get(subject_cid512)
1176            .map(|state| state.map(|state| state.watermark()))
1177            .map_err(AdmissionError::Store)
1178    }
1179
1180    /// Complete accepted current state, including current authorized body and
1181    /// provenance. This is state acceptance only, never reach/liveness or live
1182    /// possession/admission authority.
1183    pub fn accepted_state(
1184        &self,
1185        subject_cid512: &str,
1186    ) -> Result<Option<AcceptedAt9pState>, AdmissionError> {
1187        self.store
1188            .get(subject_cid512)
1189            .map_err(AdmissionError::Store)
1190    }
1191
1192    /// Admit `candidate` as a successor of `predecessor` as of `now`, enforcing
1193    /// B1 **and** duplicity detection (R6) **and** B3 terminal semantics,
1194    /// fail-closed throughout.
1195    ///
1196    /// # Predecessor anchoring (#961 — the provenance boundary)
1197    ///
1198    /// The predecessor is loaded from the complete durable accepted state, not
1199    /// supplied by the caller. The guard recomputes the predecessor's
1200    /// `H512` and anchors it against the persisted [`Watermark::record_digest`]
1201    /// **before** B1 runs, then derives the authoritative `ChainState` from the
1202    /// anchored record. This proves the `next_key_commitments` B1's
1203    /// signer-authorization gate keys off belong to the anchored head — an
1204    /// attacker who only knows the honest digest cannot authorize a pre-rotated
1205    /// evil key, because the commitments are read from the record's bytes (whose
1206    /// hash must match the watermark), never from a caller claim. Caller-supplied
1207    /// unverified `ChainState` is no longer expressible in the API.
1208    ///
1209    /// # Concurrency (FIX in #959)
1210    ///
1211    /// The whole classify-then-advance read-modify-write is serialized per-DID
1212    /// by a held admission lock, so two concurrent divergent epoch-`(N+1)`
1213    /// successors of the same head result in **exactly one**
1214    /// [`Admission::Advanced`] (the winner, which advances the watermark) and the
1215    /// other(s) classified as a fork ([`DuplicityKind::SameEpochFork`] once the
1216    /// watermark has moved to epoch `N+1`) — never two `Advanced`.
1217    ///
1218    /// # Order of checks (each fails closed before the next)
1219    ///
1220    /// 1. **Idempotent replay** — `epoch == watermark.epoch` with the candidate's
1221    ///    recomputed `H512` equal to the watermark digest is a byte-identical
1222    ///    re-presentation of the accepted head → [`Admission::AlreadyKnown`], even
1223    ///    when that head is terminal (a caller retrying a lost response after a
1224    ///    [`Admission::Frozen`] acceptance must be able to learn it succeeded).
1225    /// 2. **Terminal watermark (B3)** — if the DID's accepted head pre-commits to
1226    ///    nothing, no new successor is admissible; reject without consulting B1.
1227    /// 3. **Position vs watermark (by the candidate's OWN digest)** — for any
1228    ///    remaining candidate at `epoch <= watermark.epoch`, the verdict depends
1229    ///    only on the candidate (its epoch and its recomputed `H512`), never on a
1230    ///    caller-supplied predecessor. So B1 is not run and no predecessor
1231    ///    commitments are consulted, which is the #961 invariant in the small: the
1232    ///    guard never trusts a predecessor field to classify a non-advancing
1233    ///    record. Because B1 cannot run here (complete current-head persistence
1234    ///    does not retain the committing predecessor at `epoch - 1`), these
1235    ///    duplicity verdicts are **unauthenticated divergence indications**, not
1236    ///    proof the identity holder signed the divergent record — see
1237    ///    [`DuplicityAlarm`].
1238    ///    * `epoch < watermark` → [`DuplicityKind::BelowWatermarkFork`];
1239    ///    * `epoch == watermark` (digest necessarily differs after step 1) →
1240    ///      [`DuplicityKind::SameEpochFork`].
1241    /// 4. **Advance path — anchor then B1 (#961)** — for `epoch > watermark`,
1242    ///    recompute the predecessor's `H512` and require it to equal the
1243    ///    watermark digest BEFORE B1 runs, then derive the authoritative
1244    ///    `ChainState` from the anchored record. A predecessor that does not hash
1245    ///    to the watermark is a foreign fork head (or a forgery attempt that
1246    ///    cannot pair evil commitments with the honest digest) →
1247    ///    [`DuplicityKind::HigherEpochFork`]; its `next_key_commitments` are never
1248    ///    seen by B1. With the predecessor proven to be the head, B1
1249    ///    ([`validate_successor`]) decides the final gate; on success the watermark
1250    ///    advances — [`Admission::Frozen`] if the new head is terminal, else
1251    ///    [`Admission::Advanced`].
1252    ///
1253    /// A duplicity verdict raises the alarm on the sink and returns
1254    /// [`AdmissionError::Duplicity`]; the watermark is left **unchanged** (a fork
1255    /// never moves the honest watermark).
1256    pub fn admit_successor(
1257        &self,
1258        candidate: &UpdateRecord,
1259        now: &str,
1260    ) -> Result<Admission, AdmissionError> {
1261        let subject = &candidate.subject_cid512;
1262        // Hold the per-DID admission lock across the ENTIRE read-modify-write so
1263        // concurrent admissions of this DID serialize (FIX in #959, R6 property).
1264        self.with_admission_lock(subject, || {
1265            loop {
1266                // A DID we've never seeded has no anchored baseline; refuse rather than
1267                // trust an unanchored predecessor (fail-closed first contact).
1268                let accepted = self
1269                    .store
1270                    .get(subject)
1271                    .map_err(AdmissionError::Store)?
1272                    .ok_or_else(|| AdmissionError::NotSeeded {
1273                        subject_cid512: subject.clone(),
1274                    })?;
1275                accepted
1276                    .ensure_fresh(now)
1277                    .map_err(AdmissionError::AcceptedHeadNotFresh)?;
1278                let watermark = accepted.watermark();
1279
1280                // (1) Idempotent replay of the accepted head: same epoch AND same
1281                // recomputed digest as the persisted watermark means the candidate is
1282                // byte-identical to the record we already accepted. Return AlreadyKnown —
1283                // even when that head is terminal — so a caller retrying a rotation after
1284                // a lost response can learn its write already succeeded. No state changes
1285                // and no alarm; checked before B3 so the terminal head's own record does
1286                // not surface as FrozenIdentity.
1287                let cand_epoch = candidate.epoch;
1288                let cand_digest = record_digest(candidate);
1289                if cand_epoch == watermark.epoch && cand_digest == watermark.record_digest {
1290                    return Ok(Admission::AlreadyKnown);
1291                }
1292
1293                // (2) B3: a terminal identity admits no NEW successor, ever. Checked
1294                // before the fork classification and B1 so a frozen DID short-circuits
1295                // without spending a signature verify — and so the reason surfaced is
1296                // "frozen", not an incidental later gate.
1297                if watermark.terminal {
1298                    return Err(AdmissionError::FrozenIdentity {
1299                        epoch: watermark.epoch,
1300                    });
1301                }
1302
1303                // (3) Position vs watermark by the candidate's OWN digest/epoch. These
1304                // verdicts are independent of any predecessor, so B1 is not run and no
1305                // unanchored predecessor commitment is ever consulted (#961): the only
1306                // path that admits a successor — and therefore the only path that needs
1307                // B1's signer-authorization gate — is the advance path below.
1308                if cand_epoch < watermark.epoch {
1309                    // A valid record below the high-watermark. We keep only the
1310                    // complete current head, not full history, so we cannot prove this is the record
1311                    // we accepted at that epoch — and per R6 a client that has accepted
1312                    // epoch N never accepts < N. Fail closed as a fork; never prefer.
1313                    return Err(self.raise_duplicity(
1314                        subject,
1315                        DuplicityKind::BelowWatermarkFork,
1316                        &watermark,
1317                        cand_epoch,
1318                        cand_digest,
1319                    ));
1320                }
1321
1322                if cand_epoch == watermark.epoch {
1323                    // The equal-digest case already returned AlreadyKnown at (1); a
1324                    // same-epoch candidate with a DIFFERENT digest is a divergent record
1325                    // at an epoch we have already accepted → equivocation indication.
1326                    return Err(self.raise_duplicity(
1327                        subject,
1328                        DuplicityKind::SameEpochFork,
1329                        &watermark,
1330                        cand_epoch,
1331                        cand_digest,
1332                    ));
1333                }
1334
1335                // A higher record must explicitly extend the persisted accepted
1336                // head. This is classified before signature validation because the
1337                // retained watermark is the authority boundary; selecting a
1338                // maximum epoch on another branch is forbidden.
1339                if candidate.prev_record_digest != watermark.record_digest {
1340                    return Err(self.raise_duplicity(
1341                        subject,
1342                        DuplicityKind::HigherEpochFork,
1343                        &watermark,
1344                        cand_epoch,
1345                        cand_digest,
1346                    ));
1347                }
1348
1349                // (4) Advance path (cand_epoch > watermark). ANCHOR (#961): recompute the
1350                // predecessor's H512 from its bytes and refuse to trust ANY field of it
1351                // unless it matches the persisted watermark digest. This is the structural
1352                // enforcement — the next_key_commitments B1 is about to key off are proven
1353                // to belong to the anchored head, not a caller-forged record that merely
1354                // claims the honest digest. (A caller cannot pair evil commitments with the
1355                // honest digest: that is a BLAKE3-512 preimage. The worst they can do is
1356                // present a foreign record with its own, different digest — caught here.)
1357                // The check runs BEFORE B1 so a forged/foreign predecessor never reaches
1358                // the signer-authorization gate.
1359                let predecessor = accepted.predecessor();
1360                let pred_digest = predecessor.record_digest();
1361                if pred_digest != watermark.record_digest {
1362                    // Higher-epoch record chained through a non-watermark head — the
1363                    // "never select max epoch" trap. Fail closed, alarm, watermark stays.
1364                    return Err(self.raise_duplicity(
1365                        subject,
1366                        DuplicityKind::HigherEpochFork,
1367                        &watermark,
1368                        cand_epoch,
1369                        cand_digest,
1370                    ));
1371                }
1372
1373                // The predecessor is anchored. Derive its authoritative ChainState from
1374                // the record's own fields (never a caller claim). `derive_chain_state` only
1375                // fails on a structural decode inconsistency against an already-hashed
1376                // record — fail closed as malformed rather than trust a partial state.
1377                let predecessor_state = predecessor
1378                    .derive_chain_state()
1379                    .map_err(AdmissionError::MalformedPredecessor)?;
1380
1381                // (5) B1: is the candidate an authorized successor of the AUTHENTIC
1382                // predecessor? `predecessor_state` is proven to be the watermark head, so
1383                // the signer-authorization gate keys off anchored commitments only.
1384                let state = validate_successor(&predecessor_state, candidate, now)
1385                    .map_err(AdmissionError::Successor)?;
1386
1387                // (6) Honest forward progress: the predecessor is the head and the
1388                // candidate is a valid successor of it. Advance the watermark; freeze if
1389                // the new head pre-commits to nothing (B3).
1390                let terminal = state.next_key_commitments.is_empty();
1391                let accepted = AcceptedAt9pState::from_accepted_update(candidate.clone());
1392                debug_assert_eq!(accepted.watermark(), Watermark::from_state(&state));
1393                match self
1394                    .store
1395                    .conditional_advance(Some(watermark), &accepted)
1396                    .map_err(AdmissionError::Store)?
1397                {
1398                    ConditionalAdvance::Committed => {
1399                        return Ok(if terminal {
1400                            Admission::Frozen(state)
1401                        } else {
1402                            Admission::Advanced(state)
1403                        })
1404                    }
1405                    ConditionalAdvance::Conflict(_) => continue,
1406                }
1407            }
1408        })
1409    }
1410
1411    /// Build the [`DuplicityAlarm`], deliver it to the sink, and package the
1412    /// fail-closed error. The watermark is deliberately NOT mutated.
1413    fn raise_duplicity(
1414        &self,
1415        subject_cid512: &str,
1416        kind: DuplicityKind,
1417        watermark: &Watermark,
1418        divergent_epoch: u64,
1419        divergent_digest: [u8; H512_LEN],
1420    ) -> AdmissionError {
1421        let alarm = DuplicityAlarm {
1422            subject_cid512: subject_cid512.to_owned(),
1423            kind,
1424            watermark_epoch: watermark.epoch,
1425            watermark_digest: watermark.record_digest,
1426            divergent_epoch,
1427            divergent_digest,
1428        };
1429        self.alarm.raise(&alarm);
1430        AdmissionError::Duplicity(Box::new(alarm))
1431    }
1432}
1433
1434/// Recompute a record's `H512` digest — the value stored as the watermark's
1435/// `record_digest`. Exposed so callers reconstructing a watermark from a
1436/// persisted record (e.g. on restart) key it the same way the guard does.
1437pub fn record_digest(record: &UpdateRecord) -> [u8; H512_LEN] {
1438    // Input is a validated record (decoded or signed); use the unchecked
1439    // serializer to keep this infallible — `to_dag_cbor` would re-validate.
1440    h512(&record.encode_value())
1441}
1442
1443#[cfg(test)]
1444#[allow(
1445    clippy::unwrap_used,
1446    clippy::expect_used,
1447    clippy::indexing_slicing,
1448    clippy::panic
1449)]
1450mod tests {
1451    use super::*;
1452    use crate::at9p::{
1453        Capsule, CapsuleBody, HybridKeyPair, ServiceEndpoint, ServiceEntry, ServiceType, Transport,
1454    };
1455    use crate::at9p_sign::{sign_capsule, sign_update_record};
1456    use ed25519_dalek::SigningKey;
1457    use hyprstream_crypto::pq::{
1458        ml_dsa_generate_keypair, ml_dsa_sk_from_seed, ml_dsa_vk_bytes, MlDsaSigningKey,
1459    };
1460    use rand::rngs::OsRng;
1461
1462    const NOW: &str = "2026-07-09T00:00:00Z";
1463    const FUTURE: &str = "2099-01-01T00:00:00Z";
1464
1465    /// Deterministic audit signing keys for the WAL-sink tests. Reconstructed
1466    /// from fixed seeds so every `open`/reopen in a test signs and verifies with
1467    /// the *same* key (a random key per open would fail signature verification on
1468    /// reopen). Mirrors the pinned-hybrid pair a production node holds.
1469    fn alarm_keys() -> (SigningKey, MlDsaSigningKey) {
1470        (
1471            SigningKey::from_bytes(&[7u8; 32]),
1472            ml_dsa_sk_from_seed(&[9u8; 32]),
1473        )
1474    }
1475
1476    /// Open the signed alarm WAL at `path` with the deterministic test keys.
1477    fn open_alarm_wal(path: &std::path::Path) -> anyhow::Result<WalDuplicityAlarmSink> {
1478        let (ed_sk, pq_sk) = alarm_keys();
1479        WalDuplicityAlarmSink::open(path, ed_sk, pq_sk)
1480    }
1481
1482    /// A hybrid signer plus its public keypair (the pre-rotation commitment
1483    /// preimage). Mirrors the B1 test harness.
1484    struct Signer {
1485        ed_sk: SigningKey,
1486        pq_sk: MlDsaSigningKey,
1487        keypair: HybridKeyPair,
1488    }
1489
1490    fn signer() -> Signer {
1491        let ed_sk = SigningKey::generate(&mut OsRng);
1492        let (pq_sk, pq_vk) = ml_dsa_generate_keypair();
1493        let keypair = HybridKeyPair::new(
1494            ed_sk.verifying_key().to_bytes().to_vec(),
1495            ml_dsa_vk_bytes(&pq_vk),
1496        )
1497        .unwrap();
1498        Signer {
1499            ed_sk,
1500            pq_sk,
1501            keypair,
1502        }
1503    }
1504
1505    fn service_entries() -> Vec<ServiceEntry> {
1506        let endpoint = ServiceEndpoint::new(Transport::Iroh, "iroh://node0").unwrap();
1507        vec![ServiceEntry::new("#ns", ServiceType::NinePExport, endpoint).unwrap()]
1508    }
1509
1510    /// Capsule body whose primary subject key is `subject`, pre-committing to
1511    /// each key in `next` (empty `next` = declared-immutable / exhausted).
1512    fn body_committing_to(subject: &Signer, next: &[&Signer]) -> CapsuleBody {
1513        let mut body = CapsuleBody::new(vec![subject.keypair.clone()], service_entries()).unwrap();
1514        body.next_key_commitments = next.iter().map(|s| s.keypair.commitment_digest()).collect();
1515        body
1516    }
1517
1518    fn genesis(g: &Signer, next: &[&Signer]) -> (Capsule, ChainState) {
1519        let body = body_committing_to(g, next);
1520        let capsule = sign_capsule(body, &g.ed_sk, &g.pq_sk).unwrap();
1521        let state = ChainState::genesis(&capsule).unwrap();
1522        (capsule, state)
1523    }
1524
1525    fn verified_genesis(capsule: &Capsule) -> VerifiedCapsule {
1526        let bytes = capsule.to_dag_cbor().unwrap();
1527        crate::at9p_gate::verify_genesis_capsule(&capsule.cid512().unwrap(), &bytes).unwrap()
1528    }
1529
1530    /// Update-record signed by `signer_key`, revealing it as the new primary
1531    /// subject key and pre-committing to `next`. `salt` perturbs the label hints
1532    /// so two otherwise-identical rotations differ (divergent digest) — the
1533    /// equivocation primitive.
1534    fn update_salted(
1535        subject_cid512: &str,
1536        epoch: u64,
1537        prev_digest: [u8; H512_LEN],
1538        signer_key: &Signer,
1539        next: &[&Signer],
1540        expires_at: &str,
1541        salt: Option<&str>,
1542    ) -> UpdateRecord {
1543        let mut body = body_committing_to(signer_key, next);
1544        if let Some(s) = salt {
1545            body.label_hints = Some(vec![s.to_owned()]);
1546        }
1547        sign_update_record(
1548            subject_cid512.to_owned(),
1549            epoch,
1550            prev_digest,
1551            body,
1552            expires_at.to_owned(),
1553            &signer_key.ed_sk,
1554            &signer_key.pq_sk,
1555        )
1556        .unwrap()
1557    }
1558
1559    fn update(
1560        subject_cid512: &str,
1561        epoch: u64,
1562        prev_digest: [u8; H512_LEN],
1563        signer_key: &Signer,
1564        next: &[&Signer],
1565    ) -> UpdateRecord {
1566        update_salted(
1567            subject_cid512,
1568            epoch,
1569            prev_digest,
1570            signer_key,
1571            next,
1572            FUTURE,
1573            None,
1574        )
1575    }
1576
1577    /// A recording sink so tests can assert an alarm fired (and inspect its kind).
1578    #[derive(Default)]
1579    struct RecordingSink {
1580        alarms: Mutex<Vec<DuplicityAlarm>>,
1581    }
1582    impl DuplicityAlarmSink for RecordingSink {
1583        fn raise(&self, alarm: &DuplicityAlarm) {
1584            self.alarms.lock().push(alarm.clone());
1585        }
1586    }
1587
1588    fn sample_alarm() -> DuplicityAlarm {
1589        DuplicityAlarm {
1590            subject_cid512: "bafyat9ptestsubject".to_owned(),
1591            kind: DuplicityKind::SameEpochFork,
1592            watermark_epoch: 7,
1593            watermark_digest: [0x11; H512_LEN],
1594            divergent_epoch: 7,
1595            divergent_digest: [0x22; H512_LEN],
1596        }
1597    }
1598
1599    #[test]
1600    fn wal_alarm_is_durable_and_reopens_with_chain_intact() {
1601        let dir = tempfile::tempdir().unwrap();
1602        let path = dir.path().join("duplicity.wal");
1603        let sink = open_alarm_wal(&path).unwrap();
1604        sink.raise(&sample_alarm());
1605        let first_len = std::fs::metadata(&path).unwrap().len();
1606        assert!(first_len > ALARM_WAL_MAGIC.len() as u64);
1607        drop(sink);
1608
1609        let reopened = open_alarm_wal(&path).unwrap();
1610        reopened.raise(&DuplicityAlarm {
1611            kind: DuplicityKind::HigherEpochFork,
1612            divergent_epoch: 9,
1613            ..sample_alarm()
1614        });
1615        assert!(std::fs::metadata(path).unwrap().len() > first_len);
1616    }
1617
1618    #[test]
1619    fn wal_alarm_refuses_tampered_entry() {
1620        let dir = tempfile::tempdir().unwrap();
1621        let path = dir.path().join("duplicity.wal");
1622        let sink = open_alarm_wal(&path).unwrap();
1623        sink.raise(&sample_alarm());
1624        drop(sink);
1625
1626        let mut bytes = std::fs::read(&path).unwrap();
1627        let payload_offset = ALARM_WAL_MAGIC.len() + 4 + 32;
1628        bytes[payload_offset + 3] ^= 0x80;
1629        std::fs::write(&path, bytes).unwrap();
1630        assert!(open_alarm_wal(&path).is_err());
1631    }
1632
1633    #[test]
1634    fn wal_alarm_checkpoint_detects_tail_truncation() {
1635        let dir = tempfile::tempdir().unwrap();
1636        let path = dir.path().join("duplicity.wal");
1637        let sink = open_alarm_wal(&path).unwrap();
1638        sink.raise(&sample_alarm());
1639        drop(sink);
1640
1641        std::fs::write(&path, ALARM_WAL_MAGIC).unwrap();
1642        assert!(open_alarm_wal(&path).is_err());
1643    }
1644
1645    // ---- FIX #1: WAL-ahead-of-checkpoint crash-window recovery ------------
1646    //
1647    // Simulates a crash after an entry's WAL fsync but before its checkpoint
1648    // persist: the WAL holds a durable entry the checkpoint does not yet name.
1649    // `open` must ACCEPT this one-entry lag (the durable WAL head is
1650    // authoritative), advance the checkpoint, and let the next append chain
1651    // correctly — never brick or corrupt the log.
1652    #[test]
1653    fn wal_ahead_of_checkpoint_by_one_entry_recovers() {
1654        let dir = tempfile::tempdir().unwrap();
1655        let path = dir.path().join("duplicity.wal");
1656        let checkpoint = path.with_extension("checkpoint");
1657
1658        let sink = open_alarm_wal(&path).unwrap();
1659        sink.raise(&sample_alarm());
1660        // Capture the checkpoint as of entry A (this is the "checkpoint behind"
1661        // state the crash leaves once a *second* entry is appended).
1662        let cp_after_a = std::fs::read(&checkpoint).unwrap();
1663        sink.raise(&DuplicityAlarm {
1664            divergent_epoch: 42,
1665            ..sample_alarm()
1666        });
1667        drop(sink);
1668
1669        // Roll the checkpoint back to entry A while the WAL still holds A+B: the
1670        // exact WAL-ahead/checkpoint-behind window the reviewer flagged.
1671        std::fs::write(&checkpoint, &cp_after_a).unwrap();
1672
1673        // Recovery must succeed (not a spurious mismatch error)...
1674        let reopened = open_alarm_wal(&path).unwrap();
1675        // ...and the next append must chain cleanly, so a later reopen is clean.
1676        reopened.raise(&DuplicityAlarm {
1677            divergent_epoch: 43,
1678            ..sample_alarm()
1679        });
1680        drop(reopened);
1681        assert!(
1682            open_alarm_wal(&path).is_ok(),
1683            "post-recovery append must keep the chain valid"
1684        );
1685    }
1686
1687    // A checkpoint two-or-more entries behind is NOT a normal crash window
1688    // (the store persists the checkpoint after every single append), so it must
1689    // fail closed rather than be silently accepted.
1690    #[test]
1691    fn wal_ahead_of_checkpoint_by_two_entries_fails_closed() {
1692        let dir = tempfile::tempdir().unwrap();
1693        let path = dir.path().join("duplicity.wal");
1694        let checkpoint = path.with_extension("checkpoint");
1695
1696        let sink = open_alarm_wal(&path).unwrap();
1697        sink.raise(&sample_alarm());
1698        let cp_after_a = std::fs::read(&checkpoint).unwrap();
1699        sink.raise(&DuplicityAlarm {
1700            divergent_epoch: 2,
1701            ..sample_alarm()
1702        });
1703        sink.raise(&DuplicityAlarm {
1704            divergent_epoch: 3,
1705            ..sample_alarm()
1706        });
1707        drop(sink);
1708
1709        // Checkpoint names entry A, WAL holds A+B+C ⇒ two-entry lag ⇒ reject.
1710        std::fs::write(&checkpoint, &cp_after_a).unwrap();
1711        assert!(open_alarm_wal(&path).is_err());
1712    }
1713
1714    // FIX #3: a rolled-back / forged checkpoint (re-pointed at a truncated head
1715    // without the signing key) is rejected — the signature no longer verifies.
1716    #[test]
1717    fn wal_alarm_rejects_forged_checkpoint() {
1718        let dir = tempfile::tempdir().unwrap();
1719        let path = dir.path().join("duplicity.wal");
1720        let checkpoint = path.with_extension("checkpoint");
1721
1722        let sink = open_alarm_wal(&path).unwrap();
1723        sink.raise(&sample_alarm());
1724        drop(sink);
1725
1726        // Corrupt the checkpoint's signature bytes (leave the head intact): the
1727        // hybrid signature must fail to verify, so `open` fails closed.
1728        let mut bytes = std::fs::read(&checkpoint).unwrap();
1729        let last = bytes.len() - 1;
1730        bytes[last] ^= 0x80;
1731        std::fs::write(&checkpoint, bytes).unwrap();
1732        assert!(open_alarm_wal(&path).is_err());
1733    }
1734
1735    // FIX #3: a whole-chain rewrite to a *different but internally hash-consistent*
1736    // journal is rejected because the attacker cannot forge the per-entry hybrid
1737    // signature — even if they also delete the checkpoint.
1738    #[test]
1739    fn wal_alarm_rejects_rewrite_without_signing_key() {
1740        let dir = tempfile::tempdir().unwrap();
1741        let path = dir.path().join("duplicity.wal");
1742        let sink = open_alarm_wal(&path).unwrap();
1743        sink.raise(&sample_alarm());
1744        drop(sink);
1745
1746        // Attacker forges a fresh single-entry journal with a *valid* BLAKE3 chain
1747        // but a bogus signature (they lack the key), and deletes the checkpoint.
1748        let payload = encode_alarm(&sample_alarm()).unwrap();
1749        let previous = [0u8; 32];
1750        let mut hasher = blake3::Hasher::new();
1751        hasher.update(&previous);
1752        hasher.update(&payload);
1753        let entry_hash = *hasher.finalize().as_bytes();
1754        let forged_sig = vec![0u8; 64];
1755        let mut forged = Vec::new();
1756        forged.extend_from_slice(ALARM_WAL_MAGIC);
1757        forged.extend_from_slice(&(payload.len() as u32).to_be_bytes());
1758        forged.extend_from_slice(&previous);
1759        forged.extend_from_slice(&payload);
1760        forged.extend_from_slice(&entry_hash);
1761        forged.extend_from_slice(&(forged_sig.len() as u32).to_be_bytes());
1762        forged.extend_from_slice(&forged_sig);
1763        std::fs::write(&path, forged).unwrap();
1764        let _ = std::fs::remove_file(path.with_extension("checkpoint"));
1765        assert!(
1766            open_alarm_wal(&path).is_err(),
1767            "a rewrite without the signing key must fail the entry signature check"
1768        );
1769    }
1770
1771    impl RecordingSink {
1772        fn count(&self) -> usize {
1773            self.alarms.lock().len()
1774        }
1775        fn last_kind(&self) -> Option<DuplicityKind> {
1776            self.alarms.lock().last().map(|a| a.kind)
1777        }
1778    }
1779
1780    fn guard() -> DuplicityGuard<InMemoryWatermarkStore, RecordingSink> {
1781        DuplicityGuard::with_alarm(InMemoryWatermarkStore::new(), RecordingSink::default())
1782    }
1783
1784    // ---- honest succession advances the watermark -------------------------
1785
1786    #[test]
1787    fn watermark_advances_on_honest_succession() {
1788        let (g, n1, n2) = (signer(), signer(), signer());
1789        let (cap0, s0) = genesis(&g, &[&n1]);
1790        let guard = guard();
1791        guard.seed_genesis(&verified_genesis(&cap0)).unwrap();
1792        // Watermark starts at genesis (epoch 0, non-terminal).
1793        let wm0 = guard.watermark(&s0.subject_cid512).unwrap().unwrap();
1794        assert_eq!(wm0.epoch, 0);
1795        assert!(!wm0.terminal);
1796
1797        let r1 = update(&s0.subject_cid512, 1, s0.record_digest, &n1, &[&n2]);
1798        let s1 = match guard.admit_successor(&r1, NOW).unwrap() {
1799            Admission::Advanced(s) => s,
1800            other => panic!("expected Advanced, got {other:?}"),
1801        };
1802        assert_eq!(s1.epoch, 1);
1803
1804        // Watermark advanced to epoch 1 with r1's digest.
1805        let wm1 = guard.watermark(&s0.subject_cid512).unwrap().unwrap();
1806        assert_eq!(wm1.epoch, 1);
1807        assert_eq!(wm1.record_digest, record_digest(&r1));
1808        // No alarms on a clean chain.
1809        assert_eq!(guard.store_alarm_count(), 0);
1810
1811        // Extend once more: predecessor is now the watermark head s1.
1812        let (n3,) = (signer(),);
1813        let r2 = update(&s1.subject_cid512, 2, s1.record_digest, &n2, &[&n3]);
1814        let s2 = match guard.admit_successor(&r2, NOW).unwrap() {
1815            Admission::Advanced(s) => s,
1816            other => panic!("expected Advanced, got {other:?}"),
1817        };
1818        assert_eq!(s2.epoch, 2);
1819        assert_eq!(guard.store_alarm_count(), 0);
1820    }
1821
1822    #[test]
1823    fn expired_accepted_head_cannot_authorize_successor() {
1824        let (g, n1, n2, n3) = (signer(), signer(), signer(), signer());
1825        let (cap0, s0) = genesis(&g, &[&n1]);
1826        let guard = guard();
1827        guard.seed_genesis(&verified_genesis(&cap0)).unwrap();
1828        let r1 = update_salted(
1829            &s0.subject_cid512,
1830            1,
1831            s0.record_digest,
1832            &n1,
1833            &[&n2],
1834            "2026-07-10T00:00:00Z",
1835            None,
1836        );
1837        let s1 = match guard.admit_successor(&r1, NOW).unwrap() {
1838            Admission::Advanced(state) => state,
1839            other => panic!("expected advance, got {other:?}"),
1840        };
1841        let r2 = update(&s1.subject_cid512, 2, s1.record_digest, &n2, &[&n3]);
1842        assert!(matches!(
1843            guard.admit_successor(&r2, "2026-07-11T00:00:00Z"),
1844            Err(AdmissionError::AcceptedHeadNotFresh(_))
1845        ));
1846        assert_eq!(
1847            guard.watermark(&s0.subject_cid512).unwrap().unwrap().epoch,
1848            1
1849        );
1850        assert_eq!(guard.store_alarm_count(), 0);
1851    }
1852
1853    #[test]
1854    fn idempotent_representation_is_already_known() {
1855        let (g, n1, n2) = (signer(), signer(), signer());
1856        let (cap0, s0) = genesis(&g, &[&n1]);
1857        let guard = guard();
1858        guard.seed_genesis(&verified_genesis(&cap0)).unwrap();
1859        let r1 = update(&s0.subject_cid512, 1, s0.record_digest, &n1, &[&n2]);
1860        guard.admit_successor(&r1, NOW).unwrap();
1861        // Present the SAME record again: idempotent, no alarm, watermark unchanged.
1862        let outcome = guard.admit_successor(&r1, NOW).unwrap();
1863        assert_eq!(outcome, Admission::AlreadyKnown);
1864        assert_eq!(guard.store_alarm_count(), 0);
1865    }
1866
1867    // ---- B2 core: same-epoch divergent fork = duplicity -------------------
1868
1869    #[test]
1870    fn same_epoch_divergent_fork_is_duplicity() {
1871        let (g, n1, n2a, n2b) = (signer(), signer(), signer(), signer());
1872        let (cap0, s0) = genesis(&g, &[&n1]);
1873        let guard = guard();
1874        guard.seed_genesis(&verified_genesis(&cap0)).unwrap();
1875
1876        // Honest r1 at epoch 1, accepted → watermark (1, digest_a).
1877        let r1a = update_salted(
1878            &s0.subject_cid512,
1879            1,
1880            s0.record_digest,
1881            &n1,
1882            &[&n2a],
1883            FUTURE,
1884            Some("honest"),
1885        );
1886        guard.admit_successor(&r1a, NOW).unwrap();
1887
1888        // Divergent r1' at epoch 1: ALSO signed by the committed key n1, ALSO
1889        // chaining from genesis — individually B1-valid — but a different body
1890        // (different salt + next key) ⇒ different digest. This is the stolen-
1891        // next-key / equivocating-holder fork.
1892        let r1b = update_salted(
1893            &s0.subject_cid512,
1894            1,
1895            s0.record_digest,
1896            &n1,
1897            &[&n2b],
1898            FUTURE,
1899            Some("evil"),
1900        );
1901        assert_ne!(record_digest(&r1a), record_digest(&r1b));
1902
1903        let err = guard.admit_successor(&r1b, NOW).unwrap_err();
1904        match err {
1905            AdmissionError::Duplicity(alarm) => {
1906                assert_eq!(alarm.kind, DuplicityKind::SameEpochFork);
1907                assert_eq!(alarm.watermark_epoch, 1);
1908                assert_eq!(alarm.watermark_digest, record_digest(&r1a));
1909                assert_eq!(alarm.divergent_digest, record_digest(&r1b));
1910            }
1911            other => panic!("expected Duplicity, got {other:?}"),
1912        }
1913        // The alarm fired exactly once and the honest watermark did NOT move.
1914        assert_eq!(guard.store_alarm_count(), 1);
1915        assert_eq!(guard.last_alarm_kind(), Some(DuplicityKind::SameEpochFork));
1916        let wm = guard.watermark(&s0.subject_cid512).unwrap().unwrap();
1917        assert_eq!(wm.record_digest, record_digest(&r1a));
1918    }
1919
1920    // ---- B2 core: no max-epoch selection ----------------------------------
1921    //
1922    // Honest chain reaches epoch 2; a valid fork appears at epoch 1 (below the
1923    // watermark). It must be REJECTED, never preferred, never allowed to rewrite
1924    // history — and it must alarm.
1925    #[test]
1926    fn lower_epoch_fork_below_watermark_is_rejected_not_preferred() {
1927        let (g, n1, n2, n1_forknext) = (signer(), signer(), signer(), signer());
1928        let (cap0, s0) = genesis(&g, &[&n1]);
1929        let guard = guard();
1930        guard.seed_genesis(&verified_genesis(&cap0)).unwrap();
1931
1932        // Honest: genesis → r1 (epoch 1) → r2 (epoch 2). Watermark at epoch 2.
1933        let r1 = update_salted(
1934            &s0.subject_cid512,
1935            1,
1936            s0.record_digest,
1937            &n1,
1938            &[&n2],
1939            FUTURE,
1940            Some("honest-1"),
1941        );
1942        let s1 = match guard.admit_successor(&r1, NOW).unwrap() {
1943            Admission::Advanced(s) => s,
1944            other => panic!("{other:?}"),
1945        };
1946        let (n3,) = (signer(),);
1947        let r2 = update(&s1.subject_cid512, 2, s1.record_digest, &n2, &[&n3]);
1948        guard.admit_successor(&r2, NOW).unwrap();
1949        assert_eq!(
1950            guard.watermark(&s0.subject_cid512).unwrap().unwrap().epoch,
1951            2
1952        );
1953
1954        // A divergent BUT B1-VALID fork at epoch 1: same committed signer n1, same
1955        // genesis linkage, different body ⇒ a genuine lower-epoch fork. Naive
1956        // "max epoch" logic would keep epoch 2 (fine) but must still ALARM that an
1957        // equivocating lower branch exists; naive "prefer/select" logic must never
1958        // adopt it. We reject + alarm.
1959        let fork1 = update_salted(
1960            &s0.subject_cid512,
1961            1,
1962            s0.record_digest,
1963            &n1,
1964            &[&n1_forknext],
1965            FUTURE,
1966            Some("fork"),
1967        );
1968        let err = guard.admit_successor(&fork1, NOW).unwrap_err();
1969        match err {
1970            AdmissionError::Duplicity(alarm) => {
1971                assert_eq!(alarm.kind, DuplicityKind::BelowWatermarkFork);
1972                assert_eq!(alarm.watermark_epoch, 2);
1973                assert_eq!(alarm.divergent_epoch, 1);
1974            }
1975            other => panic!("expected Duplicity(BelowWatermarkFork), got {other:?}"),
1976        }
1977        // Watermark still at the honest epoch 2 — the fork did not rewrite it.
1978        assert_eq!(
1979            guard.watermark(&s0.subject_cid512).unwrap().unwrap().epoch,
1980            2
1981        );
1982        assert_eq!(guard.store_alarm_count(), 1);
1983    }
1984
1985    // ---- B2 core: higher-epoch record on a different fork -----------------
1986    //
1987    // A record at epoch > watermark that chains through a predecessor other than
1988    // the watermark head is the max-epoch-selection trap: it looks like progress.
1989    // It must be rejected as a fork.
1990    #[test]
1991    fn higher_epoch_off_watermark_head_is_duplicity() {
1992        let (g, n1, n2) = (signer(), signer(), signer());
1993        let (cap0, s0) = genesis(&g, &[&n1]);
1994        let guard = guard();
1995        guard.seed_genesis(&verified_genesis(&cap0)).unwrap();
1996
1997        // Honest r1 accepted → watermark at epoch 1 (digest_a).
1998        let r1a = update_salted(
1999            &s0.subject_cid512,
2000            1,
2001            s0.record_digest,
2002            &n1,
2003            &[&n2],
2004            FUTURE,
2005            Some("honest"),
2006        );
2007        let _s1a = guard.admit_successor(&r1a, NOW).unwrap();
2008
2009        // Attacker builds a DIVERGENT epoch-1 record r1b (a fork head we never
2010        // accepted), then a "successor" r2b at epoch 2 chaining through r1b. r2b
2011        // is individually B1-valid against r1b's state, and epoch 2 > watermark 1
2012        // — the classic "just take the higher epoch" bait.
2013        let (n2b, n3) = (signer(), signer());
2014        let r1b = update_salted(
2015            &s0.subject_cid512,
2016            1,
2017            s0.record_digest,
2018            &n1,
2019            &[&n2b],
2020            FUTURE,
2021            Some("evil"),
2022        );
2023        let s1b = ChainState::from_validated_update(&r1b);
2024        let r2b = update(&s1b.subject_cid512, 2, s1b.record_digest, &n2b, &[&n3]);
2025
2026        // Present r2b with its own (fork) predecessor s1b. B1 passes; the guard
2027        // catches that s1b is NOT our watermark head.
2028        let err = guard.admit_successor(&r2b, NOW).unwrap_err();
2029        match err {
2030            AdmissionError::Duplicity(alarm) => {
2031                assert_eq!(alarm.kind, DuplicityKind::HigherEpochFork);
2032                assert_eq!(alarm.watermark_epoch, 1);
2033                assert_eq!(alarm.divergent_epoch, 2);
2034            }
2035            other => panic!("expected Duplicity(HigherEpochFork), got {other:?}"),
2036        }
2037        assert_eq!(
2038            guard.watermark(&s0.subject_cid512).unwrap().unwrap().epoch,
2039            1
2040        );
2041        assert_eq!(guard.store_alarm_count(), 1);
2042    }
2043
2044    // ---- B3: declared-immutable identity has a terminal watermark ---------
2045
2046    #[test]
2047    fn immutable_identity_has_terminal_watermark() {
2048        let (g, n1) = (signer(), signer());
2049        // Genesis pre-committing to NOTHING = declared-immutable.
2050        let (cap0, s0) = genesis(&g, &[]);
2051        assert!(s0.next_key_commitments.is_empty());
2052        let guard = guard();
2053        guard.seed_genesis(&verified_genesis(&cap0)).unwrap();
2054
2055        // The seeded watermark is terminal at epoch 0.
2056        let wm = guard.watermark(&s0.subject_cid512).unwrap().unwrap();
2057        assert!(wm.terminal);
2058        assert_eq!(wm.epoch, 0);
2059
2060        // Any attempted successor is refused as frozen — B1 is not even reached.
2061        let rec = update(&s0.subject_cid512, 1, s0.record_digest, &n1, &[&n1]);
2062        let err = guard.admit_successor(&rec, NOW).unwrap_err();
2063        assert!(
2064            matches!(err, AdmissionError::FrozenIdentity { epoch: 0 }),
2065            "expected FrozenIdentity, got {err:?}"
2066        );
2067        assert_eq!(guard.store_alarm_count(), 0);
2068    }
2069
2070    // ---- B3: exhausted / frozen-forever -----------------------------------
2071    //
2072    // A holder publishes a final rotation committing to no further keys. The
2073    // rotation is ACCEPTED (valid successor), the resulting state is terminal, and
2074    // every later successor is denied — no recovery path, by design.
2075    #[test]
2076    fn exhausted_rotation_accepts_then_freezes() {
2077        let (g, n1, later) = (signer(), signer(), signer());
2078        let (cap0, s0) = genesis(&g, &[&n1]);
2079        let guard = guard();
2080        guard.seed_genesis(&verified_genesis(&cap0)).unwrap();
2081
2082        // Final rotation r1: signed by committed n1, pre-committing to EMPTY.
2083        let r1 = update(&s0.subject_cid512, 1, s0.record_digest, &n1, &[]);
2084        let s1 = match guard.admit_successor(&r1, NOW).unwrap() {
2085            Admission::Frozen(s) => s,
2086            other => panic!("expected Frozen (exhausted rotation accepted), got {other:?}"),
2087        };
2088        assert_eq!(s1.epoch, 1);
2089        assert!(s1.next_key_commitments.is_empty());
2090
2091        // Watermark is now terminal at epoch 1.
2092        let wm = guard.watermark(&s0.subject_cid512).unwrap().unwrap();
2093        assert!(wm.terminal);
2094        assert_eq!(wm.epoch, 1);
2095
2096        // Any further rotation is denied — frozen forever, no recovery.
2097        let r2 = update(&s1.subject_cid512, 2, s1.record_digest, &later, &[&later]);
2098        let err = guard.admit_successor(&r2, NOW).unwrap_err();
2099        assert!(
2100            matches!(err, AdmissionError::FrozenIdentity { epoch: 1 }),
2101            "expected FrozenIdentity at epoch 1, got {err:?}"
2102        );
2103        assert_eq!(guard.store_alarm_count(), 0);
2104    }
2105
2106    /// Replaying the exact record that froze the identity (e.g. a retry after a
2107    /// lost response) is AlreadyKnown, not FrozenIdentity: the caller must be
2108    /// able to learn its terminal rotation already succeeded. No alarm, no
2109    /// watermark change, still terminal.
2110    #[test]
2111    fn terminal_head_exact_replay_is_already_known() {
2112        let (g, n1) = (signer(), signer());
2113        let (cap0, s0) = genesis(&g, &[&n1]);
2114        let guard = guard();
2115        guard.seed_genesis(&verified_genesis(&cap0)).unwrap();
2116
2117        // Final rotation r1 (pre-commits to nothing) accepted → Frozen.
2118        let r1 = update(&s0.subject_cid512, 1, s0.record_digest, &n1, &[]);
2119        match guard.admit_successor(&r1, NOW).unwrap() {
2120            Admission::Frozen(_) => {}
2121            other => panic!("expected Frozen, got {other:?}"),
2122        }
2123
2124        // Byte-identical replay of r1: idempotent success, not FrozenIdentity.
2125        let outcome = guard.admit_successor(&r1, NOW).unwrap();
2126        assert_eq!(outcome, Admission::AlreadyKnown);
2127        // Watermark untouched and still terminal; no alarm raised.
2128        let wm = guard.watermark(&s0.subject_cid512).unwrap().unwrap();
2129        assert_eq!(wm.epoch, 1);
2130        assert!(wm.terminal);
2131        assert_eq!(guard.store_alarm_count(), 0);
2132
2133        // A DIFFERENT record is still refused as frozen.
2134        let (later,) = (signer(),);
2135        let r2 = update(&s0.subject_cid512, 2, record_digest(&r1), &later, &[&later]);
2136        let err = guard.admit_successor(&r2, NOW).unwrap_err();
2137        assert!(
2138            matches!(err, AdmissionError::FrozenIdentity { epoch: 1 }),
2139            "expected FrozenIdentity, got {err:?}"
2140        );
2141    }
2142
2143    // ---- fail-closed plumbing ---------------------------------------------
2144
2145    #[test]
2146    fn unseeded_did_is_refused() {
2147        let (g, n1, n2) = (signer(), signer(), signer());
2148        let (_cap0, s0) = genesis(&g, &[&n1]);
2149        let guard = guard();
2150        // No seed_genesis.
2151        let r1 = update(&s0.subject_cid512, 1, s0.record_digest, &n1, &[&n2]);
2152        let err = guard.admit_successor(&r1, NOW).unwrap_err();
2153        assert!(
2154            matches!(err, AdmissionError::NotSeeded { .. }),
2155            "expected NotSeeded, got {err:?}"
2156        );
2157    }
2158
2159    #[test]
2160    fn b1_rejection_propagates_without_alarm() {
2161        let (g, n1, evil, n2) = (signer(), signer(), signer(), signer());
2162        let (cap0, s0) = genesis(&g, &[&n1]);
2163        let guard = guard();
2164        guard.seed_genesis(&verified_genesis(&cap0)).unwrap();
2165        // Signed by an uncommitted key → B1 SignerNotCommitted, NOT duplicity.
2166        let rec = update(&s0.subject_cid512, 1, s0.record_digest, &evil, &[&n2]);
2167        let err = guard.admit_successor(&rec, NOW).unwrap_err();
2168        assert!(
2169            matches!(
2170                err,
2171                AdmissionError::Successor(SuccessorError::SignerNotCommitted)
2172            ),
2173            "expected Successor(SignerNotCommitted), got {err:?}"
2174        );
2175        // A B1 failure is not a fork — no alarm.
2176        assert_eq!(guard.store_alarm_count(), 0);
2177    }
2178
2179    // ---- FIX (#959): atomic per-DID admission under concurrency -----------
2180    //
2181    // Two+ threads present divergent epoch-2 successors of the SAME head. Each
2182    // is individually B1-valid; without the per-DID admission lock both could
2183    // read the head, both pass, both put → two Advanced. With the lock, exactly
2184    // one Advanced and the rest are duplicity; the watermark reflects only the
2185    // winner.
2186    #[test]
2187    fn concurrent_divergent_successors_of_same_head_yield_exactly_one_advance() {
2188        const N: usize = 4;
2189        let (g, n1, n2) = (signer(), signer(), signer());
2190        let nexts: Vec<Signer> = (0..N).map(|_| signer()).collect();
2191        let next_refs: Vec<&Signer> = nexts.iter().collect();
2192        let (cap0, s0) = genesis(&g, &[&n1]);
2193        let guard = guard();
2194        guard.seed_genesis(&verified_genesis(&cap0)).unwrap();
2195
2196        // Honest r1 (epoch 1) accepted → watermark at (1, digest_r1).
2197        let r1 = update(&s0.subject_cid512, 1, s0.record_digest, &n1, &[&n2]);
2198        let s1 = match guard.admit_successor(&r1, NOW).unwrap() {
2199            Admission::Advanced(s) => s,
2200            other => panic!("expected Advanced, got {other:?}"),
2201        };
2202        assert_eq!(guard.store_alarm_count(), 0);
2203
2204        // N divergent epoch-2 successors of s1: each signed by the key committed
2205        // at epoch 1 (n2), each chaining from s1, but a distinct body (distinct
2206        // next key + salt) ⇒ a distinct digest.
2207        let records: Vec<UpdateRecord> = (0..N)
2208            .map(|i| {
2209                update_salted(
2210                    &s1.subject_cid512,
2211                    2,
2212                    s1.record_digest,
2213                    &n2,
2214                    &[next_refs[i]],
2215                    FUTURE,
2216                    Some(&format!("fork-{i}")),
2217                )
2218            })
2219            .collect();
2220        let digests: Vec<_> = records.iter().map(record_digest).collect();
2221        let mut deduped = digests.clone();
2222        deduped.sort_unstable();
2223        deduped.dedup();
2224        assert_eq!(deduped.len(), N, "records must all diverge");
2225
2226        let outcomes: Mutex<Vec<Result<Admission, AdmissionError>>> = Mutex::new(Vec::new());
2227        let guard = &guard;
2228        std::thread::scope(|scope| {
2229            for rec in &records {
2230                let outcomes = &outcomes;
2231                scope.spawn(move || {
2232                    outcomes.lock().push(guard.admit_successor(rec, NOW));
2233                });
2234            }
2235        });
2236
2237        let outcomes = outcomes.into_inner();
2238        assert_eq!(outcomes.len(), N, "every admission must complete");
2239        let advanced = outcomes
2240            .iter()
2241            .filter(|o| matches!(o, Ok(Admission::Advanced(_))))
2242            .count();
2243        assert_eq!(advanced, 1, "exactly one Advanced; got {outcomes:?}");
2244        let forks = outcomes
2245            .iter()
2246            .filter(|o| matches!(o, Err(AdmissionError::Duplicity(_))))
2247            .count();
2248        assert_eq!(forks, N - 1);
2249        // Every fork verdict is a same-epoch fork (the watermark moved to epoch
2250        // 2 under the winner, so each loser sees its own epoch-2 digest differ).
2251        let all_same_epoch = outcomes.iter().all(|o| match o {
2252            Err(AdmissionError::Duplicity(a)) => a.kind == DuplicityKind::SameEpochFork,
2253            Ok(Admission::Advanced(_)) => true,
2254            _ => false,
2255        });
2256        assert!(all_same_epoch, "non-fork outcome: {outcomes:?}");
2257
2258        // The watermark reflects ONLY the winner: epoch 2, exactly one of the
2259        // candidate digests, and exactly one alarm was raised.
2260        let wm = guard.watermark(&s0.subject_cid512).unwrap().unwrap();
2261        assert_eq!(wm.epoch, 2);
2262        assert!(
2263            digests.contains(&wm.record_digest),
2264            "watermark digest must be one of the candidates"
2265        );
2266        assert_eq!(guard.store_alarm_count(), N - 1);
2267    }
2268
2269    #[test]
2270    fn independent_guards_share_store_cas() {
2271        const N: usize = 8;
2272        let (g, n1, n2) = (signer(), signer(), signer());
2273        let nexts: Vec<_> = (0..N).map(|_| signer()).collect();
2274        let store = Arc::new(InMemoryWatermarkStore::new());
2275        let a = DuplicityGuard::new(Arc::clone(&store));
2276        let b = DuplicityGuard::new(store);
2277        let (cap0, s0) = genesis(&g, &[&n1]);
2278        a.seed_genesis(&verified_genesis(&cap0)).unwrap();
2279        let r1 = update(&s0.subject_cid512, 1, s0.record_digest, &n1, &[&n2]);
2280        let s1 = match a.admit_successor(&r1, NOW).unwrap() {
2281            Admission::Advanced(state) => state,
2282            other => panic!("expected advance, got {other:?}"),
2283        };
2284        let records: Vec<_> = nexts
2285            .iter()
2286            .enumerate()
2287            .map(|(i, next)| {
2288                update_salted(
2289                    &s1.subject_cid512,
2290                    2,
2291                    s1.record_digest,
2292                    &n2,
2293                    &[next],
2294                    FUTURE,
2295                    Some(&format!("independent-{i}")),
2296                )
2297            })
2298            .collect();
2299        let barrier = std::sync::Barrier::new(N);
2300        let outcomes = Mutex::new(Vec::new());
2301        std::thread::scope(|scope| {
2302            for (i, record) in records.iter().enumerate() {
2303                let guard = if i % 2 == 0 { &a } else { &b };
2304                let outcomes = &outcomes;
2305                let barrier = &barrier;
2306                scope.spawn(move || {
2307                    barrier.wait();
2308                    outcomes.lock().push(guard.admit_successor(record, NOW));
2309                });
2310            }
2311        });
2312        let outcomes = outcomes.into_inner();
2313        assert_eq!(
2314            outcomes
2315                .iter()
2316                .filter(|o| matches!(o, Ok(Admission::Advanced(_))))
2317                .count(),
2318            1
2319        );
2320        assert_eq!(
2321            outcomes
2322                .iter()
2323                .filter(|o| matches!(o, Err(AdmissionError::Duplicity(_))))
2324                .count(),
2325            N - 1
2326        );
2327        assert_eq!(b.watermark(&s0.subject_cid512).unwrap().unwrap().epoch, 2);
2328    }
2329
2330    // ---- FIX (#959): seed_genesis is rollback-safe ------------------------
2331    #[test]
2332    fn seed_genesis_refuses_to_roll_back_after_advance() {
2333        let (g, n1, n2) = (signer(), signer(), signer());
2334        let (cap0, s0) = genesis(&g, &[&n1]);
2335        let guard = guard();
2336        // First seed and an idempotent re-seed of the exact same genesis are OK.
2337        guard.seed_genesis(&verified_genesis(&cap0)).unwrap();
2338        guard.seed_genesis(&verified_genesis(&cap0)).unwrap();
2339        assert_eq!(
2340            guard.watermark(&s0.subject_cid512).unwrap().unwrap().epoch,
2341            0
2342        );
2343
2344        // Advance the chain to epoch 1.
2345        let r1 = update(&s0.subject_cid512, 1, s0.record_digest, &n1, &[&n2]);
2346        guard.admit_successor(&r1, NOW).unwrap();
2347        assert_eq!(
2348            guard.watermark(&s0.subject_cid512).unwrap().unwrap().epoch,
2349            1
2350        );
2351
2352        // A stray / hostile re-seed must NOT roll the anchor back to genesis.
2353        let err = guard.seed_genesis(&verified_genesis(&cap0)).unwrap_err();
2354        assert!(
2355            matches!(
2356                err,
2357                AdmissionError::AlreadySeeded {
2358                    existing_epoch: 1,
2359                    ..
2360                }
2361            ),
2362            "expected AlreadySeeded, got {err:?}"
2363        );
2364        // Watermark unchanged at the honest epoch 1.
2365        assert_eq!(
2366            guard.watermark(&s0.subject_cid512).unwrap().unwrap().epoch,
2367            1
2368        );
2369        assert_eq!(guard.store_alarm_count(), 0);
2370    }
2371
2372    // ---- FIX #2: a real fork routes through the production guard into the
2373    // durable, signed, tamper-evident sink (end-to-end, not a hand-built alarm).
2374    #[test]
2375    fn end_to_end_fork_routes_to_durable_signed_sink() {
2376        let dir = tempfile::tempdir().unwrap();
2377        let wal = dir.path().join("dup.wal");
2378        let (ed_sk, pq_sk) = alarm_keys();
2379
2380        let (g, n1, n2a, n2b) = (signer(), signer(), signer(), signer());
2381        let (cap0, s0) = genesis(&g, &[&n1]);
2382
2383        // The PRODUCTION construction path: guard wired to the signed WAL sink.
2384        let guard =
2385            DuplicityGuard::with_durable_alarm(InMemoryWatermarkStore::new(), &wal, ed_sk, pq_sk)
2386                .unwrap();
2387        guard.seed_genesis(&verified_genesis(&cap0)).unwrap();
2388
2389        // Honest r1 accepted (no alarm).
2390        let r1a = update_salted(
2391            &s0.subject_cid512,
2392            1,
2393            s0.record_digest,
2394            &n1,
2395            &[&n2a],
2396            FUTURE,
2397            Some("honest"),
2398        );
2399        guard.admit_successor(&r1a, NOW).unwrap();
2400        assert_eq!(
2401            std::fs::metadata(&wal).unwrap().len(),
2402            ALARM_WAL_MAGIC.len() as u64,
2403            "a clean succession must not write an alarm entry"
2404        );
2405
2406        // A genuine same-epoch divergent fork → real duplicity detection.
2407        let r1b = update_salted(
2408            &s0.subject_cid512,
2409            1,
2410            s0.record_digest,
2411            &n1,
2412            &[&n2b],
2413            FUTURE,
2414            Some("evil"),
2415        );
2416        let err = guard.admit_successor(&r1b, NOW).unwrap_err();
2417        assert!(
2418            matches!(err, AdmissionError::Duplicity(_)),
2419            "expected Duplicity, got {err:?}"
2420        );
2421
2422        // The detection routed to the durable sink: the WAL grew a signed entry
2423        // that survives reopen with full chain + signature verification.
2424        drop(guard);
2425        assert!(
2426            std::fs::metadata(&wal).unwrap().len() > ALARM_WAL_MAGIC.len() as u64,
2427            "the fork must be durably recorded"
2428        );
2429        assert!(
2430            open_alarm_wal(&wal).is_ok(),
2431            "the durable signed alarm must reopen and verify"
2432        );
2433    }
2434
2435    // ---- #961: anchor the predecessor — forged ChainState cannot authorize --
2436    //
2437    // The watermark pins only (epoch, H512(record)). An attacker who learns the
2438    // honest genesis digest D0 and wants an evil key K_evil authorized cannot,
2439    // under the anchored API, present a ChainState claiming the genesis
2440    // pre-committed to K_evil: the guard takes the predecessor RECORD, recomputes
2441    // its H512 against the watermark, and reads next_key_commitments from those
2442    // verified bytes. The honest genesis committed to n1, not K_evil, so B1's
2443    // signer-authorization gate rejects K_evil — even though the attacker echoes
2444    // D0 correctly in prev_record_digest. Under the pre-#961 &ChainState API this
2445    // exact attack succeeded (forged commitments were trusted).
2446    #[test]
2447    fn forged_predecessor_cannot_authorize_uncommitted_key() {
2448        let (g, n1) = (signer(), signer());
2449        let (cap0, s0) = genesis(&g, &[&n1]);
2450        let guard = guard();
2451        guard.seed_genesis(&verified_genesis(&cap0)).unwrap();
2452
2453        // K_evil was NEVER pre-committed by the honest genesis.
2454        let (evil,) = (signer(),);
2455        // The attacker knows the honest genesis digest and echoes it correctly.
2456        let attack = update(&s0.subject_cid512, 1, s0.record_digest, &evil, &[&evil]);
2457
2458        // Present the HONEST genesis record as predecessor. The anchor passes
2459        // (its digest == watermark); the guard derives commitments [commit(n1)]
2460        // from the record's bytes, NOT from any caller claim, so K_evil is not
2461        // authorized — B1 rejects it, fail-closed.
2462        let err = guard.admit_successor(&attack, NOW).unwrap_err();
2463        assert!(
2464            matches!(
2465                err,
2466                AdmissionError::Successor(SuccessorError::SignerNotCommitted)
2467            ),
2468            "expected SignerNotCommitted (evil key not in the anchored genesis commitments), got {err:?}"
2469        );
2470        // No fork alarm for a plain B1 rejection, and the watermark did not move.
2471        assert_eq!(guard.store_alarm_count(), 0);
2472        assert_eq!(
2473            guard.watermark(&s0.subject_cid512).unwrap().unwrap().epoch,
2474            0
2475        );
2476    }
2477
2478    // ---- #961: a foreign head's commitments can never authorize a successor --
2479    //
2480    // The #961 attack at the advance path: an attacker publishes a genuine fork
2481    // head r1b whose commitments include K_evil, then a fully-valid successor r2b
2482    // (epoch > watermark) signed by K_evil and chaining from r1b. Under the pre-
2483    // #961 &ChainState API the attacker could vouch for r1b's commitments while
2484    // echoing the honest digest and B1 would authorize K_evil. Under the anchored
2485    // API the guard recomputes r1b's H512, sees it is NOT the watermark head, and
2486    // rejects at the anchor — B1 never inspects r1b's commitments, so K_evil is
2487    // never authorized. (Same shape as the B2 higher-epoch test, but framed as
2488    // the #961 commitment-forgery closure.)
2489    #[test]
2490    fn foreign_head_commitments_cannot_authorize_higher_epoch_successor() {
2491        let (g, n1, n2) = (signer(), signer(), signer());
2492        let (cap0, s0) = genesis(&g, &[&n1]);
2493        let guard = guard();
2494        guard.seed_genesis(&verified_genesis(&cap0)).unwrap();
2495
2496        // Honest r1a accepted → watermark at epoch 1 (digest of r1a), committing n2.
2497        let r1a = update_salted(
2498            &s0.subject_cid512,
2499            1,
2500            s0.record_digest,
2501            &n1,
2502            &[&n2],
2503            FUTURE,
2504            Some("honest"),
2505        );
2506        let _s1a = guard.admit_successor(&r1a, NOW).unwrap();
2507
2508        // Foreign fork head r1b: commits to K_evil (n2b), same epoch, different
2509        // digest than r1a. Its commitment to n2b is real — but it is NOT our head.
2510        let (n2b, n3) = (signer(), signer());
2511        let r1b = update_salted(
2512            &s0.subject_cid512,
2513            1,
2514            s0.record_digest,
2515            &n1,
2516            &[&n2b],
2517            FUTURE,
2518            Some("evil-head"),
2519        );
2520        assert_ne!(record_digest(&r1a), record_digest(&r1b));
2521        // r2b is a FULLY valid successor of r1b: epoch 2, signed by n2b (which r1b
2522        // committed to), chaining from r1b's digest.
2523        let r2b = update(&s0.subject_cid512, 2, record_digest(&r1b), &n2b, &[&n3]);
2524
2525        // Present r1b as the predecessor. The advance path's anchor recomputes
2526        // r1b's digest and finds it != watermark → HigherEpochFork. B1 never runs,
2527        // so n2b's commitment in the foreign head is never trusted.
2528        let err = guard.admit_successor(&r2b, NOW).unwrap_err();
2529        match err {
2530            AdmissionError::Duplicity(alarm) => {
2531                assert_eq!(alarm.kind, DuplicityKind::HigherEpochFork);
2532                assert_eq!(alarm.watermark_epoch, 1);
2533                assert_eq!(alarm.divergent_epoch, 2);
2534            }
2535            other => panic!("expected Duplicity(HigherEpochFork), got {other:?}"),
2536        }
2537        // Watermark untouched at the honest epoch 1; exactly one alarm.
2538        assert_eq!(
2539            guard.watermark(&s0.subject_cid512).unwrap().unwrap().epoch,
2540            1
2541        );
2542        assert_eq!(guard.store_alarm_count(), 1);
2543        assert_eq!(
2544            guard.last_alarm_kind(),
2545            Some(DuplicityKind::HigherEpochFork)
2546        );
2547    }
2548
2549    // Small accessors so the guard's sink can be inspected in-test.
2550    impl DuplicityGuard<InMemoryWatermarkStore, RecordingSink> {
2551        fn store_alarm_count(&self) -> usize {
2552            self.alarm.count()
2553        }
2554        fn last_alarm_kind(&self) -> Option<DuplicityKind> {
2555            self.alarm.last_kind()
2556        }
2557    }
2558}