1use core::fmt;
17
18pub const MAX_RELATION_PAIRS: usize = 8;
20pub const MAX_REPLAY_STEPS: usize = 16;
21pub const IDENTIFIER_SIZE: usize = 8;
22pub const HASH_SIZE: usize = 32;
23pub const SIGNATURE_SIZE: usize = 64;
24pub const MAX_DOMAIN_SYMBOLS: usize = 256;
25
26#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
30pub struct Node8(pub [u8; IDENTIFIER_SIZE]);
31
32#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
34pub struct Predicate8(pub [u8; IDENTIFIER_SIZE]);
35
36#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
38pub struct Object8(pub [u8; IDENTIFIER_SIZE]);
39
40#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
42pub struct Graph8(pub [u8; IDENTIFIER_SIZE]);
43
44#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
46pub struct Mask8(pub [u8; IDENTIFIER_SIZE]);
47
48#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
50pub struct Provenance8(pub [u8; IDENTIFIER_SIZE]);
51
52#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
54pub struct Admission8(pub [u8; IDENTIFIER_SIZE]);
55
56#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
58pub struct ReceiptHint8(pub [u8; IDENTIFIER_SIZE]);
59
60macro_rules! impl_newtype_helpers {
62 ($t:ident, $name:expr) => {
63 impl $t {
64 pub const fn from_bytes(bytes: [u8; IDENTIFIER_SIZE]) -> Self {
66 Self(bytes)
67 }
68
69 pub const fn as_bytes(&self) -> &[u8; IDENTIFIER_SIZE] {
71 &self.0
72 }
73 }
74
75 impl fmt::Debug for $t {
76 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
77 write!(f, "{}(hex: ", $name)?;
78 for byte in &self.0 {
79 write!(f, "{:02x}", byte)?;
80 }
81 write!(f, ")")
82 }
83 }
84 };
85}
86
87impl_newtype_helpers!(Node8, "Node8");
88impl_newtype_helpers!(Predicate8, "Predicate8");
89impl_newtype_helpers!(Object8, "Object8");
90impl_newtype_helpers!(Graph8, "Graph8");
91impl_newtype_helpers!(Mask8, "Mask8");
92impl_newtype_helpers!(Provenance8, "Provenance8");
93impl_newtype_helpers!(Admission8, "Admission8");
94impl_newtype_helpers!(ReceiptHint8, "ReceiptHint8");
95
96#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
100#[repr(u8)]
101pub enum Multiplicity {
102 Set = 0,
104 Bag = 1,
106 Stream = 2,
108 EventAddressed = 3,
110}
111
112impl Multiplicity {
113 pub fn allows_duplicates(&self) -> bool {
115 matches!(
116 self,
117 Multiplicity::Bag | Multiplicity::Stream | Multiplicity::EventAddressed
118 )
119 }
120}
121
122#[derive(Debug, Clone, Copy, PartialEq, Eq)]
124pub struct SymbolDomain {
125 pub symbols: [Option<[u8; 8]>; MAX_DOMAIN_SYMBOLS],
127 pub count: u16,
129}
130
131impl SymbolDomain {
132 pub const fn new() -> Self {
134 Self {
135 symbols: [None; MAX_DOMAIN_SYMBOLS],
136 count: 0,
137 }
138 }
139
140 pub fn insert(&mut self, symbol: [u8; 8]) -> Result<bool, RefusalCode> {
143 for i in 0..self.count as usize {
145 if let Some(existing) = self.symbols[i] {
146 if existing == symbol {
147 return Ok(false); }
149 }
150 }
151
152 if self.count >= MAX_DOMAIN_SYMBOLS as u16 {
154 return Err(RefusalCode::PageSplitRequired);
155 }
156
157 self.symbols[self.count as usize] = Some(symbol);
159 self.count += 1;
160 Ok(true)
161 }
162
163 pub fn contains(&self, symbol: &[u8; 8]) -> bool {
165 for i in 0..self.count as usize {
166 if let Some(existing) = self.symbols[i] {
167 if &existing == symbol {
168 return true;
169 }
170 }
171 }
172 false
173 }
174
175 pub fn count(&self) -> usize {
177 self.count as usize
178 }
179}
180
181impl Default for SymbolDomain {
182 fn default() -> Self {
183 Self::new()
184 }
185}
186
187#[derive(Debug, Clone, PartialEq, Eq)]
191pub struct PageSplit {
192 pub source_page_hash: [u8; HASH_SIZE],
194 pub left_page_hash: [u8; HASH_SIZE],
196 pub right_page_hash: [u8; HASH_SIZE],
198 pub timestamp: u64,
200}
201
202impl PageSplit {
203 pub fn split(
205 _source_page: &RelationPage, source_hash: [u8; HASH_SIZE], time: u64,
206 ) -> Result<Self, RefusalCode> {
207 let mut left_hash = [0u8; HASH_SIZE];
210 let mut right_hash = [0u8; HASH_SIZE];
211
212 for i in 0..16 {
214 left_hash[i] = source_hash[i] ^ 0xAA;
215 right_hash[i] = source_hash[i] ^ 0x55;
216 }
217
218 Ok(PageSplit {
219 source_page_hash: source_hash,
220 left_page_hash: left_hash,
221 right_page_hash: right_hash,
222 timestamp: time,
223 })
224 }
225}
226
227#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
231pub struct Pair2 {
232 pub subject: Node8,
234 pub object: Node8,
236 pub timestamp: Option<u64>,
238 pub event_id: Option<[u8; 8]>,
240}
241
242impl Pair2 {
243 pub const fn new(subject: Node8, object: Node8) -> Self {
245 Self {
246 subject,
247 object,
248 timestamp: None,
249 event_id: None,
250 }
251 }
252
253 pub const fn with_timestamp(subject: Node8, object: Node8, timestamp: u64) -> Self {
255 Self {
256 subject,
257 object,
258 timestamp: Some(timestamp),
259 event_id: None,
260 }
261 }
262
263 pub const fn with_event_id(subject: Node8, object: Node8, event_id: [u8; 8]) -> Self {
265 Self {
266 subject,
267 object,
268 timestamp: None,
269 event_id: Some(event_id),
270 }
271 }
272
273 pub fn to_bytes(&self) -> [u8; 32] {
275 let mut out = [0u8; 32];
276 out[0..8].copy_from_slice(self.subject.as_bytes());
277 out[8..16].copy_from_slice(self.object.as_bytes());
278
279 if let Some(ts) = self.timestamp {
280 out[16..24].copy_from_slice(&ts.to_le_bytes());
281 }
282 if let Some(eid) = self.event_id {
283 out[24..32].copy_from_slice(&eid);
284 }
285 out
286 }
287
288 pub fn pairs_equal_ignoring_metadata(&self, other: &Pair2) -> bool {
290 self.subject == other.subject && self.object == other.object
291 }
292}
293
294#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
295pub struct CompactPair {
296 pub subject_symbol: u8,
297 pub object_symbol: u8,
298}
299
300#[derive(Debug, Clone, PartialEq, Eq)]
302pub struct RelationPage {
303 pub pairs: [Option<CompactPair>; MAX_RELATION_PAIRS],
304 pub length: usize,
305 pub left_symbols: [Option<Node8>; 256],
306 pub right_symbols: [Option<Node8>; 256],
307 pub left_len: usize,
308 pub right_len: usize,
309 pub left_domain: SymbolDomain,
311 pub right_domain: SymbolDomain,
313 pub multiplicity: Multiplicity,
315 pub pair_counts: [u32; 32],
317}
318
319impl RelationPage {
320 pub const fn new() -> Self {
322 Self {
323 pairs: [None; MAX_RELATION_PAIRS],
324 length: 0,
325 left_symbols: [None; 256],
326 right_symbols: [None; 256],
327 left_len: 0,
328 right_len: 0,
329 left_domain: SymbolDomain {
330 symbols: [None; MAX_DOMAIN_SYMBOLS],
331 count: 0,
332 },
333 right_domain: SymbolDomain {
334 symbols: [None; MAX_DOMAIN_SYMBOLS],
335 count: 0,
336 },
337 multiplicity: Multiplicity::Set,
338 pair_counts: [0u32; 32],
339 }
340 }
341}
342
343impl Default for RelationPage {
344 fn default() -> Self {
345 Self::new()
346 }
347}
348
349impl RelationPage {
350 pub fn with_multiplicity(multiplicity: Multiplicity) -> Self {
352 let mut page = Self::new();
353 page.multiplicity = multiplicity;
354 page
355 }
356
357 pub fn insert(&mut self, pair: Pair2) -> bool {
360 let subject_bytes = pair.subject.as_bytes();
362 let object_bytes = pair.object.as_bytes();
363
364 if !self.left_domain.contains(subject_bytes) {
367 if self.left_domain.insert(*subject_bytes).is_err() {
368 return false; }
370 }
371
372 if !self.right_domain.contains(object_bytes) {
373 if self.right_domain.insert(*object_bytes).is_err() {
374 return false; }
376 }
377
378 let mut subject_symbol = None;
380 for i in 0..self.left_len {
381 if let Some(ref sym) = self.left_symbols[i] {
382 if sym == &pair.subject {
383 subject_symbol = Some(i as u8);
384 break;
385 }
386 }
387 }
388 let subject_symbol = match subject_symbol {
389 Some(sym) => sym,
390 None => {
391 if self.left_len >= 256 {
392 return false;
393 }
394 self.left_symbols[self.left_len] = Some(pair.subject);
395 let sym = self.left_len as u8;
396 self.left_len += 1;
397 sym
398 }
399 };
400
401 let mut object_symbol = None;
402 for i in 0..self.right_len {
403 if let Some(ref sym) = self.right_symbols[i] {
404 if sym == &pair.object {
405 object_symbol = Some(i as u8);
406 break;
407 }
408 }
409 }
410 let object_symbol = match object_symbol {
411 Some(sym) => sym,
412 None => {
413 if self.right_len >= 256 {
414 return false;
415 }
416 self.right_symbols[self.right_len] = Some(pair.object);
417 let sym = self.right_len as u8;
418 self.right_len += 1;
419 sym
420 }
421 };
422
423 let compact = CompactPair {
424 subject_symbol,
425 object_symbol,
426 };
427
428 for i in 0..MAX_RELATION_PAIRS {
430 if let Some(ref p) = self.pairs[i] {
431 if p == &compact {
432 if self.multiplicity.allows_duplicates() && i < 32 {
434 self.pair_counts[i] += 1;
435 return true;
436 }
437 return false; }
439 }
440 }
441
442 for i in 0..MAX_RELATION_PAIRS {
444 if self.pairs[i].is_none() {
445 self.pairs[i] = Some(compact);
446 if i < 32 {
447 self.pair_counts[i] = 1;
448 }
449 self.length += 1;
450 return true;
451 }
452 }
453 false }
455
456 pub fn contains(&self, pair: &Pair2) -> bool {
458 let mut subject_symbol = None;
459 for i in 0..self.left_len {
460 if let Some(ref sym) = self.left_symbols[i] {
461 if sym == &pair.subject {
462 subject_symbol = Some(i as u8);
463 break;
464 }
465 }
466 }
467 let Some(s_sym) = subject_symbol else {
468 return false;
469 };
470
471 let mut object_symbol = None;
472 for i in 0..self.right_len {
473 if let Some(ref sym) = self.right_symbols[i] {
474 if sym == &pair.object {
475 object_symbol = Some(i as u8);
476 break;
477 }
478 }
479 }
480 let Some(o_sym) = object_symbol else {
481 return false;
482 };
483
484 let compact = CompactPair {
485 subject_symbol: s_sym,
486 object_symbol: o_sym,
487 };
488
489 for i in 0..MAX_RELATION_PAIRS {
490 if let Some(ref p) = self.pairs[i] {
491 if p == &compact {
492 return true;
493 }
494 }
495 }
496 false
497 }
498
499 pub fn remove(&mut self, pair: &Pair2) -> bool {
501 let mut subject_symbol = None;
502 for i in 0..self.left_len {
503 if let Some(ref sym) = self.left_symbols[i] {
504 if sym == &pair.subject {
505 subject_symbol = Some(i as u8);
506 break;
507 }
508 }
509 }
510 let Some(s_sym) = subject_symbol else {
511 return false;
512 };
513
514 let mut object_symbol = None;
515 for i in 0..self.right_len {
516 if let Some(ref sym) = self.right_symbols[i] {
517 if sym == &pair.object {
518 object_symbol = Some(i as u8);
519 break;
520 }
521 }
522 }
523 let Some(o_sym) = object_symbol else {
524 return false;
525 };
526
527 let compact = CompactPair {
528 subject_symbol: s_sym,
529 object_symbol: o_sym,
530 };
531
532 for i in 0..MAX_RELATION_PAIRS {
533 if let Some(ref p) = self.pairs[i] {
534 if p == &compact {
535 self.pairs[i] = None;
536 self.length -= 1;
537 return true;
538 }
539 }
540 }
541 false
542 }
543}
544
545#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
550pub struct Construct8 {
551 pub subject: Node8,
553 pub predicate: Predicate8,
555 pub object: Object8,
557 pub graph: Graph8,
559 pub mask: Mask8,
561 pub provenance: Provenance8,
563 pub admission: Admission8,
565 pub receipt_hint: ReceiptHint8,
567}
568
569impl Construct8 {
570 #[allow(clippy::too_many_arguments)] pub fn new(
572 subject: Node8, predicate: Predicate8, object: Object8, graph: Graph8, mask: Mask8,
573 provenance: Provenance8, admission: Admission8, receipt_hint: ReceiptHint8,
574 ) -> Self {
575 Self {
576 subject,
577 predicate,
578 object,
579 graph,
580 mask,
581 provenance,
582 admission,
583 receipt_hint,
584 }
585 }
586
587 pub fn to_bytes(&self) -> [u8; 64] {
589 let mut out = [0u8; 64];
590 out[0..8].copy_from_slice(self.subject.as_bytes());
591 out[8..16].copy_from_slice(self.predicate.as_bytes());
592 out[16..24].copy_from_slice(self.object.as_bytes());
593 out[24..32].copy_from_slice(self.graph.as_bytes());
594 out[32..40].copy_from_slice(self.mask.as_bytes());
595 out[40..48].copy_from_slice(self.provenance.as_bytes());
596 out[48..56].copy_from_slice(self.admission.as_bytes());
597 out[56..64].copy_from_slice(self.receipt_hint.as_bytes());
598 out
599 }
600}
601
602#[derive(Clone, Copy, PartialEq, Eq)]
606pub struct Receipt {
607 pub operation_id: [u8; 16],
609 pub inputs_hash: [u8; HASH_SIZE],
611 pub outputs_hash: [u8; HASH_SIZE],
613 pub previous_receipt_hash: Option<[u8; HASH_SIZE]>,
615 pub signature: Option<[u8; SIGNATURE_SIZE]>,
617 pub public_key: Option<[u8; 32]>,
619 pub timestamp: u64,
621}
622
623impl fmt::Debug for Receipt {
624 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
625 f.debug_struct("Receipt")
626 .field("operation_id", &self.operation_id)
627 .field("inputs_hash", &HexSlice(&self.inputs_hash))
628 .field("outputs_hash", &HexSlice(&self.outputs_hash))
629 .field(
630 "previous_receipt_hash",
631 &self.previous_receipt_hash.as_ref().map(HexSlice),
632 )
633 .field("signature", &self.signature.as_ref().map(HexSlice64))
634 .field("public_key", &self.public_key.as_ref().map(HexSlice))
635 .field("timestamp", &self.timestamp)
636 .finish()
637 }
638}
639
640struct HexSlice<'a>(&'a [u8; HASH_SIZE]);
641impl fmt::Debug for HexSlice<'_> {
642 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
643 for byte in self.0 {
644 write!(f, "{:02x}", byte)?;
645 }
646 Ok(())
647 }
648}
649
650struct HexSlice64<'a>(&'a [u8; SIGNATURE_SIZE]);
651impl fmt::Debug for HexSlice64<'_> {
652 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
653 for byte in self.0 {
654 write!(f, "{:02x}", byte)?;
655 }
656 Ok(())
657 }
658}
659
660impl Receipt {
661 pub const fn new(
663 operation_id: [u8; 16], inputs_hash: [u8; HASH_SIZE], outputs_hash: [u8; HASH_SIZE],
664 previous_receipt_hash: Option<[u8; HASH_SIZE]>, timestamp: u64,
665 ) -> Self {
666 Self {
667 operation_id,
668 inputs_hash,
669 outputs_hash,
670 previous_receipt_hash,
671 signature: None,
672 public_key: None,
673 timestamp,
674 }
675 }
676
677 pub fn calculate_hash(&self) -> [u8; HASH_SIZE] {
679 let mut hasher = blake3::Hasher::new();
680 hasher.update(&self.operation_id);
681 hasher.update(&self.inputs_hash);
682 hasher.update(&self.outputs_hash);
683 if let Some(prev) = self.previous_receipt_hash {
684 hasher.update(&prev);
685 } else {
686 hasher.update(&[0u8; HASH_SIZE]);
687 }
688 hasher.update(&self.timestamp.to_le_bytes());
689 *hasher.finalize().as_bytes()
690 }
691
692 pub fn sign(mut self, signing_key: &ed25519_dalek::SigningKey) -> Self {
694 use ed25519_dalek::Signer;
695 let hash = self.calculate_hash();
696 let sig = signing_key.sign(&hash);
697 self.signature = Some(sig.to_bytes());
698 self.public_key = Some(signing_key.verifying_key().to_bytes());
699 self
700 }
701
702 pub fn verify(&self) -> Result<(), RefusalCode> {
704 use ed25519_dalek::Verifier;
705 let pk_bytes = self
706 .public_key
707 .ok_or(RefusalCode::BoundaryEvidenceMissing)?;
708 let sig_bytes = self.signature.ok_or(RefusalCode::BoundaryEvidenceMissing)?;
709
710 let verifying_key = ed25519_dalek::VerifyingKey::from_bytes(&pk_bytes)
711 .map_err(|_| RefusalCode::InvalidSignature)?;
712 let signature = ed25519_dalek::Signature::from_bytes(&sig_bytes);
713
714 let hash = self.calculate_hash();
715 verifying_key
716 .verify(&hash, &signature)
717 .map_err(|_| RefusalCode::InvalidSignature)
718 }
719}
720
721#[derive(Debug, Clone, Copy, PartialEq, Eq)]
725#[repr(u8)]
726pub enum RefusalCode {
727 BoundaryEvidenceMissing = 1,
729 ExpectedOCELMissing = 2,
731 ToolCallHashMissing = 3,
733 InvalidSignature = 4,
735 CausalInconsistency = 5,
737 ConstraintViolation = 6,
739 PageSplitRequired = 7,
741 DomainBoundsExceeded = 8,
743}
744
745#[derive(Debug, Clone, Copy, PartialEq, Eq)]
747pub struct Refusal {
748 pub code: RefusalCode,
750 pub op_hash: [u8; HASH_SIZE],
752 pub evidence: [u8; 64],
754 pub timestamp: u64,
756}
757
758impl Refusal {
759 pub const fn new(
761 code: RefusalCode, op_hash: [u8; HASH_SIZE], evidence: [u8; 64], timestamp: u64,
762 ) -> Self {
763 Self {
764 code,
765 op_hash,
766 evidence,
767 timestamp,
768 }
769 }
770}
771
772#[derive(Debug, Clone, PartialEq, Eq)]
776pub struct Replay {
777 pub steps: [Option<Construct8>; MAX_REPLAY_STEPS],
779 pub length: usize,
781}
782
783impl Replay {
784 pub const fn new() -> Self {
786 Self {
787 steps: [None; MAX_REPLAY_STEPS],
788 length: 0,
789 }
790 }
791}
792
793impl Default for Replay {
794 fn default() -> Self {
795 Self::new()
796 }
797}
798
799impl Replay {
800 pub fn push(&mut self, step: Construct8) -> bool {
802 if self.length >= MAX_REPLAY_STEPS {
803 return false;
804 }
805 self.steps[self.length] = Some(step);
806 self.length += 1;
807 true
808 }
809
810 pub fn run(&self, mut state: RelationPage, current_time: u64) -> Result<RelationPage, Refusal> {
813 for i in 0..self.length {
814 if let Some(ref step) = self.steps[i] {
815 if step.mask.as_bytes() == &[0u8; IDENTIFIER_SIZE] {
818 let mut op_hash = [0u8; HASH_SIZE];
819 op_hash[0..8].copy_from_slice(step.subject.as_bytes());
820 op_hash[8..16].copy_from_slice(step.predicate.as_bytes());
821 return Err(Refusal::new(
822 RefusalCode::ConstraintViolation,
823 op_hash,
824 step.to_bytes(),
825 current_time,
826 ));
827 }
828
829 let pair = Pair2::new(step.subject, Node8::from_bytes(*step.object.as_bytes()));
831 if !state.insert(pair) {
832 let mut op_hash = [0u8; HASH_SIZE];
834 op_hash[0..8].copy_from_slice(step.subject.as_bytes());
835 op_hash[8..16].copy_from_slice(step.predicate.as_bytes());
836 return Err(Refusal::new(
837 RefusalCode::ConstraintViolation,
838 op_hash,
839 step.to_bytes(),
840 current_time,
841 ));
842 }
843 }
844 }
845 Ok(state)
846 }
847}