Skip to main content

qualia_core_db/net/peer/fabric/
receipt.rs

1//! Durable operation receipts. A relay write is not a commit.
2
3use super::intent::PeerId;
4
5#[repr(u8)]
6#[derive(Debug, Clone, Copy, PartialEq, Eq)]
7pub enum ReceiptStatus {
8    Queued = 1,
9    Received = 2,
10    Validated = 3,
11    Committed = 4,
12    Denied = 5,
13    Expired = 6,
14}
15
16#[derive(Debug, Clone, Copy, PartialEq, Eq)]
17pub struct OpReceipt {
18    pub op_id: u64,
19    pub content_digest: [u8; 32],
20    pub peer: PeerId,
21    pub grant_generation: u32,
22    pub status: ReceiptStatus,
23    pub expiry_unix: u32,
24}
25
26impl OpReceipt {
27    /// `OpReceipt::queued`.
28    pub const fn queued(
29        op_id: u64,
30        content_digest: [u8; 32],
31        peer: PeerId,
32        grant_generation: u32,
33        expiry_unix: u32,
34    ) -> Self {
35        Self {
36            op_id,
37            content_digest,
38            peer,
39            grant_generation,
40            status: ReceiptStatus::Queued,
41            expiry_unix,
42        }
43    }
44
45    /// Replays an op receipt.
46    pub fn replay(
47        &self,
48        op_id: u64,
49        content_digest: &[u8; 32],
50        grant_live: bool,
51        grant_generation: u32,
52        now_unix: u32,
53    ) -> ReceiptStatus {
54        if now_unix >= self.expiry_unix {
55            return ReceiptStatus::Expired;
56        }
57        if !grant_live || grant_generation != self.grant_generation {
58            return ReceiptStatus::Denied;
59        }
60        if op_id != self.op_id || content_digest != &self.content_digest {
61            return ReceiptStatus::Denied;
62        }
63        ReceiptStatus::Committed
64    }
65}
66
67#[cfg(test)]
68mod tests {
69    use super::*;
70
71    #[test]
72    fn revoked_grant_cannot_commit() {
73        let r = OpReceipt::queued(9, [3u8; 32], [1u8; 32], 4, 100);
74        assert_eq!(r.replay(9, &[3u8; 32], false, 4, 10), ReceiptStatus::Denied);
75        assert_eq!(r.replay(9, &[3u8; 32], true, 5, 10), ReceiptStatus::Denied);
76        assert_eq!(r.replay(9, &[4u8; 32], true, 4, 10), ReceiptStatus::Denied);
77        assert_eq!(
78            r.replay(9, &[3u8; 32], true, 4, 10),
79            ReceiptStatus::Committed
80        );
81    }
82}