1#![deny(missing_docs)]
2use std::collections::BTreeMap;
3use std::str::FromStr;
4
5use bytes::Bytes;
6use serde::Deserialize;
7use serde::Serialize;
8
9use crate::algebra::JoinSemilattice;
10use crate::consts::DATA_TOMBSTONE_MAX_LEN;
11use crate::consts::ENTRY_DATA_MAX_LEN;
12use crate::consts::RELAY_INBOX_MAX_LEN;
13use crate::dht::Did;
14use crate::ecc::HashStr;
15use crate::error::Error;
16use crate::error::Result;
17
18mod crdt;
19pub(crate) mod inbox;
20mod provenance;
21mod retention;
22
23#[cfg(test)]
24pub(crate) use crdt::digests_computed;
25use crdt::insert_max;
26#[cfg(test)]
27pub(crate) use crdt::reset_digests;
28pub use crdt::DataTopicBuffer;
29pub use crdt::ElementDigest;
30pub use crdt::EntryCrdt;
31pub use crdt::EntryDot;
32pub use crdt::EntryTombstone;
33pub use crdt::EntryVersion;
34use provenance::materialize_data_elements;
35pub(crate) use provenance::DataProofKey;
36use provenance::RetractionWitness;
37pub use provenance::SignedDataMutation;
38pub(crate) use retention::AdmittedEntry;
39
40#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
42pub enum EntryKind {
43 Data,
45 RelayMessage,
47}
48
49impl EntryKind {
50 pub const fn max_data_len(self) -> usize {
53 match self {
54 EntryKind::Data => ENTRY_DATA_MAX_LEN,
55 EntryKind::RelayMessage => RELAY_INBOX_MAX_LEN,
56 }
57 }
58
59 pub const fn is_relay_inbox(self) -> bool {
61 matches!(self, EntryKind::RelayMessage)
62 }
63
64 pub const fn replication(self, requested: u16) -> u16 {
68 match self {
69 EntryKind::Data => requested,
70 EntryKind::RelayMessage => 1,
71 }
72 }
73
74 pub const fn tombstone_bound(self) -> TombstoneBound {
85 match self {
86 EntryKind::Data => TombstoneBound::Refuse(DATA_TOMBSTONE_MAX_LEN),
87 EntryKind::RelayMessage => TombstoneBound::Truncate(RELAY_INBOX_MAX_LEN),
88 }
89 }
90}
91
92#[derive(Clone, Copy, Debug, PartialEq, Eq)]
95pub enum TombstoneBound {
96 Refuse(usize),
98 Truncate(usize),
100}
101
102impl TombstoneBound {
103 const fn truncated(self, count: usize) -> usize {
107 match self {
108 Self::Refuse(_) => 0,
109 Self::Truncate(cap) => count.saturating_sub(cap),
110 }
111 }
112}
113
114#[derive(Clone, Copy, Debug, PartialEq, Eq)]
115enum EntryStampKind {
116 Overwrite,
117 Delta,
118}
119
120#[derive(Serialize)]
125struct OperationDigest<'a> {
126 kind: EntryKind,
127 did: Did,
128 actor: Did,
129 data: &'a [Bytes],
130}
131
132#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
134pub enum EntryOperation {
135 Overwrite(Entry),
137 Extend(Entry),
140 Tombstone(Entry),
148}
149
150#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
158pub struct PlacedEntryOperation {
159 pub placement: Did,
161 pub op: EntryOperation,
163 pub report: bool,
166}
167
168impl PlacedEntryOperation {
169 pub fn entry_key(&self) -> Result<Did> {
171 self.op.did()
172 }
173
174 pub fn validate_placement(&self, redundancy: u16) -> Result<()> {
176 validate_affine_placement(
177 self.entry_key()?,
178 self.placement,
179 self.op.kind(),
180 redundancy,
181 "placed entry operation",
182 )
183 }
184}
185
186fn validate_affine_placement(
190 entry_key: Did,
191 placement: Did,
192 kind: EntryKind,
193 redundancy: u16,
194 what: &'static str,
195) -> Result<()> {
196 if entry_key
197 .rotate_affine(kind.replication(redundancy))?
198 .contains(&placement)
199 {
200 return Ok(());
201 }
202
203 Err(Error::InvalidMessage(format!(
204 "{what} targets a placement outside the entry's affine replica set"
205 )))
206}
207
208#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
232pub struct Entry {
233 pub did: Did,
236 pub data: Vec<Bytes>,
239 pub kind: EntryKind,
241 #[serde(default)]
243 pub crdt: EntryCrdt,
244 #[serde(default)]
247 pub expires_at_ms: Option<u128>,
248}
249
250#[derive(Clone, Debug, Serialize, Deserialize)]
255pub struct PlacedEntry {
256 pub key: Did,
258 pub entry: Entry,
260 #[serde(skip)]
262 custody_incarnation: Option<u64>,
263}
264
265impl PartialEq for PlacedEntry {
266 fn eq(&self, other: &Self) -> bool {
267 self.key == other.key && self.entry == other.entry
268 }
269}
270
271impl Eq for PlacedEntry {}
272
273impl PlacedEntry {
274 pub fn new(key: Did, entry: Entry) -> Self {
276 Self {
277 key,
278 entry,
279 custody_incarnation: None,
280 }
281 }
282
283 pub(crate) fn with_custody_incarnation(mut self, incarnation: u64) -> Self {
285 self.custody_incarnation = Some(incarnation);
286 self
287 }
288
289 pub(crate) const fn custody_incarnation(&self) -> Option<u64> {
291 self.custody_incarnation
292 }
293
294 pub(crate) fn join(&self, other: Self) -> Result<Self> {
300 if self.key != other.key {
301 return Err(Error::EntryDidNotEqual);
302 }
303 Ok(Self {
304 key: self.key,
305 entry: self.entry.join(other.entry)?,
306 custody_incarnation: self.custody_incarnation.max(other.custody_incarnation),
307 })
308 }
309
310 pub fn validate_placement(&self, redundancy: u16) -> Result<()> {
312 validate_affine_placement(
313 self.entry.did,
314 self.key,
315 self.entry.kind,
316 redundancy,
317 "synced placed entry",
318 )
319 }
320}
321
322#[derive(Clone, Debug, Serialize, Deserialize)]
332pub struct SyncedEntryAck {
333 pub key: Did,
335 pub entry: Entry,
337 #[serde(skip)]
339 custody_incarnation: u64,
340}
341
342impl PartialEq for SyncedEntryAck {
343 fn eq(&self, other: &Self) -> bool {
344 self.key == other.key && self.entry == other.entry
345 }
346}
347
348impl Eq for SyncedEntryAck {}
349
350impl SyncedEntryAck {
351 pub fn new(key: Did, entry: Entry) -> Self {
353 Self {
354 key,
355 entry,
356 custody_incarnation: 0,
357 }
358 }
359
360 pub(crate) fn with_custody_incarnation(mut self, incarnation: u64) -> Self {
362 self.custody_incarnation = incarnation;
363 self
364 }
365
366 pub(crate) const fn custody_incarnation(&self) -> u64 {
368 self.custody_incarnation
369 }
370
371 pub fn confirms_local_value(&self, local: &Entry, now_ms: u128) -> bool {
383 self.entry.clone().retired_at(now_ms).eq(local)
384 }
385}
386
387#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
392pub struct EntryLookupKey {
393 pub resource: Did,
395 pub placement: Did,
397}
398
399impl EntryLookupKey {
400 pub fn new(resource: Did, placement: Did) -> Self {
402 Self {
403 resource,
404 placement,
405 }
406 }
407}
408
409#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
411pub struct PlacementMiss {
412 pub key: Did,
414 pub owner: Did,
416}
417
418impl PlacementMiss {
419 pub fn new(key: Did, owner: Did) -> Self {
421 Self { key, owner }
422 }
423}
424
425#[derive(Clone, Debug, PartialEq, Eq)]
427pub struct EntryLookupEvidence {
428 pub entry: Entry,
430 pub misses: Vec<PlacementMiss>,
432}
433
434impl EntryLookupEvidence {
435 pub fn new(entry: Entry, misses: Vec<PlacementMiss>) -> Self {
437 Self { entry, misses }
438 }
439}
440
441impl Entry {
442 pub fn new(did: Did, data: Vec<Bytes>, kind: EntryKind) -> Self {
444 Self {
445 did,
446 data,
447 kind,
448 crdt: EntryCrdt::default(),
449 expires_at_ms: None,
450 }
451 }
452
453 pub fn gen_did(topic: &str) -> Result<Did> {
455 let hash: HashStr = topic.into();
456 let did = Did::from_str(&hash.inner());
457 tracing::debug!("gen_did: topic: {}, did: {:?}", topic, did);
458 did
459 }
460}
461
462impl EntryOperation {
463 pub fn stamped(self, now_ms: u128, actor: Did) -> Result<Self> {
473 self.stamped_after(now_ms, actor, None)
474 }
475
476 pub fn stamped_after(
483 self,
484 now_ms: u128,
485 actor: Did,
486 floor: Option<EntryVersion>,
487 ) -> Result<Self> {
488 let stamp = self.stamp_kind();
489 self.try_map_entry(|entry| {
490 let entry = entry.ensure_lifetime_from(now_ms);
491 match stamp {
492 Some(kind) => entry.ensure_stamp_after(now_ms, actor, floor, kind),
493 None => {
494 let mut entry = entry;
495 if !entry.crdt.has_write_witness() {
496 entry.crdt.dots.clear();
497 }
498 Ok(entry)
499 }
500 }
501 })
502 }
503
504 const fn stamp_kind(&self) -> Option<EntryStampKind> {
508 match self {
509 EntryOperation::Overwrite(_) => Some(EntryStampKind::Overwrite),
510 EntryOperation::Extend(_) => Some(EntryStampKind::Delta),
511 EntryOperation::Tombstone(_) => None,
512 }
513 }
514
515 pub fn entry(&self) -> &Entry {
517 match self {
518 EntryOperation::Overwrite(entry)
519 | EntryOperation::Extend(entry)
520 | EntryOperation::Tombstone(entry) => entry,
521 }
522 }
523
524 fn try_map_entry(self, f: impl FnOnce(Entry) -> Result<Entry>) -> Result<Self> {
526 Ok(match self {
527 EntryOperation::Overwrite(entry) => EntryOperation::Overwrite(f(entry)?),
528 EntryOperation::Extend(entry) => EntryOperation::Extend(f(entry)?),
529 EntryOperation::Tombstone(entry) => EntryOperation::Tombstone(f(entry)?),
530 })
531 }
532
533 pub fn did(&self) -> Result<Did> {
535 Ok(self.entry().did)
536 }
537
538 pub fn kind(&self) -> EntryKind {
540 self.entry().kind
541 }
542
543 pub fn gen_default_entry(&self) -> Result<Entry> {
545 Ok(Entry::new(self.did()?, vec![], self.kind()))
546 }
547}
548
549impl TryFrom<(String, Bytes)> for Entry {
550 type Error = Error;
551 fn try_from((topic, element): (String, Bytes)) -> Result<Self> {
553 Ok(Self::new(
554 Self::gen_did(&topic)?,
555 vec![element],
556 EntryKind::Data,
557 ))
558 }
559}
560
561impl TryFrom<(String, String)> for Entry {
562 type Error = Error;
563 fn try_from((topic, text): (String, String)) -> Result<Self> {
565 (topic, Bytes::from(text)).try_into()
566 }
567}
568
569impl Entry {
570 fn with_element_dots(mut self, version: EntryVersion) -> Result<Self> {
571 self.crdt.dots = self
572 .data
573 .iter()
574 .enumerate()
575 .map(|(index, _)| EntryDot::for_index(version, index))
576 .collect::<Result<Vec<_>>>()?;
577 self.crdt.co_dots.clear();
578 self.crdt.co_registers.clear();
579 self.crdt.proofs.clear();
580 Ok(self)
581 }
582
583 fn stamp_overwrite(mut self, version: EntryVersion) -> Result<Self> {
584 self.crdt.register = Some(version);
585 self.with_element_dots(version)
586 }
587
588 fn stamp_delta(self, version: EntryVersion) -> Result<Self> {
589 self.with_element_dots(version)
590 }
591
592 fn stamp(self, version: EntryVersion, kind: EntryStampKind) -> Result<Self> {
593 match kind {
594 EntryStampKind::Overwrite => self.stamp_overwrite(version),
595 EntryStampKind::Delta => self.stamp_delta(version),
596 }
597 }
598
599 pub(super) fn operation_digest_for(&self, actor: Did, data: &[Bytes]) -> Result<Did> {
600 let digest = OperationDigest {
601 kind: self.kind,
602 did: self.did,
603 actor,
604 data,
605 };
606 let bytes = rings_codec::serialize(&digest).map_err(Error::CodecSerialize)?;
607 Did::try_from(HashStr::from_bytes(&bytes))
608 }
609
610 fn operation_digest(&self, actor: Did) -> Result<Did> {
611 self.operation_digest_for(actor, &self.data)
612 }
613
614 fn issue_version_after(
615 &self,
616 now_ms: u128,
617 actor: Did,
618 floor: Option<EntryVersion>,
619 ) -> Result<EntryVersion> {
620 EntryVersion::new(now_ms, actor, self.operation_digest(actor)?).after(floor)
621 }
622
623 fn attribute_unattributed_versions(&mut self, actor: Did) {
624 if actor.is_default() {
625 return;
626 }
627 if let Some(reg) = &mut self.crdt.register {
628 if reg.actor.is_default() {
629 reg.actor = actor;
630 }
631 }
632 for reg in &mut self.crdt.co_registers {
633 if reg.actor.is_default() {
634 reg.actor = actor;
635 }
636 }
637 for dot in &mut self.crdt.dots {
638 if dot.version.actor.is_default() {
639 dot.version.actor = actor;
640 }
641 }
642 for (_, dot) in &mut self.crdt.co_dots {
643 if dot.version.actor.is_default() {
644 dot.version.actor = actor;
645 }
646 }
647 }
648
649 fn ensure_stamp_after(
650 mut self,
651 now_ms: u128,
652 actor: Did,
653 floor: Option<EntryVersion>,
654 kind: EntryStampKind,
655 ) -> Result<Self> {
656 match self.crdt.has_write_witness() {
657 true => {
658 self.attribute_unattributed_versions(actor);
659 Ok(self)
660 }
661 false => {
662 let stray_register = (kind == EntryStampKind::Delta)
663 .then_some(self.crdt.register)
664 .flatten();
665 let version = self.issue_version_after(now_ms, actor, floor)?;
666 let mut stamped = self.stamp(version, kind)?;
667 if let Some(mut reg) = stray_register {
668 if !actor.is_default() && reg.actor.is_default() {
669 reg.actor = actor;
670 }
671 stamped.crdt.register = Some(reg);
672 }
673 Ok(stamped)
674 }
675 }
676 }
677
678 pub(super) fn versions(&self) -> impl Iterator<Item = EntryVersion> + '_ {
681 self.crdt
682 .dots
683 .iter()
684 .map(|dot| dot.version)
685 .chain(self.crdt.co_dots.iter().map(|(_, dot)| dot.version))
686 .chain(
687 self.crdt
688 .tombstones
689 .iter()
690 .map(|tombstone| tombstone.dot.version),
691 )
692 .chain(self.crdt.register)
693 .chain(self.crdt.co_registers.iter().copied())
694 }
695
696 pub(crate) fn max_observed_version(&self) -> Option<EntryVersion> {
698 self.versions().max()
699 }
700
701 fn validate_same_carrier(&self, other: &Self) -> Result<()> {
702 if !self.same_kind_as(other) {
703 return Err(Error::EntryKindNotEqual);
704 }
705 if !self.same_key_as(other) {
706 return Err(Error::EntryDidNotEqual);
707 }
708 Ok(())
709 }
710
711 fn dot_for_element(&self, index: usize) -> Result<EntryDot> {
712 if let Some(dot) = self.crdt.dots.get(index).copied() {
713 return Ok(dot);
714 }
715 EntryDot::for_index(self.crdt.legacy_floor(), index)
716 }
717
718 fn raw_buffer(&self) -> Result<DataTopicBuffer> {
721 let mut proofs = BTreeMap::new();
722 for proof in &self.crdt.proofs {
723 insert_max(&mut proofs, proof.key, proof.clone());
724 }
725 let mut register = None;
726 let mut co_registers = BTreeMap::new();
727 if let Some(floor) = self.crdt.register {
728 DataTopicBuffer::insert_register_with_proofs(
729 &mut register,
730 &mut co_registers,
731 &proofs,
732 floor,
733 );
734 }
735 for &floor in &self.crdt.co_registers {
736 DataTopicBuffer::insert_register_with_proofs(
737 &mut register,
738 &mut co_registers,
739 &proofs,
740 floor,
741 );
742 }
743 let mut values = BTreeMap::new();
744 let mut co_values = BTreeMap::new();
745 for (index, value) in self.data.iter().cloned().enumerate() {
746 DataTopicBuffer::insert_value_with_proofs(
747 &mut values,
748 &mut co_values,
749 &proofs,
750 value,
751 self.dot_for_element(index)?,
752 );
753 }
754 for &(index, dot) in &self.crdt.co_dots {
755 if let Some(value) = self.data.get(index as usize).cloned() {
756 DataTopicBuffer::insert_value_with_proofs(
757 &mut values,
758 &mut co_values,
759 &proofs,
760 value,
761 dot,
762 );
763 }
764 }
765 let mut removes = BTreeMap::new();
766 let mut co_removes = BTreeMap::new();
767 for tombstone in self.crdt.tombstones.iter() {
768 DataTopicBuffer::insert_remove_with_proofs(
769 &mut removes,
770 &mut co_removes,
771 &proofs,
772 tombstone.element,
773 tombstone.dot,
774 );
775 }
776 Ok(DataTopicBuffer {
777 register,
778 co_registers,
779 values,
780 co_values,
781 removes,
782 co_removes,
783 proofs,
784 })
785 }
786
787 pub(super) fn topic_buffer(&self) -> Result<DataTopicBuffer> {
789 let raw = self.raw_buffer()?;
790 Ok(DataTopicBuffer::normalize(
791 raw.register,
792 raw.co_registers,
793 raw.values,
794 raw.co_values,
795 raw.removes,
796 raw.co_removes,
797 raw.proofs,
798 ))
799 }
800
801 fn materialize_topic_buffer(
807 &self,
808 buffer: DataTopicBuffer,
809 expires_at_ms: Option<u128>,
810 ) -> Self {
811 let kind = self.kind;
812 let DataTopicBuffer {
813 register,
814 co_registers,
815 values,
816 co_values,
817 removes,
818 co_removes,
819 mut proofs,
820 } = buffer;
821 let mut co_registers = co_registers
822 .into_values()
823 .filter(|&version| Some(version) != register)
824 .collect::<Vec<_>>();
825 co_registers.sort();
826 let (data, dots, co_dots) = match kind {
827 EntryKind::Data => materialize_data_elements(values, co_values, kind.max_data_len()),
828 EntryKind::RelayMessage => {
829 let mut visible = values.into_iter().collect::<Vec<_>>();
830 visible.sort_by(|(left_value, left_dot), (right_value, right_dot)| {
831 left_dot
832 .cmp(right_dot)
833 .then_with(|| left_value.cmp(right_value))
834 });
835 let skip_count = visible.len().saturating_sub(kind.max_data_len());
836 let (data, dots) = visible.into_iter().skip(skip_count).unzip();
837 (data, dots, Vec::new())
838 }
839 };
840 let mut tombstones = match kind {
841 EntryKind::Data => co_removes
842 .into_iter()
843 .flat_map(|(element, actors)| {
844 actors
845 .into_values()
846 .map(move |dot| EntryTombstone { element, dot })
847 })
848 .collect::<Vec<_>>(),
849 EntryKind::RelayMessage => removes
850 .into_iter()
851 .map(|(element, dot)| EntryTombstone { element, dot })
852 .collect::<Vec<_>>(),
853 };
854 tombstones.sort_by(|left, right| {
855 left.dot
856 .cmp(&right.dot)
857 .then_with(|| left.element.cmp(&right.element))
858 });
859 let tombstone_skip = kind.tombstone_bound().truncated(tombstones.len());
860 let tombstones: Vec<EntryTombstone> = tombstones.into_iter().skip(tombstone_skip).collect();
861
862 if !proofs.is_empty() {
863 let mut surviving_adds = BTreeMap::new();
864 for (index, value) in data.iter().enumerate() {
865 let digest = ElementDigest(crate::ecc::keccak256(value.as_ref()));
866 if let Some(dot) = dots.get(index) {
867 if !dot.version.actor.is_default() {
868 surviving_adds.insert((digest, dot.version.actor), *dot);
869 }
870 }
871 for &(co_idx, dot) in &co_dots {
872 if co_idx as usize == index && !dot.version.actor.is_default() {
873 surviving_adds.insert((digest, dot.version.actor), dot);
874 }
875 }
876 }
877 proofs.retain(|key, proof| match *key {
878 DataProofKey::Add(digest, actor) => surviving_adds
879 .get(&(digest, actor))
880 .is_some_and(|dot| proof.matches_add(digest, *dot)),
881 DataProofKey::Register(_) => register
882 .into_iter()
883 .chain(co_registers.iter().copied())
884 .any(|floor| proof.matches_register(floor)),
885 DataProofKey::Remove(_, _) => tombstones
886 .iter()
887 .any(|t| proof.matches_remove(t.element, t.dot)),
888 });
889 }
890
891 Self {
892 did: self.did,
893 data,
894 kind,
895 crdt: EntryCrdt {
896 register,
897 dots,
898 tombstones,
899 co_dots,
900 co_registers,
901 proofs: proofs.into_values().collect(),
902 },
903 expires_at_ms,
904 }
905 }
906
907 pub fn join(&self, other: Self) -> Result<Self> {
909 self.validate_same_carrier(&other)?;
910 let expires_at_ms = self.joined_lifetime(&other);
911 Ok(self
912 .materialize_topic_buffer(self.raw_buffer()?.join(other.raw_buffer()?), expires_at_ms))
913 }
914
915 fn is_data_entry(&self) -> bool {
916 !self.kind.is_relay_inbox()
917 }
918
919 fn same_kind_as(&self, other: &Self) -> bool {
920 self.kind == other.kind
921 }
922
923 fn same_key_as(&self, other: &Self) -> bool {
924 self.did == other.did
925 }
926
927 pub fn try_into_storage_entry(self) -> Result<Self> {
929 let buffer = self.topic_buffer()?;
930 Ok(self.materialize_topic_buffer(buffer, self.expires_at_ms))
931 }
932
933 pub fn operate(&self, now_ms: u128, op: EntryOperation, actor: Did) -> Result<Self> {
937 match op {
938 EntryOperation::Overwrite(entry) => self.overwrite(now_ms, entry, actor),
939 EntryOperation::Extend(entry) => self.extend(now_ms, entry, actor),
940 EntryOperation::Tombstone(entry) => match self.kind {
941 EntryKind::Data if !actor.is_default() => self.tombstone_by(entry, actor),
942 EntryKind::Data | EntryKind::RelayMessage => self.tombstone(entry),
943 },
944 }
945 }
946
947 pub fn overwrite(&self, now_ms: u128, other: Self, actor: Did) -> Result<Self> {
949 if !self.is_data_entry() {
950 return Err(Error::EntryNotOverwritable);
951 }
952 self.join(other.ensure_stamp_after(
953 now_ms,
954 actor,
955 self.max_observed_version(),
956 EntryStampKind::Overwrite,
957 )?)
958 }
959
960 pub fn extend(&self, now_ms: u128, other: Self, actor: Did) -> Result<Self> {
962 self.join(other.ensure_stamp_after(
963 now_ms,
964 actor,
965 self.max_observed_version(),
966 EntryStampKind::Delta,
967 )?)
968 }
969
970 pub fn tombstone_by(&self, other: Self, actor: Did) -> Result<Self> {
973 if actor.is_default() || !self.is_data_entry() {
974 return self.tombstone(other);
975 }
976 self.validate_same_carrier(&other)?;
977 let expires_at_ms = self.expires_at_ms;
978 let witness = RetractionWitness::of(&other);
979 let mut buffer = self.topic_buffer()?;
980 let removed = buffer
981 .values
982 .iter()
983 .filter_map(|(value, primary_dot)| match buffer.co_values.get(value) {
984 Some(actors) => actors
985 .get(&actor)
986 .copied()
987 .filter(|actor_dot| witness.matches(value, actor_dot))
988 .map(|dot| (value.clone(), Some(dot))),
989 None => (primary_dot.version.actor.is_default()
990 && witness.matches(value, primary_dot))
991 .then(|| (value.clone(), None)),
992 })
993 .collect::<Vec<_>>();
994 for (value, removed_dot) in removed {
995 buffer.remove_by(&value, actor);
996 if !other.crdt.proofs.is_empty() {
997 let digest = ElementDigest(crate::ecc::keccak256(value.as_ref()));
998 let key = DataProofKey::Remove(digest, actor);
999 if let Some(exact) = other.crdt.proofs.iter().find(|p| p.key == key) {
1000 insert_max(&mut buffer.proofs, key, exact.clone());
1001 } else if let Some(dot) = removed_dot {
1002 if let Some(mut dot_proof) = other
1003 .crdt
1004 .proofs
1005 .iter()
1006 .find(|p| {
1007 p.key == DataProofKey::Remove(ElementDigest([0u8; 32]), actor)
1008 && p.witness_dot == Some(dot)
1009 })
1010 .cloned()
1011 {
1012 dot_proof.key = key;
1013 insert_max(&mut buffer.proofs, key, dot_proof);
1014 }
1015 }
1016 }
1017 }
1018 Ok(self.materialize_topic_buffer(buffer, expires_at_ms))
1019 }
1020
1021 pub fn tombstone(&self, other: Self) -> Result<Self> {
1023 self.validate_same_carrier(&other)?;
1024
1025 let expires_at_ms = self.expires_at_ms;
1026 let witness = RetractionWitness::of(&other);
1027
1028 let mut buffer = self.topic_buffer()?;
1029 let removed = buffer
1030 .values
1031 .iter()
1032 .filter(|(value, dot)| {
1033 witness.matches(value, dot)
1034 || buffer
1035 .co_values
1036 .get(*value)
1037 .is_some_and(|actors| actors.values().any(|d| witness.matches(value, d)))
1038 })
1039 .map(|(value, _)| value.clone())
1040 .collect::<Vec<_>>();
1041 removed.iter().for_each(|value| {
1042 buffer.remove(value);
1043 });
1044 Ok(self.materialize_topic_buffer(buffer, expires_at_ms))
1045 }
1046}
1047
1048#[cfg(test)]
1049mod test_entry;
1050#[cfg(test)]
1051mod test_horizon_model;
1052#[cfg(test)]
1053mod test_inbox;