Skip to main content

rings_core/dht/entry/
provenance.rs

1//! Data-topic write provenance and fair per-writer element retention (#1179, #1220).
2//!
3//! Write operations and replicated sync states on [`EntryKind::Data`](super::EntryKind::Data)
4//! carriers are classified through algebraic sum types ([`DataProvenance`], [`RetractionWitness`],
5//! [`SignedDataMutation`]) and higher-order continuation combinators (`with_live_and_then`,
6//! `and_then`, `then_some`), isolating per-actor provenance proofs from storage transitions.
7
8use std::borrow::Borrow;
9use std::cmp::Ordering;
10use std::cmp::Reverse;
11use std::collections::BTreeMap;
12use std::collections::BTreeSet;
13
14use bytes::Bytes;
15use serde::Deserialize;
16use serde::Serialize;
17
18use super::ElementDigest;
19use super::Entry;
20use super::EntryDot;
21use super::EntryKind;
22use super::EntryOperation;
23use super::EntryVersion;
24use crate::consts::TS_OFFSET_TOLERANCE_MS;
25use crate::delegation::DelegateeKey;
26use crate::dht::Did;
27use crate::ecc::keccak256;
28use crate::error::Error;
29use crate::error::Result;
30use crate::message::DomainTag;
31use crate::message::MessageSigner;
32use crate::message::MessageVerification;
33use crate::message::Principal;
34use crate::message::SigningDomain;
35
36/// Domain separation tag for per-author Swarm data mutation signatures (#1220).
37pub(crate) const DATA_MUTATION_DOMAIN_TAG: DomainTag =
38    crate::domain_tag!("rings-core:data-entry:mutation");
39
40/// Key identifying which per-actor CRDT slot a [`SignedDataMutation`] attests.
41#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
42pub(crate) enum DataProofKey {
43    /// Attests the reset floor `co_registers[actor]`.
44    Register(Did),
45    /// Attests the element add `co_values[value][actor]` where `digest = keccak256(value)`.
46    Add(ElementDigest, Did),
47    /// Attests the element removal `co_removes[digest][actor]`.
48    Remove(ElementDigest, Did),
49}
50
51impl DataProofKey {
52    pub(crate) const fn actor(self) -> Did {
53        match self {
54            Self::Register(actor) | Self::Add(_, actor) | Self::Remove(_, actor) => actor,
55        }
56    }
57
58    pub(crate) const fn is_element_add(self) -> bool {
59        matches!(self, Self::Add(_, _))
60    }
61}
62
63/// Operation kind attested by a [`DataMutationClaim`].
64#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
65pub(crate) enum DataMutationOpKind {
66    Reset,
67    Append,
68    Retract,
69}
70
71/// Fixed-size Merkle batch claim signed inside a [`SignedDataMutation`] (#1220).
72#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
73pub(crate) struct DataMutationClaim {
74    pub(crate) did: Did,
75    pub(crate) kind: DataMutationOpKind,
76    pub(crate) version: EntryVersion,
77    pub(crate) leaf_count: u32,
78    pub(crate) merkle_root: [u8; 32],
79}
80
81fn merkle_leaf_element(digest: [u8; 32]) -> [u8; 32] {
82    let mut buf = [0u8; 33];
83    buf[0] = 0x01;
84    buf[1..33].copy_from_slice(&digest);
85    keccak256(&buf)
86}
87
88fn merkle_leaf_dot(dot: EntryDot) -> [u8; 32] {
89    let mut buf = [0u8; 65];
90    buf[0] = 0x02;
91    buf[1..17].copy_from_slice(&dot.version.logical_time_ms.to_be_bytes());
92    buf[17..21].copy_from_slice(&dot.version.counter.to_be_bytes());
93    buf[21..41].copy_from_slice(dot.version.actor.as_bytes());
94    buf[41..61].copy_from_slice(dot.version.operation.as_bytes());
95    buf[61..65].copy_from_slice(&dot.index.to_be_bytes());
96    keccak256(&buf)
97}
98
99fn merkle_parent_hash(left: [u8; 32], right: [u8; 32]) -> [u8; 32] {
100    let mut buf = [0u8; 65];
101    buf[0] = 0x03;
102    buf[1..33].copy_from_slice(&left);
103    buf[33..65].copy_from_slice(&right);
104    keccak256(&buf)
105}
106
107fn compute_merkle_tree(leaves: &[[u8; 32]]) -> ([u8; 32], Vec<Vec<[u8; 32]>>) {
108    if leaves.is_empty() {
109        return ([0u8; 32], Vec::new());
110    }
111    let mut layers = vec![leaves.to_vec()];
112    while let Some(curr) = layers.last() {
113        if curr.len() <= 1 {
114            break;
115        }
116        let next = curr
117            .chunks(2)
118            .filter_map(|pair| match pair {
119                [left, right] => Some(merkle_parent_hash(*left, *right)),
120                [only] => Some(*only),
121                _ => None,
122            })
123            .collect::<Vec<_>>();
124        layers.push(next);
125    }
126    let root = layers
127        .last()
128        .and_then(|top| top.first().copied())
129        .unwrap_or([0u8; 32]);
130    let non_root_layers = layers.len().saturating_sub(1);
131    let mut branches = Vec::with_capacity(leaves.len());
132    for leaf_idx in 0..leaves.len() {
133        let mut idx = leaf_idx;
134        let mut siblings = Vec::with_capacity(non_root_layers);
135        for layer in layers.iter().take(non_root_layers) {
136            if let Some(&sibling) = layer.get(idx ^ 1) {
137                siblings.push(sibling);
138            }
139            idx /= 2;
140        }
141        branches.push(siblings);
142    }
143    (root, branches)
144}
145
146fn verify_merkle_inclusion(
147    leaf_hash: [u8; 32],
148    leaf_index: u32,
149    leaf_count: u32,
150    siblings: &[[u8; 32]],
151    expected_root: [u8; 32],
152) -> bool {
153    if leaf_count == 0 || leaf_index >= leaf_count {
154        return false;
155    }
156    let mut idx = leaf_index as usize;
157    let mut len = leaf_count as usize;
158    let mut current = leaf_hash;
159    let mut sib_iter = siblings.iter().copied();
160    while len > 1 {
161        let sibling_idx = idx ^ 1;
162        if sibling_idx < len {
163            let Some(sibling) = sib_iter.next() else {
164                return false;
165            };
166            current = if idx & 1 == 0 {
167                merkle_parent_hash(current, sibling)
168            } else {
169                merkle_parent_hash(sibling, current)
170            };
171        }
172        idx /= 2;
173        len = len.div_ceil(2);
174    }
175    sib_iter.next().is_none() && current == expected_root
176}
177
178/// Cryptographic author attestation over a Swarm-originated [`EntryKind::Data`] mutation (#1220).
179#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
180pub struct SignedDataMutation {
181    pub(crate) key: DataProofKey,
182    pub(crate) claim: DataMutationClaim,
183    pub(crate) leaf_index: u32,
184    pub(crate) witness_dot: Option<EntryDot>,
185    pub(crate) merkle_siblings: Vec<[u8; 32]>,
186    pub(crate) proof: Option<MessageVerification>,
187}
188
189#[derive(Serialize, Deserialize)]
190struct WireProofBundle {
191    batches: Vec<(DataMutationClaim, Option<MessageVerification>)>,
192    items: Vec<WireProofItem>,
193}
194
195#[derive(Serialize, Deserialize)]
196struct WireProofItem {
197    key: DataProofKey,
198    batch_index: u32,
199    leaf_index: u32,
200    witness_dot: Option<EntryDot>,
201    merkle_siblings: Vec<[u8; 32]>,
202}
203
204pub(super) fn encode_proof_bundle(proofs: &[SignedDataMutation]) -> Result<Vec<u8>> {
205    let mut batches: Vec<(DataMutationClaim, Option<MessageVerification>)> = Vec::new();
206    let mut items = Vec::with_capacity(proofs.len());
207    for mutation in proofs {
208        let batch_pos = batches
209            .iter()
210            .position(|(c, p)| *c == mutation.claim && *p == mutation.proof)
211            .unwrap_or_else(|| {
212                let idx = batches.len();
213                batches.push((mutation.claim, mutation.proof.clone()));
214                idx
215            });
216        let batch_index = u32::try_from(batch_pos).unwrap_or(u32::MAX);
217        items.push(WireProofItem {
218            key: mutation.key,
219            batch_index,
220            leaf_index: mutation.leaf_index,
221            witness_dot: mutation.witness_dot,
222            merkle_siblings: mutation.merkle_siblings.clone(),
223        });
224    }
225    rings_codec::serialize(&WireProofBundle { batches, items }).map_err(Error::CodecSerialize)
226}
227
228pub(super) fn decode_proof_bundle(raw: &[u8]) -> Result<Vec<SignedDataMutation>> {
229    let bundle =
230        rings_codec::deserialize::<WireProofBundle>(raw).map_err(Error::CodecDeserialize)?;
231    if bundle.batches.is_empty() || bundle.items.is_empty() {
232        return Err(Error::DataEntryWriteUnauthorized);
233    }
234    let mut out = Vec::with_capacity(bundle.items.len());
235    for item in bundle.items {
236        let Some((claim, proof)) = bundle.batches.get(item.batch_index as usize) else {
237            return Err(Error::DataEntryWriteUnauthorized);
238        };
239        if proof.is_none() {
240            return Err(Error::DataEntryWriteUnauthorized);
241        }
242        out.push(SignedDataMutation {
243            key: item.key,
244            claim: *claim,
245            leaf_index: item.leaf_index,
246            witness_dot: item.witness_dot,
247            merkle_siblings: item.merkle_siblings,
248            proof: proof.clone(),
249        });
250    }
251    Ok(out)
252}
253
254impl PartialOrd for SignedDataMutation {
255    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
256        Some(self.cmp(other))
257    }
258}
259
260impl Ord for SignedDataMutation {
261    fn cmp(&self, other: &Self) -> Ordering {
262        if self == other {
263            return Ordering::Equal;
264        }
265        self.key
266            .cmp(&other.key)
267            .then_with(|| self.proof.is_some().cmp(&other.proof.is_some()))
268            .then_with(|| self.effective_version().cmp(&other.effective_version()))
269            .then_with(|| self.witness_dot.cmp(&other.witness_dot))
270            .then_with(|| self.claim.cmp(&other.claim))
271            .then_with(|| {
272                self.proof
273                    .as_ref()
274                    .map(|p| p.ts_ms)
275                    .cmp(&other.proof.as_ref().map(|p| p.ts_ms))
276            })
277            .then_with(|| self.leaf_index.cmp(&other.leaf_index))
278            .then_with(|| self.merkle_siblings.cmp(&other.merkle_siblings))
279    }
280}
281
282impl SignedDataMutation {
283    fn effective_version(&self) -> EntryVersion {
284        self.witness_dot.map_or(self.claim.version, |d| d.version)
285    }
286
287    pub(crate) fn is_corrupted(&self) -> bool {
288        self.proof.is_none()
289    }
290
291    pub(crate) fn matches_register(&self, floor: EntryVersion) -> bool {
292        self.proof.is_some()
293            && self.key == DataProofKey::Register(floor.actor)
294            && self.claim.kind == DataMutationOpKind::Reset
295            && self.claim.version == floor
296    }
297
298    pub(crate) fn matches_add(&self, digest: ElementDigest, dot: EntryDot) -> bool {
299        self.proof.is_some()
300            && self.key == DataProofKey::Add(digest, dot.version.actor)
301            && matches!(
302                self.claim.kind,
303                DataMutationOpKind::Reset | DataMutationOpKind::Append
304            )
305            && self.witness_dot.is_none()
306            && self.claim.version == dot.version
307            && verify_merkle_inclusion(
308                merkle_leaf_element(digest.0),
309                self.leaf_index,
310                self.claim.leaf_count,
311                &self.merkle_siblings,
312                self.claim.merkle_root,
313            )
314    }
315
316    pub(crate) fn matches_remove(&self, digest: ElementDigest, remove_dot: EntryDot) -> bool {
317        let actor = remove_dot.version.actor;
318        if self.proof.is_none()
319            || self.key != DataProofKey::Remove(digest, actor)
320            || self.claim.kind != DataMutationOpKind::Retract
321        {
322            return false;
323        }
324        match self.witness_dot {
325            Some(dot) => {
326                dot == remove_dot
327                    && verify_merkle_inclusion(
328                        merkle_leaf_dot(dot),
329                        self.leaf_index,
330                        self.claim.leaf_count,
331                        &self.merkle_siblings,
332                        self.claim.merkle_root,
333                    )
334            }
335            None => {
336                !self.claim.version.actor.is_default()
337                    && remove_dot.version.actor == self.claim.version.actor
338                    && (remove_dot.version.logical_time_ms < self.claim.version.logical_time_ms
339                        || (remove_dot.version.logical_time_ms
340                            == self.claim.version.logical_time_ms
341                            && remove_dot.version.counter
342                                <= self.claim.version.counter.saturating_add(64)))
343                    && verify_merkle_inclusion(
344                        merkle_leaf_element(digest.0),
345                        self.leaf_index,
346                        self.claim.leaf_count,
347                        &self.merkle_siblings,
348                        self.claim.merkle_root,
349                    )
350            }
351        }
352    }
353
354    fn verify_claim_structure(&self, carrier: &Entry) -> Result<()> {
355        if self.claim.did != carrier.did {
356            return Err(Error::DataEntryWriteUnauthorized);
357        }
358        let actor = self.key.actor();
359        if actor.is_default() {
360            return Err(Error::DataEntryWriteUnauthorized);
361        }
362        let claim_matches = match (&self.key, self.claim.kind) {
363            (DataProofKey::Register(key_actor), DataMutationOpKind::Reset) => {
364                *key_actor == self.claim.version.actor
365                    && self.witness_dot.is_none()
366                    && self.merkle_siblings.is_empty()
367                    && (self.claim.leaf_count > 0 || self.claim.merkle_root == [0u8; 32])
368                    && carrier.register_floors().any(|f| f == self.claim.version)
369            }
370            (
371                DataProofKey::Add(digest, key_actor),
372                DataMutationOpKind::Reset | DataMutationOpKind::Append,
373            ) => {
374                *key_actor == self.claim.version.actor
375                    && self.witness_dot.is_none()
376                    && verify_merkle_inclusion(
377                        merkle_leaf_element(digest.0),
378                        self.leaf_index,
379                        self.claim.leaf_count,
380                        &self.merkle_siblings,
381                        self.claim.merkle_root,
382                    )
383                    && carrier.attributed_elements().any(|(value, dot)| {
384                        dot.version == self.claim.version && keccak256(value.as_ref()) == digest.0
385                    })
386            }
387            (DataProofKey::Remove(digest, key_actor), DataMutationOpKind::Retract) => {
388                *key_actor == actor
389                    && match self.witness_dot {
390                        Some(dot) => {
391                            dot.version.actor == actor
392                                && verify_merkle_inclusion(
393                                    merkle_leaf_dot(dot),
394                                    self.leaf_index,
395                                    self.claim.leaf_count,
396                                    &self.merkle_siblings,
397                                    self.claim.merkle_root,
398                                )
399                                && (carrier
400                                    .crdt
401                                    .tombstones
402                                    .iter()
403                                    .any(|t| t.element == *digest && t.dot == dot)
404                                    || (carrier.crdt.tombstones.is_empty()
405                                        && *digest == ElementDigest([0u8; 32])
406                                        && carrier.crdt.dots.contains(&dot)))
407                        }
408                        None => {
409                            !self.claim.version.actor.is_default()
410                                && self.claim.version.actor == actor
411                                && verify_merkle_inclusion(
412                                    merkle_leaf_element(digest.0),
413                                    self.leaf_index,
414                                    self.claim.leaf_count,
415                                    &self.merkle_siblings,
416                                    self.claim.merkle_root,
417                                )
418                                && (carrier.crdt.tombstones.iter().any(|t| {
419                                    t.element == *digest && self.matches_remove(t.element, t.dot)
420                                }) || (carrier.crdt.tombstones.is_empty()
421                                    && carrier.crdt.dots.is_empty()
422                                    && carrier
423                                        .data
424                                        .iter()
425                                        .any(|v| keccak256(v.as_ref()) == digest.0)))
426                        }
427                    }
428            }
429            _ => false,
430        };
431        claim_matches
432            .then_some(())
433            .ok_or(Error::DataEntryWriteUnauthorized)
434    }
435}
436
437/// The selector by which a [`EntryOperation::Tombstone`] names the elements to retract from a
438/// carrier: either explicit CRDT add dots (`Dots`) when a write witness is present, or raw payload
439/// values (`Values`) otherwise.
440pub(super) enum RetractionWitness<'a> {
441    /// Retract only elements held at one of the specified add dots.
442    Dots(BTreeSet<EntryDot>),
443    /// Retract elements whose payload bytes match one of the specified values.
444    Values(BTreeSet<&'a Bytes>),
445}
446
447impl<'a> RetractionWitness<'a> {
448    /// Construct the retraction witness carried by `entry`.
449    pub(super) fn of(entry: &'a Entry) -> Self {
450        entry
451            .crdt
452            .has_write_witness()
453            .then(|| {
454                (!entry.crdt.dots.is_empty())
455                    .then(|| Self::Dots(entry.crdt.dots.iter().copied().collect()))
456            })
457            .flatten()
458            .unwrap_or_else(|| Self::Values(entry.data.iter().collect()))
459    }
460
461    /// Whether the held element `(value, dot)` is selected by this witness.
462    pub(super) fn matches(&self, value: &Bytes, dot: &EntryDot) -> bool {
463        match self {
464            Self::Dots(dots) => dots.contains(dot),
465            Self::Values(values) => values.contains(value),
466        }
467    }
468}
469
470/// Algebraic classification of a verified data-topic write claim issued by `writer`.
471enum DataProvenance<'a> {
472    /// Full-carrier reset (`Overwrite`) authored by `writer`.
473    Reset { entry: &'a Entry, writer: Did },
474    /// Element-set append (`Extend`) authored by `writer`.
475    Append { entry: &'a Entry, writer: Did },
476    /// Element retraction (`Tombstone`) authored by `writer` under `witness`.
477    Retract {
478        witness: RetractionWitness<'a>,
479        writer: Did,
480    },
481}
482
483impl<'a> DataProvenance<'a> {
484    /// Construct a provenance proof for `(op, writer, introducer)`, or reject with
485    /// [`Error::DataEntryWriteUnauthorized`].
486    fn try_new(op: &'a EntryOperation, writer: Did, introducer: Principal) -> Result<Self> {
487        (!writer.is_default()
488            && op.entry().is_exclusively_authored_by(writer)
489            && op.entry().crdt.co_dots.is_empty()
490            && op.entry().crdt.co_registers.is_empty())
491        .then_some(())
492        .ok_or(Error::DataEntryWriteUnauthorized)
493        .and_then(|()| match op {
494            EntryOperation::Overwrite(entry) => (entry.crdt.register.is_some()
495                && entry.crdt.dots.len() == entry.data.len()
496                && entry.permits_reset_envelope_from(introducer))
497            .then_some(Self::Reset { entry, writer })
498            .ok_or(Error::DataEntryWriteUnauthorized),
499            EntryOperation::Extend(entry) => (entry.crdt.dots.len() == entry.data.len()
500                && entry.has_delta_envelope())
501            .then_some(Self::Append { entry, writer })
502            .ok_or(Error::DataEntryWriteUnauthorized),
503            EntryOperation::Tombstone(entry) => entry
504                .has_delta_envelope()
505                .then(|| Self::Retract {
506                    witness: RetractionWitness::of(entry),
507                    writer,
508                })
509                .ok_or(Error::DataEntryWriteUnauthorized),
510        })
511    }
512
513    /// Construct a provenance claim for validating `op` against a live local carrier.
514    fn for_local(op: &'a EntryOperation, writer: Did) -> Self {
515        match op {
516            EntryOperation::Overwrite(entry) => Self::Reset { entry, writer },
517            EntryOperation::Extend(entry) => Self::Append { entry, writer },
518            EntryOperation::Tombstone(entry) => Self::Retract {
519                witness: RetractionWitness::of(entry),
520                writer,
521            },
522        }
523    }
524
525    /// Verify that this write claim may be applied to `live`.
526    fn verify_on_live(&self, live: &Entry) -> Result<()> {
527        match self {
528            Self::Reset { entry, writer } => live.permits_reset_by(entry, *writer),
529            Self::Append { entry, writer } => live.permits_append_by(entry, *writer),
530            Self::Retract { witness, writer } => live.permits_retraction_by(witness, *writer),
531        }
532    }
533}
534
535impl EntryVersion {
536    /// Whether this version is explicitly attributed to `writer` (`!actor.is_default() && actor == writer`).
537    pub(super) fn is_authored_by(self, writer: Did) -> bool {
538        !self.actor.is_default() && self.actor == writer
539    }
540}
541
542impl EntryDot {
543    /// Whether this dot carries a non-default author identity (`!version.actor.is_default()`).
544    pub(super) fn is_attributed(self) -> bool {
545        !self.version.actor.is_default()
546    }
547
548    /// Return the attributed author of this dot, or `None` when unattributed.
549    fn attributed_actor(self) -> Option<Did> {
550        self.is_attributed().then_some(self.version.actor)
551    }
552}
553
554impl EntryOperation {
555    /// Attach cryptographic author proofs signed by `signer` (`actor`) to a stamped `Data`
556    /// operation before it is sent or applied by `Swarm` (#1220).
557    pub(crate) fn with_author_proofs(
558        self,
559        actor: Did,
560        signer: MessageSigner<impl Borrow<DelegateeKey>>,
561        now_ms: u128,
562    ) -> Result<Self> {
563        if self.kind() != EntryKind::Data || actor.is_default() {
564            return Ok(self);
565        }
566        match self {
567            EntryOperation::Overwrite(mut entry) => {
568                if let Some(version) = entry.crdt.register {
569                    let elements = entry
570                        .data
571                        .iter()
572                        .map(|value| keccak256(value.as_ref()))
573                        .collect::<Vec<_>>();
574                    let leaves = elements
575                        .iter()
576                        .map(|&elem| merkle_leaf_element(elem))
577                        .collect::<Vec<_>>();
578                    let (merkle_root, branches) = compute_merkle_tree(&leaves);
579                    let leaf_count = u32::try_from(elements.len()).map_err(|_| {
580                        Error::EntryDotIndexOutOfBounds {
581                            index: elements.len(),
582                        }
583                    })?;
584                    let claim = DataMutationClaim {
585                        did: entry.did,
586                        kind: DataMutationOpKind::Reset,
587                        version,
588                        leaf_count,
589                        merkle_root,
590                    };
591                    let bytes = rings_codec::serialize(&claim).map_err(Error::CodecSerialize)?;
592                    let sig = signer.sign_at(DATA_MUTATION_DOMAIN_TAG, &bytes, now_ms)?;
593                    let mut proofs = Vec::with_capacity(elements.len().saturating_add(1));
594                    proofs.push(SignedDataMutation {
595                        key: DataProofKey::Register(actor),
596                        claim,
597                        leaf_index: 0,
598                        witness_dot: None,
599                        merkle_siblings: Vec::new(),
600                        proof: Some(sig.clone()),
601                    });
602                    for (idx, (elem, merkle_siblings)) in
603                        elements.into_iter().zip(branches).enumerate()
604                    {
605                        proofs.push(SignedDataMutation {
606                            key: DataProofKey::Add(ElementDigest(elem), actor),
607                            claim,
608                            leaf_index: u32::try_from(idx).unwrap_or(u32::MAX),
609                            witness_dot: None,
610                            merkle_siblings,
611                            proof: Some(sig.clone()),
612                        });
613                    }
614                    entry.crdt.proofs = proofs;
615                }
616                Ok(EntryOperation::Overwrite(entry))
617            }
618            EntryOperation::Extend(mut entry) => {
619                if let Some(first_dot) = entry.crdt.dots.first().copied() {
620                    let elements = entry
621                        .data
622                        .iter()
623                        .map(|value| keccak256(value.as_ref()))
624                        .collect::<Vec<_>>();
625                    let leaves = elements
626                        .iter()
627                        .map(|&elem| merkle_leaf_element(elem))
628                        .collect::<Vec<_>>();
629                    let (merkle_root, branches) = compute_merkle_tree(&leaves);
630                    let leaf_count = u32::try_from(elements.len()).map_err(|_| {
631                        Error::EntryDotIndexOutOfBounds {
632                            index: elements.len(),
633                        }
634                    })?;
635                    let claim = DataMutationClaim {
636                        did: entry.did,
637                        kind: DataMutationOpKind::Append,
638                        version: first_dot.version,
639                        leaf_count,
640                        merkle_root,
641                    };
642                    let bytes = rings_codec::serialize(&claim).map_err(Error::CodecSerialize)?;
643                    let sig = signer.sign_at(DATA_MUTATION_DOMAIN_TAG, &bytes, now_ms)?;
644                    entry.crdt.proofs = elements
645                        .into_iter()
646                        .zip(branches)
647                        .enumerate()
648                        .map(|(idx, (elem, merkle_siblings))| SignedDataMutation {
649                            key: DataProofKey::Add(ElementDigest(elem), actor),
650                            claim,
651                            leaf_index: u32::try_from(idx).unwrap_or(u32::MAX),
652                            witness_dot: None,
653                            merkle_siblings,
654                            proof: Some(sig.clone()),
655                        })
656                        .collect();
657                }
658                Ok(EntryOperation::Extend(entry))
659            }
660            EntryOperation::Tombstone(mut entry) => {
661                if entry.data.is_empty() {
662                    let dots = entry.crdt.dots.clone();
663                    let leaves = dots
664                        .iter()
665                        .map(|&dot| merkle_leaf_dot(dot))
666                        .collect::<Vec<_>>();
667                    let (merkle_root, branches) = compute_merkle_tree(&leaves);
668                    let leaf_count = u32::try_from(dots.len())
669                        .map_err(|_| Error::EntryDotIndexOutOfBounds { index: dots.len() })?;
670                    let version = dots
671                        .iter()
672                        .map(|dot| dot.version)
673                        .max()
674                        .unwrap_or_else(|| EntryVersion::new(now_ms, actor, Did::default()));
675                    let claim = DataMutationClaim {
676                        did: entry.did,
677                        kind: DataMutationOpKind::Retract,
678                        version,
679                        leaf_count,
680                        merkle_root,
681                    };
682                    let bytes = rings_codec::serialize(&claim).map_err(Error::CodecSerialize)?;
683                    let sig = signer.sign_at(DATA_MUTATION_DOMAIN_TAG, &bytes, now_ms)?;
684                    entry.crdt.proofs = dots
685                        .into_iter()
686                        .zip(branches)
687                        .enumerate()
688                        .map(|(idx, (dot, merkle_siblings))| SignedDataMutation {
689                            key: DataProofKey::Remove(ElementDigest([0u8; 32]), actor),
690                            claim,
691                            leaf_index: u32::try_from(idx).unwrap_or(u32::MAX),
692                            witness_dot: Some(dot),
693                            merkle_siblings,
694                            proof: Some(sig.clone()),
695                        })
696                        .collect();
697                } else {
698                    let elements = entry
699                        .data
700                        .iter()
701                        .map(|value| keccak256(value.as_ref()))
702                        .collect::<Vec<_>>();
703                    let leaves = elements
704                        .iter()
705                        .map(|&elem| merkle_leaf_element(elem))
706                        .collect::<Vec<_>>();
707                    let (merkle_root, branches) = compute_merkle_tree(&leaves);
708                    let leaf_count = u32::try_from(elements.len()).map_err(|_| {
709                        Error::EntryDotIndexOutOfBounds {
710                            index: elements.len(),
711                        }
712                    })?;
713                    let op_digest = entry.operation_digest_for(actor, &entry.data)?;
714                    let version = EntryVersion::new(now_ms, actor, op_digest);
715                    let claim = DataMutationClaim {
716                        did: entry.did,
717                        kind: DataMutationOpKind::Retract,
718                        version,
719                        leaf_count,
720                        merkle_root,
721                    };
722                    let bytes = rings_codec::serialize(&claim).map_err(Error::CodecSerialize)?;
723                    let sig = signer.sign_at(DATA_MUTATION_DOMAIN_TAG, &bytes, now_ms)?;
724                    entry.crdt.proofs = elements
725                        .into_iter()
726                        .zip(branches)
727                        .enumerate()
728                        .map(|(idx, (elem, merkle_siblings))| SignedDataMutation {
729                            key: DataProofKey::Remove(ElementDigest(elem), actor),
730                            claim,
731                            leaf_index: u32::try_from(idx).unwrap_or(u32::MAX),
732                            witness_dot: None,
733                            merkle_siblings,
734                            proof: Some(sig.clone()),
735                        })
736                        .collect();
737                }
738                Ok(EntryOperation::Tombstone(entry))
739            }
740        }
741    }
742
743    /// Validate a data-topic write operation `self` issued by `writer` and introduced by
744    /// `introducer` at `now_ms` inside `network_id` (#1179, #1220).
745    pub(crate) fn validate_data_write(
746        &self,
747        now_ms: u128,
748        network_id: u32,
749        writer: Did,
750        introducer: Principal,
751    ) -> Result<()> {
752        self.validate_admissible_at(now_ms, network_id)
753            .and_then(|()| DataProvenance::try_new(self, writer, introducer).map(drop))
754    }
755
756    /// Validate a data-topic operation `self` issued by `writer` against the live carrier
757    /// `local` currently held at the storage slot (#1179, #1220).
758    pub(crate) fn validate_data_write_on_local(
759        &self,
760        local: Option<&Entry>,
761        writer: Did,
762    ) -> Result<()> {
763        if writer.is_default() {
764            return Err(Error::DataEntryWriteUnauthorized);
765        }
766        Entry::with_live_and_then(local, |live| {
767            DataProvenance::for_local(self, writer).verify_on_live(live)
768        })
769    }
770}
771
772impl Entry {
773    /// Evaluate `then` on `local` when a live carrier is present, or succeed with `Ok(())` when the
774    /// slot is empty.
775    pub(crate) fn with_live_and_then(
776        local: Option<&Self>,
777        then: impl FnOnce(&Self) -> Result<()>,
778    ) -> Result<()> {
779        local.map_or(Ok(()), then)
780    }
781
782    /// Iterate over all reset floors carried by `self` (`register` and `co_registers`).
783    pub(super) fn register_floors(&self) -> impl Iterator<Item = EntryVersion> + '_ {
784        self.crdt
785            .register
786            .into_iter()
787            .chain(self.crdt.co_registers.iter().copied())
788    }
789
790    /// Verify any cryptographic [`SignedDataMutation`] proofs carried on `self`, deduplicating
791    /// signature checks across shared Merkle batch claims (#1220).
792    pub(super) fn validate_data_proofs(&self, now_ms: u128, network_id: u32) -> Result<()> {
793        if self.crdt.proofs.is_empty() {
794            return Ok(());
795        }
796        let domain = SigningDomain::new(DATA_MUTATION_DOMAIN_TAG, network_id);
797        let max_ts = now_ms.saturating_add(TS_OFFSET_TOLERANCE_MS);
798        let mut verified_batches: Vec<(Did, DataMutationClaim, MessageVerification)> = Vec::new();
799        for item in &self.crdt.proofs {
800            let Some(proof) = &item.proof else {
801                return Err(Error::DataEntryWriteUnauthorized);
802            };
803            if proof.ts_ms > max_ts || item.claim.version.logical_time_ms > max_ts {
804                return Err(Error::EntryVersionAheadOfClock);
805            }
806            let actor = item.key.actor();
807            item.verify_claim_structure(self)?;
808            let already_verified = verified_batches
809                .iter()
810                .any(|(a, c, p)| *a == actor && *c == item.claim && p == proof);
811            if !already_verified {
812                let data = rings_codec::serialize(&item.claim).map_err(Error::CodecSerialize)?;
813                if !proof.verify_live_at(domain, &data, proof.ts_ms)
814                    || proof.delegation.delegator_did() != actor
815                {
816                    return Err(Error::DataEntryWriteUnauthorized);
817                }
818                verified_batches.push((actor, item.claim, proof.clone()));
819            }
820        }
821        Ok(())
822    }
823
824    /// Whether `self` carries at least one verified cryptographic proof for `actor`.
825    fn has_signed_proof_for(&self, actor: Did) -> bool {
826        self.crdt
827            .proofs
828            .iter()
829            .any(|proof| !proof.is_corrupted() && proof.key.actor() == actor)
830    }
831
832    fn has_signed_register_proof(&self, floor: EntryVersion) -> bool {
833        self.crdt
834            .proofs
835            .iter()
836            .any(|proof| proof.matches_register(floor))
837    }
838
839    fn has_signed_remove_proof(&self, element: ElementDigest, remove_dot: EntryDot) -> bool {
840        self.crdt
841            .proofs
842            .iter()
843            .any(|proof| proof.matches_remove(element, remove_dot))
844    }
845
846    /// Whether every version and proof carried by `self` is explicitly authored by `writer`.
847    pub(super) fn is_exclusively_authored_by(&self, writer: Did) -> bool {
848        !writer.is_default()
849            && self
850                .versions()
851                .all(|version| version.is_authored_by(writer))
852            && self
853                .crdt
854                .proofs
855                .iter()
856                .all(|proof| !proof.is_corrupted() && proof.key.actor() == writer)
857    }
858
859    /// Whether an `Overwrite` carrier satisfies the reset envelope invariant for `introducer`:
860    /// carries no raw tombstones and, when introduced by a remote peer, is non-empty.
861    fn permits_reset_envelope_from(&self, introducer: Principal) -> bool {
862        self.crdt.tombstones.is_empty() && (!self.data.is_empty() || introducer == Principal::Local)
863    }
864
865    /// Whether an `Extend` or `Tombstone` carrier satisfies the delta envelope invariant: carries
866    /// neither a reset register nor raw tombstones.
867    fn has_delta_envelope(&self) -> bool {
868        self.crdt.register.is_none()
869            && self.crdt.co_registers.is_empty()
870            && self.crdt.tombstones.is_empty()
871    }
872
873    /// Verify that `incoming` may reset this live carrier on behalf of `writer`.
874    fn permits_reset_by(&self, incoming: &Self, writer: Did) -> Result<()> {
875        (!incoming.data.is_empty() && self.is_exclusively_authored_by(writer))
876            .then_some(())
877            .ok_or(Error::DataEntryWriteUnauthorized)
878    }
879
880    /// Verify that `incoming` may append elements on behalf of `writer`, checking authorship
881    /// against `writer`'s own actor slot in `co_values[value]` so co-authors are never locked out
882    /// (#1220).
883    fn permits_append_by(&self, incoming: &Self, writer: Did) -> Result<()> {
884        self.topic_buffer().and_then(|buffer| {
885            incoming
886                .data
887                .iter()
888                .all(|value| {
889                    let unattributed_only = buffer
890                        .values
891                        .get(value)
892                        .is_some_and(|dot| !dot.is_attributed())
893                        && !buffer.co_values.contains_key(value);
894                    !unattributed_only
895                        && buffer
896                            .co_values
897                            .get(value)
898                            .and_then(|actors| actors.get(&writer))
899                            .is_none_or(|held_dot| held_dot.version.is_authored_by(writer))
900                })
901                .then_some(())
902                .ok_or(Error::DataEntryWriteUnauthorized)
903        })
904    }
905
906    /// Verify that `witness` retracts only `writer`'s own actor slot in `co_values[value]`
907    /// (#1220).
908    fn permits_retraction_by(&self, witness: &RetractionWitness<'_>, writer: Did) -> Result<()> {
909        self.topic_buffer().and_then(|buffer| {
910            let permitted = match witness {
911                RetractionWitness::Values(values) => values.iter().all(|value| {
912                    !buffer.values.contains_key(*value)
913                        || buffer
914                            .co_values
915                            .get(*value)
916                            .and_then(|actors| actors.get(&writer))
917                            .is_some_and(|held_dot| held_dot.version.is_authored_by(writer))
918                }),
919                RetractionWitness::Dots(dots) => {
920                    dots.iter().all(|dot| dot.version.is_authored_by(writer))
921                        && buffer.values.keys().all(|value| {
922                            buffer
923                                .dots_for(value)
924                                .filter(|held_dot| dots.contains(held_dot))
925                                .all(|held_dot| held_dot.version.is_authored_by(writer))
926                        })
927                }
928            };
929            permitted
930                .then_some(())
931                .ok_or(Error::DataEntryWriteUnauthorized)
932        })
933    }
934
935    /// Validate a synced or fetched data carrier `self` against the live carrier `local` currently
936    /// held at the slot (#1179, #1220).
937    ///
938    /// Enforces:
939    /// - Every version in `self` is explicitly attributed (`!actor.is_default() && !operation.is_default()`),
940    ///   `dots.len() == data.len()`, `co_dots` indices are in bounds, and no active element dot is
941    ///   reused in `tombstones`.
942    /// - Per-actor reset floors are self-consistent (`v.actor == floor.actor => v >= floor`).
943    /// - Cross-actor floors and tombstones merge commutatively without rejection because
944    ///   `DataTopicBuffer` scopes floors and tombstones by `actor`.
945    /// - Same-actor floors and tombstones retiring `live`'s state must carry `actor`'s
946    ///   [`SignedDataMutation`] whenever `live` holds Swarm-signed state for `actor`, and must
947    ///   carry a consistent operation witness otherwise.
948    pub(crate) fn validate_data_sync_on_local(&self, local: Option<&Self>) -> Result<()> {
949        self.validate_data_sync_structure()
950            .and_then(|()| self.permits_synced_register_on(local))
951            .and_then(|()| {
952                Self::with_live_and_then(local, |live| self.permits_synced_tombstones_on(live))
953            })
954    }
955
956    fn validate_data_sync_structure(&self) -> Result<()> {
957        if self.crdt.dots.len() != self.data.len() {
958            return Err(Error::DataEntryWriteUnauthorized);
959        }
960        if self.versions().any(|version| version.actor.is_default()) {
961            return Err(Error::DataEntryWriteUnauthorized);
962        }
963        if self
964            .crdt
965            .co_dots
966            .iter()
967            .any(|&(index, _)| (index as usize) >= self.data.len())
968        {
969            return Err(Error::DataEntryWriteUnauthorized);
970        }
971        if self.crdt.register.is_none() && !self.crdt.co_registers.is_empty() {
972            return Err(Error::DataEntryWriteUnauthorized);
973        }
974        if let Some(max_reg) = self.crdt.register {
975            if self.crdt.co_registers.iter().any(|&reg| reg >= max_reg) {
976                return Err(Error::DataEntryWriteUnauthorized);
977            }
978        }
979        let mut seen_floor_actors = BTreeSet::new();
980        for floor in self.register_floors() {
981            if !seen_floor_actors.insert(floor.actor) {
982                return Err(Error::DataEntryWriteUnauthorized);
983            }
984        }
985        Ok(())
986    }
987
988    fn floor_witness_valid_on_live(&self, floor: EntryVersion, live: &Self) -> bool {
989        if live.has_signed_proof_for(floor.actor) {
990            return self.has_signed_register_proof(floor);
991        }
992        let retires_live_same_actor = live
993            .versions()
994            .any(|version| version.actor == floor.actor && version < floor);
995        if !retires_live_same_actor {
996            return true;
997        }
998        let floor_elements = self
999            .data
1000            .iter()
1001            .enumerate()
1002            .filter(|&(index, _)| {
1003                self.crdt
1004                    .dots
1005                    .get(index)
1006                    .is_some_and(|d| d.version == floor)
1007                    || self
1008                        .crdt
1009                        .co_dots
1010                        .iter()
1011                        .any(|&(co_idx, d)| co_idx as usize == index && d.version == floor)
1012            })
1013            .map(|(_, value)| value.clone())
1014            .collect::<Vec<_>>();
1015        if floor_elements.is_empty() {
1016            floor.operation != floor.actor
1017        } else {
1018            let live_uses_synthetic_op = live
1019                .versions()
1020                .any(|v| v.actor == floor.actor && v.operation == floor.actor);
1021            live_uses_synthetic_op
1022                || self
1023                    .operation_digest_for(floor.actor, &floor_elements)
1024                    .is_ok_and(|digest| floor.operation == digest)
1025        }
1026    }
1027
1028    /// Verify that every per-actor reset floor on `self` is self-consistent and authenticated
1029    /// against `local`.
1030    fn permits_synced_register_on(&self, local: Option<&Self>) -> Result<()> {
1031        let valid = self.register_floors().all(|floor| {
1032            (!self.has_signed_proof_for(floor.actor) || self.has_signed_register_proof(floor))
1033                && self
1034                    .versions()
1035                    .filter(|version| version.actor == floor.actor)
1036                    .all(|version| version >= floor)
1037                && local.is_none_or(|live| self.floor_witness_valid_on_live(floor, live))
1038        });
1039        valid.then_some(()).ok_or(Error::DataEntryWriteUnauthorized)
1040    }
1041
1042    /// Verify that any same-actor tombstone on `self` covering a live element in `live` carries an
1043    /// authentic removal witness for that actor.
1044    fn permits_synced_tombstones_on(&self, live: &Self) -> Result<()> {
1045        if self.crdt.tombstones.is_empty() {
1046            return Ok(());
1047        }
1048        let mut by_element_actor = BTreeMap::<(ElementDigest, Did), EntryDot>::new();
1049        for tombstone in &self.crdt.tombstones {
1050            let actor = tombstone.dot.version.actor;
1051            if (self.has_signed_proof_for(actor) || live.has_signed_proof_for(actor))
1052                && !self.has_signed_remove_proof(tombstone.element, tombstone.dot)
1053            {
1054                return Err(Error::DataEntryWriteUnauthorized);
1055            }
1056            let key = (tombstone.element, actor);
1057            if by_element_actor
1058                .get(&key)
1059                .is_none_or(|current| current < &tombstone.dot)
1060            {
1061                by_element_actor.insert(key, tombstone.dot);
1062            }
1063        }
1064        live.attributed_elements()
1065            .all(|(value, held_dot)| {
1066                let actor = held_dot.version.actor;
1067                let digest = ElementDigest(keccak256(value.as_ref()));
1068                let Some(&remove_dot) = by_element_actor.get(&(digest, actor)) else {
1069                    return true;
1070                };
1071                if held_dot > remove_dot {
1072                    return true;
1073                }
1074                if live.has_signed_proof_for(actor) {
1075                    return self.has_signed_remove_proof(digest, remove_dot);
1076                }
1077                if remove_dot == held_dot {
1078                    return true;
1079                }
1080                let live_uses_synthetic_op = held_dot.version.operation == actor;
1081                live_uses_synthetic_op
1082                    || self
1083                        .operation_digest_for(actor, std::slice::from_ref(value))
1084                        .is_ok_and(|expected| remove_dot.version.operation == expected)
1085            })
1086            .then_some(())
1087            .ok_or(Error::DataEntryWriteUnauthorized)
1088    }
1089
1090    /// Iterate over `(value, dot)` pairs in `self` (both primary and co-author dots) whose dot
1091    /// carries a non-default author.
1092    fn attributed_elements(&self) -> impl Iterator<Item = (&Bytes, EntryDot)> + '_ {
1093        self.data
1094            .iter()
1095            .zip(self.crdt.dots.iter().copied())
1096            .chain(self.crdt.co_dots.iter().filter_map(|&(index, dot)| {
1097                self.data.get(index as usize).map(|value| (value, dot))
1098            }))
1099            .filter(|(_, dot)| dot.is_attributed())
1100    }
1101
1102    /// Return `self` unchanged: tombstones on `EntryKind::Data` are actor-scoped in
1103    /// [`DataTopicBuffer`](super::DataTopicBuffer), so cross-actor tombstones never cover another
1104    /// writer's dots and are never evicted (#1220).
1105    pub(crate) fn without_cross_actor_tombstones_for(
1106        self,
1107        _incoming: &Self,
1108        _fallback_actor: Did,
1109    ) -> Self {
1110        self
1111    }
1112}
1113
1114/// Materialize normalized data-topic elements under the fair per-writer cap `max_len`,
1115/// returning `(data, dots, co_dots)` (#1179, #1220).
1116///
1117/// Eviction ([`retain_fair_data_elements`]) triggers only when unique `Bytes` values exceed
1118/// `max_len`, and advances water-filling until `max_len` unique `Bytes` values are admitted so
1119/// co-author dots neither consume extra `max_len` slots nor regress a value's primary timestamp
1120/// at or below capacity, while preserving semilattice associativity across co-authored floods.
1121pub(super) fn materialize_data_elements(
1122    values: BTreeMap<Bytes, EntryDot>,
1123    mut co_values: BTreeMap<Bytes, BTreeMap<Did, EntryDot>>,
1124    max_len: usize,
1125) -> (Vec<Bytes>, Vec<EntryDot>, Vec<(u32, EntryDot)>) {
1126    if max_len == 0 {
1127        return (Vec::new(), Vec::new(), Vec::new());
1128    }
1129    if values.len() <= max_len {
1130        let mut visible = values.into_iter().collect::<Vec<_>>();
1131        visible.sort_by(|(left_value, left_dot), (right_value, right_dot)| {
1132            left_dot
1133                .cmp(right_dot)
1134                .then_with(|| left_value.cmp(right_value))
1135        });
1136        let mut data = Vec::with_capacity(visible.len());
1137        let mut dots = Vec::with_capacity(visible.len());
1138        let mut co_dots = Vec::new();
1139        for (index, (value, primary_dot)) in visible.into_iter().enumerate() {
1140            if let Some(actors) = co_values.remove(&value) {
1141                if let Ok(index_u32) = u32::try_from(index) {
1142                    let mut extra_dots = actors
1143                        .into_values()
1144                        .filter(|&dot| dot != primary_dot)
1145                        .collect::<Vec<_>>();
1146                    extra_dots.sort();
1147                    co_dots.extend(extra_dots.into_iter().map(|dot| (index_u32, dot)));
1148                }
1149            }
1150            data.push(value);
1151            dots.push(primary_dot);
1152        }
1153        return (data, dots, co_dots);
1154    }
1155
1156    let mut attributions = Vec::with_capacity(values.len());
1157    for (value, primary_dot) in values {
1158        match co_values.remove(&value) {
1159            Some(actors) if !actors.is_empty() => {
1160                if !primary_dot.is_attributed() {
1161                    attributions.push((value.clone(), primary_dot));
1162                }
1163                attributions.extend(actors.into_values().map(|dot| (value.clone(), dot)));
1164            }
1165            _ => attributions.push((value, primary_dot)),
1166        }
1167    }
1168    attributions.sort_by(|(left_value, left_dot), (right_value, right_dot)| {
1169        left_dot
1170            .cmp(right_dot)
1171            .then_with(|| left_value.cmp(right_value))
1172    });
1173    let by_value = retain_fair_data_elements(attributions, max_len);
1174    let mut primary = by_value
1175        .into_iter()
1176        .filter_map(|(value, mut actor_dots)| {
1177            actor_dots.sort();
1178            actor_dots
1179                .pop()
1180                .map(|primary_dot| (value, primary_dot, actor_dots))
1181        })
1182        .collect::<Vec<_>>();
1183    primary.sort_by(|(left_value, left_dot, _), (right_value, right_dot, _)| {
1184        left_dot
1185            .cmp(right_dot)
1186            .then_with(|| left_value.cmp(right_value))
1187    });
1188    let mut data = Vec::with_capacity(primary.len());
1189    let mut dots = Vec::with_capacity(primary.len());
1190    let mut co_dots = Vec::new();
1191    for (index, (value, primary_dot, extra_dots)) in primary.into_iter().enumerate() {
1192        if let Ok(index_u32) = u32::try_from(index) {
1193            co_dots.extend(extra_dots.into_iter().map(|dot| (index_u32, dot)));
1194        }
1195        data.push(value);
1196        dots.push(primary_dot);
1197    }
1198    (data, dots, co_dots)
1199}
1200
1201/// Retain up to `max_len` unique `Bytes` values from `visible` (already sorted ascending by
1202/// `(dot, value)`), bounding each authenticated writer (`!dot.version.actor.is_default()`) by
1203/// water-filling recency rank so neither single-writer floods nor multi-writer co-dot amplification
1204/// can evict honest writers' newest elements (#1179, #1220).
1205pub(super) fn retain_fair_data_elements(
1206    visible: Vec<(Bytes, EntryDot)>,
1207    max_len: usize,
1208) -> BTreeMap<Bytes, Vec<EntryDot>> {
1209    let total = visible.len();
1210    let (_, mut ranked) = visible.into_iter().rev().fold(
1211        (BTreeMap::<Did, usize>::new(), Vec::with_capacity(total)),
1212        |(mut seen_per_actor, mut ranked), (value, dot)| {
1213            let rank = dot.attributed_actor().map_or(usize::MAX, |actor| {
1214                let count = seen_per_actor.entry(actor).or_insert(0);
1215                std::mem::replace(count, count.saturating_add(1))
1216            });
1217            ranked.push((rank, value, dot));
1218            (seen_per_actor, ranked)
1219        },
1220    );
1221    ranked.sort_by(
1222        |(left_rank, left_value, left_dot), (right_rank, right_value, right_dot)| {
1223            left_rank
1224                .cmp(right_rank)
1225                .then_with(|| Reverse(*left_dot).cmp(&Reverse(*right_dot)))
1226                .then_with(|| Reverse(left_value).cmp(&Reverse(right_value)))
1227        },
1228    );
1229    let mut by_value = BTreeMap::<Bytes, Vec<EntryDot>>::new();
1230    for (_, value, dot) in ranked {
1231        by_value.entry(value).or_default().push(dot);
1232        if by_value.len() == max_len {
1233            break;
1234        }
1235    }
1236    by_value
1237}