qualia_core_db/net/peer/replication/
operation.rs1use crate::crypto::network::transcript::Transcript;
9use crate::net::qdnf::errors::QdnfError;
10use crate::net::qdnf::types::{Generation, StrongDigest};
11use crate::wal_intent::{bind_exact_object, ArtifactKind, IntentTable, TxId};
12
13pub const MAX_OPS: usize = 16;
14pub const MAX_PARENTS: usize = 4;
15
16const OP_ID_DOMAIN: &[u8] = b"qdnf:sync:op-id:v1-pq";
17
18#[repr(C)]
19#[derive(Clone, Copy, Debug, PartialEq, Eq)]
20pub struct OperationDesc {
21 pub author: StrongDigest,
22 pub epoch: u64,
23 pub sequence: u32,
24 pub scope: u64,
25 pub contract: StrongDigest,
26 pub purpose: StrongDigest,
27 pub payload_digest: StrongDigest,
28 pub parents: [StrongDigest; MAX_PARENTS],
29 pub parent_count: u8,
30}
31
32impl OperationDesc {
33 pub const EMPTY: Self = Self {
34 author: StrongDigest::ZERO,
35 epoch: 0,
36 sequence: 0,
37 scope: 0,
38 contract: StrongDigest::ZERO,
39 purpose: StrongDigest::ZERO,
40 payload_digest: StrongDigest::ZERO,
41 parents: [StrongDigest::ZERO; MAX_PARENTS],
42 parent_count: 0,
43 };
44}
45
46pub fn operation_id(desc: &OperationDesc) -> StrongDigest {
49 transcript_operation_id(desc).expect("bounded QSync operation transcript")
50}
51
52pub fn tx_from_operation_id(id: &StrongDigest) -> TxId {
55 let mut bytes = [0u8; 16];
56 bytes.copy_from_slice(&id.0[..16]);
57 TxId { bytes }
58}
59
60pub fn transport_ack_is_durable() -> bool {
62 false
63}
64
65pub fn source_signature_reusable_after_redaction() -> bool {
67 false
68}
69
70#[derive(Clone, Copy)]
71struct Slot {
72 occupied: bool,
73 committed: bool,
74 generation: Generation,
75 id: StrongDigest,
76 desc: OperationDesc,
77}
78
79pub struct OpTable {
80 slots: [Slot; MAX_OPS],
81}
82
83impl OpTable {
84 pub const fn new() -> Self {
86 Self {
87 slots: [Slot {
88 occupied: false,
89 committed: false,
90 generation: Generation::ZERO,
91 id: StrongDigest::ZERO,
92 desc: OperationDesc::EMPTY,
93 }; MAX_OPS],
94 }
95 }
96
97 pub fn submit(
99 &mut self,
100 desc: OperationDesc,
101 intents: &mut IntentTable,
102 writer_id: u64,
103 gen: Generation,
104 ) -> Result<StrongDigest, QdnfError> {
105 if desc.sequence == u32::MAX {
106 return Err(QdnfError::Range);
107 }
108 if desc.parent_count as usize > MAX_PARENTS {
109 return Err(QdnfError::Range);
110 }
111
112 let id = operation_id(&desc);
113
114 if let Some(idx) = self.find_id(&id) {
115 let _ = idx;
117 return Ok(id);
118 }
119
120 if self.unauthorized_epoch_replacement(&desc) {
121 return Err(QdnfError::Unauthorized);
122 }
123
124 let free = self.find_free().ok_or(QdnfError::Capacity)?;
125 let tx = tx_from_operation_id(&id);
126 let mut copy = [0u8; 512];
127 let object = bind_exact_object(ArtifactKind::Operation, &id.0, &mut copy)?;
128 intents.stage_intent(tx, object, writer_id, gen)?;
129
130 self.slots[free] = Slot {
131 occupied: true,
132 committed: false,
133 generation: gen,
134 id,
135 desc,
136 };
137 Ok(id)
138 }
139
140 pub fn commit(
142 &mut self,
143 id: StrongDigest,
144 intents: &mut IntentTable,
145 tx: TxId,
146 gen: Generation,
147 ) -> Result<(), QdnfError> {
148 let idx = self.find_id(&id).ok_or(QdnfError::Incomplete)?;
149 let expected = tx_from_operation_id(&id);
150 if tx.bytes != expected.bytes {
151 return Err(QdnfError::Malformed);
152 }
153 if self.slots[idx].committed {
154 return Ok(());
155 }
156 intents.commit(tx, gen)?;
157 self.slots[idx].committed = true;
158 self.slots[idx].generation = gen;
159 Ok(())
160 }
161
162 pub fn get_committed(&self, id: &StrongDigest) -> Result<OperationDesc, QdnfError> {
164 match self.find_id(id) {
165 Some(idx) if self.slots[idx].committed => Ok(self.slots[idx].desc),
166 _ => Err(QdnfError::Incomplete),
167 }
168 }
169
170 fn unauthorized_epoch_replacement(&self, desc: &OperationDesc) -> bool {
171 let mut i = 0usize;
172 while i < MAX_OPS {
173 let slot = &self.slots[i];
174 if slot.occupied
175 && slot.desc.author == desc.author
176 && slot.desc.scope == desc.scope
177 && desc.epoch > slot.desc.epoch
178 && desc.sequence < slot.desc.sequence
179 {
180 return true;
181 }
182 i += 1;
183 }
184 false
185 }
186
187 fn find_id(&self, id: &StrongDigest) -> Option<usize> {
188 let mut i = 0usize;
189 while i < MAX_OPS {
190 if self.slots[i].occupied && self.slots[i].id == *id {
191 return Some(i);
192 }
193 i += 1;
194 }
195 None
196 }
197
198 fn find_free(&self) -> Option<usize> {
199 let mut i = 0usize;
200 while i < MAX_OPS {
201 if !self.slots[i].occupied {
202 return Some(i);
203 }
204 i += 1;
205 }
206 None
207 }
208}
209
210fn parent_count(desc: &OperationDesc) -> usize {
211 core::cmp::min(desc.parent_count as usize, MAX_PARENTS)
212}
213
214fn transcript_operation_id(desc: &OperationDesc) -> Result<StrongDigest, QdnfError> {
215 let mut t = Transcript::new();
216 let pc = parent_count(desc);
217 t.append(b"v", OP_ID_DOMAIN)?;
218 t.append(b"author", &desc.author.0)?;
219 t.append(b"epoch", &desc.epoch.to_be_bytes())?;
220 t.append(b"sequence", &desc.sequence.to_be_bytes())?;
221 t.append(b"scope", &desc.scope.to_be_bytes())?;
222 t.append(b"contract", &desc.contract.0)?;
223 t.append(b"purpose", &desc.purpose.0)?;
224 t.append(b"payload", &desc.payload_digest.0)?;
225 t.append(b"parent_count", &[pc as u8])?;
226 let mut i = 0usize;
227 while i < pc {
228 t.append(b"parent", &desc.parents[i].0)?;
229 i += 1;
230 }
231 Ok(t.digest())
232}
233
234#[cfg(test)]
235mod tests {
236 use super::*;
237
238 fn sample(seq: u32) -> OperationDesc {
239 OperationDesc {
240 author: StrongDigest([0x11; 48]),
241 epoch: 1,
242 sequence: seq,
243 scope: 7,
244 contract: StrongDigest([0x22; 48]),
245 purpose: StrongDigest([0x33; 48]),
246 payload_digest: StrongDigest([0x44; 48]),
247 parents: [StrongDigest::ZERO; MAX_PARENTS],
248 parent_count: 0,
249 }
250 }
251
252 fn distinct(seq: u32) -> OperationDesc {
253 let mut desc = sample(seq);
254 desc.payload_digest = StrongDigest([seq as u8; 48]);
255 desc
256 }
257
258 #[test]
259 fn identical_submit_after_commit_replays_same_id() {
260 let mut table = OpTable::new();
261 let mut intents = IntentTable::new();
262 let gen = Generation(1);
263 let desc = sample(1);
264 let id = table.submit(desc, &mut intents, 9, gen).unwrap();
265 assert_eq!(id.0.len(), 48);
266 assert_ne!(id, StrongDigest::ZERO);
267 table
268 .commit(id, &mut intents, tx_from_operation_id(&id), gen)
269 .unwrap();
270 let again = table.submit(desc, &mut intents, 9, gen).unwrap();
271 assert_eq!(again, id);
272 assert_eq!(table.get_committed(&id).unwrap(), desc);
273 }
274
275 #[test]
276 fn sequence_max_at_submit_is_range() {
277 let mut table = OpTable::new();
278 let mut intents = IntentTable::new();
279 let mut desc = sample(0);
280 desc.sequence = u32::MAX;
281 assert_eq!(
282 table.submit(desc, &mut intents, 1, Generation(1)),
283 Err(QdnfError::Range)
284 );
285 }
286
287 #[test]
288 fn transport_ack_is_not_durable() {
289 assert!(!transport_ack_is_durable());
290 }
291
292 #[test]
293 fn source_signature_not_reusable_after_redaction() {
294 assert!(!source_signature_reusable_after_redaction());
295 }
296
297 #[test]
298 fn get_committed_before_commit_is_incomplete() {
299 let mut table = OpTable::new();
300 let mut intents = IntentTable::new();
301 let gen = Generation(1);
302 let id = table.submit(sample(2), &mut intents, 3, gen).unwrap();
303 assert_eq!(table.get_committed(&id), Err(QdnfError::Incomplete));
304 }
305
306 #[test]
307 fn higher_epoch_lower_sequence_is_unauthorized() {
308 let mut table = OpTable::new();
309 let mut intents = IntentTable::new();
310 let gen = Generation(1);
311 let mut first = sample(10);
312 first.epoch = 1;
313 table.submit(first, &mut intents, 4, gen).unwrap();
314 let mut replacement = first;
315 replacement.epoch = 2;
316 replacement.sequence = 5;
317 replacement.payload_digest = StrongDigest([0x55; 48]);
318 assert_eq!(
319 table.submit(replacement, &mut intents, 4, gen),
320 Err(QdnfError::Unauthorized)
321 );
322 }
323
324 #[test]
325 fn seventeenth_distinct_op_is_capacity() {
326 let mut table = OpTable::new();
327 let mut intents = IntentTable::new();
328 let gen = Generation(1);
329 let mut seq = 0u32;
330 while seq < MAX_OPS as u32 {
331 table.submit(distinct(seq), &mut intents, 8, gen).unwrap();
332 seq += 1;
333 }
334 assert_eq!(
335 table.submit(distinct(MAX_OPS as u32), &mut intents, 8, gen),
336 Err(QdnfError::Capacity)
337 );
338 }
339
340 #[test]
341 fn operation_id_is_sha384_width_and_field_sensitive() {
342 let a = sample(3);
343 let mut b = a;
344 b.sequence = 4;
345 let id_a = operation_id(&a);
346 let id_b = operation_id(&b);
347 assert_eq!(id_a.0.len(), 48);
348 assert_ne!(id_a, id_b);
349 assert_eq!(id_a, transcript_operation_id(&a).unwrap());
350 }
351}