Skip to main content

qualia_client_core/
dead_mans_switch.rs

1//! **Dead-man switch** — post-death (or believed-death) disposition of the principal's data, under
2//! **gamified validation rules**, enacted by the person's **chosen friends who hold the dataset**.
3//!
4//! The consideration (Timothy, 2026-07-06): if the principal (the person) is *considered dead*, their
5//! information may be made public, or become subject to other rules — the erasure-prevention / right-to-truth
6//! stance (a murdered person's record must not simply vanish), governed by the person's **prior
7//! self-definition** and kept **reversible** (see the post-death-continuity work).
8//!
9//! The trigger must **not** be one abusable "declare dead" button — that would let an attacker (or a
10//! betrayer) fire it falsely. So validation is **gamified**: a *rule set* of independent conditions that must
11//! all hold — a **liveness lapse** (no update / no "still here" signal from the principal for X time) **and**
12//! an **attestation threshold** (a quorum of the participating parties attesting no-contact / believed-dead /
13//! abandonment). And it is enacted by the **friends who store the encrypted dataset** (the
14//! `EncryptedCommonsPayload` storers): they hold the ciphertext *and* validate the trigger, so no single
15//! party — and no outside actor — can enact it alone.
16//!
17//! **Reversibility is central.** The principal showing up alive (`principal_alive`) resets the liveness
18//! signal and un-fires a not-yet-irreversible switch. (Honesty caveat, §9: once a [`Disposition::MakePublic`]
19//! has actually released keys to a durable commons it cannot be un-published — so *which* dispositions are
20//! reversible, and the grace/limits, are values calls for Timothy.)
21//!
22//! Domain model + invariants only; the actual **key-release** on enactment (publish the data key / issue
23//! [`ConsentCredential`](crate::consent_credential::ConsentCredential)s to the disposition parties) and the
24//! storage are the crypto/commons composition (coordinate).
25
26use serde::{Deserialize, Serialize};
27
28use crate::consent_credential::PayloadCommitment;
29
30/// A **liveness heartbeat** — the principal periodically signals "still here". Its lapse (no update for
31/// `lapse_after_secs`) is one of the trigger conditions; touching it (the person is alive) is the reversibility.
32#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
33pub struct Heartbeat {
34    pub last_seen_unix: u64,
35    /// Grace period (seconds): with no update for at least this long, the liveness signal is *lapsed*.
36    pub lapse_after_secs: u64,
37}
38
39impl Heartbeat {
40    /// Creates a new instance.
41    pub fn new(last_seen_unix: u64, lapse_after_secs: u64) -> Self {
42        Self {
43            last_seen_unix,
44            lapse_after_secs,
45        }
46    }
47    /// Has the liveness signal lapsed at `now`?
48    pub fn is_lapsed(&self, now_unix: u64) -> bool {
49        now_unix.saturating_sub(self.last_seen_unix) >= self.lapse_after_secs
50    }
51    /// The principal is alive — reset the signal (reversibility).
52    pub fn touch(&mut self, now_unix: u64) {
53        self.last_seen_unix = now_unix;
54    }
55}
56
57/// What a party attests toward the trigger.
58#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
59#[serde(rename_all = "snake_case")]
60pub enum AttestationKind {
61    /// Has had no contact with the principal.
62    NoContact,
63    /// Believes the principal is dead.
64    BelievedDead,
65    /// Releases/abandons their hold (e.g. "the last lets go" — the abandonment condition).
66    Abandon,
67}
68
69/// One participating party's attestation toward enacting the switch.
70#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
71pub struct PartyAttestation {
72    pub party_did: String,
73    pub kind: AttestationKind,
74    pub time_unix: u64,
75}
76
77/// What happens to the data if the switch fires — the person's **prior self-definition** governs.
78#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
79#[serde(rename_all = "snake_case")]
80pub enum Disposition {
81    /// Make the payload public (release the data key widely). **Irreversible in effect** once released.
82    MakePublic,
83    /// Release access to specific parties (trustees, next-of-kin, a chosen representative) — reversible
84    /// (their credentials can be revoked).
85    ReleaseTo { parties: Vec<String> },
86    /// Enact other self-defined post-death rules (e.g. the digital-vellum representation), grounded-or-refused.
87    SelfDefinedRules { rules_ref: String },
88}
89
90/// The **gamified trigger rule** — the independent conditions that must *all* hold to fire, resisting a false
91/// trigger by any single party or an outside actor.
92#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
93pub struct TriggerRule {
94    /// Require the liveness heartbeat to have lapsed (no "still here" for the grace period).
95    pub require_heartbeat_lapsed: bool,
96    /// At least this many **distinct participating parties** must attest.
97    pub attestation_threshold: usize,
98    /// The participating parties — the friends/stewards who hold the dataset and validate the trigger.
99    pub parties: Vec<String>,
100}
101
102impl TriggerRule {
103    /// Is the rule satisfied at `now`, given the heartbeat + the attestations collected? Requires (heartbeat
104    /// lapsed, if required) AND (≥ `attestation_threshold` distinct *participating* parties have attested).
105    pub fn is_satisfied(
106        &self,
107        heartbeat: &Heartbeat,
108        attestations: &[PartyAttestation],
109        now_unix: u64,
110    ) -> bool {
111        if self.require_heartbeat_lapsed && !heartbeat.is_lapsed(now_unix) {
112            return false;
113        }
114        let is_party = |did: &str| self.parties.iter().any(|p| p == did);
115        let attesters: std::collections::BTreeSet<&str> = attestations
116            .iter()
117            .map(|a| a.party_did.as_str())
118            .filter(|d| is_party(d))
119            .collect();
120        attesters.len() >= self.attestation_threshold
121    }
122}
123
124/// A dead-man switch over one commons payload.
125#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
126pub struct DeadMansSwitch {
127    /// The dataset this governs (by commitment) — held by the friends (the commons storers).
128    pub payload_commitment: PayloadCommitment,
129    pub heartbeat: Heartbeat,
130    pub trigger: TriggerRule,
131    pub disposition: Disposition,
132    /// When the switch fired (enacted), if it has.
133    #[serde(default, skip_serializing_if = "Option::is_none")]
134    pub fired_unix: Option<u64>,
135}
136
137impl DeadMansSwitch {
138    /// Is the switch *currently triggerable* — the gamified rule satisfied and not already fired?
139    pub fn is_triggered(&self, attestations: &[PartyAttestation], now_unix: u64) -> bool {
140        self.fired_unix.is_none()
141            && self
142                .trigger
143                .is_satisfied(&self.heartbeat, attestations, now_unix)
144    }
145
146    /// The principal is alive — reset the liveness signal **and un-fire** a not-yet-enacted switch. This is
147    /// the reversibility: a person showing up defeats a premature or malicious trigger.
148    pub fn principal_alive(&mut self, now_unix: u64) {
149        self.heartbeat.touch(now_unix);
150        self.fired_unix = None;
151    }
152
153    /// **Enact** the switch if triggerable: record it fired and return the [`Disposition`] to apply (which
154    /// the caller carries out — publishing the key / issuing credentials to the disposition parties). Returns
155    /// `None` if the rule is not satisfied (or it already fired).
156    pub fn enact(
157        &mut self,
158        attestations: &[PartyAttestation],
159        now_unix: u64,
160    ) -> Option<&Disposition> {
161        if self.is_triggered(attestations, now_unix) {
162            self.fired_unix = Some(now_unix);
163            Some(&self.disposition)
164        } else {
165            None
166        }
167    }
168}
169
170#[cfg(test)]
171mod tests {
172    use super::*;
173
174    const C: PayloadCommitment = [11u8; 32];
175    const DAY: u64 = 24 * 60 * 60;
176
177    fn attest(did: &str, kind: AttestationKind) -> PartyAttestation {
178        PartyAttestation {
179            party_did: did.into(),
180            kind,
181            time_unix: 0,
182        }
183    }
184
185    /// A switch requiring: heartbeat lapsed after 90 days AND 2-of-3 friends attesting.
186    fn switch() -> DeadMansSwitch {
187        DeadMansSwitch {
188            payload_commitment: C,
189            heartbeat: Heartbeat::new(1_000_000, 90 * DAY),
190            trigger: TriggerRule {
191                require_heartbeat_lapsed: true,
192                attestation_threshold: 2,
193                parties: vec![
194                    "did:wf:alice".into(),
195                    "did:wf:bob".into(),
196                    "did:wf:carol".into(),
197                ],
198            },
199            disposition: Disposition::MakePublic,
200            fired_unix: None,
201        }
202    }
203
204    #[test]
205    fn does_not_fire_while_the_principal_is_alive_even_if_friends_attest() {
206        let s = switch();
207        let now = 1_000_000 + 10 * DAY; // heartbeat fresh (10 days < 90)
208        let attests = vec![
209            attest("did:wf:alice", AttestationKind::BelievedDead),
210            attest("did:wf:bob", AttestationKind::NoContact),
211        ];
212        assert!(
213            !s.is_triggered(&attests, now),
214            "fresh liveness signal defeats the trigger"
215        );
216    }
217
218    #[test]
219    fn does_not_fire_on_one_partys_say_so_below_threshold() {
220        let s = switch();
221        let now = 1_000_000 + 200 * DAY; // heartbeat lapsed
222        let one = vec![attest("did:wf:alice", AttestationKind::BelievedDead)];
223        assert!(
224            !s.is_triggered(&one, now),
225            "a single party cannot enact it (resists false trigger)"
226        );
227    }
228
229    #[test]
230    fn fires_only_when_liveness_lapsed_and_the_quorum_attests() {
231        let mut s = switch();
232        let now = 1_000_000 + 200 * DAY; // lapsed
233        let quorum = vec![
234            attest("did:wf:alice", AttestationKind::BelievedDead),
235            attest("did:wf:bob", AttestationKind::NoContact),
236        ];
237        assert!(s.is_triggered(&quorum, now));
238        // Enact → returns the disposition, records fired.
239        assert_eq!(s.enact(&quorum, now), Some(&Disposition::MakePublic));
240        assert!(s.fired_unix.is_some());
241        // Idempotent — does not re-fire.
242        assert!(s.enact(&quorum, now + DAY).is_none());
243    }
244
245    #[test]
246    fn non_party_attestations_do_not_count_toward_the_quorum() {
247        let s = switch();
248        let now = 1_000_000 + 200 * DAY;
249        // An outsider + one real party = still below the 2-party threshold.
250        let mixed = vec![
251            attest("did:wf:stranger", AttestationKind::BelievedDead),
252            attest("did:wf:alice", AttestationKind::BelievedDead),
253        ];
254        assert!(
255            !s.is_triggered(&mixed, now),
256            "only participating parties count"
257        );
258    }
259
260    #[test]
261    fn reversibility_the_principal_returning_alive_defeats_and_unfires_it() {
262        let mut s = switch();
263        let now = 1_000_000 + 200 * DAY;
264        let quorum = vec![
265            attest("did:wf:alice", AttestationKind::BelievedDead),
266            attest("did:wf:bob", AttestationKind::NoContact),
267        ];
268        assert!(s.enact(&quorum, now).is_some(), "fired");
269        // The person shows up alive → reset + un-fire (reversibility).
270        s.principal_alive(now + DAY);
271        assert!(s.fired_unix.is_none(), "un-fired");
272        assert!(
273            !s.is_triggered(&quorum, now + 2 * DAY),
274            "fresh liveness defeats the same attestations"
275        );
276    }
277
278    #[test]
279    fn abandonment_by_all_parties_is_a_configurable_rule() {
280        // A rule where the condition is that ALL parties abandon (attestation_threshold == parties.len()),
281        // heartbeat not required — "when the last lets go".
282        let mut s = switch();
283        s.trigger.require_heartbeat_lapsed = false;
284        s.trigger.attestation_threshold = 3; // all three
285        s.disposition = Disposition::SelfDefinedRules {
286            rules_ref: "vellum:self-defined".into(),
287        };
288        let all = vec![
289            attest("did:wf:alice", AttestationKind::Abandon),
290            attest("did:wf:bob", AttestationKind::Abandon),
291            attest("did:wf:carol", AttestationKind::Abandon),
292        ];
293        assert!(
294            s.is_triggered(&all, 0),
295            "all parties abandoning satisfies this rule"
296        );
297        // Two-of-three abandoning does not.
298        assert!(!s.is_triggered(&all[..2], 0));
299    }
300
301    #[test]
302    fn serde_round_trips() {
303        let s = switch();
304        let back: DeadMansSwitch =
305            serde_json::from_str(&serde_json::to_string(&s).unwrap()).unwrap();
306        assert_eq!(s, back);
307    }
308}