Skip to main content

rings_core/dht/
entry.rs

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/// DHT storage entry categories.
41#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
42pub enum EntryKind {
43    /// Application elements stored in the DHT, each as its bytes.
44    Data,
45    /// A relay inbox: messages held for an offline peer (see the `inbox` module).
46    RelayMessage,
47}
48
49impl EntryKind {
50    /// The greatest number of visible elements a carrier of this kind keeps; when the cap binds,
51    /// the oldest elements are the ones dropped.
52    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    /// Whether this kind is a relay inbox.
60    pub const fn is_relay_inbox(self) -> bool {
61        matches!(self, EntryKind::RelayMessage)
62    }
63
64    /// The affine placements a carrier of this kind gets when `requested` is configured: a relay
65    /// inbox has one placement, its key, and is replicated to the members of that key instead
66    /// (`dht::relay_holder`, #777), never to affine rotations.
67    pub const fn replication(self, requested: u16) -> u16 {
68        match self {
69            EntryKind::Data => requested,
70            EntryKind::RelayMessage => 1,
71        }
72    }
73
74    /// How a carrier of this kind bounds its removes (removal-stability paper, Law 5 and
75    /// Prop. 3).
76    ///
77    /// A data topic refuses past [`DATA_TOMBSTONE_MAX_LEN`] and never truncates: a dropped
78    /// tombstone could be one whose add is still inside its element horizon at another replica,
79    /// which would then resurrect it; a refused write drops nothing. A relay inbox keeps the
80    /// newest [`RELAY_INBOX_MAX_LEN`] removals: a lagging member (#777) may still resurrect an
81    /// element whose removal fell off the cap, and its redelivery is refused by the recipient's
82    /// receiver window and retired again, so the cap costs a redelivery, never a duplicate
83    /// dispatch.
84    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/// How a carrier bounds its removes: by refusing a write past the bound, or by keeping the newest
93/// removes up to it.
94#[derive(Clone, Copy, Debug, PartialEq, Eq)]
95pub enum TombstoneBound {
96    /// A write whose result would hold more removes is refused, changing nothing.
97    Refuse(usize),
98    /// Only the newest removes, by dot, up to the bound are kept.
99    Truncate(usize),
100}
101
102impl TombstoneBound {
103    /// How many of `count` removes, oldest first, materialization drops: the excess over a
104    /// truncating bound, and none under a refusing one, which [`Entry::check_tombstone_bound`]
105    /// enforces instead.
106    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// Canonical stamp input for EntryVersion.operation.
121//
122// This digest is an unreleased CRDT tie-break witness between nodes running the
123// same code, not a stable storage key or cross-version protocol identifier.
124#[derive(Serialize)]
125struct OperationDigest<'a> {
126    kind: EntryKind,
127    did: Did,
128    actor: Did,
129    data: &'a [Bytes],
130}
131
132/// Operations supported by a DHT storage entry.
133#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
134pub enum EntryOperation {
135    /// Create or update an [`Entry`].
136    Overwrite(Entry),
137    /// Add payloads to a data topic or a relay inbox.
138    /// This operation will create an [`Entry`] if it does not exist.
139    Extend(Entry),
140    /// Remove observed data or relay-message payloads.
141    ///
142    /// The payload identifies the entry carrier and the values to
143    /// remove. If CRDT dots are present, the payloads the receiver holds at those
144    /// dots are removed; otherwise the receiver removes the payloads it holds
145    /// with matching bytes. Each removal is a covering remove at the dot the
146    /// receiver holds (see [`EntryTombstone`]).
147    Tombstone(Entry),
148}
149
150/// A storage operation targeted at one concrete affine placement key.
151///
152/// Invariant: `placement` must be one of the affine replica keys derived from
153/// the operation's entry DID under the replication its kind gets from the
154/// receiver's configured storage redundancy (a relay inbox has one placement,
155/// its DID). The sender may choose a replica from that set, but cannot choose
156/// where the replica set itself lives.
157#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
158pub struct PlacedEntryOperation {
159    /// Placement key that must receive the operation.
160    pub placement: Did,
161    /// Operation to apply at `placement`.
162    pub op: EntryOperation,
163    /// Whether the owner that applies or refuses the operation at `placement` reports it to the
164    /// operation's origin (`message::types::store_report`, #866).
165    pub report: bool,
166}
167
168impl PlacedEntryOperation {
169    /// Return the entry identity carried by this operation.
170    pub fn entry_key(&self) -> Result<Did> {
171        self.op.did()
172    }
173
174    /// Enforce that `placement` belongs to the operation's entry.
175    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
186/// Enforce that `placement` lies in the affine replica set of a carrier of `kind` identified
187/// by `entry_key`: the set has `kind.replication(redundancy)` keys, one for a relay inbox. The
188/// error names the rejected carrier as `what`.
189fn 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/// A DHT storage entry with an [`EntryKind`] and a ring key represented as [`Did`].
209///
210/// An [`Entry`] is data stored by Chord storage on a [`PeerRing`](super::PeerRing). It is not a
211/// Chord node and does not participate in successor, predecessor, or finger-table
212/// membership.
213///
214/// The [`Did`] of an [`Entry`] is in the following format:
215/// * If kind value is [EntryKind::Data], it's sha1 of data topic.
216/// * If kind value is [EntryKind::RelayMessage], it's the destination Did of the held
217///   messages plus 1, the position just after the destination, which lies in the
218///   destination's own storage interval once it is online (see the `inbox` module).
219///
220/// The kind is part of the carrier's storage identity: a data topic and a relay inbox at the
221/// same position are distinct slots, so neither can shadow the other.
222///
223/// Retention: every entry accepted into storage carries a retention bound `expires_at_ms`,
224/// stamped by the origin at the operation boundary and bounded by the receiver at admission
225/// (see the `retention` module and `Entry::validate_admissible_at`). The bound joins by
226/// `max`, so every accepted write extends the carrier's life to at least its own bound, and an
227/// entry whose bound has elapsed (and that holds no remove still inside its horizon) is dropped
228/// on the next read instead of being served or replicated. Inside a live data carrier, every
229/// element expires individually at its dot's issue time plus the element horizon
230/// ([`EntryKind::element_horizon_ms`], see [`Entry::retired_at`]).
231#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
232pub struct Entry {
233    /// The ring key of this entry. It has the same representation as a node DID, but a
234    /// different domain meaning.
235    pub did: Did,
236    /// The elements of this carrier, each as its bytes: the application's own encoding of the
237    /// value, carried and digested as is, never re-encoded as text.
238    pub data: Vec<Bytes>,
239    /// The type indicates how the data is encoded and how the Did is generated.
240    pub kind: EntryKind,
241    /// CRDT metadata that makes replicated merge a join-semilattice operation.
242    #[serde(default)]
243    pub crdt: EntryCrdt,
244    /// Retention bound in milliseconds since the Unix epoch. `None` only before the operation
245    /// boundary stamps it; a stored value without a bound is treated as not live.
246    #[serde(default)]
247    pub expires_at_ms: Option<u128>,
248}
249
250/// An [`Entry`] paired with its Chord placement key.
251///
252/// `key` is the DHT storage location. `entry.did` is the resource identity. These two
253/// values may differ for redundant replicas.
254#[derive(Clone, Debug, Serialize, Deserialize)]
255pub struct PlacedEntry {
256    /// The key used to place this value in DHT storage.
257    pub key: Did,
258    /// The stored entry value.
259    pub entry: Entry,
260    /// Local custody incarnation observed when this entry was queued for hand-off.
261    #[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    /// Pair an entry value with the key where it is stored.
275    pub fn new(key: Did, entry: Entry) -> Self {
276        Self {
277            key,
278            entry,
279            custody_incarnation: None,
280        }
281    }
282
283    /// Attach the local custody incarnation observed when this entry was queued for hand-off.
284    pub(crate) fn with_custody_incarnation(mut self, incarnation: u64) -> Self {
285        self.custody_incarnation = Some(incarnation);
286        self
287    }
288
289    /// The local custody incarnation observed when this entry was queued for hand-off, if any.
290    pub(crate) const fn custody_incarnation(&self) -> Option<u64> {
291        self.custody_incarnation
292    }
293
294    /// Semilattice join of two [`PlacedEntry`] values targeting the same placement key `key` and
295    /// carrier identity `(entry.kind, entry.did)`.
296    ///
297    /// Law: over a fixed placement fibre `(key, entry.kind, entry.did)`, [`PlacedEntry`] is the
298    /// product join-semilattice `(Entry, Entry::join) × (Option<u64>, max)`.
299    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    /// Enforce that `key` belongs to `entry.did`'s affine replica set.
311    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/// Durable-storage acknowledgement for an entry hand-off delta.
323///
324/// `key` is the placement key updated by the receiver. `entry` is the copied
325/// delta that the receiver joined into its local least upper bound. Before
326/// deleting, the sender compares the copied value with its current local value,
327/// both normalized and projected by [`Entry::retired_at`] at the sender's clock,
328/// and verifies that the acknowledgement is bound to the current local custody
329/// incarnation of that storage slot; if the sender has observed any newer durable
330/// delta or custody re-acquisition meanwhile, deletion is skipped.
331#[derive(Clone, Debug, Serialize, Deserialize)]
332pub struct SyncedEntryAck {
333    /// The placement key durably persisted by the sync receiver.
334    pub key: Did,
335    /// The copied value the sync receiver durably joined.
336    pub entry: Entry,
337    /// Local custody incarnation that emitted the hand-off this acknowledgement confirms.
338    #[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    /// Witness that `entry` was durably joined at `key`.
352    pub fn new(key: Did, entry: Entry) -> Self {
353        Self {
354            key,
355            entry,
356            custody_incarnation: 0,
357        }
358    }
359
360    /// Bind this acknowledgement to the sender's local custody incarnation `incarnation`.
361    pub(crate) fn with_custody_incarnation(mut self, incarnation: u64) -> Self {
362        self.custody_incarnation = incarnation;
363        self
364    }
365
366    /// The sender's local custody incarnation bound to this acknowledgement.
367    pub(crate) const fn custody_incarnation(&self) -> u64 {
368        self.custody_incarnation
369    }
370
371    /// Returns whether this ack proves that `local` equals the copied value at the clock
372    /// `now_ms`.
373    ///
374    /// Pre: both the copied value and `local` are normalized, and `local` is already projected
375    /// at `now_ms`: `local` is the live stored value a storage read returns, and the copy is
376    /// admitted only equal to one the sender took from its own storage.
377    /// Post: the comparison is on both values projected to the element horizon at `now_ms`
378    /// ([`Entry::retired_at`]), so an element or remove that merely crossed its horizon between
379    /// the copy and the ack is not mistaken for a newer write: the copy was projected at an
380    /// earlier clock, and projecting it again at `now_ms` yields what `local` is when nothing
381    /// was written meanwhile. It computes no digest.
382    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/// A lookup request for a concrete placement of an entry identity.
388///
389/// `resource` is `id(e)`. `placement` is one element of
390/// `place(resource, REDUNDANT)`.
391#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
392pub struct EntryLookupKey {
393    /// Entry identity being searched.
394    pub resource: Did,
395    /// Placement key being interrogated.
396    pub placement: Did,
397}
398
399impl EntryLookupKey {
400    /// Pair an entry identity with one of its placement keys.
401    pub fn new(resource: Did, placement: Did) -> Self {
402        Self {
403            resource,
404            placement,
405        }
406    }
407}
408
409/// A placement key observed missing during lookup.
410#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
411pub struct PlacementMiss {
412    /// Placement key whose responsible owner returned `None`.
413    pub key: Did,
414    /// Owner that was responsible for `key` when the miss was observed.
415    pub owner: Did,
416}
417
418impl PlacementMiss {
419    /// Witness that `owner` was queried for `key` and did not have the entry.
420    pub fn new(key: Did, owner: Did) -> Self {
421        Self { key, owner }
422    }
423}
424
425/// A successful lookup result plus the missing placements observed before it.
426#[derive(Clone, Debug, PartialEq, Eq)]
427pub struct EntryLookupEvidence {
428    /// Entry found by the lookup.
429    pub entry: Entry,
430    /// Placement misses observed as part of the same lookup.
431    pub misses: Vec<PlacementMiss>,
432}
433
434impl EntryLookupEvidence {
435    /// Construct lookup evidence.
436    pub fn new(entry: Entry, misses: Vec<PlacementMiss>) -> Self {
437        Self { entry, misses }
438    }
439}
440
441impl Entry {
442    /// Construct an entry with empty CRDT metadata.
443    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    /// Generate did from topic.
454    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    /// Return this operation with CRDT versions and the retention bound assigned at the
464    /// operation boundary `now_ms`.
465    ///
466    /// Existing CRDT witnesses and an existing retention bound are preserved so forwarded
467    /// operations keep the origin's dot/version and lifetime instead of being reissued by every
468    /// routing hop.
469    ///
470    /// Post: every carried entry has `expires_at_ms = Some(_)`; an absent bound becomes
471    /// `now_ms + kind.default_lifetime_ms()`.
472    pub fn stamped(self, now_ms: u128, actor: Did) -> Result<Self> {
473        self.stamped_after(now_ms, actor, None)
474    }
475
476    /// [`Self::stamped`], issuing any version it stamps strictly after `floor`: the issue law of
477    /// a node that stamps its operations in order (#1075), `logical_time = max(now, floor + 1)`
478    /// when `now` alone would not exceed `floor` (`EntryVersion::after`).
479    ///
480    /// Post: a version this call issues is greater than `floor`; an operation that already
481    /// carries its witnesses is returned with them unchanged.
482    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    /// The write witness each operation kind must carry: per-element dots of `kind` (plus a
505    /// reset register for an overwrite), or `None` for a reference operation, which names
506    /// existing dots or values and issues none.
507    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    /// The entry this operation carries.
516    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    /// Apply `f` to the carried entry, keeping the operation kind.
525    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    /// Extract the did of target Entry.
534    pub fn did(&self) -> Result<Did> {
535        Ok(self.entry().did)
536    }
537
538    /// Extract the kind of target Entry.
539    pub fn kind(&self) -> EntryKind {
540        self.entry().kind
541    }
542
543    /// Generate a target Entry when it is not existed.
544    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    /// The data-topic delta holding the one element `element` of `topic`.
552    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    /// The data-topic delta holding the text `text` of `topic` as its UTF-8 bytes.
564    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    /// Every version this entry carries: element dots, co-author dots, tombstones, and reset
679    /// floors.
680    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    /// The greatest version this carrier holds: of a dot, a remove, or a register floor.
697    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    /// This entry's carrier state before normalization: every element with its dot and every
719    /// remove, each keyed by its greatest dot, and the reset floors.
720    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    /// This entry's normalized carrier state (see [`DataTopicBuffer::normalize`]).
788    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    /// Materialize a normalized buffer as an entry: elements in dot order under the count cap,
802    /// removes in dot order, truncated only under a truncating tombstone bound.
803    ///
804    /// Pre: `buffer` is normalized, so no element is below its actor's register floor or covered
805    /// by a matching remove, and no digest is computed here unless `proofs` is non-empty.
806    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    /// Merge two entries from the same replicated carrier.
908    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    /// Normalize an entry immediately before it is persisted.
928    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    /// The entry point of [EntryOperation] at the operation-boundary time `now_ms`, which
934    /// stamps any unstamped witness. Will dispatch to different operation handlers according to
935    /// the variant.
936    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    /// Overwrite current data with new data.
948    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    /// Add `other`'s payloads to this carrier.
961    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    /// Remove observed data payloads authored by `actor`, leaving other co-authors' attributions
971    /// intact (#1220).
972    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    /// Remove observed data or relay-message payloads.
1022    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;