qualia_core_db/sensing/local_custody/
chain.rs1use std::path::Path;
8
9use super::{
10 entry_size, publish_bundle, validate_root, CustodyAuthority, CustodyError, PublishedBundle,
11 SidecarReceipt, SIDECAR_BYTES,
12};
13
14#[derive(Clone, Copy, Debug, PartialEq, Eq)]
17pub enum ChainHead {
18 Empty,
19 Present { sequence: u64, checkpoint: [u8; 32] },
20}
21
22#[derive(Clone, Copy, Debug, PartialEq, Eq)]
24pub enum HeadCommit {
25 Committed,
26 Conflict,
28 Indeterminate,
30}
31
32#[derive(Clone, Copy, Debug, PartialEq, Eq)]
34pub enum ChainAuthorityError {
35 Unavailable,
36 NotAuthorized,
37 InvalidState,
38}
39
40pub trait ChainAuthority: CustodyAuthority {
49 fn authenticated_head(
50 &mut self,
51 root: &Path,
52 chain_id: &[u8; 32],
53 ) -> Result<ChainHead, ChainAuthorityError>;
54
55 fn compare_and_commit(
56 &mut self,
57 root: &Path,
58 chain_id: &[u8; 32],
59 expected: ChainHead,
60 next: ChainHead,
61 receipt: &SidecarReceipt,
62 ) -> HeadCommit;
63}
64
65#[derive(Debug)]
66pub enum ChainPublicationError {
67 Authority(ChainAuthorityError),
68 InvalidHead,
69 WrongSequence,
70 WrongPredecessor,
71 SequenceExhausted,
72 Publication(CustodyError),
73 PublishedUncommitted {
76 bundle: PublishedBundle,
77 outcome: HeadCommit,
78 },
79}
80
81#[derive(Clone, Copy, Debug, PartialEq, Eq)]
84pub struct ChainPublication {
85 pub bundle: PublishedBundle,
86 pub head: ChainHead,
87}
88
89fn expected_transition(
90 head: ChainHead,
91 receipt: &SidecarReceipt,
92) -> Result<ChainHead, ChainPublicationError> {
93 if receipt.chain_id().iter().all(|byte| *byte == 0) {
94 return Err(ChainPublicationError::InvalidHead);
95 }
96 match head {
97 ChainHead::Empty => {
98 if receipt.sequence() != 0 {
99 return Err(ChainPublicationError::WrongSequence);
100 }
101 if receipt.previous().iter().any(|byte| *byte != 0) {
102 return Err(ChainPublicationError::WrongPredecessor);
103 }
104 }
105 ChainHead::Present {
106 sequence,
107 checkpoint,
108 } => {
109 if checkpoint.iter().all(|byte| *byte == 0) {
110 return Err(ChainPublicationError::InvalidHead);
111 }
112 let next = sequence
113 .checked_add(1)
114 .ok_or(ChainPublicationError::SequenceExhausted)?;
115 if receipt.sequence() != next {
116 return Err(ChainPublicationError::WrongSequence);
117 }
118 if receipt.previous() != &checkpoint {
119 return Err(ChainPublicationError::WrongPredecessor);
120 }
121 }
122 }
123 let checkpoint = receipt.checkpoint();
124 if checkpoint.iter().all(|byte| *byte == 0) {
125 return Err(ChainPublicationError::InvalidHead);
126 }
127 Ok(ChainHead::Present {
128 sequence: receipt.sequence(),
129 checkpoint,
130 })
131}
132
133#[allow(clippy::too_many_arguments)]
139pub fn publish_chain_bundle(
140 root: &Path,
141 sidecar: &[u8; SIDECAR_BYTES],
142 payload: &[u8],
143 receipt: &SidecarReceipt,
144 byte_budget: usize,
145 authority: &mut impl ChainAuthority,
146) -> Result<ChainPublication, ChainPublicationError> {
147 validate_root(root).map_err(ChainPublicationError::Publication)?;
148 let total =
149 entry_size(payload.len(), byte_budget).map_err(ChainPublicationError::Publication)?;
150 receipt
151 .verify_with_authority(sidecar, payload, payload.len(), authority)
152 .map_err(|error| ChainPublicationError::Publication(CustodyError::Receipt(error)))?;
153 if !authority.permit_publish(root, receipt, sidecar, payload, total) {
154 return Err(ChainPublicationError::Publication(
155 CustodyError::PermissionDenied,
156 ));
157 }
158 let expected = authority
159 .authenticated_head(root, receipt.chain_id())
160 .map_err(ChainPublicationError::Authority)?;
161 let next = expected_transition(expected, receipt)?;
162 let bundle = publish_bundle(root, sidecar, payload, receipt, byte_budget, authority)
163 .map_err(ChainPublicationError::Publication)?;
164 let outcome = authority.compare_and_commit(root, receipt.chain_id(), expected, next, receipt);
165 match outcome {
166 HeadCommit::Committed => Ok(ChainPublication { bundle, head: next }),
167 HeadCommit::Conflict | HeadCommit::Indeterminate => {
168 Err(ChainPublicationError::PublishedUncommitted { bundle, outcome })
169 }
170 }
171}
172
173#[cfg(test)]
174#[path = "chain_tests.rs"]
175mod tests;