Skip to main content

rings_core/dht/entry/
crdt.rs

1//! CRDT carriers for DHT entries.
2//!
3//! State variables:
4//! - `register` is an optional LWW reset floor for overwrite.
5//! - `values` is an LWW element set keyed by element bytes: each payload keeps its greatest
6//!   add dot.
7//! - `removes` is the remove side, keyed by payload digest: each digest keeps its greatest
8//!   remove dot, and a remove `(e, r)` covers every add `(v, d)` with `digest(v) = e ∧ d ≤ r`.
9//!
10//! ```text
11//!   covered(v, d)  ≜  ∃ r. removes[digest(v)] = r ∧ d ≤ r
12//!   visible(v, d)  ≜  values[v] = d ∧ (register = ⊥ ∨ register ≤ d.version) ∧ ¬covered(v, d)
13//! ```
14//!
15//! A remove covers a payload's dots up to its own, not one exact dot, because `values` keeps
16//! only the greatest dot per payload: a dot superseded by a later dot of the same payload is
17//! forgotten, so a remove naming only the surviving dot would let a stale replica that still
18//! holds the superseded one resurrect the payload (#874). Under the covering remove the
19//! forgotten dot needs no storage at all, and the carrier is an LWW element set: a remove at
20//! `r` wins over every add of the payload at or below `r`, an add above `r` wins over it.
21//! "At or below" is the dot order, which leads with the hybrid logical time: a re-add issued
22//! after the remove in real time by a writer whose clock runs behind (by at most `σ`) can lie
23//! below `r` and stays removed. A value-witness remove carries no dot, so each owner covers the
24//! dot it holds when the remove arrives; delivered after the same client's re-add, it covers
25//! that re-add too. A remove that must not outrun its issuer's view names the issuer's dots
26//! (the dot-witness path of `Entry::tombstone`).
27//!
28//! Semilattice laws:
29//! - `DataTopicBuffer` join is the product of three join-semilattices, `register` under `max`
30//!   and `values`, `removes` under pointwise `max`, followed by the normalization
31//!   `DataTopicBuffer::new`. The normalization is a closure operator whose dropped elements stay
32//!   dropped under every further join (a floor and a covering remove only grow), so the join is
33//!   idempotent, commutative, and associative over normalized carriers. A data topic and a relay
34//!   inbox are the same carrier; their per-kind authority, tombstone cap, and element horizon
35//!   are enforced by the entry, not by a second set type.
36//!
37//! Constructor postconditions:
38//! - `DataTopicBuffer::new` preserves only values and removes whose dot is at or after the reset
39//!   floor when a reset floor exists, and only values no remove covers.
40
41use std::collections::BTreeMap;
42
43use bytes::Bytes;
44use serde::Deserialize;
45use serde::Serialize;
46
47use crate::algebra::JoinSemilattice;
48use crate::dht::Did;
49use crate::ecc::keccak256;
50use crate::error::Error;
51use crate::error::Result;
52
53/// Hybrid logical version for LWW entry registers and element dots: the HLC pair
54/// `(logical_time_ms, counter)` followed by the issuer, ordered lexicographically in field order.
55///
56/// `logical_time_ms` starts from the wall-clock millisecond observed at the storage-operation
57/// boundary; a version issued after a floor that dominates it keeps the floor's millisecond and
58/// raises `counter` instead (`EntryVersion::after`), so strict ascent never moves the millisecond
59/// ahead of the clock (#1075). `actor` and `operation` make concurrent writes of different
60/// issuers at one `(logical_time_ms, counter)` totally ordered without claiming recency.
61#[derive(
62    Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize,
63)]
64pub struct EntryVersion {
65    /// Hybrid logical time in milliseconds.
66    #[serde(alias = "epoch_ms")]
67    pub logical_time_ms: u128,
68    /// Logical counter within `logical_time_ms`: raised, instead of the millisecond, when a
69    /// version is issued after a floor at the same or a later millisecond.
70    pub counter: u32,
71    /// Storage node that first stamped the operation.
72    pub actor: Did,
73    /// Deterministic digest of the stamped operation payload.
74    #[serde(default)]
75    pub operation: Did,
76}
77
78impl EntryVersion {
79    /// Construct a version from an explicit hybrid logical time and actor.
80    pub fn new(logical_time_ms: u128, actor: Did, operation: Did) -> Self {
81        Self {
82            logical_time_ms,
83            counter: 0,
84            actor,
85            operation,
86        }
87    }
88
89    /// The HLC issue step: `max(self, (l_f, c_f + 1, actor, operation))`. When `self`, the
90    /// version at the issuer's clock `(now, 0, …)`, already exceeds `floor`, it is returned, so
91    /// the millisecond follows the clock and the counter restarts at 0; only when `now ≤ l_f`
92    /// does the counter step at `floor`'s millisecond.
93    ///
94    /// Laws: `v.after(f) > f`; `v.after(f).logical_time_ms = max(v.logical_time_ms, l_f)`, so
95    /// strict ascent never advances the millisecond past the greater of the two; and
96    /// `counter < 2³²` per millisecond, totally: at `c_f = u32::MAX` the step is refused with
97    /// `EntryVersionAheadOfClock`, since the only way past it would advance the millisecond
98    /// beyond the floor, which the caller's cap forbids; the writer is refused, never made to
99    /// wait. The bound needs `2³²` versions issued after floors at one millisecond, more than
100    /// `4·10¹²` writes a second, so no writer reaches it.
101    pub(super) fn after(self, floor: Option<Self>) -> Result<Self> {
102        if self.counter >= PROOF_CHUNK_SENTINEL_COUNTER {
103            return Err(Error::EntryVersionAheadOfClock);
104        }
105        let Some(floor) = floor else {
106            return Ok(self);
107        };
108        if self > floor {
109            return Ok(self);
110        }
111        let counter = floor
112            .counter
113            .checked_add(1)
114            .filter(|&counter| counter < PROOF_CHUNK_SENTINEL_COUNTER)
115            .ok_or(Error::EntryVersionAheadOfClock)?;
116        Ok(Self {
117            logical_time_ms: floor.logical_time_ms,
118            counter,
119            actor: self.actor,
120            operation: self.operation,
121        })
122    }
123}
124
125/// Unique add witness for one visible entry payload element.
126#[derive(
127    Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize,
128)]
129pub struct EntryDot {
130    /// LWW version that issued this element.
131    pub version: EntryVersion,
132    /// Element position inside the issuing operation.
133    pub index: u32,
134}
135
136impl EntryDot {
137    pub(super) fn for_index(version: EntryVersion, index: usize) -> Result<Self> {
138        let index = u32::try_from(index).map_err(|_| Error::EntryDotIndexOutOfBounds { index })?;
139        Ok(Self { version, index })
140    }
141}
142
143/// Content address of one element: the Keccak-256 digest of its bytes.
144///
145/// A remove names the payload it removes by this digest rather than by its bytes, so a
146/// tombstone costs a constant number of bytes whatever the payload size.
147///
148/// Law: `ElementDigest::of(u) = ElementDigest::of(v) ⟺ u = v`, up to Keccak-256 collision
149/// resistance.
150#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
151pub struct ElementDigest(pub [u8; 32]);
152
153#[cfg(test)]
154thread_local! {
155    /// Test instrumentation: the element digests computed on this thread, so a test can bound
156    /// the hashing an operation performs.
157    static DIGESTS_COMPUTED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
158}
159
160/// Test instrumentation: reset this thread's digest count.
161#[cfg(test)]
162pub(crate) fn reset_digests() {
163    DIGESTS_COMPUTED.with(|computed| computed.set(0));
164}
165
166/// Test instrumentation: the element digests computed on this thread since the last reset.
167#[cfg(test)]
168pub(crate) fn digests_computed() -> usize {
169    DIGESTS_COMPUTED.with(|computed| computed.get())
170}
171
172impl ElementDigest {
173    /// The digest of the element `value`: the Keccak-256 of its bytes.
174    pub fn of(value: &Bytes) -> Self {
175        #[cfg(test)]
176        DIGESTS_COMPUTED.with(|computed| computed.set(computed.get() + 1));
177        Self(keccak256(value.as_ref()))
178    }
179}
180
181/// Remove witness for one payload: it covers every add of the payload whose digest is `element`
182/// at or below `dot` (see the module documentation).
183#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
184pub struct EntryTombstone {
185    /// Digest of the removed payload.
186    pub element: ElementDigest,
187    /// Greatest add dot of the payload the remove covers.
188    pub dot: EntryDot,
189}
190
191impl EntryTombstone {
192    /// Remove witness covering the adds of `value` at or below `dot`.
193    pub fn of(value: &Bytes, dot: EntryDot) -> Self {
194        Self {
195            element: ElementDigest::of(value),
196            dot,
197        }
198    }
199}
200
201const SENTINEL_TIME_MS: u128 = u64::MAX as u128;
202const CO_DOT_SENTINEL_COUNTER: u32 = u32::MAX;
203const CO_REGISTER_SENTINEL_COUNTER: u32 = u32::MAX - 1;
204pub(super) const PROOF_CHUNK_SENTINEL_COUNTER: u32 = u32::MAX - 2;
205
206fn is_sentinel_version(version: EntryVersion, sentinel_counter: u32) -> bool {
207    (version.logical_time_ms == SENTINEL_TIME_MS || version.logical_time_ms == u128::MAX)
208        && version.counter == sentinel_counter
209        && version.actor.is_default()
210        && version.operation.is_default()
211}
212
213fn co_dot_sentinel_version() -> EntryVersion {
214    EntryVersion {
215        logical_time_ms: SENTINEL_TIME_MS,
216        counter: CO_DOT_SENTINEL_COUNTER,
217        actor: Did::default(),
218        operation: Did::default(),
219    }
220}
221
222fn co_register_sentinel_version() -> EntryVersion {
223    EntryVersion {
224        logical_time_ms: SENTINEL_TIME_MS,
225        counter: CO_REGISTER_SENTINEL_COUNTER,
226        actor: Did::default(),
227        operation: Did::default(),
228    }
229}
230
231fn data_proof_sentinel_version() -> EntryVersion {
232    EntryVersion {
233        logical_time_ms: SENTINEL_TIME_MS,
234        counter: PROOF_CHUNK_SENTINEL_COUNTER,
235        actor: Did::default(),
236        operation: Did::default(),
237    }
238}
239
240const DOT_CHUNK_BYTES: usize = 52;
241const MAX_PROOF_BUNDLE_BYTES: usize = 1024 * 1024;
242
243fn pack_proof_chunk(chunk: &[u8], chunk_index: usize) -> EntryDot {
244    let mut buf = [0u8; DOT_CHUNK_BYTES];
245    if let Some(prefix) = buf.get_mut(..chunk.len()) {
246        prefix.copy_from_slice(chunk);
247    }
248    let logical_time_ms = u128::from(u64::from_be_bytes(
249        buf.get(0..8)
250            .and_then(|s| s.try_into().ok())
251            .unwrap_or_default(),
252    ));
253    let counter = u32::from_be_bytes(
254        buf.get(8..12)
255            .and_then(|s| s.try_into().ok())
256            .unwrap_or_default(),
257    );
258    let actor_bytes: [u8; 20] = buf
259        .get(12..32)
260        .and_then(|s| s.try_into().ok())
261        .unwrap_or_default();
262    let op_bytes: [u8; 20] = buf
263        .get(32..52)
264        .and_then(|s| s.try_into().ok())
265        .unwrap_or_default();
266    EntryDot {
267        version: EntryVersion {
268            logical_time_ms,
269            counter,
270            actor: ethereum_types::H160::from(actor_bytes).into(),
271            operation: ethereum_types::H160::from(op_bytes).into(),
272        },
273        index: u32::try_from(chunk_index).unwrap_or(u32::MAX),
274    }
275}
276
277fn unpack_proof_chunk(dot: EntryDot, expected_chunk_idx: usize) -> Result<[u8; DOT_CHUNK_BYTES]> {
278    if u32::try_from(expected_chunk_idx).ok() != Some(dot.index) {
279        return Err(Error::DataEntryWriteUnauthorized);
280    }
281    let low_time = u64::try_from(dot.version.logical_time_ms)
282        .map_err(|_| Error::DataEntryWriteUnauthorized)?;
283    let mut buf = [0u8; DOT_CHUNK_BYTES];
284    if let Some(slice) = buf.get_mut(0..8) {
285        slice.copy_from_slice(&low_time.to_be_bytes());
286    }
287    if let Some(slice) = buf.get_mut(8..12) {
288        slice.copy_from_slice(&dot.version.counter.to_be_bytes());
289    }
290    if let Some(slice) = buf.get_mut(12..32) {
291        slice.copy_from_slice(dot.version.actor.as_bytes());
292    }
293    if let Some(slice) = buf.get_mut(32..52) {
294        slice.copy_from_slice(dot.version.operation.as_bytes());
295    }
296    Ok(buf)
297}
298
299/// CRDT metadata carried beside the entry payload.
300///
301/// `register` is the LWW reset floor used by overwrite. `dots` are per-element
302/// add witnesses used by data/topic and relay element sets. `tombstones` is the
303/// remove side: one covering remove per removed `(payload, actor)`. `co_dots`,
304/// `co_registers`, and `proofs` preserve per-actor add witnesses, secondary
305/// per-actor reset floors, and Swarm cryptographic author proofs, packed into
306/// the `dots` sequence on the wire and on disk so the 3-field `EntryCrdt`
307/// layout remains compatible with persisted `FileStorage` records.
308#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
309#[serde(into = "WireEntryCrdt", try_from = "WireEntryCrdt")]
310pub struct EntryCrdt {
311    /// Optional greatest LWW reset floor for the entry payload.
312    pub register: Option<EntryVersion>,
313    /// Per-element add dots. An element without one is given the dot of its index above the
314    /// register floor (`EntryDot::for_index`).
315    pub dots: Vec<EntryDot>,
316    /// Covering removes, scoped per `(payload, actor)` for `Data` and per `payload` for `RelayMessage`.
317    pub tombstones: Vec<EntryTombstone>,
318    /// Additional per-actor add dots `(element_index, dot)` for elements concurrently held by
319    /// multiple attributed writers.
320    pub co_dots: Vec<(u32, EntryDot)>,
321    /// Secondary per-actor reset floors when multiple attributed writers reset the carrier.
322    pub co_registers: Vec<EntryVersion>,
323    /// Cryptographic author proofs for Swarm-originated data mutations.
324    pub proofs: Vec<super::provenance::SignedDataMutation>,
325}
326
327#[derive(Serialize, Deserialize)]
328#[serde(rename = "EntryCrdt")]
329struct WireEntryCrdt {
330    register: Option<EntryVersion>,
331    dots: Vec<EntryDot>,
332    tombstones: Vec<EntryTombstone>,
333}
334
335impl From<EntryCrdt> for WireEntryCrdt {
336    fn from(crdt: EntryCrdt) -> Self {
337        let co_dot_sentinel = co_dot_sentinel_version();
338        let co_reg_sentinel = co_register_sentinel_version();
339        let proof_sentinel = data_proof_sentinel_version();
340        let mut dots = Vec::with_capacity(
341            crdt.dots
342                .len()
343                .saturating_add(crdt.co_dots.len().saturating_mul(2))
344                .saturating_add(crdt.co_registers.len().saturating_mul(2)),
345        );
346        dots.extend(crdt.dots);
347        dots.extend(crdt.co_dots.into_iter().flat_map(|(elem_idx, dot)| {
348            [
349                EntryDot {
350                    version: co_dot_sentinel,
351                    index: elem_idx,
352                },
353                dot,
354            ]
355        }));
356        dots.extend(crdt.co_registers.into_iter().flat_map(|version| {
357            [
358                EntryDot {
359                    version: co_reg_sentinel,
360                    index: 0,
361                },
362                EntryDot { version, index: 0 },
363            ]
364        }));
365        if !crdt.proofs.is_empty() {
366            if let Ok(encoded) = super::provenance::encode_proof_bundle(&crdt.proofs) {
367                if encoded.len() <= MAX_PROOF_BUNDLE_BYTES {
368                    if let Ok(byte_len) = u32::try_from(encoded.len()) {
369                        dots.push(EntryDot {
370                            version: proof_sentinel,
371                            index: byte_len,
372                        });
373                        for (chunk_idx, chunk) in encoded.chunks(DOT_CHUNK_BYTES).enumerate() {
374                            dots.push(pack_proof_chunk(chunk, chunk_idx));
375                        }
376                    }
377                }
378            }
379        }
380        Self {
381            register: crdt.register,
382            dots,
383            tombstones: crdt.tombstones,
384        }
385    }
386}
387
388impl TryFrom<WireEntryCrdt> for EntryCrdt {
389    type Error = Error;
390
391    fn try_from(wire: WireEntryCrdt) -> Result<Self> {
392        let mut dots = Vec::with_capacity(wire.dots.len());
393        let mut co_dots = Vec::new();
394        let mut co_registers = Vec::new();
395        let mut proofs = Vec::new();
396        let mut saw_proof_sentinel = false;
397        let mut iter = wire.dots.into_iter();
398        while let Some(dot) = iter.next() {
399            if is_sentinel_version(dot.version, CO_DOT_SENTINEL_COUNTER) {
400                let co_dot = iter.next().ok_or(Error::DataEntryWriteUnauthorized)?;
401                co_dots.push((dot.index, co_dot));
402            } else if is_sentinel_version(dot.version, CO_REGISTER_SENTINEL_COUNTER) {
403                let reg_dot = iter.next().ok_or(Error::DataEntryWriteUnauthorized)?;
404                co_registers.push(reg_dot.version);
405            } else if is_sentinel_version(dot.version, PROOF_CHUNK_SENTINEL_COUNTER) {
406                if saw_proof_sentinel {
407                    return Err(Error::DataEntryWriteUnauthorized);
408                }
409                saw_proof_sentinel = true;
410                let byte_len = dot.index as usize;
411                if byte_len == 0 || byte_len > MAX_PROOF_BUNDLE_BYTES {
412                    return Err(Error::DataEntryWriteUnauthorized);
413                }
414                let chunk_count = byte_len.div_ceil(DOT_CHUNK_BYTES);
415                if chunk_count > iter.len() {
416                    return Err(Error::DataEntryWriteUnauthorized);
417                }
418                let mut raw = Vec::with_capacity(chunk_count.saturating_mul(DOT_CHUNK_BYTES));
419                for chunk_idx in 0..chunk_count {
420                    let chunk_dot = iter.next().ok_or(Error::DataEntryWriteUnauthorized)?;
421                    raw.extend_from_slice(&unpack_proof_chunk(chunk_dot, chunk_idx)?);
422                }
423                if raw
424                    .get(byte_len..)
425                    .is_none_or(|padding| padding.iter().any(|&b| b != 0))
426                {
427                    return Err(Error::DataEntryWriteUnauthorized);
428                }
429                raw.truncate(byte_len);
430                proofs = super::provenance::decode_proof_bundle(&raw)?;
431            } else {
432                dots.push(dot);
433            }
434        }
435        Ok(Self {
436            register: wire.register,
437            dots,
438            tombstones: wire.tombstones,
439            co_dots,
440            co_registers,
441            proofs,
442        })
443    }
444}
445
446impl EntryCrdt {
447    pub(crate) fn encode_proof_dots(
448        proofs: &[super::provenance::SignedDataMutation],
449    ) -> Vec<EntryDot> {
450        let mut dots = Vec::new();
451        if !proofs.is_empty() {
452            if let Ok(encoded) = super::provenance::encode_proof_bundle(proofs) {
453                if encoded.len() <= MAX_PROOF_BUNDLE_BYTES {
454                    if let Ok(byte_len) = u32::try_from(encoded.len()) {
455                        dots.push(EntryDot {
456                            version: data_proof_sentinel_version(),
457                            index: byte_len,
458                        });
459                        for (chunk_idx, chunk) in encoded.chunks(DOT_CHUNK_BYTES).enumerate() {
460                            dots.push(pack_proof_chunk(chunk, chunk_idx));
461                        }
462                    }
463                }
464            }
465        }
466        dots
467    }
468
469    pub(crate) fn decode_proof_dots(
470        dots: Vec<EntryDot>,
471    ) -> Vec<super::provenance::SignedDataMutation> {
472        if dots.is_empty() {
473            return Vec::new();
474        }
475        Self::try_from(WireEntryCrdt {
476            register: None,
477            dots,
478            tombstones: Vec::new(),
479        })
480        .map(|crdt| crdt.proofs)
481        .unwrap_or_default()
482    }
483
484    pub(super) fn has_write_witness(&self) -> bool {
485        let witnessed = |version: &EntryVersion| {
486            !version.actor.is_default() && (!version.operation.is_default() || version.counter != 0)
487        };
488        self.register.as_ref().is_some_and(witnessed)
489            || self.co_registers.iter().any(witnessed)
490            || self
491                .dots
492                .iter()
493                .chain(self.co_dots.iter().map(|(_, dot)| dot))
494                .any(|dot| witnessed(&dot.version))
495    }
496
497    /// Return the bottom floor used only to lift legacy payloads without dots.
498    pub(super) fn legacy_floor(&self) -> EntryVersion {
499        self.register.unwrap_or_default()
500    }
501}
502
503/// Bounded LWW element set used by data topic buffers.
504#[derive(Clone, Debug, Default, PartialEq, Eq)]
505pub struct DataTopicBuffer {
506    /// The greatest reset floor across overwrites.
507    pub(super) register: Option<EntryVersion>,
508    /// Per-actor reset floors keyed by attributed writer DID.
509    pub(super) co_registers: BTreeMap<Did, EntryVersion>,
510    /// Every element held and not covered by a remove, with the greatest dot that added it.
511    pub(super) values: BTreeMap<Bytes, EntryDot>,
512    /// Per-actor add dots for each held element, keyed by attributed writer DID.
513    pub(super) co_values: BTreeMap<Bytes, BTreeMap<Did, EntryDot>>,
514    /// Greatest remove per element digest across all actors.
515    pub(super) removes: BTreeMap<ElementDigest, EntryDot>,
516    /// Per-actor removes for each element digest, keyed by writer DID (`Did::default()` for unattributed).
517    pub(super) co_removes: BTreeMap<ElementDigest, BTreeMap<Did, EntryDot>>,
518    /// Cryptographic author proofs keyed by `(Register | Add | Remove, actor)`.
519    pub(super) proofs:
520        BTreeMap<super::provenance::DataProofKey, super::provenance::SignedDataMutation>,
521}
522
523/// Insert `value` at `key`, keeping the greater value when `key` is already present: the join of
524/// one singleton into a pointwise-`max` map.
525pub(super) fn insert_max<K: Ord, V: Ord>(map: &mut BTreeMap<K, V>, key: K, value: V) {
526    if map.get(&key).is_none_or(|current| current.lt(&value)) {
527        map.insert(key, value);
528    }
529}
530
531fn has_register_proof(
532    proofs: &BTreeMap<super::provenance::DataProofKey, super::provenance::SignedDataMutation>,
533    actor: Did,
534    floor: EntryVersion,
535) -> bool {
536    !actor.is_default()
537        && proofs
538            .get(&super::provenance::DataProofKey::Register(actor))
539            .is_some_and(|p| p.matches_register(floor))
540}
541
542fn has_add_proof(
543    proofs: &BTreeMap<super::provenance::DataProofKey, super::provenance::SignedDataMutation>,
544    digest: ElementDigest,
545    actor: Did,
546    dot: EntryDot,
547) -> bool {
548    !actor.is_default()
549        && proofs
550            .get(&super::provenance::DataProofKey::Add(digest, actor))
551            .is_some_and(|p| p.matches_add(digest, dot))
552}
553
554fn has_remove_proof(
555    proofs: &BTreeMap<super::provenance::DataProofKey, super::provenance::SignedDataMutation>,
556    digest: ElementDigest,
557    actor: Did,
558    dot: EntryDot,
559) -> bool {
560    !actor.is_default()
561        && proofs
562            .get(&super::provenance::DataProofKey::Remove(digest, actor))
563            .is_some_and(|p| p.matches_remove(digest, dot))
564}
565
566impl DataTopicBuffer {
567    /// Record `version` as a reset floor, preferring signed floors over unsigned floors for the
568    /// same attributed actor.
569    pub(super) fn insert_register_with_proofs(
570        register: &mut Option<EntryVersion>,
571        co_registers: &mut BTreeMap<Did, EntryVersion>,
572        proofs: &BTreeMap<super::provenance::DataProofKey, super::provenance::SignedDataMutation>,
573        version: EntryVersion,
574    ) {
575        if !version.actor.is_default() {
576            let cand_signed = has_register_proof(proofs, version.actor, version);
577            let replace = co_registers.get(&version.actor).is_none_or(|&curr| {
578                let curr_signed = has_register_proof(proofs, version.actor, curr);
579                (cand_signed, version) > (curr_signed, curr)
580            });
581            if replace {
582                co_registers.insert(version.actor, version);
583            }
584        }
585        *register = (*register).max(Some(version));
586    }
587
588    /// Record `(element, dot)` into `removes` and `co_removes`.
589    pub(super) fn insert_remove(
590        removes: &mut BTreeMap<ElementDigest, EntryDot>,
591        co_removes: &mut BTreeMap<ElementDigest, BTreeMap<Did, EntryDot>>,
592        element: ElementDigest,
593        dot: EntryDot,
594    ) {
595        insert_max(
596            co_removes.entry(element).or_default(),
597            dot.version.actor,
598            dot,
599        );
600        insert_max(removes, element, dot);
601    }
602
603    /// Record `(element, dot)` into `removes` and `co_removes`, preferring signed removes over
604    /// unsigned removes for the same `(element, actor)`.
605    pub(super) fn insert_remove_with_proofs(
606        removes: &mut BTreeMap<ElementDigest, EntryDot>,
607        co_removes: &mut BTreeMap<ElementDigest, BTreeMap<Did, EntryDot>>,
608        proofs: &BTreeMap<super::provenance::DataProofKey, super::provenance::SignedDataMutation>,
609        element: ElementDigest,
610        dot: EntryDot,
611    ) {
612        let actor = dot.version.actor;
613        let cand_signed = has_remove_proof(proofs, element, actor, dot);
614        let actors = co_removes.entry(element).or_default();
615        let replace = actors.get(&actor).is_none_or(|&curr| {
616            let curr_signed = has_remove_proof(proofs, element, actor, curr);
617            (cand_signed, dot) > (curr_signed, curr)
618        });
619        if replace {
620            actors.insert(actor, dot);
621        }
622        insert_max(removes, element, dot);
623    }
624
625    /// Record `(value, dot)` into `values` and `co_values`, preferring signed adds over unsigned
626    /// adds for the same `(value, actor)` when `proofs` is non-empty.
627    pub(super) fn insert_value_with_proofs(
628        values: &mut BTreeMap<Bytes, EntryDot>,
629        co_values: &mut BTreeMap<Bytes, BTreeMap<Did, EntryDot>>,
630        proofs: &BTreeMap<super::provenance::DataProofKey, super::provenance::SignedDataMutation>,
631        value: Bytes,
632        dot: EntryDot,
633    ) {
634        let actor = dot.version.actor;
635        if !actor.is_default() {
636            let actors = co_values.entry(value.clone()).or_default();
637            let replace = if proofs.is_empty() {
638                actors.get(&actor).is_none_or(|&curr| dot > curr)
639            } else {
640                let digest = ElementDigest(keccak256(value.as_ref()));
641                let cand_signed = has_add_proof(proofs, digest, actor, dot);
642                actors.get(&actor).is_none_or(|&curr| {
643                    let curr_signed = has_add_proof(proofs, digest, actor, curr);
644                    (cand_signed, dot) > (curr_signed, curr)
645                })
646            };
647            if replace {
648                actors.insert(actor, dot);
649            }
650        }
651        insert_max(values, value, dot);
652    }
653
654    /// Normalize a carrier: drop what the reset floor or a covering remove shadows.
655    #[allow(dead_code)]
656    pub(super) fn new(
657        register: Option<EntryVersion>,
658        values: BTreeMap<Bytes, EntryDot>,
659        removes: BTreeMap<ElementDigest, EntryDot>,
660    ) -> Self {
661        let mut co_values = BTreeMap::<Bytes, BTreeMap<Did, EntryDot>>::new();
662        for (value, dot) in &values {
663            if !dot.version.actor.is_default() {
664                insert_max(
665                    co_values.entry(value.clone()).or_default(),
666                    dot.version.actor,
667                    *dot,
668                );
669            }
670        }
671        Self::with_co_values(register, values, co_values, removes)
672    }
673
674    /// Normalize a carrier with explicit per-actor add dots `co_values`.
675    pub(super) fn with_co_values(
676        register: Option<EntryVersion>,
677        values: BTreeMap<Bytes, EntryDot>,
678        co_values: BTreeMap<Bytes, BTreeMap<Did, EntryDot>>,
679        removes: BTreeMap<ElementDigest, EntryDot>,
680    ) -> Self {
681        let mut co_registers = BTreeMap::new();
682        if let Some(floor) = register {
683            if !floor.actor.is_default() {
684                co_registers.insert(floor.actor, floor);
685            }
686        }
687        let mut co_removes = BTreeMap::<ElementDigest, BTreeMap<Did, EntryDot>>::new();
688        for (&element, &dot) in &removes {
689            insert_max(
690                co_removes.entry(element).or_default(),
691                dot.version.actor,
692                dot,
693            );
694        }
695        Self::normalize(
696            register,
697            co_registers,
698            values,
699            co_values,
700            removes,
701            co_removes,
702            BTreeMap::new(),
703        )
704    }
705
706    /// Normalize full per-actor state:
707    /// - An attributed floor `co_registers[actor]` drops versions of that same `actor` below it
708    ///   (and unattributed versions below it); an unattributed floor drops all versions below it.
709    /// - An attributed remove `co_removes[digest][actor]` covers dots of that same `actor` at or
710    ///   below it (and unattributed dots at or below it); an unattributed remove covers all dots
711    ///   at or below it.
712    pub(super) fn normalize(
713        register: Option<EntryVersion>,
714        mut co_registers: BTreeMap<Did, EntryVersion>,
715        mut values: BTreeMap<Bytes, EntryDot>,
716        mut co_values: BTreeMap<Bytes, BTreeMap<Did, EntryDot>>,
717        mut removes: BTreeMap<ElementDigest, EntryDot>,
718        mut co_removes: BTreeMap<ElementDigest, BTreeMap<Did, EntryDot>>,
719        mut proofs: BTreeMap<
720            super::provenance::DataProofKey,
721            super::provenance::SignedDataMutation,
722        >,
723    ) -> Self {
724        let mut scratch_register = register;
725        if let Some(floor) = register {
726            if !floor.actor.is_default() {
727                Self::insert_register_with_proofs(
728                    &mut scratch_register,
729                    &mut co_registers,
730                    &proofs,
731                    floor,
732                );
733            }
734        }
735        let unattributed_floor = register.filter(|floor| floor.actor.is_default());
736
737        for (value, dot) in &values {
738            if !dot.version.actor.is_default() {
739                let actor = dot.version.actor;
740                let actors = co_values.entry(value.clone()).or_default();
741                let replace = if proofs.is_empty() {
742                    actors.get(&actor).is_none_or(|&curr| *dot > curr)
743                } else {
744                    let digest = ElementDigest(keccak256(value.as_ref()));
745                    let cand_signed = has_add_proof(&proofs, digest, actor, *dot);
746                    actors.get(&actor).is_none_or(|&curr| {
747                        let curr_signed = has_add_proof(&proofs, digest, actor, curr);
748                        (cand_signed, *dot) > (curr_signed, curr)
749                    })
750                };
751                if replace {
752                    actors.insert(actor, *dot);
753                }
754            }
755        }
756        for (&element, &dot) in &removes {
757            Self::insert_remove_with_proofs(
758                &mut BTreeMap::new(),
759                &mut co_removes,
760                &proofs,
761                element,
762                dot,
763            );
764        }
765
766        if !proofs.is_empty() {
767            let mut signed_actors = std::collections::BTreeSet::new();
768            for (&actor, &floor) in &co_registers {
769                if has_register_proof(&proofs, actor, floor) {
770                    signed_actors.insert(actor);
771                }
772            }
773            for (value, actors) in &co_values {
774                let digest = ElementDigest(keccak256(value.as_ref()));
775                for (&actor, &dot) in actors {
776                    if has_add_proof(&proofs, digest, actor, dot) {
777                        signed_actors.insert(actor);
778                    }
779                }
780            }
781            for (&digest, actors) in &co_removes {
782                for (&actor, &dot) in actors {
783                    if has_remove_proof(&proofs, digest, actor, dot) {
784                        signed_actors.insert(actor);
785                    }
786                }
787            }
788            if !signed_actors.is_empty() {
789                co_registers.retain(|&actor, &mut floor| {
790                    !signed_actors.contains(&actor) || has_register_proof(&proofs, actor, floor)
791                });
792                for (value, actors) in &mut co_values {
793                    let digest = ElementDigest(keccak256(value.as_ref()));
794                    actors.retain(|&actor, &mut dot| {
795                        !signed_actors.contains(&actor)
796                            || has_add_proof(&proofs, digest, actor, dot)
797                    });
798                }
799                for (&digest, actors) in &mut co_removes {
800                    actors.retain(|&actor, &mut dot| {
801                        !signed_actors.contains(&actor)
802                            || has_remove_proof(&proofs, digest, actor, dot)
803                    });
804                }
805            }
806        }
807
808        if let Some(u_floor) = unattributed_floor {
809            co_registers.retain(|_, floor| *floor >= u_floor);
810        }
811        let max_floor = unattributed_floor
812            .into_iter()
813            .chain(co_registers.values().copied())
814            .max();
815
816        let kept_by_floors = |version: EntryVersion| -> bool {
817            if unattributed_floor.is_some_and(|floor| version < floor) {
818                return false;
819            }
820            if version.actor.is_default() {
821                max_floor.is_none_or(|floor| version >= floor)
822            } else {
823                co_registers
824                    .get(&version.actor)
825                    .is_none_or(|floor| version >= *floor)
826            }
827        };
828
829        if max_floor.is_some() {
830            co_values.values_mut().for_each(|actors| {
831                actors.retain(|_, dot| kept_by_floors(dot.version));
832            });
833            co_removes.values_mut().for_each(|actors| {
834                actors.retain(|_, dot| kept_by_floors(dot.version));
835            });
836        }
837        co_removes.retain(|_, actors| !actors.is_empty());
838        removes.clear();
839        for (&element, actors) in &co_removes {
840            if let Some(max_dot) = actors.values().copied().max() {
841                removes.insert(element, max_dot);
842            }
843        }
844
845        values.retain(|value, primary_dot| {
846            let actor_removes = (!co_removes.is_empty())
847                .then(|| co_removes.get(&ElementDigest::of(value)))
848                .flatten();
849            let unattributed_remove =
850                actor_removes.and_then(|map| map.get(&Did::default()).copied());
851            let max_any_remove = actor_removes.and_then(|map| map.values().copied().max());
852
853            if let Some(actors) = co_values.get_mut(value) {
854                actors.retain(|actor, actor_dot| {
855                    unattributed_remove.is_none_or(|rem| *actor_dot > rem)
856                        && actor_removes
857                            .and_then(|map| map.get(actor))
858                            .is_none_or(|rem| *actor_dot > *rem)
859                });
860            }
861
862            let unattributed_survives = primary_dot.version.actor.is_default()
863                && kept_by_floors(primary_dot.version)
864                && max_any_remove.is_none_or(|rem| *primary_dot > rem);
865
866            let best_attributed = co_values
867                .get(value)
868                .and_then(|actors| actors.values().copied().max());
869            let surviving = match (unattributed_survives, best_attributed) {
870                (true, Some(attr)) => Some((*primary_dot).max(attr)),
871                (true, None) => Some(*primary_dot),
872                (false, attr) => attr,
873            };
874            match surviving {
875                Some(best) => {
876                    *primary_dot = best;
877                    true
878                }
879                None => false,
880            }
881        });
882        co_values.retain(|value, actors| values.contains_key(value) && !actors.is_empty());
883
884        if !proofs.is_empty() {
885            let live_adds = co_values
886                .iter()
887                .flat_map(|(value, actors)| {
888                    let digest = ElementDigest(keccak256(value.as_ref()));
889                    actors
890                        .iter()
891                        .map(move |(&actor, &dot)| ((digest, actor), dot))
892                })
893                .collect::<BTreeMap<_, _>>();
894            proofs.retain(|key, mutation| match *key {
895                super::provenance::DataProofKey::Register(actor) => co_registers
896                    .get(&actor)
897                    .is_some_and(|floor| mutation.matches_register(*floor)),
898                super::provenance::DataProofKey::Add(digest, actor) => live_adds
899                    .get(&(digest, actor))
900                    .is_some_and(|dot| mutation.matches_add(digest, *dot)),
901                super::provenance::DataProofKey::Remove(digest, actor) => co_removes
902                    .get(&digest)
903                    .and_then(|actors| actors.get(&actor))
904                    .is_some_and(|dot| mutation.matches_remove(digest, *dot)),
905            });
906        }
907
908        Self {
909            register: max_floor,
910            co_registers,
911            values,
912            co_values,
913            removes,
914            co_removes,
915            proofs,
916        }
917    }
918
919    /// Iterate over all surviving add dots held for `value` (`values` and `co_values`).
920    #[allow(dead_code)]
921    pub(super) fn dots_for<'a>(&'a self, value: &'a Bytes) -> impl Iterator<Item = EntryDot> + 'a {
922        self.values.get(value).copied().into_iter().chain(
923            self.co_values
924                .get(value)
925                .into_iter()
926                .flat_map(|actors| actors.values().copied()),
927        )
928    }
929
930    /// Record a covering remove for `value` across all held dots (used by relay inboxes and
931    /// unattributed carrier removal).
932    pub(super) fn remove(&mut self, value: &Bytes) {
933        let removed_actors = self.co_values.remove(value);
934        let primary = self.values.remove(value);
935        if removed_actors.is_some() || primary.is_some() {
936            let digest = ElementDigest::of(value);
937            if let Some(actors) = removed_actors {
938                for (_, dot) in actors {
939                    Self::insert_remove(&mut self.removes, &mut self.co_removes, digest, dot);
940                }
941            }
942            if let Some(dot) = primary {
943                if dot.version.actor.is_default() || !self.co_removes.contains_key(&digest) {
944                    Self::insert_remove(&mut self.removes, &mut self.co_removes, digest, dot);
945                }
946            }
947        }
948    }
949
950    /// Record an actor-scoped covering remove for `value` on behalf of `actor`, leaving other
951    /// co-authors' dots for `value` untouched (#1220).
952    pub(super) fn remove_by(&mut self, value: &Bytes, actor: Did) {
953        if actor.is_default() {
954            self.remove(value);
955            return;
956        }
957        let mut removed_dot = None;
958        if let Some(actors) = self.co_values.get_mut(value) {
959            removed_dot = actors.remove(&actor);
960            if actors.is_empty() {
961                self.co_values.remove(value);
962            }
963        }
964        if let Some(dot) = removed_dot {
965            let digest = ElementDigest::of(value);
966            Self::insert_remove(&mut self.removes, &mut self.co_removes, digest, dot);
967            self.proofs
968                .remove(&super::provenance::DataProofKey::Add(digest, actor));
969            match self
970                .co_values
971                .get(value)
972                .and_then(|actors| actors.values().copied().max())
973            {
974                Some(remaining_max) => {
975                    self.values.insert(value.clone(), remaining_max);
976                }
977                None => {
978                    self.values.remove(value);
979                }
980            }
981        } else if self
982            .values
983            .get(value)
984            .is_some_and(|dot| dot.version.actor.is_default())
985        {
986            self.remove(value);
987        }
988    }
989}
990
991impl JoinSemilattice for DataTopicBuffer {
992    fn join(mut self, other: Self) -> Self {
993        for (key, proof) in other.proofs {
994            insert_max(&mut self.proofs, key, proof);
995        }
996        let unattributed_register = self
997            .register
998            .filter(|floor| floor.actor.is_default())
999            .max(other.register.filter(|floor| floor.actor.is_default()));
1000        if let Some(floor) = self.register.filter(|floor| !floor.actor.is_default()) {
1001            Self::insert_register_with_proofs(
1002                &mut self.register,
1003                &mut self.co_registers,
1004                &self.proofs,
1005                floor,
1006            );
1007        }
1008        if let Some(floor) = other.register.filter(|floor| !floor.actor.is_default()) {
1009            Self::insert_register_with_proofs(
1010                &mut self.register,
1011                &mut self.co_registers,
1012                &self.proofs,
1013                floor,
1014            );
1015        }
1016        for (_, floor) in other.co_registers {
1017            Self::insert_register_with_proofs(
1018                &mut self.register,
1019                &mut self.co_registers,
1020                &self.proofs,
1021                floor,
1022            );
1023        }
1024        for (element, dot) in other.removes {
1025            Self::insert_remove_with_proofs(
1026                &mut self.removes,
1027                &mut self.co_removes,
1028                &self.proofs,
1029                element,
1030                dot,
1031            );
1032        }
1033        for (element, actors) in other.co_removes {
1034            for (_, dot) in actors {
1035                Self::insert_remove_with_proofs(
1036                    &mut self.removes,
1037                    &mut self.co_removes,
1038                    &self.proofs,
1039                    element,
1040                    dot,
1041                );
1042            }
1043        }
1044        for (value, dot) in other.values {
1045            Self::insert_value_with_proofs(
1046                &mut self.values,
1047                &mut self.co_values,
1048                &self.proofs,
1049                value,
1050                dot,
1051            );
1052        }
1053        for (value, actors) in other.co_values {
1054            for (_, dot) in actors {
1055                Self::insert_value_with_proofs(
1056                    &mut self.values,
1057                    &mut self.co_values,
1058                    &self.proofs,
1059                    value.clone(),
1060                    dot,
1061                );
1062            }
1063        }
1064        Self::normalize(
1065            unattributed_register.or(self.register),
1066            self.co_registers,
1067            self.values,
1068            self.co_values,
1069            self.removes,
1070            self.co_removes,
1071            self.proofs,
1072        )
1073    }
1074}