Skip to main content

qualia_core_db/net/peer/replication/
dtn.rs

1//! Delay-tolerant transfer holds and effect uniqueness (E11.4, E11.6).
2//!
3//! Release requires unexpired time and current authority generation.
4//! Transport retry is not a second user-visible effect. Tombstoned ids
5//! cannot apply. Cancelled resume is [`QdnfError::Cancelled`].
6//! Duplicate [`commit_pair`](super::pair::commit_pair) is already
7//! idempotent by `operation_id`. The mailbox is not Bundle Protocol.
8
9use crate::net::peer::replication::operation::{operation_id, OperationDesc};
10use crate::net::peer::replication::receipts::{self, ReceiptTable};
11use crate::net::peer::replication::resume::{resume_block, ResumeTable};
12use crate::net::peer::replication::tombstone::{Tombstone, TombstoneTable};
13use crate::net::qdnf::errors::QdnfError;
14use crate::net::qdnf::types::{Generation, StrongDigest};
15
16/// Held DTN object: operation identity, expiry, and authority generation.
17#[repr(C)]
18#[derive(Clone, Copy, Debug, PartialEq, Eq)]
19pub struct DtnHold {
20    pub op_id: StrongDigest,
21    pub expiry: u64,
22    pub authority: Generation,
23}
24
25/// Release after expiry and current-authority checks.
26///
27/// `now > expiry` → [`QdnfError::Expired`].
28/// `authority != live_authority` → [`QdnfError::Unauthorized`].
29pub fn release_hold(
30    now: u64,
31    expiry: u64,
32    authority: Generation,
33    live_authority: Generation,
34) -> Result<(), QdnfError> {
35    if now > expiry {
36        return Err(QdnfError::Expired);
37    }
38    if authority != live_authority {
39        return Err(QdnfError::Unauthorized);
40    }
41    Ok(())
42}
43
44/// Transport retry must not create a second user-visible effect.
45#[inline]
46pub fn retry_is_new_effect() -> bool {
47    false
48}
49
50/// Mailbox store-and-forward is not Bundle Protocol compatible.
51#[inline]
52pub fn mailbox_is_bundle_protocol() -> bool {
53    false
54}
55
56/// Dedup key: SHA-384 [`operation_id`].
57#[inline]
58pub fn effect_id(desc: &OperationDesc) -> StrongDigest {
59    operation_id(desc)
60}
61
62/// Apply a local effect unless the id is tombstoned (rollback / retain).
63///
64/// Tombstoned → [`QdnfError::Revoked`]. Unknown identity follows receipts.
65pub fn apply_live_effect(
66    receipts: &mut ReceiptTable,
67    tombstones: &TombstoneTable,
68    id: StrongDigest,
69) -> Result<(), QdnfError> {
70    if tombstones.contains(&id) {
71        return Err(QdnfError::Revoked);
72    }
73    receipts::apply_effect(receipts, id)
74}
75
76/// Retain a tombstone so a later apply cannot succeed.
77pub fn rollback_tombstone(
78    tombstones: &mut TombstoneTable,
79    id: StrongDigest,
80    epoch: u64,
81    sequence: u32,
82) -> Result<(), QdnfError> {
83    tombstones.retain(Tombstone {
84        op_id: id,
85        epoch,
86        sequence,
87    })
88}
89
90/// Cancelled resume cannot continue as a live transfer.
91pub fn resume_if_open(
92    table: &ResumeTable,
93    pin: u8,
94    block_index: u8,
95    cancelled: bool,
96) -> Result<(), QdnfError> {
97    if cancelled {
98        return Err(QdnfError::Cancelled);
99    }
100    resume_block(table, pin, block_index)
101}
102
103/// Retry an already-applied effect: same `operation_id`, not a new effect.
104pub fn transport_retry_effect(
105    receipts: &mut ReceiptTable,
106    tombstones: &TombstoneTable,
107    id: StrongDigest,
108) -> Result<(), QdnfError> {
109    if retry_is_new_effect() {
110        return Err(QdnfError::Conflict);
111    }
112    apply_live_effect(receipts, tombstones, id)
113}
114
115#[cfg(test)]
116mod tests {
117    use super::*;
118    use crate::net::peer::replication::manifest::{ByteRange, ContentManifest};
119    use crate::net::peer::replication::operation::MAX_PARENTS;
120    use crate::net::peer::replication::receipts::{bind_identity, class_of, ReceiptClass};
121    use crate::net::peer::replication::resume::{mark_verified, pin};
122
123    fn digest(tag: u8) -> StrongDigest {
124        StrongDigest([tag; 48])
125    }
126
127    fn desc(seq: u32) -> OperationDesc {
128        OperationDesc {
129            author: StrongDigest([0x11; 48]),
130            epoch: 1,
131            sequence: seq,
132            scope: 7,
133            contract: StrongDigest([0x22; 48]),
134            purpose: StrongDigest([0x33; 48]),
135            payload_digest: StrongDigest([seq as u8; 48]),
136            parents: [StrongDigest::ZERO; MAX_PARENTS],
137            parent_count: 0,
138        }
139    }
140
141    #[test]
142    fn retry_is_not_a_duplicate_effect() {
143        assert!(!retry_is_new_effect());
144        assert!(!mailbox_is_bundle_protocol());
145        let mut receipts = ReceiptTable::new();
146        let tombstones = TombstoneTable::new();
147        let id = effect_id(&desc(1));
148        bind_identity(&mut receipts, id).unwrap();
149        apply_live_effect(&mut receipts, &tombstones, id).unwrap();
150        transport_retry_effect(&mut receipts, &tombstones, id).unwrap();
151        assert_eq!(class_of(&receipts, id).unwrap(), ReceiptClass::Effect);
152        release_hold(10, 20, Generation(1), Generation(1)).unwrap();
153        assert_eq!(
154            release_hold(21, 20, Generation(1), Generation(1)),
155            Err(QdnfError::Expired)
156        );
157        assert_eq!(
158            release_hold(10, 20, Generation(1), Generation(2)),
159            Err(QdnfError::Unauthorized)
160        );
161    }
162
163    #[test]
164    fn tombstoned_id_cannot_apply_effect() {
165        let mut receipts = ReceiptTable::new();
166        let mut tombstones = TombstoneTable::new();
167        let id = digest(4);
168        bind_identity(&mut receipts, id).unwrap();
169        rollback_tombstone(&mut tombstones, id, 1, 1).unwrap();
170        assert_eq!(
171            apply_live_effect(&mut receipts, &tombstones, id),
172            Err(QdnfError::Revoked)
173        );
174        assert_eq!(class_of(&receipts, id).unwrap(), ReceiptClass::Identity);
175    }
176
177    #[test]
178    fn cancelled_resume_is_cancelled() {
179        let mut table = ResumeTable::new();
180        let ranges = [ByteRange { offset: 0, len: 4 }];
181        let m = ContentManifest::bind(digest(9), 0, 64, &ranges).unwrap();
182        let pin_id = pin(&mut table, m).unwrap();
183        mark_verified(&mut table, pin_id, 0).unwrap();
184        resume_if_open(&table, pin_id, 0, false).unwrap();
185        assert_eq!(
186            resume_if_open(&table, pin_id, 0, true),
187            Err(QdnfError::Cancelled)
188        );
189    }
190}